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

The following examples show how to use org.eclipse.lsp4j.jsonrpc.messages.Either. 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 File: HTMLCompletionExtensionsTest.java    From lemminx with 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 #2
Source File: CodeActionProvider.java    From vscode-as3mxml with 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 #3
Source File: HoverHandlerTest.java    From eclipse.jdt.ls with 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 #4
Source File: LauncherTest.java    From lsp4j with 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 #5
Source File: GenerateDelegateMethodsActionTest.java    From eclipse.jdt.ls with 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 #6
Source File: HashCodeEqualsActionTest.java    From eclipse.jdt.ls with 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 #7
Source File: GenerateConstructorsActionTest.java    From eclipse.jdt.ls with 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 #8
Source File: TeiidDdlTextDocumentService.java    From syndesis with 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 #9
Source File: SourceAssistProcessor.java    From eclipse.jdt.ls with 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 #10
Source File: SyntaxServerTest.java    From eclipse.jdt.ls with 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 #11
Source File: AbstractDefinitionTest.java    From n4js with 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 #12
Source File: GroovyServicesCompletionTests.java    From groovy-language-server with 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 #13
Source File: GroovyServicesCompletionTests.java    From groovy-language-server with 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 #14
Source File: GroovyServicesCompletionTests.java    From groovy-language-server with 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 #15
Source File: GroovyServicesCompletionTests.java    From groovy-language-server with 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 #16
Source File: CamelTextDocumentServiceTest.java    From camel-language-server with 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 #17
Source File: GroovyServicesCompletionTests.java    From groovy-language-server with 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 #18
Source File: XMLAssert.java    From lemminx with Eclipse Public License 2.0 5 votes vote down vote up
private static String getHoverLabel(Hover hover) {
	Either<List<Either<String, MarkedString>>, MarkupContent> contents = hover != null ? hover.getContents() : null;
	if (contents == null) {
		return null;
	}
	return contents.getRight().getValue();
}
 
Example #19
Source File: GenerateDelegateMethodsActionTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testGenerateDelegateMethodsDisabled_interface() throws JavaModelException {
	//@formatter:off
	ICompilationUnit unit = fPackageP.createCompilationUnit("A.java", "package p;\r\n" +
			"\r\n" +
			"public interface A {\r\n" +
			"	public final String name = \"test\";\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 interfaces", CodeActionHandlerTest.containsKind(codeActions, JavaCodeActionKind.SOURCE_GENERATE_DELEGATE_METHODS));
}
 
Example #20
Source File: CodeActions.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public List<? extends CodeGenerator> create(Lookup context) {
    JTextComponent component = context.lookup(JTextComponent.class);
    if (component == null) {
        return Collections.emptyList();
    }
    FileObject file = NbEditorUtilities.getFileObject(component.getDocument());
    if (file == null) {
        return Collections.emptyList();
    }
    LSPBindings server = LSPBindings.getBindings(file);
    if (server == null) {
        return Collections.emptyList();
    }
    String uri = Utils.toURI(file);
    try {
        List<Either<Command, CodeAction>> commands =
                server.getTextDocumentService().codeAction(new CodeActionParams(new TextDocumentIdentifier(uri),
                new Range(Utils.createPosition(component.getDocument(), component.getSelectionStart()),
                        Utils.createPosition(component.getDocument(), component.getSelectionEnd())),
                new CodeActionContext(Collections.emptyList()))).get();
        return commands.stream().map(cmd -> new CodeGenerator() {
            @Override
            public String getDisplayName() {
                return cmd.isLeft() ? cmd.getLeft().getTitle() : cmd.getRight().getTitle();
            }

            @Override
            public void invoke() {
                Utils.applyCodeAction(server, cmd);
            }
        }).collect(Collectors.toList());
    } catch (BadLocationException | InterruptedException | ExecutionException ex) {
        Exceptions.printStackTrace(ex);
        return Collections.emptyList();
    }
}
 
Example #21
Source File: CompleteIdOnDirectEndpointsTest.java    From camel-language-server with Apache License 2.0 5 votes vote down vote up
@Test
void testSEDAEndpointCompletion() throws Exception {
	CamelLanguageServer camelLanguageServer = initializeLanguageServer(new FileInputStream("src/test/resources/workspace/direct-endpoint-test.xml"), ".xml");
	Position positionInMiddleOfcomponentPart = new Position(33, 41);
	CompletableFuture<Either<List<CompletionItem>, CompletionList>> completions = getCompletionFor(camelLanguageServer, positionInMiddleOfcomponentPart);
	List<CompletionItem> items = completions.get().getLeft();
	assertThat(items).hasSize(2);
	for (CompletionItem completionItem : items) {
		TextEdit textEdit = completionItem.getTextEdit();
		assertThat(textEdit.getNewText()).isIn("seda:name", "seda:processing");
	}
}
 
Example #22
Source File: XMLAssert.java    From lemminx with Eclipse Public License 2.0 5 votes vote down vote up
public static CodeAction ca(Diagnostic d, TextEdit... te) {
	CodeAction codeAction = new CodeAction();
	codeAction.setTitle("");
	codeAction.setDiagnostics(Arrays.asList(d));

	VersionedTextDocumentIdentifier versionedTextDocumentIdentifier = new VersionedTextDocumentIdentifier(FILE_URI,
			0);

	TextDocumentEdit textDocumentEdit = new TextDocumentEdit(versionedTextDocumentIdentifier, Arrays.asList(te));
	WorkspaceEdit workspaceEdit = new WorkspaceEdit(Collections.singletonList(Either.forLeft(textDocumentEdit)));
	codeAction.setEdit(workspaceEdit);
	return codeAction;
}
 
Example #23
Source File: CamelKModelineTraitPropertyNameTest.java    From camel-language-server with Apache License 2.0 5 votes vote down vote up
@Test
void testProvideCompletionWithDefaultValueAString() throws Exception {
	CamelLanguageServer camelLanguageServer = initializeLanguageServer("// camel-k: trait=container.");
	CompletableFuture<Either<List<CompletionItem>, CompletionList>> completions = getCompletionFor(camelLanguageServer, new Position(0, 28));
	CompletionItem completionItem = findCompletionItemWithLabel(completions, "port-name");
	assertThat(completionItem.getInsertText()).isEqualTo("port-name=http");
}
 
Example #24
Source File: DocumentSymbolHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private static List<? extends DocumentSymbol> internalGetHierarchicalSymbols(IProject project, IProgressMonitor monitor, String className)
		throws JavaModelException, UnsupportedEncodingException, InterruptedException, ExecutionException {
	String uri = ClassFileUtil.getURI(project, className);
	TextDocumentIdentifier identifier = new TextDocumentIdentifier(uri);
	DocumentSymbolParams params = new DocumentSymbolParams();
	params.setTextDocument(identifier);
	//@formatter:off
	List<DocumentSymbol> symbols = new DocumentSymbolHandler(true)
			.documentSymbol(params, monitor).stream()
			.map(Either::getRight).collect(toList());
	//@formatter:on
	assertTrue(symbols.size() > 0);
	return symbols;
}
 
Example #25
Source File: InvalidEnumQuickfixTest.java    From camel-language-server with Apache License 2.0 5 votes vote down vote up
@Test
void testReturnCodeActionForQuickfix() throws FileNotFoundException, InterruptedException, ExecutionException {
	TextDocumentIdentifier textDocumentIdentifier = initAnLaunchDiagnostic();

	Diagnostic diagnostic = lastPublishedDiagnostics.getDiagnostics().get(0);
	CodeActionContext context = new CodeActionContext(lastPublishedDiagnostics.getDiagnostics(), Collections.singletonList(CodeActionKind.QuickFix));
	CompletableFuture<List<Either<Command,CodeAction>>> codeActions = camelLanguageServer.getTextDocumentService().codeAction(new CodeActionParams(textDocumentIdentifier, diagnostic.getRange(), context));
	
	checkRetrievedCodeAction(textDocumentIdentifier, diagnostic, codeActions);
}
 
Example #26
Source File: GenerateConstructorsActionTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testGenerateConstructorsDisabled_interface() throws JavaModelException {
	//@formatter:off
	ICompilationUnit unit = fPackageP.createCompilationUnit("A.java", "package p;\r\n" +
			"\r\n" +
			"public interface A {\r\n" +
			"	public final String name = \"test\";\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 interfaces", CodeActionHandlerTest.containsKind(codeActions, JavaCodeActionKind.SOURCE_GENERATE_CONSTRUCTORS));
}
 
Example #27
Source File: CompleteIdOnDirectEndpointsTest.java    From camel-language-server with Apache License 2.0 5 votes vote down vote up
@Test
void testDirectVMEndpointCompletion() throws Exception {
	CamelLanguageServer camelLanguageServer = initializeLanguageServer(new FileInputStream("src/test/resources/workspace/direct-endpoint-test.xml"), ".xml");
	Position positionInMiddleOfcomponentPart = new Position(17, 45);
	CompletableFuture<Either<List<CompletionItem>, CompletionList>> completions = getCompletionFor(camelLanguageServer, positionInMiddleOfcomponentPart);
	List<CompletionItem> items = completions.get().getLeft();
	assertThat(items).hasSize(2);
	for (CompletionItem completionItem : items) {
		TextEdit textEdit = completionItem.getTextEdit();
		assertThat(textEdit.getNewText()).isIn("direct-vm:name", "direct-vm:processing");
	}
}
 
Example #28
Source File: XLanguageServerImpl.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Prepare the rename operation. Executed in a read request.
 */
protected Either<Range, PrepareRenameResult> prepareRename(OpenFileContext ofc, TextDocumentPositionParams params,
		CancelIndicator cancelIndicator) {
	URI uri = ofc.getURI();
	IRenameService2 renameService = getService(uri, IRenameService2.class);
	if (renameService == null) {
		throw new UnsupportedOperationException();
	}
	IRenameService2.PrepareRenameOptions options = new IRenameService2.PrepareRenameOptions();
	options.setLanguageServerAccess(access);
	options.setParams(params);
	options.setCancelIndicator(cancelIndicator);
	return renameService.prepareRename(options);
}
 
Example #29
Source File: CamelLanguageServerTest.java    From camel-language-server with Apache License 2.0 5 votes vote down vote up
@Test
void testProvideCompletionForJavaOnRealFile() throws Exception {
	File f = new File("src/test/resources/workspace/camel.java");
	assertThat(f).exists();
	try (FileInputStream fis = new FileInputStream(f)) {
		CamelLanguageServer cls = initializeLanguageServer(fis, ".java");
		CompletableFuture<Either<List<CompletionItem>, CompletionList>> completions = getCompletionFor(cls, new Position(15, 14));
		assertThat(completions.get().getLeft()).contains(createExpectedAhcCompletionItem(15, 14, 15, 27));
	}
}
 
Example #30
Source File: ReorgQuickFixTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private WorkspaceEdit getWorkspaceEdit(Either<Command, CodeAction> codeAction) {
	Command c = codeAction.isLeft() ? codeAction.getLeft() : codeAction.getRight().getCommand();
	assertEquals(CodeActionHandler.COMMAND_ID_APPLY_EDIT, c.getCommand());
	assertNotNull(c.getArguments());
	assertTrue(c.getArguments().get(0) instanceof WorkspaceEdit);
	return (WorkspaceEdit) c.getArguments().get(0);
}