Java 类org.eclipse.lsp4j.Command 实例源码

项目:eclipse.jdt.ls    文件:CodeActionHandlerTest.java   
@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();
    }
}
项目:SOMns-vscode    文件:SomMinitest.java   
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;
}
项目:eclipse.jdt.ls    文件:JDTLanguageServer.java   
@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));
    });
}
项目:eclipse.jdt.ls    文件:CodeActionHandlerTest.java   
@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());
}
项目:eclipse.jdt.ls    文件:CodeActionHandlerTest.java   
@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());
}
项目:eclipse.jdt.ls    文件:CodeLensHandlerTest.java   
@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());
}
项目:eclipse.jdt.ls    文件:AbstractQuickFixTest.java   
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);
}
项目:eclipse.jdt.ls    文件:AbstractQuickFixTest.java   
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);
}
项目:eclipse.jdt.ls    文件:AbstractQuickFixTest.java   
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());
    }
项目:eclipse.jdt.ls    文件:AbstractQuickFixTest.java   
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());
}
项目:xtext-core    文件:CodeActionService.java   
@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;
}
项目:xtext-core    文件:AbstractLanguageServerTest.java   
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();
}
项目:xtext-core    文件:LanguageServerImpl.java   
@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);
}
项目:codelens-eclipse    文件:LSPCodeLens.java   
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);
    }
}
项目:vscode-javac    文件:CodeActions.java   
public List<Command> find(CodeActionParams params) {
    return params.getContext()
            .getDiagnostics()
            .stream()
            .flatMap(diagnostic -> findCodeActionsForDiagnostic(diagnostic))
            .collect(Collectors.toList());
}
项目:vscode-javac    文件:CodeActions.java   
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();
}
项目:vscode-javac    文件:CodeActions.java   
/** 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);
}
项目:SOMns-vscode    文件:SomLanguageServer.java   
@Override
public CompletableFuture<List<? extends Command>> codeAction(final CodeActionParams params) {
  // TODO Auto-generated method stub
  return null;
}
项目:SOMns-vscode    文件:SomMinitest.java   
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;
}
项目:eclipse.jdt.ls    文件:ProjectsManager.java   
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);
    }
}
项目:eclipse.jdt.ls    文件:CodeActionHandler.java   
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);
}
项目:eclipse.jdt.ls    文件:CodeActionHandler.java   
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($));
}
项目:eclipse.jdt.ls    文件:CodeActionHandlerTest.java   
@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());
}
项目:eclipse.jdt.ls    文件:CodeLensHandlerTest.java   
@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());
}
项目:xtext-core    文件:CodeLensService.java   
@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;
}
项目:camel-language-server    文件:CamelTextDocumentService.java   
@Override
public CompletableFuture<List<? extends Command>> codeAction(CodeActionParams params) {
    LOGGER.info("codeAction: " + params.getTextDocument());
    return CompletableFuture.completedFuture(Collections.emptyList());
}
项目:vscode-javac    文件:CodeActions.java   
private Stream<Command> findCodeActionsForDiagnostic(Diagnostic diagnostic) {
    return codeActionsFor(diagnostic);
}
项目:vscode-javac    文件:CodeActions.java   
private Command importClassCommand(String packageName, String className) {
    return new Command(
            "Import " + packageName + "." + className,
            "Java.importClass",
            ImmutableList.of(file.toString(), packageName, className));
}
项目:SOMns-vscode    文件:CodeLens.java   
public CodeLens(@NonNull final Range range, final Command command, final Object data) {
  this(range);
  this.command = command;
  this.data = data;
}
项目:SOMns-vscode    文件:CodeLens.java   
/**
 * The command this code lens represents.
 */
@Pure
public Command getCommand() {
  return this.command;
}
项目:SOMns-vscode    文件:CodeLens.java   
/**
 * The command this code lens represents.
 */
public void setCommand(final Command command) {
  this.command = command;
}
项目:eclipse.jdt.ls    文件:ActionableNotification.java   
/**
 * @return the commands
 */
public List<Command> getCommands() {
    return commands;
}
项目:eclipse.jdt.ls    文件:ActionableNotification.java   
public ActionableNotification withCommands(List<Command> commands) {
    this.commands = commands;
    return this;
}
项目:eclipse.jdt.ls    文件:JavaClientConnection.java   
/**
 * 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);
}
项目:xtext-core    文件:AbstractLanguageServerTest.java   
@Pure
public Procedure1<? super List<? extends Command>> getAssertCodeActions() {
  return this.assertCodeActions;
}
项目:xtext-core    文件:AbstractLanguageServerTest.java   
public void setAssertCodeActions(final Procedure1<? super List<? extends Command>> assertCodeActions) {
  this.assertCodeActions = assertCodeActions;
}
项目:lsp4j    文件:CodeLens.java   
public CodeLens(@NonNull final Range range, final Command command, final Object data) {
  this(range);
  this.command = command;
  this.data = data;
}
项目:lsp4j    文件:CodeLens.java   
/**
 * The command this code lens represents.
 */
@Pure
public Command getCommand() {
  return this.command;
}
项目:lsp4j    文件:CodeLens.java   
/**
 * The command this code lens represents.
 */
public void setCommand(final Command command) {
  this.command = command;
}
项目:lsp4j    文件:MockLanguageServer.java   
@Override
public CompletableFuture<List<? extends Command>> codeAction(CodeActionParams params) {
    throw new UnsupportedOperationException();
}