org.eclipse.lsp4j.Command Java Examples

The following examples show how to use org.eclipse.lsp4j.Command. 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: ReorgQuickFixTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testWrongDefaultPackageStatement() throws Exception {
	IPackageFragment pack1 = fSourceFolder.createPackageFragment("test2", false, null);
	StringBuilder buf = new StringBuilder();
	buf.append("public class E {\n");
	buf.append("}\n");
	ICompilationUnit cu = pack1.createCompilationUnit("E.java", buf.toString(), false, null);
	List<Either<Command, CodeAction>> codeActions = evaluateCodeActions(cu);

	Either<Command, CodeAction> codeAction = findAction(codeActions, "Add package declaration 'test2;'");
	assertNotNull(codeAction);
	buf = new StringBuilder();
	buf.append("package test2;\n");
	buf.append("\n");
	buf.append("public class E {\n");
	buf.append("}\n");
	assertEquals(buf.toString(), evaluateCodeActionCommand(codeAction));

	codeAction = findAction(codeActions, "Move 'E.java' to the default package");
	assertNotNull(codeAction);
	assertRenameFileOperation(codeAction, ResourceUtils.fixURI(pack1.getResource().getRawLocation().append("../E.java").toFile().toURI()));
}
 
Example #2
Source File: EditorEventManager.java    From lsp4intellij with Apache License 2.0 6 votes vote down vote up
/**
 * Sends commands to execute to the server and applies the changes returned if the future returns a WorkspaceEdit
 *
 * @param commands The commands to execute
 */
public void executeCommands(List<Command> commands) {
    pool(() -> {
        if (editor.isDisposed()) {
            return;
        }
        commands.stream().map(c -> {
            ExecuteCommandParams params = new ExecuteCommandParams();
            params.setArguments(c.getArguments());
            params.setCommand(c.getCommand());
            return requestManager.executeCommand(params);
        }).filter(Objects::nonNull).forEach(f -> {
            try {
                f.get(getTimeout(EXECUTE_COMMAND), TimeUnit.MILLISECONDS);
                wrapper.notifySuccess(Timeouts.EXECUTE_COMMAND);
            } catch (TimeoutException te) {
                LOG.warn(te);
                wrapper.notifyFailure(Timeouts.EXECUTE_COMMAND);
            } catch (JsonRpcException | ExecutionException | InterruptedException e) {
                LOG.warn(e);
                wrapper.crashed(e);
            }
        });
    });
}
 
Example #3
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 #4
Source File: CommandExecutor.java    From intellij-quarkus with Eclipse Public License 2.0 6 votes vote down vote up
private static DataContext createDataContext(Command command, URI context,
                                                    Application workbench) {

    return new DataContext() {
        @Nullable
        @Override
        public Object getData(@NotNull String dataId) {
            if (LSP_COMMAND_PARAMETER_TYPE_ID.equals(dataId)) {
                return command;
            } else if (LSP_PATH_PARAMETER_TYPE_ID.equals(dataId)) {
                return context;
            }
            return null;
        }
    };
}
 
Example #5
Source File: GenerateConstructorsActionTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testGenerateConstructorsEnabled() throws JavaModelException {
	//@formatter:off
	ICompilationUnit unit = fPackageP.createCompilationUnit("A.java", "package p;\r\n" +
			"\r\n" +
			"public class A {\r\n" +
			"	String name;\r\n" +
			"}"
			, true, null);
	//@formatter:on
	CodeActionParams params = CodeActionUtil.constructCodeActionParams(unit, "String name");
	List<Either<Command, CodeAction>> codeActions = server.codeAction(params).join();
	Assert.assertNotNull(codeActions);
	Either<Command, CodeAction> constructorAction = CodeActionHandlerTest.findAction(codeActions, JavaCodeActionKind.SOURCE_GENERATE_CONSTRUCTORS);
	Assert.assertNotNull(constructorAction);
	Command constructorCommand = CodeActionHandlerTest.getCommand(constructorAction);
	Assert.assertNotNull(constructorCommand);
	Assert.assertEquals(SourceAssistProcessor.COMMAND_ID_ACTION_GENERATECONSTRUCTORSPROMPT, constructorCommand.getCommand());
}
 
Example #6
Source File: AbstractQuickfix.java    From camel-language-server with Apache License 2.0 6 votes vote down vote up
public List<Either<Command, CodeAction>> apply(CodeActionParams params) {
	TextDocumentItem openedDocument = camelTextDocumentService.getOpenedDocument(params.getTextDocument().getUri());
	List<Diagnostic> diagnostics = params.getContext().getDiagnostics();
	List<Either<Command, CodeAction>> res = new ArrayList<>();
	for(Diagnostic diagnostic : diagnostics) {
		if(diagnostic.getCode()!= null && getDiagnosticId().equals(diagnostic.getCode().getLeft())) {
			CharSequence currentValueInError = retrieveCurrentErrorValue(openedDocument, diagnostic);
			if(currentValueInError != null) {
				List<String> possibleProperties = retrievePossibleValues(openedDocument, camelTextDocumentService.getCamelCatalog(), diagnostic.getRange().getStart());
				int distanceThreshold = Math.round(currentValueInError.length() * 0.4f);
				LevenshteinDistance levenshteinDistance = new LevenshteinDistance(distanceThreshold);
				List<String> mostProbableProperties = possibleProperties.stream()
						.filter(possibleProperty -> levenshteinDistance.apply(possibleProperty, currentValueInError) != -1)
						.collect(Collectors.toList());
				for (String mostProbableProperty : mostProbableProperties) {
					res.add(Either.forRight(createCodeAction(params, diagnostic, mostProbableProperty)));
				}
			}
		}
	}
	return res;
}
 
Example #7
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 #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_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 #9
Source File: CodeActionProvider.java    From vscode-as3mxml with Apache License 2.0 6 votes vote down vote up
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));
}
 
Example #10
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 #11
Source File: GenerateToStringActionTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testGenerateToStringEnabled() throws JavaModelException {
	//@formatter:off
	ICompilationUnit unit = fPackageP.createCompilationUnit("A.java", "package p;\r\n" +
			"\r\n" +
			"public class A {\r\n" +
			"	String name;\r\n" +
			"}"
			, true, null);
	//@formatter:on
	CodeActionParams params = CodeActionUtil.constructCodeActionParams(unit, "String name");
	List<Either<Command, CodeAction>> codeActions = server.codeAction(params).join();
	Assert.assertNotNull(codeActions);
	Either<Command, CodeAction> toStringAction = CodeActionHandlerTest.findAction(codeActions, JavaCodeActionKind.SOURCE_GENERATE_TO_STRING);
	Assert.assertNotNull(toStringAction);
	Command toStringCommand = CodeActionHandlerTest.getCommand(toStringAction);
	Assert.assertNotNull(toStringCommand);
	Assert.assertEquals(SourceAssistProcessor.COMMAND_ID_ACTION_GENERATETOSTRINGPROMPT, toStringCommand.getCommand());
}
 
Example #12
Source File: GenerateConstructorsActionTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testGenerateConstructorsDisabled_anonymous() throws JavaModelException {
	//@formatter:off
	ICompilationUnit unit = fPackageP.createCompilationUnit("A.java", "package p;\r\n" +
			"\r\n" +
			"public class A {\r\n" +
			"	public Runnable getRunnable() {\r\n" +
			"		return new Runnable() {\r\n" +
			"			@Override\r\n" +
			"			public void run() {\r\n" +
			"			}\r\n" +
			"		};\r\n" +
			"	}\r\n" +
			"}"
			, true, null);
	//@formatter:on
	CodeActionParams params = CodeActionUtil.constructCodeActionParams(unit, "run()");
	List<Either<Command, CodeAction>> codeActions = server.codeAction(params).join();
	Assert.assertNotNull(codeActions);
	Assert.assertFalse("The operation is not applicable to anonymous", CodeActionHandlerTest.containsKind(codeActions, JavaCodeActionKind.SOURCE_GENERATE_CONSTRUCTORS));
}
 
Example #13
Source File: RedundantInterfaceQuickFixTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testIgnoreRedundantSuperinterface() throws Exception {
	Map<String, String> testProjectOptions = fJProject.getOptions(false);
	testProjectOptions.put(JavaCore.COMPILER_PB_REDUNDANT_SUPERINTERFACE, JavaCore.IGNORE);
	fJProject.setOptions(testProjectOptions);
	IPackageFragment pack = fSourceFolder.createPackageFragment("test", false, null);
	StringBuilder buf = new StringBuilder();
	buf.append("package test;\n");
	buf.append("public class RedundantInterface implements Int1, Int2 {}\n");
	buf.append("interface Int1 {}\n");
	buf.append("interface Int2 extends Int1 {}\n");
	ICompilationUnit cu = pack.createCompilationUnit("RedundantInterface.java", buf.toString(), true, null);
	Range selection = new Range(new Position(1, 45), new Position(1, 45));
	setIgnoredCommands(ActionMessages.GenerateConstructorsAction_ellipsisLabel, ActionMessages.GenerateConstructorsAction_label);
	List<Either<Command, CodeAction>> codeActions = evaluateCodeActions(cu, selection);
	assertEquals(0, codeActions.size());
}
 
Example #14
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>> getGetterSetterAction(CodeActionParams params, IInvocationContext context, IType type) {
	try {
		AccessorField[] accessors = GenerateGetterSetterOperation.getUnimplementedAccessors(type);
		if (accessors == null || accessors.length == 0) {
			return Optional.empty();
		} else if (accessors.length == 1 || !preferenceManager.getClientPreferences().isAdvancedGenerateAccessorsSupported()) {
			GenerateGetterSetterOperation operation = new GenerateGetterSetterOperation(type, context.getASTRoot(), preferenceManager.getPreferences().isCodeGenerationTemplateGenerateComments());
			TextEdit edit = operation.createTextEdit(null, accessors);
			return convertToWorkspaceEditAction(params.getContext(), context.getCompilationUnit(), ActionMessages.GenerateGetterSetterAction_label, JavaCodeActionKind.SOURCE_GENERATE_ACCESSORS, edit);
		} else {
			Command command = new Command(ActionMessages.GenerateGetterSetterAction_ellipsisLabel, COMMAND_ID_ACTION_GENERATEACCESSORSPROMPT, Collections.singletonList(params));
			if (preferenceManager.getClientPreferences().isSupportedCodeActionKind(JavaCodeActionKind.SOURCE_GENERATE_ACCESSORS)) {
				CodeAction codeAction = new CodeAction(ActionMessages.GenerateGetterSetterAction_ellipsisLabel);
				codeAction.setKind(JavaCodeActionKind.SOURCE_GENERATE_ACCESSORS);
				codeAction.setCommand(command);
				codeAction.setDiagnostics(Collections.EMPTY_LIST);
				return Optional.of(Either.forRight(codeAction));
			} else {
				return Optional.of(Either.forLeft(command));
			}
		}
	} catch (OperationCanceledException | CoreException e) {
		JavaLanguageServerPlugin.logException("Failed to generate Getter and Setter source action", e);
		return Optional.empty();
	}
}
 
Example #15
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 #16
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>> getOverrideMethodsAction(CodeActionParams params) {
	if (!preferenceManager.getClientPreferences().isOverrideMethodsPromptSupported()) {
		return Optional.empty();
	}

	Command command = new Command(ActionMessages.OverrideMethodsAction_label, COMMAND_ID_ACTION_OVERRIDEMETHODSPROMPT, Collections.singletonList(params));
	if (preferenceManager.getClientPreferences().isSupportedCodeActionKind(JavaCodeActionKind.SOURCE_OVERRIDE_METHODS)) {
		CodeAction codeAction = new CodeAction(ActionMessages.OverrideMethodsAction_label);
		codeAction.setKind(JavaCodeActionKind.SOURCE_OVERRIDE_METHODS);
		codeAction.setCommand(command);
		codeAction.setDiagnostics(Collections.EMPTY_LIST);
		return Optional.of(Either.forRight(codeAction));
	} else {
		return Optional.of(Either.forLeft(command));
	}
}
 
Example #17
Source File: N4JSCodeActionService.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public List<Either<Command, CodeAction>> getCodeActions(Options options) {
	CodeActionAcceptor acceptor = new CodeActionAcceptor();

	List<Diagnostic> diagnostics = null;
	if (options.getCodeActionParams() != null && options.getCodeActionParams().getContext() != null) {
		diagnostics = options.getCodeActionParams().getContext().getDiagnostics();
	}
	if (diagnostics == null) {
		diagnostics = Collections.emptyList();
	}

	for (Diagnostic diag : diagnostics) {
		cancelManager.checkCanceled(options.getCancelIndicator());
		findQuickfixes(diag.getCode(), options, acceptor);
	}

	findSourceActions(options, acceptor);

	cancelManager.checkCanceled(options.getCancelIndicator());
	return acceptor.getList();
}
 
Example #18
Source File: AbstractQuickFixTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
protected List<Either<Command, CodeAction>> evaluateCodeActions(ICompilationUnit cu) throws JavaModelException {

		CompilationUnit astRoot = CoreASTProvider.getInstance().getAST(cu, CoreASTProvider.WAIT_YES, null);
		IProblem[] problems = astRoot.getProblems();

		Range range = getRange(cu, problems);
		return evaluateCodeActions(cu, range);
	}
 
Example #19
Source File: CommandExecutor.java    From intellij-quarkus with Eclipse Public License 2.0 5 votes vote down vote up
private static CompletableFuture<LanguageServer> getLanguageServerForCommand(Project project,
                                                                             Command command,
                                                                             Document document, LanguageServersRegistry.LanguageServerDefinition languageServerDefinition) throws IOException {
    CompletableFuture<LanguageServer> languageServerFuture = LanguageServiceAccessor.getInstance(project)
            .getInitializedLanguageServer(document, languageServerDefinition, serverCapabilities -> {
                ExecuteCommandOptions provider = serverCapabilities.getExecuteCommandProvider();
                return provider != null && provider.getCommands().contains(command.getCommand());
            });
    return languageServerFuture;
}
 
Example #20
Source File: AbstractQuickFixTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Checks if the action has the same title as this. If it has, then assert that
 * that action is equivalent to this in kind and content.
 */
public void assertEquivalent(Either<Command, CodeAction> action) throws Exception {
	String title = getTitle(action);
	assertEquals("Unexpected command :", name, title);
	if (!ALL_KINDS.equals(kind) && action.isRight()) {
		assertEquals(title + " has the wrong kind ", kind, action.getRight().getKind());
	}
	String actionContent = evaluateCodeActionCommand(action);
	assertEquals(title + " has the wrong content ", content, actionContent);
}
 
Example #21
Source File: CodeLensHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testResolveImplementationsCodeLens() {
	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
	Position p = (Position) args.get(1);
	assertEquals(5, p.getLine());
	assertEquals(17, p.getCharacter());

	//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());
}
 
Example #22
Source File: SourceAssistProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private Optional<Either<Command, CodeAction>> getOrganizeImportsAction(CodeActionParams params) {
	Command command = new Command(CorrectionMessages.ReorgCorrectionsSubProcessor_organizeimports_description, COMMAND_ID_ACTION_ORGANIZEIMPORTS, Collections.singletonList(params));
	CodeAction codeAction = new CodeAction(CorrectionMessages.ReorgCorrectionsSubProcessor_organizeimports_description);
	codeAction.setKind(CodeActionKind.SourceOrganizeImports);
	codeAction.setCommand(command);
	codeAction.setDiagnostics(Collections.EMPTY_LIST);
	return Optional.of(Either.forRight(codeAction));

}
 
Example #23
Source File: RLSRunCommandTest.java    From corrosion with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testMapEntryArgument() {
	Map<String, Object> argument = createArgument(binary, arguments, environment);
	Command command = new Command(TITLE, COMMAND_ID, Arrays.asList(argument));
	Optional<RLSRunCommand> lspCommand = RLSRunCommand.fromLSPCommand(command);
	assertFalse(lspCommand.isPresent());
}
 
Example #24
Source File: JSONCodeActionService.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
private Command createInstallNpmCommand(Options options, Diagnostic diag) {
	EObject element = getEObject(options, diag);
	if (element instanceof NameValuePair) {
		NameValuePair pair = (NameValuePair) element;
		String projectName = pair.getName();
		String version = JSONModelUtils.asStringOrNull(pair.getValue());
		return new Command("Install npm package to workspace", INSTALL_NPM,
				Arrays.asList(projectName, version, options.getCodeActionParams().getTextDocument().getUri()));
	}
	return null;
}
 
Example #25
Source File: SourceAssistProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private Optional<Either<Command, CodeAction>> getHashCodeEqualsAction(CodeActionParams params) {
	if (!preferenceManager.getClientPreferences().isHashCodeEqualsPromptSupported()) {
		return Optional.empty();
	}
	Command command = new Command(ActionMessages.GenerateHashCodeEqualsAction_label, COMMAND_ID_ACTION_HASHCODEEQUALSPROMPT, Collections.singletonList(params));
	if (preferenceManager.getClientPreferences().isSupportedCodeActionKind(JavaCodeActionKind.SOURCE_GENERATE_HASHCODE_EQUALS)) {
		CodeAction codeAction = new CodeAction(ActionMessages.GenerateHashCodeEqualsAction_label);
		codeAction.setKind(JavaCodeActionKind.SOURCE_GENERATE_HASHCODE_EQUALS);
		codeAction.setCommand(command);
		codeAction.setDiagnostics(Collections.EMPTY_LIST);
		return Optional.of(Either.forRight(codeAction));
	} else {
		return Optional.of(Either.forLeft(command));
	}
}
 
Example #26
Source File: CommandExecutor.java    From intellij-quarkus with Eclipse Public License 2.0 5 votes vote down vote up
@SuppressWarnings("unused") // ECJ compiler for some reason thinks handlerService == null is always false
private static boolean executeCommandClientSide(Command command, Document document) {
    Application workbench = ApplicationManager.getApplication();
    if (workbench == null) {
        return false;
    }
    URI context = LSPIJUtils.toUri(document);
    AnAction parameterizedCommand = createEclipseCoreCommand(command, context, workbench);
    if (parameterizedCommand == null) {
        return false;
    }
    DataContext dataContext = createDataContext(command, context, workbench);
    ActionUtil.invokeAction(parameterizedCommand, dataContext, ActionPlaces.UNKNOWN, null, null);
    return true;
}
 
Example #27
Source File: CommandExecutor.java    From intellij-quarkus with Eclipse Public License 2.0 5 votes vote down vote up
private static AnAction createEclipseCoreCommand(Command command, URI context,
                                                             Application workbench) {
    // Usually commands are defined via extension point, but we synthesize one on
    // the fly for the command ID, since we do not want downstream users
    // having to define them.
    String commandId = command.getCommand();
    return ActionManager.getInstance().getAction(commandId);
}
 
Example #28
Source File: SourceAssistProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private Optional<Either<Command, CodeAction>> getGenerateConstructorsAction(CodeActionParams params, IInvocationContext context, IType type, String kind) {
	try {
		if (type == null || type.isAnnotation() || type.isInterface() || type.isAnonymous() || type.getCompilationUnit() == null) {
			return Optional.empty();
		}
	} catch (JavaModelException e) {
		return Optional.empty();
	}

	if (preferenceManager.getClientPreferences().isGenerateConstructorsPromptSupported()) {
		CheckConstructorsResponse status = GenerateConstructorsHandler.checkConstructorStatus(type);
		if (status.constructors.length == 0) {
			return Optional.empty();
		}
		if (status.constructors.length == 1 && status.fields.length == 0) {
			TextEdit edit = GenerateConstructorsHandler.generateConstructors(type, status.constructors, status.fields);
			return convertToWorkspaceEditAction(params.getContext(), type.getCompilationUnit(), ActionMessages.GenerateConstructorsAction_label, kind, edit);
		}

		Command command = new Command(ActionMessages.GenerateConstructorsAction_ellipsisLabel, COMMAND_ID_ACTION_GENERATECONSTRUCTORSPROMPT, Collections.singletonList(params));
		if (preferenceManager.getClientPreferences().isSupportedCodeActionKind(JavaCodeActionKind.SOURCE_GENERATE_CONSTRUCTORS)) {
			CodeAction codeAction = new CodeAction(ActionMessages.GenerateConstructorsAction_ellipsisLabel);
			codeAction.setKind(kind);
			codeAction.setCommand(command);
			codeAction.setDiagnostics(Collections.emptyList());
			return Optional.of(Either.forRight(codeAction));
		} else {
			return Optional.of(Either.forLeft(command));
		}
	}

	return Optional.empty();
}
 
Example #29
Source File: GenerateAccessorsActionTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testGenerateAccessorsDisabled_emptyFields() throws JavaModelException {
	//@formatter:off
	ICompilationUnit unit = fPackageP.createCompilationUnit("A.java", "package p;\r\n" +
			"\r\n" +
			"public class A {\r\n" +
			"}"
			, true, null);
	//@formatter:on
	CodeActionParams params = CodeActionUtil.constructCodeActionParams(unit, "class A");
	List<Either<Command, CodeAction>> codeActions = server.codeAction(params).join();
	Assert.assertNotNull(codeActions);
	Either<Command, CodeAction> generateAccessorsAction = CodeActionHandlerTest.findAction(codeActions, JavaCodeActionKind.SOURCE_GENERATE_ACCESSORS);
	Assert.assertNull(generateAccessorsAction);
}
 
Example #30
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();
    }
}