org.eclipse.lsp4j.CodeActionContext Java Examples

The following examples show how to use org.eclipse.lsp4j.CodeActionContext. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CodeActionHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@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());
}
 
Example #2
Source File: SourceAssistProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
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));
	}
}
 
Example #3
Source File: SourceAssistProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
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);
}
 
Example #4
Source File: CodeActionHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@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());
}
 
Example #5
Source File: CodeActionHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@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));
	}
}
 
Example #6
Source File: CodeActionAcceptor.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
/** 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));
}
 
Example #7
Source File: CodeActionHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@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));
	}
}
 
Example #8
Source File: CodeActionHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@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));
	}
}
 
Example #9
Source File: UnknownPropertyQuickfixTest.java    From camel-language-server with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #10
Source File: UnknownPropertyQuickfixTest.java    From camel-language-server with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #11
Source File: CodeActionHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@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();
	}
}
 
Example #12
Source File: DocumentLifeCycleHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
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());
	}
 
Example #13
Source File: MavenJavaDiagnosticsMicroProfileHealthTest.java    From intellij-quarkus with Eclipse Public License 2.0 5 votes vote down vote up
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;
}
 
Example #14
Source File: CodeActionHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@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));
}
 
Example #15
Source File: CodeActionHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@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));
	}
}
 
Example #16
Source File: CodeActionHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@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());
}
 
Example #17
Source File: CodeActionHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@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));
}
 
Example #18
Source File: CodeActionHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void test_filterTypes() throws Exception {
	//@formatter:off
	ICompilationUnit unit = getWorkingCopy(
			"src/org/sample/Foo.java",
			"package org.sample;\n"+
			"\n"+
			"public class Foo {\n"+
			"	List foo;\n"+
			"}\n");
	//@formatter:on
	CodeActionParams params = new CodeActionParams();
	params.setTextDocument(new TextDocumentIdentifier(JDTUtils.toURI(unit)));
	final Range range = CodeActionUtil.getRange(unit, "List");
	params.setRange(range);
	params.setContext(new CodeActionContext(Collections.emptyList()));
	List<Either<Command, CodeAction>> codeActions = getCodeActions(params);
	Assert.assertNotNull(codeActions);
	Assert.assertTrue("No organize imports action", containsKind(codeActions, CodeActionKind.SourceOrganizeImports));
	try {
		List<String> filteredTypes = new ArrayList<>();
		filteredTypes.add("java.util.*");
		PreferenceManager.getPrefs(null).setFilteredTypes(filteredTypes);
		codeActions = getCodeActions(params);
		assertNotNull(codeActions);
		Assert.assertFalse("No need for organize imports action", containsKind(codeActions, CodeActionKind.SourceOrganizeImports));
	} finally {
		PreferenceManager.getPrefs(null).setFilteredTypes(Collections.emptyList());
	}
}
 
Example #19
Source File: NonProjectFixTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private List<Either<Command, CodeAction>> getCodeActions(ICompilationUnit cu, IProblem problem) throws JavaModelException {		
	CodeActionParams parms = new CodeActionParams();
	Range range = JDTUtils.toRange(cu, problem.getSourceStart(), 0);

	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(problem), true));
	context.setOnly(Arrays.asList(CodeActionKind.QuickFix));
	parms.setContext(context);

	return new CodeActionHandler(this.preferenceManager).getCodeActionCommands(parms, new NullProgressMonitor());
}
 
Example #20
Source File: CodeActionUtil.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
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;
}
 
Example #21
Source File: LanguageClientImpl.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example #22
Source File: CodeActions.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@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();
    }
}
 
Example #23
Source File: N4JSCodeActionService.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
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;
}
 
Example #24
Source File: QuickfixContext.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * 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;
}
 
Example #25
Source File: AbstractOrganizeImportsTest.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
@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);
}
 
Example #26
Source File: AbstractCodeActionTest.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
@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());
	}
}
 
Example #27
Source File: InvalidEnumQuickfixTest.java    From camel-language-server with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #28
Source File: UnknownPropertyQuickfixTest.java    From camel-language-server with Apache License 2.0 5 votes vote down vote up
@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();
}
 
Example #29
Source File: UnknownPropertyQuickfixTest.java    From camel-language-server with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #30
Source File: UnknownPropertyQuickfixTest.java    From camel-language-server with Apache License 2.0 5 votes vote down vote up
@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);
}