org.eclipse.lsp4j.TextDocumentIdentifier Java Examples

The following examples show how to use org.eclipse.lsp4j.TextDocumentIdentifier. 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: 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 #2
Source Project: eclipse.jdt.ls   Author: eclipse   File: ImplementationsHandlerTest.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testUnimplementedMethodImplementation_includeDefinition() {
	URI uri = project.getFile("src/org/sample/FooService.java").getRawLocationURI();
	String fileURI = ResourceUtils.fixURI(uri);

	TextDocumentPositionParams param = new TextDocumentPositionParams();
	param.setPosition(new Position(15, 13)); //Position over someMethod()
	param.setTextDocument(new TextDocumentIdentifier(fileURI));
	List<? extends Location> implementations = handler.findImplementations(param, monitor);
	assertNotNull("findImplementations should not return null", implementations);
	assertEquals(implementations.toString(), 1, implementations.size());
	Location foo = implementations.get(0);
	assertTrue("Unexpected implementation : " + foo.getUri(), foo.getUri().contains("org/sample/AbstractFoo.java"));
	//check range points to someMethod() position
	assertEquals(new Position(4, 15), foo.getRange().getStart());
	assertEquals(new Position(4, 25), foo.getRange().getEnd());
}
 
Example #3
Source Project: groovy-language-server   Author: prominic   File: GroovyServicesTypeDefinitionTests.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void testLocalVariableTypeDefinitionFromAssignment() throws Exception {
	Path filePath = srcRoot.resolve("Definitions.groovy");
	String uri = filePath.toUri().toString();
	StringBuilder contents = new StringBuilder();
	contents.append("class TypeDefinitions {\n");
	contents.append("  public TypeDefinitions() {\n");
	contents.append("    TypeDefinitions localVar\n");
	contents.append("    localVar = null\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, 6);
	List<? extends Location> locations = services
			.typeDefinition(new TextDocumentPositionParams(textDocument, position)).get().getLeft();
	Assertions.assertEquals(1, locations.size());
	Location location = locations.get(0);
	Assertions.assertEquals(uri, location.getUri());
	Assertions.assertEquals(0, location.getRange().getStart().getLine());
	Assertions.assertEquals(0, location.getRange().getStart().getCharacter());
	Assertions.assertEquals(5, location.getRange().getEnd().getLine());
	Assertions.assertEquals(1, location.getRange().getEnd().getCharacter());
}
 
Example #4
Source Project: eclipse.jdt.ls   Author: eclipse   File: CodeActionHandlerTest.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testCodeAction_exception() throws JavaModelException {
	URI uri = project.getFile("nopackage/Test.java").getRawLocationURI();
	ICompilationUnit cu = JDTUtils.resolveCompilationUnit(uri);
	try {
		cu.becomeWorkingCopy(new NullProgressMonitor());
		CodeActionParams params = new CodeActionParams();
		params.setTextDocument(new TextDocumentIdentifier(uri.toString()));
		final Range range = new Range();
		range.setStart(new Position(0, 17));
		range.setEnd(new Position(0, 17));
		params.setRange(range);
		CodeActionContext context = new CodeActionContext();
		context.setDiagnostics(Collections.emptyList());
		params.setContext(context);
		List<Either<Command, CodeAction>> codeActions = getCodeActions(params);
		Assert.assertNotNull(codeActions);
	} finally {
		cu.discardWorkingCopy();
	}
}
 
Example #5
Source Project: groovy-language-server   Author: prominic   File: GroovyServicesTypeDefinitionTests.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void testMemberMethodTypeDefinitionFromDeclaration() throws Exception {
	Path filePath = srcRoot.resolve("Definitions.groovy");
	String uri = filePath.toUri().toString();
	StringBuilder contents = new StringBuilder();
	contents.append("class TypeDefinitions {\n");
	contents.append("  public TypeDefinitions 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(1, 27);
	List<? extends Location> locations = services
			.typeDefinition(new TextDocumentPositionParams(textDocument, position)).get().getLeft();
	Assertions.assertEquals(1, locations.size());
	Location location = locations.get(0);
	Assertions.assertEquals(uri, location.getUri());
	Assertions.assertEquals(0, location.getRange().getStart().getLine());
	Assertions.assertEquals(0, location.getRange().getStart().getCharacter());
	Assertions.assertEquals(3, location.getRange().getEnd().getLine());
	Assertions.assertEquals(1, location.getRange().getEnd().getCharacter());
}
 
Example #6
Source Project: groovy-language-server   Author: prominic   File: GroovyServicesTypeDefinitionTests.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void testMemberMethodTypeDefinitionFromCall() throws Exception {
	Path filePath = srcRoot.resolve("Definitions.groovy");
	String uri = filePath.toUri().toString();
	StringBuilder contents = new StringBuilder();
	contents.append("class TypeDefinitions {\n");
	contents.append("  public TypeDefinitions memberMethod() {\n");
	contents.append("  }\n");
	contents.append("  public TypeDefinitions() {\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(4, 6);
	List<? extends Location> locations = services
			.typeDefinition(new TextDocumentPositionParams(textDocument, position)).get().getLeft();
	Assertions.assertEquals(1, locations.size());
	Location location = locations.get(0);
	Assertions.assertEquals(uri, location.getUri());
	Assertions.assertEquals(0, location.getRange().getStart().getLine());
	Assertions.assertEquals(0, location.getRange().getStart().getCharacter());
	Assertions.assertEquals(6, location.getRange().getEnd().getLine());
	Assertions.assertEquals(1, location.getRange().getEnd().getCharacter());
}
 
Example #7
Source Project: groovy-language-server   Author: prominic   File: GroovyServicesCompletionTests.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void testMemberAccessOnMemberVariableAfterDot() 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 memberVar\n");
	contents.append("  public Completion() {\n");
	contents.append("    memberVar.\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, 14);
	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 #8
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 #9
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 #10
Source Project: groovy-language-server   Author: prominic   File: GroovyServicesCompletionTests.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void testCompletionForParameterOnPartialVariableExpression() 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("    par\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(2, 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("paramName") && item.getKind().equals(CompletionItemKind.Variable);
	}).collect(Collectors.toList());
	Assertions.assertEquals(1, filteredItems.size());
}
 
Example #11
Source Project: groovy-language-server   Author: prominic   File: GroovyServicesCompletionTests.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void testCompletionForParameterOnCompleteVariableExpression() 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("    paramName\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(2, 13);
	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("paramName") && item.getKind().equals(CompletionItemKind.Variable);
	}).collect(Collectors.toList());
	Assertions.assertEquals(1, filteredItems.size());
}
 
Example #12
Source Project: netbeans   Author: apache   File: Formatter.java    License: Apache License 2.0 6 votes vote down vote up
private void rangeFormat(FileObject fo, LSPBindings bindings) throws BadLocationException {
    DocumentRangeFormattingParams drfp = new DocumentRangeFormattingParams();
    drfp.setTextDocument(new TextDocumentIdentifier(Utils.toURI(fo)));
    drfp.setOptions(new FormattingOptions(
        IndentUtils.indentLevelSize(ctx.document()),
        IndentUtils.isExpandTabs(ctx.document())));
    drfp.setRange(new Range(
        Utils.createPosition(ctx.document(), ctx.startOffset()),
        Utils.createPosition(ctx.document(), ctx.endOffset())));
    List<TextEdit> edits = new ArrayList<>();
    try {
        edits = new ArrayList<>(bindings.getTextDocumentService().rangeFormatting(drfp).get());
    } catch (InterruptedException | ExecutionException ex) {
        LOG.log(Level.INFO,
            String.format("LSP document rangeFormat failed for {0}", fo),
            ex);
    }

    applyTextEdits(edits);
}
 
Example #13
Source Project: xtext-core   Author: eclipse   File: AbstractLanguageServerTest.java    License: Eclipse Public License 2.0 6 votes vote down vote up
protected void testFormatting(final Procedure1<? super DocumentFormattingParams> paramsConfigurator, final Procedure1<? super FormattingConfiguration> configurator) {
  try {
    @Extension
    final FormattingConfiguration configuration = new FormattingConfiguration();
    configuration.setFilePath(("MyModel." + this.fileExtension));
    configurator.apply(configuration);
    final FileInfo fileInfo = this.initializeContext(configuration);
    DocumentFormattingParams _documentFormattingParams = new DocumentFormattingParams();
    final Procedure1<DocumentFormattingParams> _function = (DocumentFormattingParams it) -> {
      String _uri = fileInfo.getUri();
      TextDocumentIdentifier _textDocumentIdentifier = new TextDocumentIdentifier(_uri);
      it.setTextDocument(_textDocumentIdentifier);
      if ((paramsConfigurator != null)) {
        paramsConfigurator.apply(it);
      }
    };
    DocumentFormattingParams _doubleArrow = ObjectExtensions.<DocumentFormattingParams>operator_doubleArrow(_documentFormattingParams, _function);
    final CompletableFuture<List<? extends TextEdit>> changes = this.languageServer.formatting(_doubleArrow);
    String _contents = fileInfo.getContents();
    final Document result = new Document(Integer.valueOf(1), _contents).applyChanges(ListExtensions.<TextEdit>reverse(CollectionLiterals.<TextEdit>newArrayList(((TextEdit[])Conversions.unwrapArray(changes.get(), TextEdit.class)))));
    this.assertEqualsStricter(configuration.getExpectedText(), result.getContents());
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}
 
Example #14
Source Project: groovy-language-server   Author: prominic   File: GroovyServicesDefinitionTests.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void testMemberVariableDefinitionFromDeclaration() throws Exception {
	Path filePath = srcRoot.resolve("Definitions.groovy");
	String uri = filePath.toUri().toString();
	StringBuilder contents = new StringBuilder();
	contents.append("class Definitions {\n");
	contents.append("  public int memberVar\n");
	contents.append("}\n");
	TextDocumentItem textDocumentItem = new TextDocumentItem(uri, LANGUAGE_GROOVY, 1, contents.toString());
	services.didOpen(new DidOpenTextDocumentParams(textDocumentItem));
	TextDocumentIdentifier textDocument = new TextDocumentIdentifier(uri);
	Position position = new Position(1, 18);
	List<? extends Location> locations = services.definition(new TextDocumentPositionParams(textDocument, position))
			.get().getLeft();
	Assertions.assertEquals(1, locations.size());
	Location location = locations.get(0);
	Assertions.assertEquals(uri, location.getUri());
	Assertions.assertEquals(1, location.getRange().getStart().getLine());
	Assertions.assertEquals(2, location.getRange().getStart().getCharacter());
	Assertions.assertEquals(1, location.getRange().getEnd().getLine());
	Assertions.assertEquals(22, location.getRange().getEnd().getCharacter());
}
 
Example #15
Source Project: groovy-language-server   Author: prominic   File: GroovyServicesDefinitionTests.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void testMemberMethodDefinitionFromCall() throws Exception {
	Path filePath = srcRoot.resolve("Definitions.groovy");
	String uri = filePath.toUri().toString();
	StringBuilder contents = new StringBuilder();
	contents.append("class Definitions {\n");
	contents.append("  public void memberMethod() {}\n");
	contents.append("  public Definitions() {\n");
	contents.append("    memberMethod()\n");
	contents.append("  }\n");
	contents.append("}\n");
	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, 6);
	List<? extends Location> locations = services.definition(new TextDocumentPositionParams(textDocument, position))
			.get().getLeft();
	Assertions.assertEquals(1, locations.size());
	Location location = locations.get(0);
	Assertions.assertEquals(uri, location.getUri());
	Assertions.assertEquals(1, location.getRange().getStart().getLine());
	Assertions.assertEquals(2, location.getRange().getStart().getCharacter());
	Assertions.assertEquals(1, location.getRange().getEnd().getLine());
	Assertions.assertEquals(31, location.getRange().getEnd().getCharacter());
}
 
Example #16
Source Project: groovy-language-server   Author: prominic   File: GroovyServicesDefinitionTests.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void testClassDefinitionFromVariableDeclaration() throws Exception {
	Path filePath = srcRoot.resolve("Definitions.groovy");
	String uri = filePath.toUri().toString();
	StringBuilder contents = new StringBuilder();
	contents.append("class Definitions {\n");
	contents.append("  public Definitions() {\n");
	contents.append("    Definitions d\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(2, 6);
	List<? extends Location> locations = services.definition(new TextDocumentPositionParams(textDocument, position))
			.get().getLeft();
	Assertions.assertEquals(1, locations.size());
	Location location = locations.get(0);
	Assertions.assertEquals(uri, location.getUri());
	Assertions.assertEquals(0, location.getRange().getStart().getLine());
	Assertions.assertEquals(0, location.getRange().getStart().getCharacter());
	Assertions.assertEquals(4, location.getRange().getEnd().getLine());
	Assertions.assertEquals(1, location.getRange().getEnd().getCharacter());
}
 
Example #17
Source Project: groovy-language-server   Author: prominic   File: GroovyServicesDefinitionTests.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void testClassDefinitionFromClassExpression() throws Exception {
	Path filePath = srcRoot.resolve("Definitions.groovy");
	String uri = filePath.toUri().toString();
	StringBuilder contents = new StringBuilder();
	contents.append("class Definitions {\n");
	contents.append("  public static void staticMethod() {}\n");
	contents.append("  public Definitions() {\n");
	contents.append("    Definitions.staticMethod()\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, 6);
	List<? extends Location> locations = services.definition(new TextDocumentPositionParams(textDocument, position))
			.get().getLeft();
	Assertions.assertEquals(1, locations.size());
	Location location = locations.get(0);
	Assertions.assertEquals(uri, location.getUri());
	Assertions.assertEquals(0, location.getRange().getStart().getLine());
	Assertions.assertEquals(0, location.getRange().getStart().getCharacter());
	Assertions.assertEquals(5, location.getRange().getEnd().getLine());
	Assertions.assertEquals(1, location.getRange().getEnd().getCharacter());
}
 
Example #18
Source Project: eclipse.jdt.ls   Author: eclipse   File: CodeActionHandlerTest.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testCodeAction_sourceActionsOnly() throws Exception {
	//@formatter:off
	ICompilationUnit unit = getWorkingCopy(
			"src/java/Foo.java",
			"import java.sql.*; \n" +
			"public class Foo {\n"+
			"	void foo() {\n"+
			"	}\n"+
			"}\n");
	//@formatter:on
	CodeActionParams params = new CodeActionParams();
	params.setTextDocument(new TextDocumentIdentifier(JDTUtils.toURI(unit)));
	final Range range = CodeActionUtil.getRange(unit, "foo()");
	params.setRange(range);
	params.setContext(new CodeActionContext(Collections.emptyList(), Collections.singletonList(CodeActionKind.Source)));
	List<Either<Command, CodeAction>> sourceActions = getCodeActions(params);

	Assert.assertNotNull(sourceActions);
	Assert.assertFalse("No source actions were found", sourceActions.isEmpty());
	for (Either<Command, CodeAction> codeAction : sourceActions) {
		Assert.assertTrue("Unexpected kind:" + codeAction.getRight().getKind(), codeAction.getRight().getKind().startsWith(CodeActionKind.Source));
	}
}
 
Example #19
Source Project: eclipse.jdt.ls   Author: eclipse   File: FormatterHandlerTest.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testDisableFormattingOnType() throws Exception {
	//@formatter:off
	String text =  "package org.sample;\n"
				+ "\n"
				+ "    public      class     Baz {  \n"
				+ "String          name       ;\n"
				+ "}\n";
			//@formatter:on
	ICompilationUnit unit = getWorkingCopy("src/org/sample/Baz.java", text);

	String uri = JDTUtils.toURI(unit);
	TextDocumentIdentifier textDocument = new TextDocumentIdentifier(uri);
	FormattingOptions options = new FormattingOptions(4, true);// ident == 4 spaces

	DocumentOnTypeFormattingParams params = new DocumentOnTypeFormattingParams(new Position(3, 28), "\n");
	params.setTextDocument(textDocument);
	params.setOptions(options);
	//Check it's disabled by default
	List<? extends TextEdit> edits = server.onTypeFormatting(params).get();
	assertNotNull(edits);

	String newText = TextEditUtil.apply(unit, edits);
	assertEquals(text, newText);
}
 
Example #20
Source Project: groovy-language-server   Author: prominic   File: GroovyServicesDefinitionTests.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void testParameterDefinitionFromDeclarationInMethod() throws Exception {
	Path filePath = srcRoot.resolve("Definitions.groovy");
	String uri = filePath.toUri().toString();
	StringBuilder contents = new StringBuilder();
	contents.append("class Definitions {\n");
	contents.append("  public void memberMethod(int param) {\n");
	contents.append("  }\n");
	contents.append("}\n");
	TextDocumentItem textDocumentItem = new TextDocumentItem(uri, LANGUAGE_GROOVY, 1, contents.toString());
	services.didOpen(new DidOpenTextDocumentParams(textDocumentItem));
	TextDocumentIdentifier textDocument = new TextDocumentIdentifier(uri);
	Position position = new Position(1, 33);
	List<? extends Location> locations = services.definition(new TextDocumentPositionParams(textDocument, position))
			.get().getLeft();
	Assertions.assertEquals(1, locations.size());
	Location location = locations.get(0);
	Assertions.assertEquals(uri, location.getUri());
	Assertions.assertEquals(1, location.getRange().getStart().getLine());
	Assertions.assertEquals(27, location.getRange().getStart().getCharacter());
	Assertions.assertEquals(1, location.getRange().getEnd().getLine());
	Assertions.assertEquals(36, location.getRange().getEnd().getCharacter());
}
 
Example #21
Source Project: eclipse.jdt.ls   Author: eclipse   File: ImplementationsHandlerTest.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testMethodSuperInvocationImplementation() {
	URI uri = project.getFile("src/org/sample/FooChild.java").getRawLocationURI();
	String fileURI = ResourceUtils.fixURI(uri);

	TextDocumentPositionParams param = new TextDocumentPositionParams();
	param.setPosition(new Position(5, 14)); //Position over super.someMethod
	param.setTextDocument(new TextDocumentIdentifier(fileURI));
	List<? extends Location> implementations = handler.findImplementations(param, monitor);
	assertNotNull("findImplementations should not return null", implementations);
	assertEquals(implementations.toString(), 1, implementations.size());
	Location foo = implementations.get(0);
	assertTrue("Unexpected implementation : " + foo.getUri(), foo.getUri().contains("org/sample/Foo.java"));
	//check range points to someMethod() position
	assertEquals(new Position(8, 13), foo.getRange().getStart());
	assertEquals(new Position(8, 23), foo.getRange().getEnd());
}
 
Example #22
Source Project: rdflint   Author: imas   File: RdfLintLanguageServerTest.java    License: MIT License 6 votes vote down vote up
@Test
public void diagnosticsClose() throws Exception {
  RdfLintLanguageServer lsp = new RdfLintLanguageServer();
  InitializeParams initParams = new InitializeParams();
  String rootPath = this.getClass().getClassLoader().getResource("testValidatorsImpl/").getPath();
  String parentPath = rootPath + "TrimValidator/turtle_needtrim";
  initParams.setRootUri(RdfLintLanguageServer.convertFilePath2Uri(parentPath));
  lsp.initialize(initParams);

  LanguageClient client = mock(LanguageClient.class);
  lsp.connect(client);

  DidCloseTextDocumentParams closeParams = new DidCloseTextDocumentParams();
  closeParams.setTextDocument(new TextDocumentIdentifier());
  closeParams.getTextDocument()
      .setUri(RdfLintLanguageServer.convertFilePath2Uri(parentPath + "/needtrim.rdf"));

  lsp.didClose(closeParams);
  verify(client, times(2)).publishDiagnostics(any());
}
 
Example #23
Source Project: camel-language-server   Author: camel-tooling   File: UnknownPropertyQuickfixTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void testReturnCodeActionForQuickfixEvenWithInvalidRangeDiagnostic() throws FileNotFoundException, InterruptedException, ExecutionException {
	TextDocumentIdentifier textDocumentIdentifier = initAnLaunchDiagnostic();
	
	Diagnostic diagnostic = lastPublishedDiagnostics.getDiagnostics().get(0);

	List<Diagnostic> diagnostics = new ArrayList<Diagnostic>();
	Diagnostic diagnosticWithInvalidRange = new Diagnostic(new Range(new Position(9,100), new Position(9,101)), "a different diagnostic coming with an invalid range.");
	diagnosticWithInvalidRange.setCode(DiagnosticService.ERROR_CODE_UNKNOWN_PROPERTIES);
	diagnostics.add(diagnosticWithInvalidRange);
	diagnostics.addAll(lastPublishedDiagnostics.getDiagnostics());
	
	CodeActionContext context = new CodeActionContext(diagnostics, Collections.singletonList(CodeActionKind.QuickFix));
	CompletableFuture<List<Either<Command,CodeAction>>> codeActions = camelLanguageServer.getTextDocumentService().codeAction(new CodeActionParams(textDocumentIdentifier, diagnostic.getRange(), context));
	
	checkRetrievedCodeAction(textDocumentIdentifier, diagnostic, codeActions);
}
 
Example #24
Source Project: eclipse.jdt.ls   Author: eclipse   File: ImplementationsHandlerTest.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testMethodImplementation_includeDefinition() {
	URI uri = project.getFile("src/org/sample/FooService.java").getRawLocationURI();
	String fileURI = ResourceUtils.fixURI(uri);

	TextDocumentPositionParams param = new TextDocumentPositionParams();
	param.setPosition(new Position(11, 13)); //Position over someMethod()
	param.setTextDocument(new TextDocumentIdentifier(fileURI));
	List<? extends Location> implementations = handler.findImplementations(param, monitor);
	assertNotNull("findImplementations should not return null", implementations);
	assertEquals(implementations.toString(), 2, implementations.size());
	Location foo = implementations.get(0);
	assertTrue("Unexpected implementation : " + foo.getUri(), foo.getUri().contains("org/sample/Foo.java"));
	//check range points to someMethod() position
	assertEquals(new Position(8, 13), foo.getRange().getStart());
	assertEquals(new Position(8, 23), foo.getRange().getEnd());
	foo = implementations.get(1);
	assertTrue("Unexpected implementation : " + foo.getUri(), foo.getUri().contains("org/sample/FooChild.java"));
	//check range points to someMethod() position
	assertEquals(new Position(4, 13), foo.getRange().getStart());
	assertEquals(new Position(4, 23), foo.getRange().getEnd());
}
 
Example #25
Source Project: eclipse.jdt.ls   Author: eclipse   File: CodeActionHandlerTest.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void test_noUnnecessaryCodeActions() throws Exception{
	//@formatter:off
	ICompilationUnit unit = getWorkingCopy(
			"src/org/sample/Foo.java",
			"package org.sample;\n"+
			"\n"+
			"public class Foo {\n"+
			"	private String foo;\n"+
			"	public String getFoo() {\n"+
			"	  return foo;\n"+
			"	}\n"+
			"   \n"+
			"	public void setFoo(String newFoo) {\n"+
			"	  foo = newFoo;\n"+
			"	}\n"+
			"}\n");
	//@formatter:on
	CodeActionParams params = new CodeActionParams();
	params.setTextDocument(new TextDocumentIdentifier(JDTUtils.toURI(unit)));
	final Range range = CodeActionUtil.getRange(unit, "String foo;");
	params.setRange(range);
	params.setContext(new CodeActionContext(Collections.emptyList()));
	List<Either<Command, CodeAction>> codeActions = getCodeActions(params);
	Assert.assertNotNull(codeActions);
	Assert.assertFalse("No need for organize imports action", containsKind(codeActions, CodeActionKind.SourceOrganizeImports));
	Assert.assertFalse("No need for generate getter and setter action", containsKind(codeActions, JavaCodeActionKind.SOURCE_GENERATE_ACCESSORS));
}
 
Example #26
Source Project: groovy-language-server   Author: prominic   File: DefinitionProvider.java    License: Apache License 2.0 5 votes vote down vote up
public CompletableFuture<Either<List<? extends Location>, List<? extends LocationLink>>> provideDefinition(
		TextDocumentIdentifier textDocument, Position position) {
	if (ast == null) {
		//this shouldn't happen, but let's avoid an exception if something
		//goes terribly wrong.
		return CompletableFuture.completedFuture(Either.forLeft(Collections.emptyList()));
	}
	URI uri = URI.create(textDocument.getUri());
	ASTNode offsetNode = ast.getNodeAtLineAndColumn(uri, position.getLine(), position.getCharacter());
	if (offsetNode == null) {
		return CompletableFuture.completedFuture(Either.forLeft(Collections.emptyList()));
	}

	ASTNode definitionNode = GroovyASTUtils.getDefinition(offsetNode, true, ast);
	if (definitionNode == null || definitionNode.getLineNumber() == -1 || definitionNode.getColumnNumber() == -1) {
		return CompletableFuture.completedFuture(Either.forLeft(Collections.emptyList()));
	}

	URI definitionURI = ast.getURI(definitionNode);
	if (definitionURI == null) {
		definitionURI = uri;
	}

	Location location = new Location(definitionURI.toString(),
			GroovyLanguageServerUtils.astNodeToRange(definitionNode));
	return CompletableFuture.completedFuture(Either.forLeft(Collections.singletonList(location)));
}
 
Example #27
Source Project: groovy-language-server   Author: prominic   File: TypeDefinitionProvider.java    License: Apache License 2.0 5 votes vote down vote up
public CompletableFuture<Either<List<? extends Location>, List<? extends LocationLink>>> provideTypeDefinition(
		TextDocumentIdentifier textDocument, Position position) {
	if (ast == null) {
		//this shouldn't happen, but let's avoid an exception if something
		//goes terribly wrong.
		return CompletableFuture.completedFuture(Either.forLeft(Collections.emptyList()));
	}
	URI uri = URI.create(textDocument.getUri());
	ASTNode offsetNode = ast.getNodeAtLineAndColumn(uri, position.getLine(), position.getCharacter());
	if (offsetNode == null) {
		return CompletableFuture.completedFuture(Either.forLeft(Collections.emptyList()));
	}

	ASTNode definitionNode = GroovyASTUtils.getTypeDefinition(offsetNode, ast);
	if (definitionNode == null || definitionNode.getLineNumber() == -1 || definitionNode.getColumnNumber() == -1) {
		return CompletableFuture.completedFuture(Either.forLeft(Collections.emptyList()));
	}

	URI definitionURI = ast.getURI(definitionNode);
	if (definitionURI == null) {
		definitionURI = uri;
	}

	Location location = new Location(definitionURI.toString(),
			GroovyLanguageServerUtils.astNodeToRange(definitionNode));
	return CompletableFuture.completedFuture(Either.forLeft(Collections.singletonList(location)));
}
 
Example #28
Source Project: xtext-core   Author: eclipse   File: RenameTest3.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testRenameAutoQuote() {
  try {
    StringConcatenation _builder = new StringConcatenation();
    _builder.append("type Foo {");
    _builder.newLine();
    _builder.append("}");
    _builder.newLine();
    final String model = _builder.toString();
    final String file = this.writeFile("foo/Foo.renametl", model);
    this.initialize();
    final TextDocumentIdentifier identifier = new TextDocumentIdentifier(file);
    final Position position = new Position(0, 6);
    PrepareRenameParams _prepareRenameParams = new PrepareRenameParams(identifier, position);
    final Range range = this.languageServer.prepareRename(_prepareRenameParams).get().getLeft();
    this.assertEquals("Foo", new Document(Integer.valueOf(0), model).getSubstring(range));
    final RenameParams params = new RenameParams(identifier, position, "type");
    final WorkspaceEdit workspaceEdit = this.languageServer.rename(params).get();
    StringConcatenation _builder_1 = new StringConcatenation();
    _builder_1.append("changes :");
    _builder_1.newLine();
    _builder_1.append("documentChanges : ");
    _builder_1.newLine();
    _builder_1.append("    ");
    _builder_1.append("Foo.renametl <1> : ^type [[0, 5] .. [0, 8]]");
    _builder_1.newLine();
    this.assertEquals(_builder_1.toString(), this.toExpectation(workspaceEdit));
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}
 
Example #29
Source Project: netbeans   Author: apache   File: MarkOccurrences.java    License: Apache License 2.0 5 votes vote down vote up
private OffsetsBag computeHighlights(Document doc, int caretPos) {
    AttributeSet attr = getColoring(doc);
    OffsetsBag result = new OffsetsBag(doc);
    FileObject file = NbEditorUtilities.getFileObject(doc);
    if (file == null) {
        return result;
    }
    LSPBindings server = LSPBindings.getBindings(file);
    if (server == null) {
        return result;
    }
    Boolean hasDocumentHighlight = server.getInitResult().getCapabilities().getDocumentHighlightProvider();
    if (hasDocumentHighlight == null || !hasDocumentHighlight) {
        return result;
    }
    String uri = Utils.toURI(file);
    try {
        List<? extends DocumentHighlight> highlights =
                server.getTextDocumentService().documentHighlight(new TextDocumentPositionParams(new TextDocumentIdentifier(uri), Utils.createPosition(doc, caretPos))).get();
        for (DocumentHighlight h : highlights) {
            result.addHighlight(Utils.getOffset(doc, h.getRange().getStart()), Utils.getOffset(doc, h.getRange().getEnd()), attr);
        }
        return result;
    } catch (BadLocationException | InterruptedException | ExecutionException ex) {
        Exceptions.printStackTrace(ex);
        return result;
    }
}
 
Example #30
Source Project: corrosion   Author: eclipse   File: ImplementationsSearchQuery.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@Override public IStatus run(IProgressMonitor monitor) {
	startTime = System.currentTimeMillis();
	// Cancel last references future if needed.
	if (references != null) {
		references.cancel(true);
	}
	AbstractTextSearchResult textResult = (AbstractTextSearchResult) getSearchResult();
	textResult.removeAll();

	try {
		// Execute LSP "references" service
		ReferenceParams params = new ReferenceParams();
		params.setContext(new ReferenceContext(true));
		params.setTextDocument(new TextDocumentIdentifier(info.getFileUri().toString()));
		params.setPosition(position);
		info.getInitializedLanguageClient().thenCompose(languageServer -> ((RLSServerInterface) languageServer).implementations(params)).thenAccept(locs -> {
			// Loop for each LSP Location and convert it to Match search.
			for (Location loc : locs) {
				Match match = toMatch(loc);
				result.addMatch(match);
			}
		});
		return Status.OK_STATUS;
	} catch (Exception ex) {
		return new Status(IStatus.ERROR, LanguageServerPlugin.getDefault().getBundle().getSymbolicName(), ex.getMessage(), ex);
	}
}