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 Project: lsp4intellij   Author: ballerina-platform   File: EditorEventManager.java    License: 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 #2
Source Project: eclipse.jdt.ls   Author: eclipse   File: CodeActionHandlerTest.java    License: 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 #3
Source Project: intellij-quarkus   Author: redhat-developer   File: CommandExecutor.java    License: 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 #4
Source Project: camel-language-server   Author: camel-tooling   File: AbstractQuickfix.java    License: 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 #5
Source Project: camel-language-server   Author: camel-tooling   File: UnknownPropertyQuickfixTest.java    License: 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 #6
Source Project: vscode-as3mxml   Author: BowlerHatLLC   File: CodeActionProvider.java    License: 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 #7
Source Project: n4js   Author: eclipse   File: N4JSCodeActionService.java    License: 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 #8
Source Project: n4js   Author: eclipse   File: CodeActionAcceptor.java    License: 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 #9
Source Project: eclipse.jdt.ls   Author: eclipse   File: CodeActionHandlerTest.java    License: 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 #10
Source Project: eclipse.jdt.ls   Author: eclipse   File: RedundantInterfaceQuickFixTest.java    License: 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 #11
Source Project: eclipse.jdt.ls   Author: eclipse   File: GenerateConstructorsActionTest.java    License: 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 #12
Source Project: eclipse.jdt.ls   Author: eclipse   File: ReorgQuickFixTest.java    License: 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 #13
Source Project: eclipse.jdt.ls   Author: eclipse   File: SourceAssistProcessor.java    License: 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 #14
Source Project: eclipse.jdt.ls   Author: eclipse   File: SourceAssistProcessor.java    License: 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 Project: eclipse.jdt.ls   Author: eclipse   File: CodeActionHandlerTest.java    License: 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 #16
Source Project: eclipse.jdt.ls   Author: eclipse   File: GenerateConstructorsActionTest.java    License: 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 #17
Source Project: eclipse.jdt.ls   Author: eclipse   File: GenerateToStringActionTest.java    License: 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 #18
Source Project: intellij-quarkus   Author: redhat-developer   File: CommandExecutor.java    License: 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 #19
Source Project: intellij-quarkus   Author: redhat-developer   File: CommandExecutor.java    License: 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 #20
Source Project: intellij-quarkus   Author: redhat-developer   File: CommandExecutor.java    License: 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 #21
Source Project: lemminx   Author: eclipse   File: InvalidPathWarner.java    License: Eclipse Public License 2.0 5 votes vote down vote up
private void sendInvalidFilePathWarning(Set<String> invalidPaths, PathFeature feature) {
	String message = createWarningMessage(feature.getSettingId(), invalidPaths);

	Command command = new Command("Configure setting", ClientCommands.OPEN_SETTINGS,
				Collections.singletonList(feature.getSettingId()));

	super.sendNotification(message, MessageType.Error, command);
}
 
Example #22
Source Project: eclipse.jdt.ls   Author: eclipse   File: MissingEnumQuickFixTest.java    License: Eclipse Public License 2.0 5 votes vote down vote up
private TextEdit getTextEdit(Either<Command, CodeAction> codeAction) {
	Command c = codeAction.isLeft() ? codeAction.getLeft() : codeAction.getRight().getCommand();
	Assert.assertEquals(CodeActionHandler.COMMAND_ID_APPLY_EDIT, c.getCommand());
	Assert.assertNotNull(c.getArguments());
	Assert.assertTrue(c.getArguments().get(0) instanceof WorkspaceEdit);
	WorkspaceEdit we = (WorkspaceEdit) c.getArguments().get(0);
	Iterator<Entry<String, List<TextEdit>>> editEntries = we.getChanges().entrySet().iterator();
	Entry<String, List<TextEdit>> entry = editEntries.next();
	TextEdit edit = entry.getValue().get(0);
	return edit;
}
 
Example #23
Source Project: eclipse.jdt.ls   Author: eclipse   File: GenerateToStringActionTest.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testGenerateToStringDisabled_interface() throws JavaModelException {
	//@formatter:off
	ICompilationUnit unit = fPackageP.createCompilationUnit("A.java", "package p;\r\n" +
			"\r\n" +
			"public interface A {\r\n" +
			"	public final String name = \"test\";\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);
	Assert.assertFalse("The operation is not applicable to interfaces", CodeActionHandlerTest.containsKind(codeActions, JavaCodeActionKind.SOURCE_GENERATE_TO_STRING));
}
 
Example #24
Source Project: camel-language-server   Author: camel-tooling   File: UnknownPropertyQuickfixTest.java    License: 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 #25
Source Project: eclipse.jdt.ls   Author: eclipse   File: AssignToVariableRefactorTest.java    License: Eclipse Public License 2.0 5 votes vote down vote up
private void testAssignField(ICompilationUnit cu, Range range) throws JavaModelException {
	List<Either<Command, CodeAction>> codeActions = evaluateCodeActions(cu, range);
	assertEquals(1, codeActions.size());
	Either<Command, CodeAction> codeAction = codeActions.get(0);
	CodeAction action = codeAction.getRight();
	assertEquals(JavaCodeActionKind.REFACTOR_ASSIGN_FIELD, action.getKind());
	assertEquals("Assign statement to new field", action.getTitle());
	Command c = action.getCommand();
	assertEquals(RefactorProposalUtility.APPLY_REFACTORING_COMMAND_ID, c.getCommand());
	assertNotNull(c.getArguments());
	assertEquals(RefactorProposalUtility.ASSIGN_FIELD_COMMAND, c.getArguments().get(0));
}
 
Example #26
Source Project: eclipse.jdt.ls   Author: eclipse   File: AbstractQuickFixTest.java    License: Eclipse Public License 2.0 5 votes vote down vote up
protected void assertCodeActionExists(ICompilationUnit cu, Expected expected) throws Exception {
	List<Either<Command, CodeAction>> codeActions = evaluateCodeActions(cu);
	for (Either<Command, CodeAction> c : codeActions) {
		if (Objects.equals(expected.name, getTitle(c))) {
			expected.assertEquivalent(c);
			return;
		}
	}
	String allCommands = codeActions.stream().map(a -> getTitle(a)).collect(Collectors.joining("\n"));
	fail(expected.name + " not found in " + allCommands);
}
 
Example #27
Source Project: camel-language-server   Author: camel-tooling   File: InvalidEnumQuickfixTest.java    License: Apache License 2.0 5 votes vote down vote up
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, 49, 9, 54);
	assertThat(textEdit.getNewText()).isEqualTo("InOnly");
}
 
Example #28
Source Project: n4js   Author: eclipse   File: AbstractCodeActionTest.java    License: 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 #29
Source Project: n4js   Author: eclipse   File: StringLSP4J.java    License: Eclipse Public License 1.0 5 votes vote down vote up
/** @return string for given element */
public String toString(Command command) {
	if (command == null) {
		return "";
	}
	List<Object> argumentsRelativized = command.getArguments().stream()
			.map(this::relativizeIfURIString)
			.collect(Collectors.toList());
	String str = Strings.join(", ",
			command.getTitle(),
			command.getCommand(),
			Strings.toString(argumentsRelativized));

	return "(" + str + ")";
}
 
Example #30
Source Project: eclipse.jdt.ls   Author: eclipse   File: CodeActionHandlerTest.java    License: 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());
	}
}