@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<? extends Command> commands = server.codeAction(params).join(); Assert.assertNotNull(commands); Assert.assertEquals(0, commands.size()); } finally { cu.discardWorkingCopy(); } }
private static CodeLens addTestMethod(final MixinDefinition def, final String documentUri, final SInvokable i) { CodeLens lens = new CodeLens(); Command cmd = new Command(); cmd.setCommand(COMMAND); cmd.setTitle("Run test"); Range r = SomAdapter.toRange(i.getSourceSection()); cmd.setArguments(Lists.newArrayList(documentUri, def.getName().getString() + "." + i.getSignature().getString(), r.getStart().getLine(), r.getStart().getCharacter(), r.getEnd().getLine(), r.getEnd().getCharacter())); lens.setCommand(cmd); lens.setRange(r); return lens; }
@Override public CompletableFuture<List<? extends Command>> codeAction(CodeActionParams params) { logInfo(">> document/codeAction"); CodeActionHandler handler = new CodeActionHandler(); return computeAsync((cc) -> { IProgressMonitor monitor = toMonitor(cc); try { Job.getJobManager().join(DocumentLifeCycleHandler.DOCUMENT_LIFE_CYCLE_JOBS, monitor); } catch (OperationCanceledException ignorable) { // No need to pollute logs when query is cancelled } catch (InterruptedException e) { JavaLanguageServerPlugin.logException(e.getMessage(), e); } return handler.getCodeActionCommands(params, toMonitor(cc)); }); }
@Test public void testCodeAction_removeUnusedImport() throws Exception{ ICompilationUnit unit = getWorkingCopy( "src/java/Foo.java", "import java.sql.*; \n" + "public class Foo {\n"+ " void foo() {\n"+ " }\n"+ "}\n"); CodeActionParams params = new CodeActionParams(); params.setTextDocument(new TextDocumentIdentifier(JDTUtils.toURI(unit))); final Range range = getRange(unit, "java.sql"); params.setRange(range); params.setContext(new CodeActionContext(Arrays.asList(getDiagnostic(Integer.toString(IProblem.UnusedImport), range)))); List<? extends Command> commands = server.codeAction(params).join(); Assert.assertNotNull(commands); Assert.assertEquals(2, commands.size()); Command c = commands.get(0); Assert.assertEquals(CodeActionHandler.COMMAND_ID_APPLY_EDIT, c.getCommand()); }
@Test public void testCodeAction_removeUnterminatedString() throws Exception{ ICompilationUnit unit = getWorkingCopy( "src/java/Foo.java", "public class Foo {\n"+ " void foo() {\n"+ "String s = \"some str\n" + " }\n"+ "}\n"); CodeActionParams params = new CodeActionParams(); params.setTextDocument(new TextDocumentIdentifier(JDTUtils.toURI(unit))); final Range range = getRange(unit, "some str"); params.setRange(range); params.setContext(new CodeActionContext(Arrays.asList(getDiagnostic(Integer.toString(IProblem.UnterminatedString), range)))); List<? extends Command> commands = server.codeAction(params).join(); Assert.assertNotNull(commands); Assert.assertEquals(1, commands.size()); Command c = commands.get(0); Assert.assertEquals(CodeActionHandler.COMMAND_ID_APPLY_EDIT, c.getCommand()); }
@SuppressWarnings("unchecked") @Test public void testResolveImplementationsCodeLense() { 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 Map<String, Object> map = (Map<String, Object>) args.get(1); assertEquals(5.0, map.get("line")); assertEquals(17.0, map.get("character")); //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()); }
protected void assertCodeActionExists(ICompilationUnit cu, Expected expected) throws Exception { List<Command> codeActionCommands = evaluateCodeActions(cu); for (Command c : codeActionCommands) { String actual = evaluateCodeActionCommand(c); if (expected.content.equals(actual)) { assertEquals(expected.name, c.getTitle()); return; } } String res = ""; for (Command command : codeActionCommands) { if (res.length() > 0) { res += '\n'; } res += command.getTitle(); } assertEquals("Not found.", expected.name, res); }
protected void assertCodeActions(ICompilationUnit cu, Expected... expected) throws Exception { List<Command> codeActionCommands = evaluateCodeActions(cu); if (codeActionCommands.size() != expected.length) { String res = ""; for (Command command : codeActionCommands) { res += " '" + command.getTitle() + "'"; } assertEquals("Number of code actions: " + res, expected.length, codeActionCommands.size()); } int k = 0; String aStr = "", eStr = "", testContent = ""; for (Command c : codeActionCommands) { String actual = evaluateCodeActionCommand(c); Expected e = expected[k++]; if (!e.name.equals(c.getTitle()) || !e.content.equals(actual)) { aStr += '\n' + c.getTitle() + '\n' + actual; eStr += '\n' + e.name + '\n' + e.content; } testContent += generateTest(actual, c.getTitle(), k); } if (aStr.length() > 0) { aStr += '\n' + testContent; } assertEquals(eStr, aStr); }
protected List<Command> evaluateCodeActions(ICompilationUnit cu) throws JavaModelException { CompilationUnit astRoot = SharedASTProvider.getInstance().getAST(cu, null); IProblem[] problems = astRoot.getProblems(); Range range = getRange(cu, problems); CodeActionParams parms = new CodeActionParams(); TextDocumentIdentifier textDocument = new TextDocumentIdentifier(); textDocument.setUri(JDTUtils.toURI(cu)); parms.setTextDocument(textDocument); parms.setRange(range); CodeActionContext context = new CodeActionContext(); context.setDiagnostics(DiagnosticsHandler.toDiagnosticsArray(Arrays.asList(problems))); parms.setContext(context); return new CodeActionHandler().getCodeActionCommands(parms, new NullProgressMonitor()); }
private String evaluateCodeActionCommand(Command c) throws BadLocationException, JavaModelException { Assert.assertEquals(CodeActionHandler.COMMAND_ID_APPLY_EDIT, c.getCommand()); Assert.assertNotNull(c.getArguments()); Assert.assertTrue(c.getArguments().get(0) instanceof WorkspaceEdit); WorkspaceEdit we = (WorkspaceEdit) c.getArguments().get(0); Iterator<Entry<String, List<TextEdit>>> editEntries = we.getChanges().entrySet().iterator(); Entry<String, List<TextEdit>> entry = editEntries.next(); assertNotNull("No edits generated", entry); assertEquals("More than one resource modified", false, editEntries.hasNext()); ICompilationUnit cu = JDTUtils.resolveCompilationUnit(entry.getKey()); assertNotNull("CU not found: " + entry.getKey(), cu); Document doc = new Document(); doc.set(cu.getSource()); return TextEditUtil.apply(doc, entry.getValue()); }
@Override public List<? extends Command> getCodeActions(final Document document, final XtextResource resource, final CodeActionParams params, final CancelIndicator indicator) { final ArrayList<Command> commands = CollectionLiterals.<Command>newArrayList(); List<Diagnostic> _diagnostics = params.getContext().getDiagnostics(); for (final Diagnostic d : _diagnostics) { String _code = d.getCode(); if (_code != null) { switch (_code) { case TestLanguageValidator.INVALID_NAME: Command _fixInvalidName = this.fixInvalidName(d, document, resource, params); commands.add(_fixInvalidName); break; case TestLanguageValidator.UNSORTED_MEMBERS: Command _fixUnsortedMembers = this.fixUnsortedMembers(d, document, resource, params); commands.add(_fixUnsortedMembers); break; } } } return commands; }
protected String _toExpectation(final Command it) { StringConcatenation _builder = new StringConcatenation(); _builder.append("command : "); String _command = it.getCommand(); _builder.append(_command); _builder.newLineIfNotEmpty(); _builder.append("title : "); String _title = it.getTitle(); _builder.append(_title); _builder.newLineIfNotEmpty(); _builder.append("args : "); _builder.newLine(); _builder.append("\t"); final Function1<Object, CharSequence> _function = (Object it_1) -> { return this.toExpectation(it_1); }; String _join = IterableExtensions.<Object>join(it.getArguments(), ",", _function); _builder.append(_join, "\t"); _builder.newLineIfNotEmpty(); return _builder.toString(); }
@Override public CompletableFuture<List<? extends Command>> codeAction(final CodeActionParams params) { final Function1<CancelIndicator, List<? extends Command>> _function = (CancelIndicator cancelIndicator) -> { final URI uri = this._uriExtensions.toUri(params.getTextDocument().getUri()); final IResourceServiceProvider serviceProvider = this.languagesRegistry.getResourceServiceProvider(uri); ICodeActionService _get = null; if (serviceProvider!=null) { _get=serviceProvider.<ICodeActionService>get(ICodeActionService.class); } final ICodeActionService service = _get; if ((service == null)) { return CollectionLiterals.<Command>emptyList(); } final Function2<Document, XtextResource, List<? extends Command>> _function_1 = (Document doc, XtextResource resource) -> { return service.getCodeActions(doc, resource, params, cancelIndicator); }; return this.workspaceManager.<List<? extends Command>>doRead(uri, _function_1); }; return this.requestManager.<List<? extends Command>>runRead(_function); }
public void update(org.eclipse.lsp4j.CodeLens cl) { Command command = cl.getCommand(); if (command != null) { org.eclipse.jface.text.provisional.codelens.Command c = new org.eclipse.jface.text.provisional.codelens.Command( command.getTitle(), command.getCommand()); super.setCommand(c); } }
public List<Command> find(CodeActionParams params) { return params.getContext() .getDiagnostics() .stream() .flatMap(diagnostic -> findCodeActionsForDiagnostic(diagnostic)) .collect(Collectors.toList()); }
private Stream<Command> codeActionsFor(Diagnostic diagnostic) { if (diagnostic.getCode().equals("compiler.err.cant.resolve.location")) { return cannotFindSymbolClassName(diagnostic.getMessage()) .map(Stream::of) .orElseGet(Stream::empty) .flatMap(this::addImportActions); } else return Stream.empty(); }
/** Search for symbols on the classpath and sourcepath that match name */ private Stream<Command> addImportActions(String name) { Stream<Command> sourcePath = index.allTopLevelClasses() .filter(c -> c.className.equals(name)) .map(c -> importClassCommand(c.packageName, c.className)); Stream<Command> classPath = compiler.classPathIndex .topLevelClasses() .filter(c -> c.getSimpleName().equals(name)) .map(c -> importClassCommand(c.getPackageName(), c.getSimpleName())); return Stream.concat(sourcePath, classPath); }
@Override public CompletableFuture<List<? extends Command>> codeAction(final CodeActionParams params) { // TODO Auto-generated method stub return null; }
private static CodeLens createTestLense(final MixinDefinition def, final String documentUri) { CodeLens lens = new CodeLens(); Command cmd = new Command(); cmd.setCommand(COMMAND); cmd.setTitle("Run tests"); Range r = SomAdapter.toRange(def.getNameSourceSection()); cmd.setArguments(Lists.newArrayList(documentUri, def.getName().getString(), r.getStart().getLine(), r.getStart().getCharacter(), r.getEnd().getLine(), r.getEnd().getCharacter())); lens.setCommand(cmd); lens.setRange(r); return lens; }
public void fileChanged(String uriString, CHANGE_TYPE changeType) { if (uriString == null) { return; } IResource resource = JDTUtils.findFile(uriString); if (resource == null) { return; } try { if (changeType == CHANGE_TYPE.DELETED) { resource = resource.getParent(); } if (resource != null) { resource.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor()); } if (isBuildFile(resource)) { FeatureStatus status = preferenceManager.getPreferences().getUpdateBuildConfigurationStatus(); switch (status) { case automatic: updateProject(resource.getProject()); break; case disabled: break; default: if (client != null) { String cmd = "java.projectConfiguration.status"; TextDocumentIdentifier uri = new TextDocumentIdentifier(uriString); ActionableNotification updateProjectConfigurationNotification = new ActionableNotification().withSeverity(MessageType.Info) .withMessage("A build file was modified. Do you want to synchronize the Java classpath/configuration?").withCommands(asList(new Command("Never", cmd, asList(uri, FeatureStatus.disabled)), new Command("Now", cmd, asList(uri, FeatureStatus.interactive)), new Command("Always", cmd, asList(uri, FeatureStatus.automatic)))); client.sendActionableNotification(updateProjectConfigurationNotification); } } } } catch (CoreException e) { JavaLanguageServerPlugin.logException("Problem refreshing workspace", e); } }
private Command getCommandFromProposal(CUCorrectionProposal proposal) throws CoreException { String name = proposal.getName(); TextChange textChange = proposal.getTextChange(); TextEdit edit = textChange.getEdit(); ICompilationUnit unit = proposal.getCompilationUnit(); return textEditToCommand(unit, name, edit); }
private static Command textEditToCommand(ICompilationUnit unit, String label, TextEdit textEdit) { TextEditConverter converter = new TextEditConverter(unit, textEdit); String uri = JDTUtils.toURI(unit); WorkspaceEdit $ = new WorkspaceEdit(); $.getChanges().put(uri, converter.convert()); return new Command(label, COMMAND_ID_APPLY_EDIT, Arrays.asList($)); }
@Test @Ignore public void testCodeAction_superfluousSemicolon() throws Exception{ ICompilationUnit unit = getWorkingCopy( "src/java/Foo.java", "public class Foo {\n"+ " void foo() {\n"+ ";" + " }\n"+ "}\n"); CodeActionParams params = new CodeActionParams(); params.setTextDocument(new TextDocumentIdentifier(JDTUtils.toURI(unit))); final Range range = getRange(unit, ";"); params.setRange(range); params.setContext(new CodeActionContext(Arrays.asList(getDiagnostic(Integer.toString(IProblem.SuperfluousSemicolon), range)))); List<? extends Command> commands = server.codeAction(params).join(); Assert.assertNotNull(commands); Assert.assertEquals(1, commands.size()); Command c = commands.get(0); Assert.assertEquals(CodeActionHandler.COMMAND_ID_APPLY_EDIT, c.getCommand()); Assert.assertNotNull(c.getArguments()); Assert.assertTrue(c.getArguments().get(0) instanceof WorkspaceEdit); WorkspaceEdit we = (WorkspaceEdit) c.getArguments().get(0); List<org.eclipse.lsp4j.TextEdit> edits = we.getChanges().get(JDTUtils.toURI(unit)); Assert.assertEquals(1, edits.size()); Assert.assertEquals("", edits.get(0).getNewText()); Assert.assertEquals(range, edits.get(0).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 Map<String, Object> map = (Map<String, Object>)args.get(1); assertEquals(5.0, map.get("line")); assertEquals(13.0, map.get("character")); //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()); }
@Override public CodeLens resolveCodeLens(final Document document, final XtextResource resource, final CodeLens codeLens, final CancelIndicator indicator) { Command _command = codeLens.getCommand(); String _title = codeLens.getCommand().getTitle(); String _plus = (_title + "(RESOLVED)"); _command.setTitle(_plus); return codeLens; }
@Override public CompletableFuture<List<? extends Command>> codeAction(CodeActionParams params) { LOGGER.info("codeAction: " + params.getTextDocument()); return CompletableFuture.completedFuture(Collections.emptyList()); }
private Stream<Command> findCodeActionsForDiagnostic(Diagnostic diagnostic) { return codeActionsFor(diagnostic); }
private Command importClassCommand(String packageName, String className) { return new Command( "Import " + packageName + "." + className, "Java.importClass", ImmutableList.of(file.toString(), packageName, className)); }
public CodeLens(@NonNull final Range range, final Command command, final Object data) { this(range); this.command = command; this.data = data; }
/** * The command this code lens represents. */ @Pure public Command getCommand() { return this.command; }
/** * The command this code lens represents. */ public void setCommand(final Command command) { this.command = command; }
/** * @return the commands */ public List<Command> getCommands() { return commands; }
public ActionableNotification withCommands(List<Command> commands) { this.commands = commands; return this; }
/** * Sends a message to the client to be presented to users, with possible commands to execute */ public void sendActionableNotification(MessageType severity, String message, Object data, List<Command> commands) { ActionableNotification notification = new ActionableNotification().withSeverity(severity).withMessage(message).withData(data).withCommands(commands); sendActionableNotification(notification); }
@Pure public Procedure1<? super List<? extends Command>> getAssertCodeActions() { return this.assertCodeActions; }
public void setAssertCodeActions(final Procedure1<? super List<? extends Command>> assertCodeActions) { this.assertCodeActions = assertCodeActions; }
@Override public CompletableFuture<List<? extends Command>> codeAction(CodeActionParams params) { throw new UnsupportedOperationException(); }