下面列出了怎么用org.eclipse.lsp4j.CodeActionContext的API类实例代码及写法,或者点击链接到github查看源代码。
@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);
}
@Test
void testNoErrorWithDiagnosticWithoutCode() throws FileNotFoundException, InterruptedException, ExecutionException {
TextDocumentIdentifier textDocumentIdentifier = initAnLaunchDiagnostic();
Diagnostic diagnostic = lastPublishedDiagnostics.getDiagnostics().get(0);
List<Diagnostic> diagnostics = new ArrayList<Diagnostic>();
Diagnostic diagnosticWithoutCode = new Diagnostic(new Range(new Position(9,33), new Position(9,37)), "a different diagnostic coming without code.");
diagnostics.add(diagnosticWithoutCode);
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);
}
/** Adds a quick-fix code action with the given title, edit and command */
public void acceptQuickfixCodeAction(QuickfixContext context, String title, WorkspaceEdit edit, Command command) {
if (edit == null && command == null) {
return;
}
CodeAction codeAction = new CodeAction();
codeAction.setTitle(title);
codeAction.setEdit(edit);
codeAction.setCommand(command);
codeAction.setKind(CodeActionKind.QuickFix);
if (context.options != null && context.options.getCodeActionParams() != null) {
CodeActionContext cac = context.options.getCodeActionParams().getContext();
if (cac != null && cac.getDiagnostics() != null) {
codeAction.setDiagnostics(cac.getDiagnostics());
}
}
codeActions.add(Either.forRight(codeAction));
}
private void addSourceActionCommand(List<Either<Command, CodeAction>> result, CodeActionContext context, Optional<Either<Command, CodeAction>> target) {
if (!target.isPresent()) {
return;
}
Either<Command, CodeAction> targetAction = target.get();
if (context.getOnly() != null && !context.getOnly().isEmpty()) {
Stream<String> acceptedActionKinds = context.getOnly().stream();
String actionKind = targetAction.getLeft() == null ? targetAction.getRight().getKind() : targetAction.getLeft().getCommand();
if (!acceptedActionKinds.filter(kind -> actionKind != null && actionKind.startsWith(kind)).findFirst().isPresent()) {
return;
}
}
result.add(targetAction);
}
private Optional<Either<Command, CodeAction>> convertToWorkspaceEditAction(CodeActionContext context, ICompilationUnit cu, String name, String kind, TextEdit edit) {
WorkspaceEdit workspaceEdit = convertToWorkspaceEdit(cu, edit);
if (!ChangeUtil.hasChanges(workspaceEdit)) {
return Optional.empty();
}
Command command = new Command(name, CodeActionHandler.COMMAND_ID_APPLY_EDIT, Collections.singletonList(workspaceEdit));
if (preferenceManager.getClientPreferences().isSupportedCodeActionKind(kind)) {
CodeAction codeAction = new CodeAction(name);
codeAction.setKind(kind);
codeAction.setCommand(command);
codeAction.setDiagnostics(context.getDiagnostics());
return Optional.of(Either.forRight(codeAction));
} else {
return Optional.of(Either.forLeft(command));
}
}
@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 = CodeActionUtil.getRange(unit, "java.sql");
params.setRange(range);
params.setContext(new CodeActionContext(Arrays.asList(getDiagnostic(Integer.toString(IProblem.UnusedImport), range))));
List<Either<Command, CodeAction>> codeActions = getCodeActions(params);
Assert.assertNotNull(codeActions);
Assert.assertTrue(codeActions.size() >= 3);
Assert.assertEquals(codeActions.get(0).getRight().getKind(), CodeActionKind.QuickFix);
Assert.assertEquals(codeActions.get(1).getRight().getKind(), CodeActionKind.QuickFix);
Assert.assertEquals(codeActions.get(2).getRight().getKind(), CodeActionKind.SourceOrganizeImports);
Command c = codeActions.get(0).getRight().getCommand();
Assert.assertEquals(CodeActionHandler.COMMAND_ID_APPLY_EDIT, c.getCommand());
}
@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));
}
}
@Test
public void testCodeAction_refactorActionsOnly() throws Exception {
ICompilationUnit unit = getWorkingCopy(
"src/java/Foo.java",
"public class Foo {\n"+
" void foo() {\n"+
" String bar = \"astring\";"+
" }\n"+
"}\n");
CodeActionParams params = new CodeActionParams();
params.setTextDocument(new TextDocumentIdentifier(JDTUtils.toURI(unit)));
final Range range = CodeActionUtil.getRange(unit, "bar");
params.setRange(range);
CodeActionContext context = new CodeActionContext(
Arrays.asList(getDiagnostic(Integer.toString(IProblem.LocalVariableIsNeverUsed), range)),
Collections.singletonList(CodeActionKind.Refactor)
);
params.setContext(context);
List<Either<Command, CodeAction>> refactorActions = getCodeActions(params);
Assert.assertNotNull(refactorActions);
Assert.assertFalse("No refactor actions were found", refactorActions.isEmpty());
for (Either<Command, CodeAction> codeAction : refactorActions) {
Assert.assertTrue("Unexpected kind:" + codeAction.getRight().getKind(), codeAction.getRight().getKind().startsWith(CodeActionKind.Refactor));
}
}
@Test
public void testCodeAction_quickfixActionsOnly() throws Exception {
ICompilationUnit unit = getWorkingCopy(
"src/java/Foo.java",
"public class Foo {\n"+
" void foo() {\n"+
" String bar = \"astring\";"+
" }\n"+
"}\n");
CodeActionParams params = new CodeActionParams();
params.setTextDocument(new TextDocumentIdentifier(JDTUtils.toURI(unit)));
final Range range = CodeActionUtil.getRange(unit, "bar");
params.setRange(range);
CodeActionContext context = new CodeActionContext(
Arrays.asList(getDiagnostic(Integer.toString(IProblem.LocalVariableIsNeverUsed), range)),
Collections.singletonList(CodeActionKind.QuickFix)
);
params.setContext(context);
List<Either<Command, CodeAction>> quickfixActions = getCodeActions(params);
Assert.assertNotNull(quickfixActions);
Assert.assertFalse("No quickfix actions were found", quickfixActions.isEmpty());
for (Either<Command, CodeAction> codeAction : quickfixActions) {
Assert.assertTrue("Unexpected kind:" + codeAction.getRight().getKind(), codeAction.getRight().getKind().startsWith(CodeActionKind.QuickFix));
}
}
@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 = CodeActionUtil.getRange(unit, "some str");
params.setRange(range);
params.setContext(new CodeActionContext(Arrays.asList(getDiagnostic(Integer.toString(IProblem.UnterminatedString), range))));
List<Either<Command, CodeAction>> codeActions = getCodeActions(params);
Assert.assertNotNull(codeActions);
Assert.assertFalse(codeActions.isEmpty());
Assert.assertEquals(codeActions.get(0).getRight().getKind(), CodeActionKind.QuickFix);
Command c = codeActions.get(0).getRight().getCommand();
Assert.assertEquals(CodeActionHandler.COMMAND_ID_APPLY_EDIT, c.getCommand());
}
@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();
}
}
protected List<Either<Command, CodeAction>> getCodeActions(ICompilationUnit cu) throws JavaModelException {
CompilationUnit astRoot = CoreASTProvider.getInstance().getAST(cu, CoreASTProvider.WAIT_YES, 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(cu, Arrays.asList(problems), true));
context.setOnly(Arrays.asList(CodeActionKind.QuickFix));
parms.setContext(context);
return new CodeActionHandler(this.preferenceManager).getCodeActionCommands(parms, new NullProgressMonitor());
}
private MicroProfileJavaCodeActionParams createCodeActionParams(String uri, Diagnostic d) {
TextDocumentIdentifier textDocument = new TextDocumentIdentifier(uri);
Range range = d.getRange();
CodeActionContext context = new CodeActionContext();
context.setDiagnostics(Arrays.asList(d));
MicroProfileJavaCodeActionParams codeActionParams = new MicroProfileJavaCodeActionParams(textDocument, range,
context);
codeActionParams.setResourceOperationSupported(true);
return codeActionParams;
}
public List<CodeAction> doCodeActions(CodeActionContext context, Range range, DOMDocument document,
SharedSettings sharedSettings) {
List<CodeAction> codeActions = new ArrayList<>();
if (context.getDiagnostics() != null) {
for (Diagnostic diagnostic : context.getDiagnostics()) {
for (ICodeActionParticipant codeActionParticipant : extensionsRegistry.getCodeActionsParticipants()) {
codeActionParticipant.doCodeAction(diagnostic, range, document, codeActions,
sharedSettings, extensionsRegistry);
}
}
}
return codeActions;
}
@Override
public CompletableFuture<List<Either<Command, CodeAction>>> codeAction(CodeActionParams params) {
LOGGER.info("codeAction: {}", params.getTextDocument());
CodeActionContext context = params.getContext();
if (context != null && (context.getOnly() == null || context.getOnly().contains(CodeActionKind.QuickFix))) {
return CompletableFuture.supplyAsync(() -> {
List<Either<Command, CodeAction>> allQuickfixes = new ArrayList<>();
allQuickfixes.addAll(new UnknownPropertyQuickfix(this).apply(params));
allQuickfixes.addAll(new InvalidEnumQuickfix(this).apply(params));
return allQuickfixes;
});
} else {
return CompletableFuture.completedFuture(Collections.emptyList());
}
}
@Test
void testReturnCodeActionForQuickfix() throws FileNotFoundException, InterruptedException, ExecutionException {
TextDocumentIdentifier textDocumentIdentifier = initAnLaunchDiagnostic();
Diagnostic diagnostic = lastPublishedDiagnostics.getDiagnostics().get(0);
CodeActionContext context = new CodeActionContext(lastPublishedDiagnostics.getDiagnostics(), Collections.singletonList(CodeActionKind.QuickFix));
CompletableFuture<List<Either<Command,CodeAction>>> codeActions = camelLanguageServer.getTextDocumentService().codeAction(new CodeActionParams(textDocumentIdentifier, diagnostic.getRange(), context));
checkRetrievedCodeAction(textDocumentIdentifier, diagnostic, codeActions);
}
@Test
void testReturnCodeActionForQuickfixWhenNoCodeActionKindSpecified() throws FileNotFoundException, InterruptedException, ExecutionException {
TextDocumentIdentifier textDocumentIdentifier = initAnLaunchDiagnostic();
Diagnostic diagnostic = lastPublishedDiagnostics.getDiagnostics().get(0);
CodeActionContext context = new CodeActionContext(lastPublishedDiagnostics.getDiagnostics());
CompletableFuture<List<Either<Command,CodeAction>>> codeActions = camelLanguageServer.getTextDocumentService().codeAction(new CodeActionParams(textDocumentIdentifier, diagnostic.getRange(), context));
checkRetrievedCodeAction(textDocumentIdentifier, diagnostic, codeActions);
}
@Test
void testReturnNoCodeActionForOtherThanQuickfix() throws FileNotFoundException, InterruptedException, ExecutionException {
TextDocumentIdentifier textDocumentIdentifier = initAnLaunchDiagnostic();
List<String> codeActionKinds = Stream.of(CodeActionKind.Refactor, CodeActionKind.RefactorExtract, CodeActionKind.RefactorInline, CodeActionKind.RefactorRewrite, CodeActionKind.Source, CodeActionKind.SourceOrganizeImports)
.collect(Collectors.toList());
Diagnostic diagnostic = lastPublishedDiagnostics.getDiagnostics().get(0);
CodeActionContext context = new CodeActionContext(lastPublishedDiagnostics.getDiagnostics(), codeActionKinds);
CompletableFuture<List<Either<Command,CodeAction>>> codeActions = camelLanguageServer.getTextDocumentService().codeAction(new CodeActionParams(textDocumentIdentifier, diagnostic.getRange(), context));
assertThat(codeActions.get()).isEmpty();
}
@Test
void testReturnCodeActionForQuickfix() throws FileNotFoundException, InterruptedException, ExecutionException {
TextDocumentIdentifier textDocumentIdentifier = initAnLaunchDiagnostic();
Diagnostic diagnostic = lastPublishedDiagnostics.getDiagnostics().get(0);
CodeActionContext context = new CodeActionContext(lastPublishedDiagnostics.getDiagnostics(), Collections.singletonList(CodeActionKind.QuickFix));
CompletableFuture<List<Either<Command,CodeAction>>> codeActions = camelLanguageServer.getTextDocumentService().codeAction(new CodeActionParams(textDocumentIdentifier, diagnostic.getRange(), context));
checkRetrievedCodeAction(textDocumentIdentifier, diagnostic, codeActions);
}
@Override
protected void performTest(Project project, String moduleName, N4JSTestCodeActionConfiguration tcac)
throws InterruptedException, ExecutionException {
CodeActionParams codeActionParams = new CodeActionParams();
Range range = new Range();
Position posStart = new Position(tcac.getLine(), tcac.getColumn());
Position posEnd = tcac.getEndLine() >= 0 && tcac.getEndColumn() >= 0
? new Position(tcac.getEndLine(), tcac.getEndColumn())
: posStart;
range.setStart(posStart);
range.setEnd(posEnd);
codeActionParams.setRange(range);
CodeActionContext context = new CodeActionContext();
FileURI uri = getFileURIFromModuleName(moduleName);
context.setDiagnostics(Lists.newArrayList(getIssues(uri)));
codeActionParams.setContext(context);
TextDocumentIdentifier textDocument = new TextDocumentIdentifier();
textDocument.setUri(uri.toString());
codeActionParams.setTextDocument(textDocument);
CompletableFuture<List<Either<Command, CodeAction>>> future = languageServer.codeAction(codeActionParams);
List<Either<Command, CodeAction>> result = future.get();
if (tcac.getAssertCodeActions() != null) {
tcac.getAssertCodeActions().apply(result);
} else {
String resultStr = result.stream()
.map(cmdOrAction -> getStringLSP4J().toString3(cmdOrAction))
.collect(Collectors.joining("\n-----\n"));
assertEquals(tcac.getExpectedCodeActions().trim(), resultStr.trim());
}
}
@Override
protected void performTest(Project project, String moduleName, TestOrganizeImportsConfiguration config)
throws Exception {
FileURI uri = getFileURIFromModuleName(moduleName);
if (config.expectedIssues.isEmpty()) {
assertNoIssues();
} else {
assertIssues(Collections.singletonMap(uri, config.expectedIssues));
}
TextDocumentIdentifier id = new TextDocumentIdentifier(uri.toString());
Range range = new Range(new Position(0, 0), new Position(0, 0));
CodeActionContext context = new CodeActionContext();
CodeActionParams params = new CodeActionParams(id, range, context);
CompletableFuture<List<Either<Command, CodeAction>>> codeActionFuture = languageServer.codeAction(params);
List<Either<Command, CodeAction>> result = codeActionFuture.join();
Command organizeImportsCommand = result.stream()
.map(e -> e.isLeft() ? e.getLeft() : e.getRight().getCommand())
.filter(cmd -> cmd != null
&& Objects.equals(cmd.getCommand(), N4JSCommandService.N4JS_ORGANIZE_IMPORTS))
.findFirst().orElse(null);
Assert.assertNotNull("code action for organize imports not found", organizeImportsCommand);
ExecuteCommandParams execParams = new ExecuteCommandParams(
organizeImportsCommand.getCommand(),
organizeImportsCommand.getArguments());
CompletableFuture<Object> execFuture = languageServer.executeCommand(execParams);
execFuture.join();
joinServerRequests();
assertContentOfFileOnDisk(uri, config.expectedCode);
}
/**
* Return the current diagnostic or null, if it cannot be determined generically.
*/
public Diagnostic getDiagnostic() {
CodeActionContext context = options.getCodeActionParams().getContext();
for (Diagnostic d : context.getDiagnostics()) {
if (issueCode.equals(d.getCode())) {
if (Ranges.containsRange(d.getRange(), options.getCodeActionParams().getRange())) {
return d;
}
}
}
return null;
}
private Options createOptions(XtextResource res, XDocument doc, TextDocumentIdentifier docIdentifier,
LSPIssue issue, CancelIndicator cancelIndicator) {
Diagnostic diagnostic = diagnosticIssueConverter.toDiagnostic(issue);
CodeActionContext context = new CodeActionContext(Collections.singletonList(diagnostic));
CodeActionParams codeActionParams = new CodeActionParams(docIdentifier, diagnostic.getRange(), context);
Options newOptions = languageServer.toOptions(codeActionParams, doc, res, cancelIndicator);
return newOptions;
}
@Override
public List<? extends CodeGenerator> create(Lookup context) {
JTextComponent component = context.lookup(JTextComponent.class);
if (component == null) {
return Collections.emptyList();
}
FileObject file = NbEditorUtilities.getFileObject(component.getDocument());
if (file == null) {
return Collections.emptyList();
}
LSPBindings server = LSPBindings.getBindings(file);
if (server == null) {
return Collections.emptyList();
}
String uri = Utils.toURI(file);
try {
List<Either<Command, CodeAction>> commands =
server.getTextDocumentService().codeAction(new CodeActionParams(new TextDocumentIdentifier(uri),
new Range(Utils.createPosition(component.getDocument(), component.getSelectionStart()),
Utils.createPosition(component.getDocument(), component.getSelectionEnd())),
new CodeActionContext(Collections.emptyList()))).get();
return commands.stream().map(cmd -> new CodeGenerator() {
@Override
public String getDisplayName() {
return cmd.isLeft() ? cmd.getLeft().getTitle() : cmd.getRight().getTitle();
}
@Override
public void invoke() {
Utils.applyCodeAction(server, cmd);
}
}).collect(Collectors.toList());
} catch (BadLocationException | InterruptedException | ExecutionException ex) {
Exceptions.printStackTrace(ex);
return Collections.emptyList();
}
}
@Override
public synchronized List<Fix> getFixes() {
if (!computing && !computed) {
computing = true;
bindings.runOnBackground(() -> {
try {
List<Either<Command, CodeAction>> commands =
bindings.getTextDocumentService().codeAction(new CodeActionParams(new TextDocumentIdentifier(fileUri),
diagnostic.getRange(),
new CodeActionContext(Collections.singletonList(diagnostic)))).get();
List<Fix> fixes = commands.stream()
.map(cmd -> new CommandBasedFix(cmd))
.collect(Collectors.toList());
synchronized (this) {
this.fixes = Collections.unmodifiableList(fixes);
this.computed = true;
this.computing = false;
}
pcs.firePropertyChange(PROP_COMPUTED, null, null);
pcs.firePropertyChange(PROP_FIXES, null, null);
} catch (InterruptedException | ExecutionException ex) {
Exceptions.printStackTrace(ex);
}
});
}
return fixes;
}
public static CodeActionParams constructCodeActionParams(ICompilationUnit unit, Range range) {
CodeActionParams params = new CodeActionParams();
params.setTextDocument(new TextDocumentIdentifier(JDTUtils.toURI(unit)));
params.setRange(range);
params.setContext(new CodeActionContext(Collections.emptyList()));
return params;
}
@Test
public void testCodeAction_organizeImportsSourceActionOnly() throws Exception {
ICompilationUnit unit = getWorkingCopy(
"src/java/Foo.java",
"import java.util.List;\n"+
"public class Foo {\n"+
" void foo() {\n"+
" String bar = \"astring\";"+
" }\n"+
"}\n");
CodeActionParams params = new CodeActionParams();
params.setTextDocument(new TextDocumentIdentifier(JDTUtils.toURI(unit)));
final Range range = CodeActionUtil.getRange(unit, "bar");
params.setRange(range);
CodeActionContext context = new CodeActionContext(
Arrays.asList(getDiagnostic(Integer.toString(IProblem.LocalVariableIsNeverUsed), range)),
Collections.singletonList(CodeActionKind.SourceOrganizeImports)
);
params.setContext(context);
List<Either<Command, CodeAction>> codeActions = getCodeActions(params);
Assert.assertNotNull(codeActions);
Assert.assertFalse("No organize imports actions were found", codeActions.isEmpty());
for (Either<Command, CodeAction> codeAction : codeActions) {
Assert.assertTrue("Unexpected kind:" + codeAction.getRight().getKind(), codeAction.getRight().getKind().startsWith(CodeActionKind.SourceOrganizeImports));
}
}
@Test
public void testCodeAction_allKindsOfActions() throws Exception {
ICompilationUnit unit = getWorkingCopy(
"src/java/Foo.java",
"public class Foo {\n"+
" void foo() {\n"+
" String bar = \"astring\";"+
" }\n"+
"}\n");
CodeActionParams params = new CodeActionParams();
params.setTextDocument(new TextDocumentIdentifier(JDTUtils.toURI(unit)));
final Range range = CodeActionUtil.getRange(unit, "bar");
params.setRange(range);
CodeActionContext context = new CodeActionContext(
Arrays.asList(getDiagnostic(Integer.toString(IProblem.LocalVariableIsNeverUsed), range))
);
params.setContext(context);
List<Either<Command, CodeAction>> codeActions = getCodeActions(params);
Assert.assertNotNull(codeActions);
Assert.assertFalse("No code actions were found", codeActions.isEmpty());
boolean hasQuickFix = codeActions.stream().anyMatch(codeAction -> codeAction.getRight().getKind().startsWith(CodeActionKind.QuickFix));
assertTrue("No quickfix actions were found", hasQuickFix);
boolean hasRefactor = codeActions.stream().anyMatch(codeAction -> codeAction.getRight().getKind().startsWith(CodeActionKind.Refactor));
assertTrue("No refactor actions were found", hasRefactor);
boolean hasSource = codeActions.stream().anyMatch(codeAction -> codeAction.getRight().getKind().startsWith(CodeActionKind.Source));
assertTrue("No source actions were found", hasSource);
List<String> baseKinds = codeActions.stream().map(codeAction -> getBaseKind(codeAction.getRight().getKind())).collect(Collectors.toList());
assertTrue("quickfix actions should be ahead of refactor actions", baseKinds.lastIndexOf(CodeActionKind.QuickFix) < baseKinds.indexOf(CodeActionKind.Refactor));
assertTrue("refactor actions should be ahead of source actions", baseKinds.lastIndexOf(CodeActionKind.Refactor) < baseKinds.indexOf(CodeActionKind.Source));
}
@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 = CodeActionUtil.getRange(unit, ";");
params.setRange(range);
params.setContext(new CodeActionContext(Arrays.asList(getDiagnostic(Integer.toString(IProblem.SuperfluousSemicolon), range))));
List<Either<Command, CodeAction>> codeActions = getCodeActions(params);
Assert.assertNotNull(codeActions);
Assert.assertEquals(1, codeActions.size());
Assert.assertEquals(codeActions.get(0), CodeActionKind.QuickFix);
Command c = getCommand(codeActions.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());
}
@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));
}