下面列出了怎么用org.eclipse.lsp4j.CodeLens的API类实例代码及写法,或者点击链接到github查看源代码。
public static void testCodeLensFor(String value, String fileURI, CodeLens... expected) throws BadLocationException {
TextDocument document = new TextDocument(value, fileURI != null ? fileURI : "test://test/test.xml");
XMLLanguageService xmlLanguageService = new XMLLanguageService();
ContentModelSettings settings = new ContentModelSettings();
settings.setUseCache(false);
xmlLanguageService.doSave(new SettingsSaveContext(settings));
DOMDocument xmlDocument = DOMParser.getInstance().parse(document,
xmlLanguageService.getResolverExtensionManager());
xmlLanguageService.setDocumentProvider((uri) -> xmlDocument);
XMLCodeLensSettings codeLensSettings = new XMLCodeLensSettings();
ExtendedCodeLensCapabilities codeLensCapabilities = new ExtendedCodeLensCapabilities(
new CodeLensKindCapabilities(Arrays.asList(CodeLensKind.References)));
codeLensSettings.setCodeLens(codeLensCapabilities);
List<? extends CodeLens> actual = xmlLanguageService.getCodeLens(xmlDocument, codeLensSettings, () -> {
});
assertCodeLens(actual, expected);
}
/**
* Remove the document uri from the data of the given code lense.
*/
protected URI uninstallURI(CodeLens lens) {
URI result = null;
Object data = lens.getData();
if (data instanceof String) {
result = URI.createURI(data.toString());
lens.setData(null);
} else {
if (data instanceof List<?>) {
List<?> l = ((List<?>) data);
result = URI.createURI(l.get(0).toString());
lens.setData(l.get(1));
}
}
return result;
}
@Test
@SuppressWarnings("unchecked")
public void testGetCodeLensSymbolsForClass() throws Exception {
Preferences implementationsCodeLenses = Preferences.createFrom(Collections.singletonMap(Preferences.IMPLEMENTATIONS_CODE_LENS_ENABLED_KEY, "true"));
Mockito.reset(preferenceManager);
when(preferenceManager.getPreferences()).thenReturn(implementationsCodeLenses);
handler = new CodeLensHandler(preferenceManager);
String uriString = ClassFileUtil.getURI(project, "java.lang.Runnable");
String payload = createCodeLensSymbolRequest(new URI(uriString));
CodeLensParams codeLensParams = getParams(payload);
String uri = codeLensParams.getTextDocument().getUri();
assertFalse(uri.isEmpty());
List<CodeLens> lenses = handler.getCodeLensSymbols(uri, monitor);
assertEquals("Found " + lenses, 2, lenses.size());
List<Object> data = (List<Object>) lenses.get(0).getData();
assertTrue("Unexpected type " + data, data.contains(CodeLensHandler.REFERENCES_TYPE));
data = (List<Object>) lenses.get(1).getData();
assertTrue("Unexpected type " + data, data.contains(CodeLensHandler.IMPLEMENTATION_TYPE));
}
@Test
public void testDisableCodeLensSymbols() throws Exception {
Preferences noCodeLenses = Preferences.createFrom(Collections.singletonMap(Preferences.REFERENCES_CODE_LENS_ENABLED_KEY, "false"));
Mockito.reset(preferenceManager);
when(preferenceManager.getPreferences()).thenReturn(noCodeLenses);
handler = new CodeLensHandler(preferenceManager);
String payload = createCodeLensSymbolsRequest("src/java/IFoo.java");
CodeLensParams codeLensParams = getParams(payload);
String uri = codeLensParams.getTextDocument().getUri();
assertFalse(uri.isEmpty());
//when
List<CodeLens> result = handler.getCodeLensSymbols(uri, monitor);
//then
assertEquals(0, result.size());
}
@Test
public void testEnableImplementationsCodeLensSymbols() throws Exception {
Preferences implementationsCodeLenses = Preferences.createFrom(Collections.singletonMap(Preferences.IMPLEMENTATIONS_CODE_LENS_ENABLED_KEY, "true"));
Mockito.reset(preferenceManager);
when(preferenceManager.getPreferences()).thenReturn(implementationsCodeLenses);
handler = new CodeLensHandler(preferenceManager);
String payload = createCodeLensSymbolsRequest("src/java/IFoo.java");
CodeLensParams codeLensParams = getParams(payload);
String uri = codeLensParams.getTextDocument().getUri();
assertFalse(uri.isEmpty());
//when
List<CodeLens> result = handler.getCodeLensSymbols(uri, monitor);
//then
assertEquals(2, result.size());
CodeLens lens = result.get(1);
@SuppressWarnings("unchecked")
List<Object> data = (List<Object>) lens.getData();
String type = (String) data.get(2);
assertEquals(type, "implementations");
}
@Test
public void testDisableImplementationsCodeLensSymbols() throws Exception {
Preferences noImplementationsCodeLenses = Preferences.createFrom(Collections.singletonMap(Preferences.IMPLEMENTATIONS_CODE_LENS_ENABLED_KEY, "false"));
Mockito.reset(preferenceManager);
when(preferenceManager.getPreferences()).thenReturn(noImplementationsCodeLenses);
Preferences noReferencesCodeLenses = Preferences.createFrom(Collections.singletonMap(Preferences.REFERENCES_CODE_LENS_ENABLED_KEY, "false"));
Mockito.reset(preferenceManager);
when(preferenceManager.getPreferences()).thenReturn(noReferencesCodeLenses);
handler = new CodeLensHandler(preferenceManager);
String payload = createCodeLensSymbolsRequest("src/java/IFoo.java");
CodeLensParams codeLensParams = getParams(payload);
String uri = codeLensParams.getTextDocument().getUri();
assertFalse(uri.isEmpty());
//when
List<CodeLens> result = handler.getCodeLensSymbols(uri, monitor);
//then
assertEquals(0, result.size());
}
@Test
public void testCodeLens() {
final Procedure1<AbstractLanguageServerTest.TestCodeLensConfiguration> _function = (AbstractLanguageServerTest.TestCodeLensConfiguration it) -> {
StringConcatenation _builder = new StringConcatenation();
_builder.append("type Foo {}");
_builder.newLine();
_builder.append("type Bar {");
_builder.newLine();
_builder.append("\t");
_builder.append("Foo foo");
_builder.newLine();
_builder.append("}");
_builder.newLine();
it.setModel(_builder.toString());
final Procedure1<List<? extends CodeLens>> _function_1 = (List<? extends CodeLens> it_1) -> {
this.assertEquals("Do Awesome Stuff(RESOLVED)", IterableExtensions.head(it_1).getCommand().getTitle());
Object _data = IterableExtensions.head(it_1).getData();
Assert.assertEquals(1, ((Position) _data).getLine());
};
it.setAssertCodeLenses(_function_1);
};
this.testCodeLens(_function);
}
/**
* Remove the document uri from the data of the given code lense.
*/
protected URI uninstallURI(CodeLens lens) {
URI result = null;
Object data = lens.getData();
if (data instanceof String) {
result = URI.createURI(data.toString());
lens.setData(null);
} else {
if (data instanceof List<?>) {
List<?> l = (List<?>) data;
result = URI.createURI(l.get(0).toString());
lens.setData(l.get(1));
}
}
return result;
}
@Override
public CompletableFuture<List<? extends CodeLens>> codeLens(CodeLensParams params) {
if (!sharedSettings.getCodeLensSettings().isEnabled()) {
return CompletableFuture.completedFuture(Collections.emptyList());
}
return computeDOMAsync(params.getTextDocument(), (cancelChecker, xmlDocument) -> {
return getXMLLanguageService().getCodeLens(xmlDocument, sharedSettings.getCodeLensSettings(),
cancelChecker);
});
}
public List<? extends CodeLens> getCodelens(DOMDocument xmlDocument, XMLCodeLensSettings settings, CancelChecker cancelChecker) {
ICodeLensRequest request = new CodeLensRequest(xmlDocument, settings);
List<CodeLens> lenses = new ArrayList<>();
for (ICodeLensParticipant participant : extensionsRegistry.getCodeLensParticipants()) {
participant.doCodeLens(request, lenses, cancelChecker);
}
return lenses;
}
public static void assertCodeLens(List<? extends CodeLens> actual, CodeLens... expected) {
assertEquals(expected.length, actual.size());
for (int i = 0; i < expected.length; i++) {
assertEquals(expected[i].getRange(), actual.get(i).getRange());
Command expectedCommand = expected[i].getCommand();
Command actualCommand = actual.get(i).getCommand();
if (expectedCommand != null && actualCommand != null) {
assertEquals(expectedCommand.getTitle(), actualCommand.getTitle());
assertEquals(expectedCommand.getCommand(), actualCommand.getCommand());
}
assertEquals(expected[i].getData(), actual.get(i).getData());
}
}
/**
* Put the document uri into the data of the given code lenses.
*/
protected void installURI(List<? extends CodeLens> codeLenses, String uri) {
for (CodeLens lens : codeLenses) {
Object data = lens.getData();
if (data != null) {
lens.setData(Arrays.asList(uri, lens.getData()));
} else {
lens.setData(uri);
}
}
}
@Override
public CompletableFuture<List<? extends CodeLens>> codeLens(CodeLensParams params) {
URI uri = getURI(params.getTextDocument());
return openFilesManager.runInOpenFileContext(uri, "codeLens", (ofc, ci) -> {
return codeLens(ofc, params, ci);
});
}
/**
* Compute the code lenses.
*/
protected List<? extends CodeLens> codeLens(OpenFileContext ofc, CodeLensParams params,
CancelIndicator cancelIndicator) {
URI uri = ofc.getURI();
ICodeLensService codeLensService = getService(uri, ICodeLensService.class);
if ((codeLensService == null)) {
return Collections.emptyList();
}
XtextResource res = ofc.getResource();
XDocument doc = ofc.getDocument();
List<? extends CodeLens> result = codeLensService.computeCodeLenses(doc, res, params, cancelIndicator);
installURI(result, uri.toString());
return result;
}
@Override
public CompletableFuture<CodeLens> resolveCodeLens(CodeLens unresolved) {
URI uri = uninstallURI(unresolved);
if ((uri == null)) {
return CompletableFuture.completedFuture(unresolved);
}
return openFilesManager.runInOpenOrTemporaryFileContext(uri, "resolveCodeLens", (ofc, ci) -> {
return resolveCodeLens(ofc, unresolved, ci);
});
}
/**
* Resolve the given code lens.
*/
protected CodeLens resolveCodeLens(OpenFileContext ofc, CodeLens unresolved, CancelIndicator cancelIndicator) {
URI uri = ofc.getURI();
ICodeLensResolver resolver = getService(uri, ICodeLensResolver.class);
if (resolver == null) {
return unresolved;
}
XtextResource res = ofc.getResource();
XDocument doc = ofc.getDocument();
return resolver.resolveCodeLens(doc, res, unresolved, cancelIndicator);
}
public List<CodeLens> getCodeLensSymbols(String uri, IProgressMonitor monitor) {
if (!preferenceManager.getPreferences().isCodeLensEnabled()) {
return Collections.emptyList();
}
final ICompilationUnit unit = JDTUtils.resolveCompilationUnit(uri);
IClassFile classFile = null;
if (unit == null) {
classFile = JDTUtils.resolveClassFile(uri);
if (classFile == null) {
return Collections.emptyList();
}
} else {
if (!unit.getResource().exists() || monitor.isCanceled()) {
return Collections.emptyList();
}
}
try {
ITypeRoot typeRoot = unit != null ? unit : classFile;
IJavaElement[] elements = typeRoot.getChildren();
LinkedHashSet<CodeLens> lenses = new LinkedHashSet<>(elements.length);
collectCodeLenses(typeRoot, elements, lenses, monitor);
if (monitor.isCanceled()) {
lenses.clear();
}
return new ArrayList<>(lenses);
} catch (JavaModelException e) {
JavaLanguageServerPlugin.logException("Problem getting code lenses for" + unit.getElementName(), e);
}
return Collections.emptyList();
}
private CodeLens getCodeLens(String type, IJavaElement element, ITypeRoot typeRoot) throws JavaModelException {
ISourceRange r = ((ISourceReference) element).getNameRange();
if (r == null) {
return null;
}
CodeLens lens = new CodeLens();
final Range range = JDTUtils.toRange(typeRoot, r.getOffset(), r.getLength());
lens.setRange(range);
String uri = ResourceUtils.toClientUri(JDTUtils.toUri(typeRoot));
lens.setData(Arrays.asList(uri, range.getStart(), type));
return lens;
}
@Override
public CompletableFuture<List<? extends CodeLens>> codeLens(CodeLensParams params) {
logInfo(">> document/codeLens");
CodeLensHandler handler = new CodeLensHandler(preferenceManager);
return computeAsync((monitor) -> {
waitForLifecycleJobs(monitor);
return handler.getCodeLensSymbols(params.getTextDocument().getUri(), monitor);
});
}
@Override
public CompletableFuture<CodeLens> resolveCodeLens(CodeLens unresolved) {
logInfo(">> codeLens/resolve");
CodeLensHandler handler = new CodeLensHandler(preferenceManager);
return computeAsync((monitor) -> {
waitForLifecycleJobs(monitor);
return handler.resolve(unresolved, monitor);
});
}
@Test
public void testGetCodeLensSymbols() throws Exception {
String payload = createCodeLensSymbolsRequest("src/java/Foo.java");
CodeLensParams codeLensParams = getParams(payload);
String uri = codeLensParams.getTextDocument().getUri();
assertFalse(uri.isEmpty());
//when
List<CodeLens> result = handler.getCodeLensSymbols(uri, monitor);
//then
assertEquals("Found " + result, 3, result.size());
CodeLens cl = result.get(0);
Range r = cl.getRange();
//CodeLens on main method
assertRange(7, 20, 24, r);
cl = result.get(1);
r = cl.getRange();
// CodeLens on foo method
assertRange(14, 13, 16, r);
cl = result.get(2);
r = cl.getRange();
//CodeLens on Foo type
assertRange(5, 13, 16, r);
}
@Test
public void testGetCodeLenseBoundaries() {
List<CodeLens> result = handler.getCodeLensSymbols(null, monitor);
assertNotNull(result);
assertEquals(0, result.size());
String payload = createCodeLensSymbolsRequest("src/java/Missing.java");
CodeLensParams codeLensParams = getParams(payload);
String uri = codeLensParams.getTextDocument().getUri();
result = handler.getCodeLensSymbols(uri, monitor);
assertEquals(0, result.size());
}
@SuppressWarnings("unchecked")
@Test
public void testResolveImplementationsCodeLens() {
String source = "src/java/IFoo.java";
String payload = createCodeLensImplementationsRequest(source, 5, 17, 21);
CodeLens lens = getParams(payload);
Range range = lens.getRange();
assertRange(5, 17, 21, range);
CodeLens result = handler.resolve(lens, monitor);
assertNotNull(result);
//Check if command found
Command command = result.getCommand();
assertNotNull(command);
assertEquals("2 implementations", command.getTitle());
assertEquals("java.show.implementations", command.getCommand());
//Check codelens args
List<Object> args = command.getArguments();
assertEquals(3, args.size());
//Check we point to the Bar class
String sourceUri = args.get(0).toString();
assertTrue(sourceUri.endsWith("IFoo.java"));
//CodeLens position
Position p = (Position) args.get(1);
assertEquals(5, p.getLine());
assertEquals(17, p.getCharacter());
//Reference location
List<Location> locations = (List<Location>) args.get(2);
assertEquals(2, locations.size());
Location loc = locations.get(0);
assertTrue(loc.getUri().endsWith("src/java/Foo2.java"));
assertRange(5, 13, 17, loc.getRange());
}
@SuppressWarnings("unchecked")
@Test
public void testResolveCodeLense() {
String source = "src/java/Foo.java";
String payload = createCodeLensRequest(source, 5, 13, 16);
CodeLens lens = getParams(payload);
Range range = lens.getRange();
assertRange(5, 13, 16, range);
CodeLens result = handler.resolve(lens, monitor);
assertNotNull(result);
//Check if command found
Command command = result.getCommand();
assertNotNull(command);
assertEquals("1 reference", command.getTitle());
assertEquals("java.show.references", command.getCommand());
//Check codelens args
List<Object> args = command.getArguments();
assertEquals(3, args.size());
//Check we point to the Bar class
String sourceUri = args.get(0).toString();
assertTrue(sourceUri.endsWith(source));
//CodeLens position
Position p = (Position) args.get(1);
assertEquals(5, p.getLine());
assertEquals(13, p.getCharacter());
//Reference location
List<Location> locations = (List<Location>) args.get(2);
assertEquals(1, locations.size());
Location loc = locations.get(0);
assertTrue(loc.getUri().endsWith("src/java/Bar.java"));
assertRange(5, 25, 28, loc.getRange());
}
@Test
public void testResolveCodeLenseBoundaries() {
CodeLens result = handler.resolve(null, monitor);
assertNull(result);
String payload = createCodeLensRequest("src/java/Missing.java", 5, 13, 16);
CodeLens lens = getParams(payload);
result = handler.resolve(lens, monitor);
assertSame(lens, result);
assertNotNull(result.getCommand());
}
@Test
public void testIgnoreLombokCodeLensSymbols() throws Exception {
String payload = createCodeLensSymbolsRequest("src/java/Bar.java");
CodeLensParams codeLensParams = getParams(payload);
String uri = codeLensParams.getTextDocument().getUri();
assertFalse(uri.isEmpty());
//when
List<CodeLens> result = handler.getCodeLensSymbols(uri, monitor);
//then
assertEquals("Found " + result, 4, result.size());
//CodeLens on constructor
CodeLens cl = result.get(0);
assertRange(7, 11, 14, cl.getRange());
//CodeLens on somethingFromJPAModelGen
cl = result.get(1);
assertRange(16, 16, 40, cl.getRange());
// CodeLens on foo
cl = result.get(2);
assertRange(22, 16, 19, cl.getRange());
//CodeLens on Bar type
cl = result.get(3);
assertRange(5, 13, 16, cl.getRange());
}
@Override
public List<? extends CodeLens> computeCodeLenses(Document document, XtextResource resource, CodeLensParams params,
CancelIndicator indicator) {
CodeLens codeLens = new CodeLens();
Command command = new Command();
command.setCommand("do.this");
command.setTitle("Do Awesome Stuff");
command.setArguments(Lists.newArrayList("foo", Integer.valueOf(1), Boolean.valueOf(true)));
codeLens.setCommand(command);
Position _position = new Position(1, 2);
codeLens.setData(_position);
return Lists.newArrayList(codeLens);
}
/**
* Put the document uri into the data of the given code lenses.
*/
protected void installURI(List<? extends CodeLens> codeLenses, String uri) {
for (CodeLens lens : codeLenses) {
Object data = lens.getData();
if (data != null) {
lens.setData(Arrays.asList(uri, lens.getData()));
} else {
lens.setData(uri);
}
}
}
/**
* Compute the code lenses. Executed in a read request.
* @since 2.20
*/
protected List<? extends CodeLens> codeLens(CodeLensParams params, CancelIndicator cancelIndicator) {
URI uri = getURI(params.getTextDocument());
ICodeLensService codeLensService = getService(uri, ICodeLensService.class);
if (codeLensService == null) {
return Collections.emptyList();
}
return workspaceManager.doRead(uri, (document, resource) -> {
List<? extends CodeLens> result = codeLensService.computeCodeLenses(document, resource, params,
cancelIndicator);
installURI(result, uri.toString());
return result;
});
}
@Override
public CompletableFuture<CodeLens> resolveCodeLens(CodeLens unresolved) {
URI uri = uninstallURI(unresolved);
if (uri == null) {
return CompletableFuture.completedFuture(unresolved);
}
return requestManager.runRead((cancelIndicator) -> resolveCodeLens(uri, unresolved, cancelIndicator));
}