下面列出了org.eclipse.lsp4j.CodeActionOptions#org.eclipse.lsp4j.CodeActionKind 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Makes a CodeAction to create a file and add content to the file.
*
* @param title The displayed name of the CodeAction
* @param docURI The file to create
* @param content The text to put into the newly created document.
* @param diagnostic The diagnostic that this CodeAction will fix
*/
public static CodeAction createFile(String title, String docURI, String content, Diagnostic diagnostic) {
List<Either<TextDocumentEdit, ResourceOperation>> actionsToTake = new ArrayList<>(2);
// 1. create an empty file
actionsToTake.add(Either.forRight(new CreateFile(docURI, new CreateFileOptions(false, true))));
// 2. update the created file with the given content
VersionedTextDocumentIdentifier identifier = new VersionedTextDocumentIdentifier(docURI, 0);
TextEdit te = new TextEdit(new Range(new Position(0, 0), new Position(0, 0)), content);
actionsToTake.add(Either.forLeft(new TextDocumentEdit(identifier, Collections.singletonList(te))));
WorkspaceEdit createAndAddContentEdit = new WorkspaceEdit(actionsToTake);
CodeAction codeAction = new CodeAction(title);
codeAction.setEdit(createAndAddContentEdit);
codeAction.setDiagnostics(Collections.singletonList(diagnostic));
codeAction.setKind(CodeActionKind.QuickFix);
return codeAction;
}
@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);
}
private static void createCodeActionsForGenerateGetterAndSetter(IVariableNode variableNode, String uri, String fileText, Range codeActionsRange, List<Either<Command, CodeAction>> codeActions)
{
WorkspaceEdit getSetEdit = createWorkspaceEditForGenerateGetterAndSetter(
variableNode, uri, fileText, true, true);
CodeAction getAndSetCodeAction = new CodeAction();
getAndSetCodeAction.setTitle("Generate 'get' and 'set' accessors");
getAndSetCodeAction.setEdit(getSetEdit);
getAndSetCodeAction.setKind(CodeActionKind.RefactorRewrite);
codeActions.add(Either.forRight(getAndSetCodeAction));
WorkspaceEdit getterEdit = createWorkspaceEditForGenerateGetterAndSetter(
variableNode, uri, fileText, true, false);
CodeAction getterCodeAction = new CodeAction();
getterCodeAction.setTitle("Generate 'get' accessor (make read-only)");
getterCodeAction.setEdit(getterEdit);
getterCodeAction.setKind(CodeActionKind.RefactorRewrite);
codeActions.add(Either.forRight(getterCodeAction));
WorkspaceEdit setterEdit = createWorkspaceEditForGenerateGetterAndSetter(
variableNode, uri, fileText, false, true);
CodeAction setterCodeAction = new CodeAction();
setterCodeAction.setTitle("Generate 'set' accessor (make write-only)");
setterCodeAction.setEdit(setterEdit);
setterCodeAction.setKind(CodeActionKind.RefactorRewrite);
codeActions.add(Either.forRight(setterCodeAction));
}
/** 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));
}
public void organizeImportsInCompilationUnit(ICompilationUnit unit, WorkspaceEdit rootEdit) {
try {
InnovationContext context = new InnovationContext(unit, 0, unit.getBuffer().getLength() - 1);
CUCorrectionProposal proposal = new CUCorrectionProposal("OrganizeImports", CodeActionKind.SourceOrganizeImports, unit, null, IProposalRelevance.ORGANIZE_IMPORTS) {
@Override
protected void addEdits(IDocument document, TextEdit editRoot) throws CoreException {
CompilationUnit astRoot = context.getASTRoot();
OrganizeImportsOperation op = new OrganizeImportsOperation(unit, astRoot, true, false, true, null);
TextEdit edit = op.createTextEdit(null);
TextEdit staticEdit = OrganizeImportsHandler.wrapStaticImports(edit, astRoot, unit);
if (staticEdit.getChildrenSize() > 0) {
editRoot.addChild(staticEdit);
}
}
};
addWorkspaceEdit(unit, proposal, rootEdit);
} catch (CoreException e) {
JavaLanguageServerPlugin.logException("Problem organize imports ", e);
}
}
public static void addCasesOmittedProposals(IInvocationContext context, IProblemLocationCore problem, Collection<ChangeCorrectionProposal> proposals) {
ASTNode selectedNode = problem.getCoveringNode(context.getASTRoot());
if (selectedNode instanceof Expression && selectedNode.getLocationInParent() == SwitchStatement.EXPRESSION_PROPERTY) {
AST ast = selectedNode.getAST();
SwitchStatement parent = (SwitchStatement) selectedNode.getParent();
for (Statement statement : (List<Statement>) parent.statements()) {
if (statement instanceof SwitchCase && ((SwitchCase) statement).isDefault()) {
// insert //$CASES-OMITTED$:
ASTRewrite rewrite = ASTRewrite.create(ast);
rewrite.setTargetSourceRangeComputer(new NoCommentSourceRangeComputer());
ListRewrite listRewrite = rewrite.getListRewrite(parent, SwitchStatement.STATEMENTS_PROPERTY);
ASTNode casesOmittedComment = rewrite.createStringPlaceholder("//$CASES-OMITTED$", ASTNode.EMPTY_STATEMENT); //$NON-NLS-1$
listRewrite.insertBefore(casesOmittedComment, statement, null);
String label = CorrectionMessages.LocalCorrectionsSubProcessor_insert_cases_omitted;
ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, CodeActionKind.QuickFix, context.getCompilationUnit(), rewrite, IProposalRelevance.INSERT_CASES_OMITTED);
proposals.add(proposal);
break;
}
}
}
}
/**
* Proposes a getter for this field.
*
* @param context
* the proposal parameter
* @param relevance
* relevance of this proposal
* @return the proposal if available or null
*/
private static ChangeCorrectionProposal addGetterProposal(ProposalParameter context, int relevance) {
IMethodBinding method = findGetter(context);
if (method != null) {
Expression mi = createMethodInvocation(context, method, null);
context.astRewrite.replace(context.accessNode, mi, null);
String label = Messages.format(CorrectionMessages.GetterSetterCorrectionSubProcessor_replacewithgetter_description, BasicElementLabels.getJavaCodeString(ASTNodes.asString(context.accessNode)));
ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, CodeActionKind.QuickFix, context.compilationUnit, context.astRewrite, relevance);
return proposal;
} else {
IJavaElement element = context.variableBinding.getJavaElement();
if (element instanceof IField) {
IField field = (IField) element;
try {
if (RefactoringAvailabilityTester.isSelfEncapsulateAvailable(field)) {
return new SelfEncapsulateFieldProposal(relevance, field);
}
} catch (JavaModelException e) {
JavaLanguageServerPlugin.log(e);
}
}
}
return null;
}
public static void getAmbiguousTypeReferenceProposals(IInvocationContext context, IProblemLocationCore problem,
Collection<ChangeCorrectionProposal> proposals) throws CoreException {
final ICompilationUnit cu= context.getCompilationUnit();
int offset= problem.getOffset();
int len= problem.getLength();
IJavaElement[] elements= cu.codeSelect(offset, len);
for (int i= 0; i < elements.length; i++) {
IJavaElement curr= elements[i];
if (curr instanceof IType && !TypeFilter.isFiltered((IType) curr)) {
String qualifiedTypeName= ((IType) curr).getFullyQualifiedName('.');
CompilationUnit root= context.getASTRoot();
String label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_importexplicit_description, BasicElementLabels.getJavaElementName(qualifiedTypeName));
ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, CodeActionKind.QuickFix, cu, ASTRewrite.create(root.getAST()), IProposalRelevance.IMPORT_EXPLICIT);
ImportRewrite imports= proposal.createImportRewrite(root);
imports.addImport(qualifiedTypeName);
proposals.add(proposal);
}
}
}
public static void getRemoveJavadocTagProposals(IInvocationContext context, IProblemLocationCore problem,
Collection<ChangeCorrectionProposal> proposals) {
ASTNode node= problem.getCoveringNode(context.getASTRoot());
while (node != null && !(node instanceof TagElement)) {
node= node.getParent();
}
if (node == null) {
return;
}
ASTRewrite rewrite= ASTRewrite.create(node.getAST());
rewrite.remove(node, null);
String label= CorrectionMessages.JavadocTagsSubProcessor_removetag_description;
proposals.add(new ASTRewriteCorrectionProposal(label, CodeActionKind.QuickFix, context.getCompilationUnit(), rewrite,
IProposalRelevance.REMOVE_TAG));
}
public static void getInvalidQualificationProposals(IInvocationContext context, IProblemLocationCore problem,
Collection<ChangeCorrectionProposal> proposals) {
ASTNode node= problem.getCoveringNode(context.getASTRoot());
if (!(node instanceof Name)) {
return;
}
Name name= (Name) node;
IBinding binding= name.resolveBinding();
if (!(binding instanceof ITypeBinding)) {
return;
}
ITypeBinding typeBinding= (ITypeBinding)binding;
AST ast= node.getAST();
ASTRewrite rewrite= ASTRewrite.create(ast);
rewrite.replace(name, ast.newName(typeBinding.getQualifiedName()), null);
String label= CorrectionMessages.JavadocTagsSubProcessor_qualifylinktoinner_description;
ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, CodeActionKind.QuickFix, context.getCompilationUnit(),
rewrite, IProposalRelevance.QUALIFY_INNER_TYPE_NAME);
proposals.add(proposal);
}
@Test
public void testRemovingNotPrefixWhenInvertVariable() throws Exception {
IPackageFragment pack1 = testSourceFolder.createPackageFragment("test", false, null);
StringBuilder buf = new StringBuilder();
buf.append("package test;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" boolean notLie = 3 != 5;\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu = pack1.createCompilationUnit("E.java", buf.toString(), false, null);
buf = new StringBuilder();
buf.append("package test;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" boolean lie = 3 == 5;\n");
buf.append(" }\n");
buf.append("}\n");
Expected expected = new Expected(INVERT_BOOLEAN_VARIABLE, buf.toString(), CodeActionKind.Refactor);
Range replacedRange = CodeActionUtil.getRange(cu, "notLie", 0);
assertCodeActions(cu, replacedRange, expected);
}
@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));
}
}
private void createCodeActionsForUnusedImport(Path path, Diagnostic diagnostic, WorkspaceFolderData folderData, List<Either<Command, CodeAction>> codeActions)
{
String fileText = fileTracker.getText(path);
if(fileText == null)
{
return;
}
Range range = diagnostic.getRange();
WorkspaceEdit edit = CodeActionsUtils.createWorkspaceEditForRemoveUnusedImport(fileText, path.toUri().toString(), diagnostic.getRange());
if (edit == null)
{
return;
}
int startOffset = LanguageServerCompilerUtils.getOffsetFromPosition(new StringReader(fileText), range.getStart());
int endOffset = LanguageServerCompilerUtils.getOffsetFromPosition(new StringReader(fileText), range.getEnd());
String importText = fileText.substring(startOffset, endOffset);
CodeAction codeAction = new CodeAction();
codeAction.setTitle("Remove " + importText);
codeAction.setEdit(edit);
codeAction.setKind(CodeActionKind.QuickFix);
codeAction.setDiagnostics(Collections.singletonList(diagnostic));
codeActions.add(Either.forRight(codeAction));
}
@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());
}
private void findSourceActions(Path path, List<Either<Command, CodeAction>> codeActions)
{
Command organizeCommand = new Command();
organizeCommand.setTitle("Organize Imports");
organizeCommand.setCommand(ICommandConstants.ORGANIZE_IMPORTS_IN_URI);
JsonObject uri = new JsonObject();
uri.addProperty("external", path.toUri().toString());
organizeCommand.setArguments(Lists.newArrayList(
uri
));
CodeAction organizeImports = new CodeAction();
organizeImports.setKind(CodeActionKind.SourceOrganizeImports);
organizeImports.setTitle(organizeCommand.getTitle());
organizeImports.setCommand(organizeCommand);
codeActions.add(Either.forRight(organizeImports));
}
@Test
public void testUnimplementedMethods() throws Exception {
IJavaProject javaProject = newEmptyProject();
IPackageFragmentRoot sourceFolder = javaProject.getPackageFragmentRoot(javaProject.getProject().getFolder("src"));
IPackageFragment pack1 = sourceFolder.createPackageFragment("test1", false, null);
StringBuilder buf = new StringBuilder();
buf.append("package test1;\n");
buf.append("public interface E {\n");
buf.append(" void foo();\n");
buf.append("}\n");
pack1.createCompilationUnit("E.java", buf.toString(), false, null);
buf = new StringBuilder();
buf.append("package test1;\n");
buf.append("public class F implements E {\n");
buf.append("}\n");
ICompilationUnit cu = pack1.createCompilationUnit("F.java", buf.toString(), false, null);
openDocument(cu, cu.getSource(), 1);
List<Either<Command, CodeAction>> codeActions = getCodeActions(cu);
assertEquals(codeActions.size(), 1);
assertEquals(codeActions.get(0).getRight().getKind(), CodeActionKind.QuickFix);
}
@Test
public void testRemoveDeadCodeAfterIf() throws Exception {
IJavaProject javaProject = newEmptyProject();
IPackageFragmentRoot sourceFolder = javaProject.getPackageFragmentRoot(javaProject.getProject().getFolder("src"));
IPackageFragment pack1 = sourceFolder.createPackageFragment("test1", false, null);
StringBuilder buf = new StringBuilder();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public boolean foo(boolean b1) {\n");
buf.append(" if (false) {\n");
buf.append(" return true;\n");
buf.append(" }\n");
buf.append(" return false;\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu = pack1.createCompilationUnit("E.java", buf.toString(), false, null);
List<Either<Command, CodeAction>> codeActions = getCodeActions(cu);
assertEquals(codeActions.size(), 1);
assertEquals(codeActions.get(0).getRight().getKind(), CodeActionKind.QuickFix);
}
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());
}
@Before
public void setup() throws Exception {
fJProject1 = newEmptyProject();
Hashtable<String, String> options = TestOptions.getDefaultOptions();
fJProject1.setOptions(options);
fSourceFolder = fJProject1.getPackageFragmentRoot(fJProject1.getProject().getFolder("src"));
setOnly(CodeActionKind.Refactor);
this.setIgnoredCommands("Extract to method");
}
@Test
public void testInvertConditionalAndOperator() throws Exception {
IPackageFragment pack1 = testSourceFolder.createPackageFragment("test", false, null);
StringBuilder buf = new StringBuilder();
buf.append("package test;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" if (true && true)\n");
buf.append(" return;\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu = pack1.createCompilationUnit("E.java", buf.toString(), false, null);
buf = new StringBuilder();
buf.append("package test;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" if (false || false)\n");
buf.append(" return;\n");
buf.append(" }\n");
buf.append("}\n");
Expected expected = new Expected("Invert conditions", buf.toString(), CodeActionKind.Refactor);
Range replacedRange = CodeActionUtil.getRange(cu, "true && true", "true && true".length());
assertCodeActions(cu, replacedRange, expected);
Range nonSelectionRange = CodeActionUtil.getRange(cu, "true && true", 0);
assertCodeActions(cu, nonSelectionRange, expected);
}
protected CodeAction createCodeAction(CodeActionParams params, Diagnostic diagnostic, String possibleProperty) {
CodeAction codeAction = new CodeAction("Did you mean "+possibleProperty + "?");
codeAction.setDiagnostics(Collections.singletonList(diagnostic));
codeAction.setKind(CodeActionKind.QuickFix);
Map<String, List<TextEdit>> changes = new HashMap<>();
TextEdit textEdit = new TextEdit(diagnostic.getRange(), possibleProperty);
changes.put(params.getTextDocument().getUri(), Arrays.asList(textEdit));
codeAction.setEdit(new WorkspaceEdit(changes));
return codeAction;
}
@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());
}
}
private ServerCapabilities createServerCapabilities() {
ServerCapabilities capabilities = new ServerCapabilities();
capabilities.setTextDocumentSync(TextDocumentSyncKind.Full);
capabilities.setCompletionProvider(new CompletionOptions(Boolean.TRUE, Arrays.asList(".","?","&", "\"", "=")));
capabilities.setHoverProvider(Boolean.TRUE);
capabilities.setDocumentSymbolProvider(Boolean.TRUE);
capabilities.setReferencesProvider(Boolean.TRUE);
capabilities.setDefinitionProvider(Boolean.TRUE);
capabilities.setCodeActionProvider(new CodeActionOptions(Arrays.asList(CodeActionKind.QuickFix)));
return capabilities;
}
@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();
}
@Before
public void setup() throws Exception {
fJProject1 = newEmptyProject();
Hashtable<String, String> options = TestOptions.getDefaultOptions();
fJProject1.setOptions(options);
fSourceFolder = fJProject1.getPackageFragmentRoot(fJProject1.getProject().getFolder("src"));
setOnly(CodeActionKind.Refactor);
}
private void checkRetrievedCodeAction(TextDocumentIdentifier textDocumentIdentifier, Diagnostic diagnostic, CompletableFuture<List<Either<Command, CodeAction>>> codeActions)
throws InterruptedException, ExecutionException {
assertThat(codeActions.get()).hasSize(1);
CodeAction codeAction = codeActions.get().get(0).getRight();
assertThat(codeAction.getDiagnostics()).containsOnly(diagnostic);
assertThat(codeAction.getKind()).isEqualTo(CodeActionKind.QuickFix);
List<TextEdit> createdChanges = codeAction.getEdit().getChanges().get(textDocumentIdentifier.getUri());
assertThat(createdChanges).isNotEmpty();
TextEdit textEdit = createdChanges.get(0);
Range range = textEdit.getRange();
new RangeChecker().check(range, 9, 33, 9, 37);
assertThat(textEdit.getNewText()).isEqualTo("delay");
}
@Test
public void testInlineLocalVariable() throws Exception {
IPackageFragment pack1 = testSourceFolder.createPackageFragment("test", false, null);
StringBuilder buf = new StringBuilder();
buf.append("package test;\n");
buf.append("public class E {\n");
buf.append(" public void foo(String[] parameters, int j) {\n");
buf.append(" int /*]*/temp/*[*/ = parameters.length + j;\n");
buf.append(" int temp1 = temp;\n");
buf.append(" System.out.println(temp);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu = pack1.createCompilationUnit("E.java", buf.toString(), false, null);
buf = new StringBuilder();
buf.append("package test;\n");
buf.append("public class E {\n");
buf.append(" public void foo(String[] parameters, int j) {\n");
buf.append(" int temp1 = parameters.length + j;\n");
buf.append(" System.out.println(parameters.length + j);\n");
buf.append(" }\n");
buf.append("}\n");
Expected expected = new Expected(INLINE_LOCAL_VARIABLE, buf.toString(), CodeActionKind.RefactorInline);
assertCodeActions(cu, expected);
}
@Before
public void setup() throws Exception {
fJProject1 = newEmptyProject();
Hashtable<String, String> options = TestOptions.getDefaultOptions();
fJProject1.setOptions(options);
fSourceFolder = fJProject1.getPackageFragmentRoot(fJProject1.getProject().getFolder("src"));
this.setOnly(CodeActionKind.Source);
this.setIgnoredKind(new String[0]);
}
@Test
public void testCombinedConditionWithPartialSelection2() throws Exception {
IPackageFragment pack1 = testSourceFolder.createPackageFragment("test", false, null);
StringBuilder buf = new StringBuilder();
buf.append("package test;\n");
buf.append("public class E {\n");
buf.append(" public boolean isValid() {\n");
buf.append(" return true;\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" if (isValid() || 3 < 5)\n");
buf.append(" return;\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu = pack1.createCompilationUnit("E.java", buf.toString(), false, null);
buf = new StringBuilder();
buf.append("package test;\n");
buf.append("public class E {\n");
buf.append(" public boolean isValid() {\n");
buf.append(" return true;\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" if (isValid() || 3 >= 5)\n");
buf.append(" return;\n");
buf.append(" }\n");
buf.append("}\n");
Expected expected = new Expected("Invert conditions", buf.toString(), CodeActionKind.Refactor);
Range replacedRange = CodeActionUtil.getRange(cu, "3 < 5", "3 < 5".length());
assertCodeActions(cu, replacedRange, expected);
}