Java Code Examples for org.eclipse.lsp4j.jsonrpc.messages.Either

The following examples show how to use org.eclipse.lsp4j.jsonrpc.messages.Either. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source Project: eclipse.jdt.ls   Author: eclipse   File: HoverHandlerTest.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testHoverWhenLinkDoesNotExist() throws Exception {
	importProjects("maven/salut");
	project = WorkspaceHelper.getProject("salut");
	handler = new HoverHandler(preferenceManager);

	//given
	String payload = createHoverRequest("src/main/java/java/Foo2.java", 51, 25);
	TextDocumentPositionParams position = getParams(payload);

	// when
	Hover hover = handler.hover(position, monitor);
	assertNotNull("Hover is null", hover);
	assertEquals("Unexpected hover contents:\n" + hover.getContents(), 2, hover.getContents().getLeft().size());
	Either<String, MarkedString> javadoc = hover.getContents().getLeft().get(1);
	String content = null;
	assertTrue("javadoc has null content", javadoc != null && javadoc.getLeft() != null && (content = javadoc.getLeft()) != null);
	assertMatches("This link doesnt work LinkToSomethingNotFound", content);
}
 
Example #2
Source Project: eclipse.jdt.ls   Author: eclipse   File: SyntaxServerTest.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testDocumentSymbol() throws Exception {
	when(preferenceManager.getClientPreferences().isHierarchicalDocumentSymbolSupported()).thenReturn(Boolean.TRUE);

	URI fileURI = openFile("maven/salut4", "src/main/java/java/Foo.java");
	TextDocumentIdentifier identifier = new TextDocumentIdentifier(fileURI.toString());
	DocumentSymbolParams params = new DocumentSymbolParams(identifier);
	List<Either<SymbolInformation, DocumentSymbol>> result = server.documentSymbol(params).join();
	assertNotNull(result);
	assertEquals(2, result.size());
	Either<SymbolInformation, DocumentSymbol> symbol = result.get(0);
	assertTrue(symbol.isRight());
	assertEquals("java", symbol.getRight().getName());
	assertEquals(SymbolKind.Package, symbol.getRight().getKind());
	symbol = result.get(1);
	assertTrue(symbol.isRight());
	assertEquals("Foo", symbol.getRight().getName());
	assertEquals(SymbolKind.Class, symbol.getRight().getKind());
	List<DocumentSymbol> children = symbol.getRight().getChildren();
	assertNotNull(children);
	assertEquals(1, children.size());
	assertEquals("main(String[])", children.get(0).getName());
	assertEquals(SymbolKind.Method, children.get(0).getKind());
}
 
Example #3
Source Project: groovy-language-server   Author: prominic   File: GroovyServicesCompletionTests.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void testMemberAccessOnLocalArrayAfterDot() throws Exception {
	Path filePath = srcRoot.resolve("Completion.groovy");
	String uri = filePath.toUri().toString();
	StringBuilder contents = new StringBuilder();
	contents.append("class Completion {\n");
	contents.append("  public Completion() {\n");
	contents.append("    String[] localVar\n");
	contents.append("    localVar[0].\n");
	contents.append("  }\n");
	contents.append("}");
	TextDocumentItem textDocumentItem = new TextDocumentItem(uri, LANGUAGE_GROOVY, 1, contents.toString());
	services.didOpen(new DidOpenTextDocumentParams(textDocumentItem));
	TextDocumentIdentifier textDocument = new TextDocumentIdentifier(uri);
	Position position = new Position(3, 16);
	Either<List<CompletionItem>, CompletionList> result = services
			.completion(new CompletionParams(textDocument, position)).get();
	Assertions.assertTrue(result.isLeft());
	List<CompletionItem> items = result.getLeft();
	Assertions.assertTrue(items.size() > 0);
	List<CompletionItem> filteredItems = items.stream().filter(item -> {
		return item.getLabel().equals("charAt") && item.getKind().equals(CompletionItemKind.Method);
	}).collect(Collectors.toList());
	Assertions.assertEquals(1, filteredItems.size());
}
 
Example #4
Source Project: groovy-language-server   Author: prominic   File: GroovyServicesCompletionTests.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void testMemberAccessOnLocalVariableWithPartialPropertyExpression() throws Exception {
	Path filePath = srcRoot.resolve("Completion.groovy");
	String uri = filePath.toUri().toString();
	StringBuilder contents = new StringBuilder();
	contents.append("class Completion {\n");
	contents.append("  public Completion() {\n");
	contents.append("    String localVar\n");
	contents.append("    localVar.charA\n");
	contents.append("  }\n");
	contents.append("}");
	TextDocumentItem textDocumentItem = new TextDocumentItem(uri, LANGUAGE_GROOVY, 1, contents.toString());
	services.didOpen(new DidOpenTextDocumentParams(textDocumentItem));
	TextDocumentIdentifier textDocument = new TextDocumentIdentifier(uri);
	Position position = new Position(3, 18);
	Either<List<CompletionItem>, CompletionList> result = services
			.completion(new CompletionParams(textDocument, position)).get();
	Assertions.assertTrue(result.isLeft());
	List<CompletionItem> items = result.getLeft();
	List<CompletionItem> filteredItems = items.stream().filter(item -> {
		return item.getLabel().equals("charAt") && item.getKind().equals(CompletionItemKind.Method);
	}).collect(Collectors.toList());
	Assertions.assertEquals(1, filteredItems.size());
}
 
Example #5
Source Project: groovy-language-server   Author: prominic   File: GroovyServicesCompletionTests.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void testMemberAccessOnLocalVariableWithExistingMethodCallExpressionOnNextLine() throws Exception {
	Path filePath = srcRoot.resolve("Completion.groovy");
	String uri = filePath.toUri().toString();
	StringBuilder contents = new StringBuilder();
	contents.append("class Completion {\n");
	contents.append("  public Completion() {\n");
	contents.append("    String localVar\n");
	contents.append("    localVar.\n");
	contents.append("    method()\n");
	contents.append("  }\n");
	contents.append("}");
	TextDocumentItem textDocumentItem = new TextDocumentItem(uri, LANGUAGE_GROOVY, 1, contents.toString());
	services.didOpen(new DidOpenTextDocumentParams(textDocumentItem));
	TextDocumentIdentifier textDocument = new TextDocumentIdentifier(uri);
	Position position = new Position(3, 13);
	Either<List<CompletionItem>, CompletionList> result = services
			.completion(new CompletionParams(textDocument, position)).get();
	Assertions.assertTrue(result.isLeft());
	List<CompletionItem> items = result.getLeft();
	Assertions.assertTrue(items.size() > 0);
	List<CompletionItem> filteredItems = items.stream().filter(item -> {
		return item.getLabel().equals("charAt") && item.getKind().equals(CompletionItemKind.Method);
	}).collect(Collectors.toList());
	Assertions.assertEquals(1, filteredItems.size());
}
 
Example #6
Source Project: groovy-language-server   Author: prominic   File: GroovyServicesCompletionTests.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void testCompletionForMemberMethodOnCompleteVariableExpression() throws Exception {
	Path filePath = srcRoot.resolve("Completion.groovy");
	String uri = filePath.toUri().toString();
	StringBuilder contents = new StringBuilder();
	contents.append("class Completion {\n");
	contents.append("  String memberMethod() {}\n");
	contents.append("  public Completion() {\n");
	contents.append("    memberMethod\n");
	contents.append("  }\n");
	contents.append("}");
	TextDocumentItem textDocumentItem = new TextDocumentItem(uri, LANGUAGE_GROOVY, 1, contents.toString());
	services.didOpen(new DidOpenTextDocumentParams(textDocumentItem));
	TextDocumentIdentifier textDocument = new TextDocumentIdentifier(uri);
	Position position = new Position(3, 7);
	Either<List<CompletionItem>, CompletionList> result = services
			.completion(new CompletionParams(textDocument, position)).get();
	Assertions.assertTrue(result.isLeft());
	List<CompletionItem> items = result.getLeft();
	List<CompletionItem> filteredItems = items.stream().filter(item -> {
		return item.getLabel().equals("memberMethod") && item.getKind().equals(CompletionItemKind.Method);
	}).collect(Collectors.toList());
	Assertions.assertEquals(1, filteredItems.size());
}
 
Example #7
Source Project: camel-language-server   Author: camel-tooling   File: CamelTextDocumentServiceTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void testChangeEventUpdatesStoredText() throws Exception {
	CamelLanguageServer camelLanguageServer = initializeLanguageServer("<to uri=\"\" xmlns=\"http://camel.apache.org/schema/blueprint\"></to>\n");
	
	DidChangeTextDocumentParams changeEvent = new DidChangeTextDocumentParams();
	VersionedTextDocumentIdentifier textDocument = new VersionedTextDocumentIdentifier();
	textDocument.setUri(DUMMY_URI+".xml");
	changeEvent.setTextDocument(textDocument);
	TextDocumentContentChangeEvent contentChange = new TextDocumentContentChangeEvent("<to xmlns=\"http://camel.apache.org/schema/blueprint\" uri=\"\"></to>\n");
	changeEvent.setContentChanges(Collections.singletonList(contentChange));
	camelLanguageServer.getTextDocumentService().didChange(changeEvent);
	
	//check old position doesn't provide completion
	CompletableFuture<Either<List<CompletionItem>, CompletionList>> completionsAtOldPosition = getCompletionFor(camelLanguageServer, new Position(0, 11));
	assertThat(completionsAtOldPosition.get().getLeft()).isEmpty();
	
	//check new position provides completion
	CompletableFuture<Either<List<CompletionItem>, CompletionList>> completionsAtNewPosition = getCompletionFor(camelLanguageServer, new Position(0, 58));
	assertThat(completionsAtNewPosition.get().getLeft()).isNotEmpty();
	
}
 
Example #8
Source Project: groovy-language-server   Author: prominic   File: GroovyServicesCompletionTests.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void testCompletionForLocalVariableOnPartialVariableExpression() throws Exception {
	Path filePath = srcRoot.resolve("Completion.groovy");
	String uri = filePath.toUri().toString();
	StringBuilder contents = new StringBuilder();
	contents.append("class Completion {\n");
	contents.append("  public void testMethod(String paramName) {\n");
	contents.append("    String localVar\n");
	contents.append("    loc\n");
	contents.append("  }\n");
	contents.append("}");
	TextDocumentItem textDocumentItem = new TextDocumentItem(uri, LANGUAGE_GROOVY, 1, contents.toString());
	services.didOpen(new DidOpenTextDocumentParams(textDocumentItem));
	TextDocumentIdentifier textDocument = new TextDocumentIdentifier(uri);
	Position position = new Position(3, 7);
	Either<List<CompletionItem>, CompletionList> result = services
			.completion(new CompletionParams(textDocument, position)).get();
	Assertions.assertTrue(result.isLeft());
	List<CompletionItem> items = result.getLeft();
	List<CompletionItem> filteredItems = items.stream().filter(item -> {
		return item.getLabel().equals("localVar") && item.getKind().equals(CompletionItemKind.Variable);
	}).collect(Collectors.toList());
	Assertions.assertEquals(1, filteredItems.size());
}
 
Example #9
Source Project: n4js   Author: eclipse   File: AbstractDefinitionTest.java    License: Eclipse Public License 1.0 6 votes vote down vote up
@Override
protected void performTest(Project project, String moduleName, DefinitionTestConfiguration dtc)
		throws InterruptedException, ExecutionException, URISyntaxException {

	TextDocumentPositionParams textDocumentPositionParams = new TextDocumentPositionParams();
	String completeFileUri = getFileURIFromModuleName(dtc.getFilePath()).toString();
	textDocumentPositionParams.setTextDocument(new TextDocumentIdentifier(completeFileUri));
	textDocumentPositionParams.setPosition(new Position(dtc.getLine(), dtc.getColumn()));
	CompletableFuture<Either<List<? extends Location>, List<? extends LocationLink>>> definitionsFuture = languageServer
			.definition(textDocumentPositionParams);

	Either<List<? extends Location>, List<? extends LocationLink>> definitions = definitionsFuture.get();
	if (dtc.getAssertDefinitions() != null) {
		dtc.getAssertDefinitions().apply(definitions.getLeft());
	} else {
		String actualSignatureHelp = getStringLSP4J().toString4(definitions);
		assertEquals(dtc.getExpectedDefinitions().trim(), actualSignatureHelp.trim());
	}
}
 
Example #10
Source Project: eclipse.jdt.ls   Author: eclipse   File: SourceAssistProcessor.java    License: Eclipse Public License 2.0 6 votes vote down vote up
private void addSourceActionCommand(List<Either<Command, CodeAction>> result, CodeActionContext context, Optional<Either<Command, CodeAction>> target) {
	if (!target.isPresent()) {
		return;
	}

	Either<Command, CodeAction> targetAction = target.get();
	if (context.getOnly() != null && !context.getOnly().isEmpty()) {
		Stream<String> acceptedActionKinds = context.getOnly().stream();
		String actionKind = targetAction.getLeft() == null ? targetAction.getRight().getKind() : targetAction.getLeft().getCommand();
		if (!acceptedActionKinds.filter(kind -> actionKind != null && actionKind.startsWith(kind)).findFirst().isPresent()) {
			return;
		}
	}

	result.add(targetAction);
}
 
Example #11
Source Project: syndesis   Author: syndesisio   File: TeiidDdlTextDocumentService.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public CompletableFuture<Either<List<CompletionItem>, CompletionList>> completion(
        CompletionParams completionParams) {
    String uri = completionParams.getTextDocument().getUri();
    LOGGER.debug("completion: {}", uri);
    TextDocumentItem doc = openedDocuments.get(uri);

    // get applicable completion items
    List<CompletionItem> items = completionProvider.getCompletionItems(doc.getText(),
            completionParams.getPosition());

    // if items exist, return them
    if (items != null && !items.isEmpty()) {
        return CompletableFuture.completedFuture(Either.forLeft(items));
    }

    // if items do no exist return empty results
    return CompletableFuture.completedFuture(Either.forLeft(Collections.emptyList()));
}
 
Example #12
Source Project: lemminx   Author: eclipse   File: HTMLCompletionExtensionsTest.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void onTagOpen(ICompletionRequest completionRequest, ICompletionResponse completionResponse)
		throws Exception {
	Range range = completionRequest.getReplaceRange();
	HTMLTag.HTML_TAGS.forEach(t -> {
		String tag = t.getTag();
		String label = t.getLabel();
		CompletionItem item = new CompletionItem();
		item.setLabel(tag);
		item.setFilterText(completionRequest.getFilterForStartTagName(tag));
		item.setKind(CompletionItemKind.Property);
		item.setDocumentation(Either.forLeft(label));
		item.setTextEdit(new TextEdit(range, "<" + tag + "/>"));
		item.setInsertTextFormat(InsertTextFormat.PlainText);
		completionResponse.addCompletionItem(item);
	});
}
 
Example #13
Source Project: eclipse.jdt.ls   Author: eclipse   File: GenerateDelegateMethodsActionTest.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testGenerateDelegateMethodsEnabled() throws JavaModelException {
	//@formatter:off
	ICompilationUnit unit = fPackageP.createCompilationUnit("A.java", "package p;\r\n" +
			"\r\n" +
			"public class A {\r\n" +
			"	String name;\r\n" +
			"}"
			, true, null);
	//@formatter:on
	CodeActionParams params = CodeActionUtil.constructCodeActionParams(unit, "String name");
	List<Either<Command, CodeAction>> codeActions = server.codeAction(params).join();
	Assert.assertNotNull(codeActions);
	Either<Command, CodeAction> delegateMethodsAction = CodeActionHandlerTest.findAction(codeActions, JavaCodeActionKind.SOURCE_GENERATE_DELEGATE_METHODS);
	Assert.assertNotNull(delegateMethodsAction);
	Command delegateMethodsCommand = CodeActionHandlerTest.getCommand(delegateMethodsAction);
	Assert.assertNotNull(delegateMethodsCommand);
	Assert.assertEquals(SourceAssistProcessor.COMMAND_ID_ACTION_GENERATEDELEGATEMETHODSPROMPT, delegateMethodsCommand.getCommand());
}
 
Example #14
Source Project: eclipse.jdt.ls   Author: eclipse   File: HashCodeEqualsActionTest.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testHashCodeEqualsDisabled_enum() throws JavaModelException {
	//@formatter:off
	ICompilationUnit unit = fPackageP.createCompilationUnit("A.java", "package p;\r\n" +
			"\r\n" +
			"public enum A {\r\n" +
			"	MONDAY,\r\n" +
			"	TUESDAY;\r\n" +
			"	private String name;\r\n" +
			"}"
			, true, null);
	//@formatter:on
	CodeActionParams params = CodeActionUtil.constructCodeActionParams(unit, "String name");
	List<Either<Command, CodeAction>> codeActions = server.codeAction(params).join();
	Assert.assertNotNull(codeActions);
	Assert.assertFalse("The operation is not applicable to enums", CodeActionHandlerTest.containsKind(codeActions, JavaCodeActionKind.SOURCE_GENERATE_HASHCODE_EQUALS));
}
 
Example #15
Source Project: vscode-as3mxml   Author: BowlerHatLLC   File: CodeActionProvider.java    License: Apache License 2.0 6 votes vote down vote up
private void findSourceActions(Path path, List<Either<Command, CodeAction>> codeActions)
{
    Command organizeCommand = new Command();
    organizeCommand.setTitle("Organize Imports");
    organizeCommand.setCommand(ICommandConstants.ORGANIZE_IMPORTS_IN_URI);
    JsonObject uri = new JsonObject();
    uri.addProperty("external", path.toUri().toString());
    organizeCommand.setArguments(Lists.newArrayList(
        uri
    ));
    CodeAction organizeImports = new CodeAction();
    organizeImports.setKind(CodeActionKind.SourceOrganizeImports);
    organizeImports.setTitle(organizeCommand.getTitle());
    organizeImports.setCommand(organizeCommand);
    codeActions.add(Either.forRight(organizeImports));
}
 
Example #16
Source Project: lsp4j   Author: eclipse   File: LauncherTest.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Test public void testRequest() throws Exception {
	CompletionParams p = new CompletionParams();
	p.setPosition(new Position(1,1));
	p.setTextDocument(new TextDocumentIdentifier("test/foo.txt"));
	
	CompletionList result = new CompletionList();
	result.setIsIncomplete(true);
	result.setItems(new ArrayList<>());
	
	CompletionItem item = new CompletionItem();
	item.setDetail("test");
	item.setDocumentation("doc");
	item.setFilterText("filter");
	item.setInsertText("insert");
	item.setKind(CompletionItemKind.Field);
	result.getItems().add(item);
	
	server.expectedRequests.put("textDocument/completion", new Pair<>(p, result));
	CompletableFuture<Either<List<CompletionItem>, CompletionList>> future = clientLauncher.getRemoteProxy().getTextDocumentService().completion(p);
	Assert.assertEquals(Either.forRight(result).toString(), future.get(TIMEOUT, TimeUnit.MILLISECONDS).toString());
	client.joinOnEmpty();
}
 
Example #17
Source Project: eclipse.jdt.ls   Author: eclipse   File: GenerateConstructorsActionTest.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testGenerateConstructorsEnabled() throws JavaModelException {
	//@formatter:off
	ICompilationUnit unit = fPackageP.createCompilationUnit("A.java", "package p;\r\n" +
			"\r\n" +
			"public class A {\r\n" +
			"	String name;\r\n" +
			"}"
			, true, null);
	//@formatter:on
	CodeActionParams params = CodeActionUtil.constructCodeActionParams(unit, "String name");
	List<Either<Command, CodeAction>> codeActions = server.codeAction(params).join();
	Assert.assertNotNull(codeActions);
	Either<Command, CodeAction> constructorAction = CodeActionHandlerTest.findAction(codeActions, JavaCodeActionKind.SOURCE_GENERATE_CONSTRUCTORS);
	Assert.assertNotNull(constructorAction);
	Command constructorCommand = CodeActionHandlerTest.getCommand(constructorAction);
	Assert.assertNotNull(constructorCommand);
	Assert.assertEquals(SourceAssistProcessor.COMMAND_ID_ACTION_GENERATECONSTRUCTORSPROMPT, constructorCommand.getCommand());
}
 
Example #18
Source Project: xtext-core   Author: eclipse   File: AbstractLanguageServerTest.java    License: Eclipse Public License 2.0 5 votes vote down vote up
protected void testDocumentSymbol(final Procedure1<? super DocumentSymbolConfiguraiton> configurator) {
  try {
    @Extension
    final DocumentSymbolConfiguraiton configuration = new DocumentSymbolConfiguraiton();
    configuration.setFilePath(("MyModel." + this.fileExtension));
    configurator.apply(configuration);
    final String fileUri = this.initializeContext(configuration).getUri();
    TextDocumentIdentifier _textDocumentIdentifier = new TextDocumentIdentifier(fileUri);
    DocumentSymbolParams _documentSymbolParams = new DocumentSymbolParams(_textDocumentIdentifier);
    final CompletableFuture<List<Either<SymbolInformation, DocumentSymbol>>> symbolsFuture = this.languageServer.documentSymbol(_documentSymbolParams);
    final List<Either<SymbolInformation, DocumentSymbol>> symbols = symbolsFuture.get();
    Procedure1<? super List<Either<SymbolInformation, DocumentSymbol>>> _assertSymbols = configuration.getAssertSymbols();
    boolean _tripleNotEquals = (_assertSymbols != null);
    if (_tripleNotEquals) {
      configuration.getAssertSymbols().apply(symbols);
    } else {
      final Function1<Either<SymbolInformation, DocumentSymbol>, Object> _function = (Either<SymbolInformation, DocumentSymbol> it) -> {
        Object _xifexpression = null;
        if (this.hierarchicalDocumentSymbolSupport) {
          _xifexpression = it.getRight();
        } else {
          _xifexpression = it.getLeft();
        }
        return _xifexpression;
      };
      final List<Object> unwrappedSymbols = ListExtensions.<Either<SymbolInformation, DocumentSymbol>, Object>map(symbols, _function);
      final String actualSymbols = this.toExpectation(unwrappedSymbols);
      this.assertEquals(configuration.getExpectedSymbols(), actualSymbols);
    }
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}
 
Example #19
Source Project: lsp4j   Author: eclipse   File: EitherTypeAdapter.java    License: Eclipse Public License 2.0 5 votes vote down vote up
public EitherTypeAdapter(Gson gson, TypeToken<Either<L, R>> typeToken, Predicate<JsonElement> leftChecker, Predicate<JsonElement> rightChecker) {
	this.typeToken = typeToken;
	Type[] elementTypes = TypeUtils.getElementTypes(typeToken, Either.class);
	this.left = new EitherTypeArgument<L>(gson, elementTypes[0]);
	this.right = new EitherTypeArgument<R>(gson, elementTypes[1]);
	this.leftChecker = leftChecker;
	this.rightChecker = rightChecker;
}
 
Example #20
Source Project: n4js   Author: eclipse   File: XLanguageServerImpl.java    License: Eclipse Public License 1.0 5 votes vote down vote up
/**
 * @since 2.18
 */
@Override
public CompletableFuture<Either<Range, PrepareRenameResult>> prepareRename(TextDocumentPositionParams params) {
	URI uri = getURI(params);
	return openFilesManager.runInOpenFileContext(uri, "prepareRename", (ofc, ci) -> {
		return prepareRename(ofc, params, ci);
	});
}
 
Example #21
@Test
void testProvideCompletionInsideValue() throws Exception {
	CompletableFuture<Either<List<CompletionItem>, CompletionList>> completions = retrieveCompletion(new Position(0, 45));
	
	CompletionItem expectedCompletionItem = new CompletionItem("true");
	expectedCompletionItem.setTextEdit(new TextEdit(new Range(new Position(0, 44), new Position(0, 45)), "true"));
	assertThat(completions.get().getLeft()).containsOnly(expectedCompletionItem);
}
 
Example #22
Source Project: lsp4j   Author: eclipse   File: EitherTypeAdapter.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void write(JsonWriter out, Either<L, R> value) throws IOException {
	if (value == null) {
		out.nullValue();
	} else if (value.isLeft()) {
		left.write(out, value.getLeft());
	} else {
		right.write(out, value.getRight());
	}
}
 
Example #23
Source Project: camel-language-server   Author: camel-tooling   File: CamelKModelineCompletionTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
void testProvideCompletionAtTheEndOfLine() throws Exception {
	CamelLanguageServer camelLanguageServer = initializeLanguageServer("// camel-k: language=groovy trait=service.enabled=false ");
	
	CompletableFuture<Either<List<CompletionItem>, CompletionList>> completions = getCompletionFor(camelLanguageServer, new Position(0, 56));
	
	List<CompletionItem> completionItems = completions.get().getLeft();
	assertThat(completionItems).hasSize(10);
	checkTraitCompletionAvailable(completionItems);
}
 
Example #24
Source Project: eclipse.jdt.ls   Author: eclipse   File: GenerateDelegateMethodsActionTest.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testGenerateDelegateMethodsDisabled() throws JavaModelException {
	//@formatter:off
	ICompilationUnit unit = fPackageP.createCompilationUnit("A.java", "package p;\r\n" +
			"\r\n" +
			"public class A {\r\n" +
			"}"
			, true, null);
	//@formatter:on
	CodeActionParams params = CodeActionUtil.constructCodeActionParams(unit, "class A");
	List<Either<Command, CodeAction>> codeActions = server.codeAction(params).join();
	Assert.assertNotNull(codeActions);
	Assert.assertFalse("No delegatable fields found.", CodeActionHandlerTest.containsKind(codeActions, JavaCodeActionKind.SOURCE_GENERATE_DELEGATE_METHODS));
}
 
Example #25
Source Project: vscode-as3mxml   Author: BowlerHatLLC   File: ActionScriptServices.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns a list of all items to display in the completion list at a
 * specific position in a document. Called automatically by VSCode as the
 * user types, and may not necessarily be triggered only on "." or ":".
 */
@Override
public CompletableFuture<Either<List<CompletionItem>, CompletionList>> completion(CompletionParams params)
{
    return CompletableFutures.computeAsync(compilerWorkspace.getExecutorService(), cancelToken ->
    {
        cancelToken.checkCanceled();

        //make sure that the latest changes have been passed to
        //workspace.fileChanged() before proceeding
        if(realTimeProblemsChecker != null)
        {
            realTimeProblemsChecker.updateNow();
        }

        compilerWorkspace.startBuilding();
        try
        {
            CompletionProvider provider = new CompletionProvider(workspaceFolderManager,
                    fileTracker, completionSupportsSnippets, frameworkSDKIsRoyale);
            return provider.completion(params, cancelToken);
        }
        finally
        {
            compilerWorkspace.doneBuilding();
        }
    });
}
 
Example #26
Source Project: lsp4j   Author: eclipse   File: ServerCapabilities.java    License: Eclipse Public License 2.0 5 votes vote down vote up
public void setTextDocumentSync(final TextDocumentSyncOptions textDocumentSync) {
  if (textDocumentSync == null) {
    this.textDocumentSync = null;
    return;
  }
  this.textDocumentSync = Either.forRight(textDocumentSync);
}
 
Example #27
Source Project: eclipse.jdt.ls   Author: eclipse   File: JDTLanguageServer.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@Override
public CompletableFuture<Either<List<? extends Location>, List<? extends LocationLink>>> definition(DefinitionParams position) {
	logInfo(">> document/definition");
	NavigateToDefinitionHandler handler = new NavigateToDefinitionHandler(this.preferenceManager);
	return computeAsync((monitor) -> {
		waitForLifecycleJobs(monitor);
		return Either.forLeft(handler.definition(position, monitor));
	});
}
 
Example #28
Source Project: vscode-as3mxml   Author: BowlerHatLLC   File: ActionScriptServices.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Finds where the type of the definition referenced at the current position
 * in a text document is defined.
 */
@Override
public CompletableFuture<Either<List<? extends Location>, List<? extends LocationLink>>> typeDefinition(TypeDefinitionParams params)
{
    return CompletableFutures.computeAsync(compilerWorkspace.getExecutorService(), cancelToken ->
    {
        cancelToken.checkCanceled();

        //make sure that the latest changes have been passed to
        //workspace.fileChanged() before proceeding
        if(realTimeProblemsChecker != null)
        {
            realTimeProblemsChecker.updateNow();
        }

        compilerWorkspace.startBuilding();
        try
        {
            TypeDefinitionProvider provider = new TypeDefinitionProvider(workspaceFolderManager, fileTracker);
            return provider.typeDefinition(params, cancelToken);
        }
        finally
        {
            compilerWorkspace.doneBuilding();
        }
    });
}
 
Example #29
Source Project: lsp4j   Author: eclipse   File: StackFrame.java    License: Eclipse Public License 2.0 5 votes vote down vote up
public void setModuleId(final Integer moduleId) {
  if (moduleId == null) {
    this.moduleId = null;
    return;
  }
  this.moduleId = Either.forLeft(moduleId);
}
 
Example #30
Source Project: eclipse.jdt.ls   Author: eclipse   File: AdvancedExtractTest.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testExtractMethod() throws Exception {
	IPackageFragment pack1 = fSourceFolder.createPackageFragment("test1", false, null);

	StringBuilder buf = new StringBuilder();
	buf.append("package test1;\n");
	buf.append("\n");
	buf.append("public class E {\n");
	buf.append("    public int foo(boolean b1, boolean b2) {\n");
	buf.append("        int n = 0;\n");
	buf.append("        int i = 0;\n");
	buf.append("        /*[*/\n");
	buf.append("        if (b1)\n");
	buf.append("            i = 1;\n");
	buf.append("        if (b2)\n");
	buf.append("            n = n + i;\n");
	buf.append("        /*]*/\n");
	buf.append("        return n;\n");
	buf.append("    }\n");
	buf.append("}\n");

	ICompilationUnit cu = pack1.createCompilationUnit("E.java", buf.toString(), false, null);
	Range selection = getRange(cu, null);
	List<Either<Command, CodeAction>> codeActions = evaluateCodeActions(cu, selection);
	Assert.assertNotNull(codeActions);
	Either<Command, CodeAction> extractMethodAction = CodeActionHandlerTest.findAction(codeActions, JavaCodeActionKind.REFACTOR_EXTRACT_METHOD);
	Assert.assertNotNull(extractMethodAction);
	Command extractMethodCommand = CodeActionHandlerTest.getCommand(extractMethodAction);
	Assert.assertNotNull(extractMethodCommand);
	Assert.assertEquals(RefactorProposalUtility.APPLY_REFACTORING_COMMAND_ID, extractMethodCommand.getCommand());
	Assert.assertNotNull(extractMethodCommand.getArguments());
	Assert.assertEquals(2, extractMethodCommand.getArguments().size());
	Assert.assertEquals(RefactorProposalUtility.EXTRACT_METHOD_COMMAND, extractMethodCommand.getArguments().get(0));
}