org.eclipse.lsp4j.CodeAction Java Examples

The following examples show how to use org.eclipse.lsp4j.CodeAction. 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_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 #2
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 #3
Source File: cvc_complex_type_2_1CodeAction.java    From lemminx with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void doCodeAction(Diagnostic diagnostic, Range range, DOMDocument document, List<CodeAction> codeActions,
		SharedSettings sharedSettings, IComponentProvider componentProvider) {
	try {
		int offset = document.offsetAt(range.getStart());
		DOMNode node = document.findNodeAt(offset);
		if (node != null && node.isElement()) {
			DOMElement element = (DOMElement) node;
			int startOffset;
			if(element.isSelfClosed()) {
				startOffset = element.getEnd();
			}
			else {
				startOffset = element.getStartTagCloseOffset();
			}
			int endOffset = element.getEnd();
			Range diagnosticRange = XMLPositionUtility.createRange(startOffset, endOffset, document);
			CodeAction removeContentAction = CodeActionFactory.replace("Set element as empty", diagnosticRange,
					"/>", document.getTextDocument(), diagnostic);
			codeActions.add(removeContentAction);
		}

	} catch (BadLocationException e) {
		// Do nothing
	}
}
 
Example #4
Source File: EqRequiredInAttributeCodeAction.java    From lemminx with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void doCodeAction(Diagnostic diagnostic, Range range, DOMDocument document, List<CodeAction> codeActions,
		SharedSettings sharedSettings, IComponentProvider componentProvider) {
	Range diagnosticRange = diagnostic.getRange();

	// Insert =""
	try {
		int offset = document.offsetAt(range.getStart());
		DOMNode node = document.findNodeAt(offset);
		if (node != null && node.isElement()) {
			String tagName = ((DOMElement) node).getTagName();
			if (tagName != null) {
				String insertText = "=\"\"";
				CodeAction insertEqualsAndQuotesAction = CodeActionFactory.insert("Insert '" + insertText + "'",
						diagnosticRange.getEnd(), insertText, document.getTextDocument(), diagnostic);
				codeActions.add(insertEqualsAndQuotesAction);
			}
		}
	} catch (BadLocationException e) {
		// do nothing
	}
}
 
Example #5
Source File: cvc_complex_type_3_2_2CodeAction.java    From lemminx with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void doCodeAction(Diagnostic diagnostic, Range range, DOMDocument document, List<CodeAction> codeActions,
		SharedSettings sharedSettings, IComponentProvider componentProvider) {
	Range diagnosticRange = diagnostic.getRange();
	try {
		int offset = document.offsetAt(diagnosticRange.getEnd());
		DOMAttr attr = document.findAttrAt(offset);
		if (attr != null) {
			// Remove attribute
			int startOffset = attr.getStart();
			int endOffset = attr.getEnd();
			Range attrRange = new Range(document.positionAt(startOffset), document.positionAt(endOffset));
			CodeAction removeAttributeAction = CodeActionFactory.remove("Remove '" + attr.getName() + "' attribute",
					attrRange, document.getTextDocument(), diagnostic);
			codeActions.add(removeAttributeAction);
		}
	} catch (BadLocationException e) {
		// Do nothing
	}
}
 
Example #6
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 #7
Source File: ReorgQuickFixTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testWrongPackageStatementFromDefault() throws Exception {
	IPackageFragment pack1 = fSourceFolder.createPackageFragment("", false, null);
	StringBuilder buf = new StringBuilder();
	buf.append("package test2;\n");
	buf.append("\n");
	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, "Remove package declaration 'package test2'");
	assertNotNull(codeAction);
	buf = new StringBuilder();
	buf.append("\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 package 'test2'");
	assertNotNull(codeAction);
	assertRenameFileOperation(codeAction, ResourceUtils.fixURI(pack1.getResource().getRawLocation().append("test2/E.java").toFile().toURI()));
}
 
Example #8
Source File: cvc_enumeration_validCodeAction.java    From lemminx with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void doCodeAction(Diagnostic diagnostic, Range range, DOMDocument document, List<CodeAction> codeActions,
		SharedSettings sharedSettings, IComponentProvider componentProvider) {
	try {
		int offset = document.offsetAt(range.getStart());
		DOMNode node = document.findNodeBefore(offset);
		if (node != null && node.isElement()) {
			DOMElement element = (DOMElement) node;
			ContentModelManager contentModelManager = componentProvider.getComponent(ContentModelManager.class);
			for (CMDocument cmDocument : contentModelManager.findCMDocument(element)) {
				CMElementDeclaration cmElement = cmDocument.findCMElement(element);
				if (cmElement != null) {
					cmElement.getEnumerationValues().forEach(value -> {
						// Replace text content
						CodeAction replaceTextContentAction = CodeActionFactory.replace(
								"Replace with '" + value + "'", range, value, document.getTextDocument(),
								diagnostic);
						codeActions.add(replaceTextContentAction);
					});
				}
			}
		}
	} catch (Exception e) {
		// do nothing
	}
}
 
Example #9
Source File: AbstractFixMissingGrammarCodeAction.java    From lemminx with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void doCodeAction(Diagnostic diagnostic, Range range, DOMDocument document, List<CodeAction> codeActions,
		SharedSettings sharedSettings, IComponentProvider componentProvider) {

	String missingFilePath = getPathFromDiagnostic(diagnostic);
	if (StringUtils.isEmpty(missingFilePath)) {
		return;
	}
	Path p = Paths.get(missingFilePath);
	if (p.toFile().exists()) {
		return;
	}

	// Generate XSD from the DOM document
	FileContentGeneratorManager generator = componentProvider.getComponent(FileContentGeneratorManager.class);
	String schemaTemplate = generator.generate(document, sharedSettings, getFileContentGeneratorSettings());

	// Create code action to create the XSD file with the generated XSD content
	CodeAction makeSchemaFile = CodeActionFactory.createFile("Generate missing file '" + p.toFile().getName() + "'",
			"file:///" + missingFilePath, schemaTemplate, diagnostic);

	codeActions.add(makeSchemaFile);
}
 
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: 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 #12
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 #13
Source File: XMLAssert.java    From lemminx with Eclipse Public License 2.0 6 votes vote down vote up
public static void assertCodeActions(List<CodeAction> actual, CodeAction... expected) {
	actual.stream().forEach(ca -> {
		// we don't want to compare title, etc
		ca.setCommand(null);
		ca.setKind(null);
		ca.setTitle("");
		if (ca.getDiagnostics() != null) {
			ca.getDiagnostics().forEach(d -> {
				d.setSeverity(null);
				d.setMessage("");
				d.setSource(null);
			});
		}
	});

	assertEquals(expected.length, actual.size());
	assertArrayEquals(expected, actual.toArray());
}
 
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>> getGenerateDelegateMethodsAction(CodeActionParams params, IInvocationContext context, IType type) {
	try {
		if (!preferenceManager.getClientPreferences().isGenerateDelegateMethodsPromptSupported() || !GenerateDelegateMethodsHandler.supportsGenerateDelegateMethods(type)) {
			return Optional.empty();
		}
	} catch (JavaModelException e) {
		return Optional.empty();
	}

	Command command = new Command(ActionMessages.GenerateDelegateMethodsAction_label, COMMAND_ID_ACTION_GENERATEDELEGATEMETHODSPROMPT, Collections.singletonList(params));
	if (preferenceManager.getClientPreferences().isSupportedCodeActionKind(JavaCodeActionKind.SOURCE_GENERATE_DELEGATE_METHODS)) {
		CodeAction codeAction = new CodeAction(ActionMessages.GenerateDelegateMethodsAction_label);
		codeAction.setKind(JavaCodeActionKind.SOURCE_GENERATE_DELEGATE_METHODS);
		codeAction.setCommand(command);
		codeAction.setDiagnostics(Collections.EMPTY_LIST);
		return Optional.of(Either.forRight(codeAction));
	} else {
		return Optional.of(Either.forLeft(command));
	}
}
 
Example #15
Source File: ReorgQuickFixTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testWrongPackageStatementInEnum() throws Exception {
	IPackageFragment pack1 = fSourceFolder.createPackageFragment("test1", false, null);
	StringBuilder buf = new StringBuilder();
	buf.append("package test2;\n");
	buf.append("\n");
	buf.append("public enum 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, "Change package declaration to 'test1'");
	assertNotNull(codeAction);
	buf = new StringBuilder();
	buf.append("package test1;\n");
	buf.append("\n");
	buf.append("public enum E {\n");
	buf.append("}\n");
	assertEquals(buf.toString(), evaluateCodeActionCommand(codeAction));

	codeAction = findAction(codeActions, "Move 'E.java' to package 'test2'");
	assertNotNull(codeAction);
	assertRenameFileOperation(codeAction, ResourceUtils.fixURI(cu.getResource().getRawLocationURI()).replace("test1", "test2"));
}
 
Example #16
Source File: HashCodeEqualsActionTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testHashCodeEqualsDisabled_enum() throws JavaModelException {
	//@formatter:off
	ICompilationUnit unit = fPackageP.createCompilationUnit("A.java", "package p;\r\n" +
			"\r\n" +
			"public enum A {\r\n" +
			"	MONDAY,\r\n" +
			"	TUESDAY;\r\n" +
			"	private 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);
	Assert.assertFalse("The operation is not applicable to enums", CodeActionHandlerTest.containsKind(codeActions, JavaCodeActionKind.SOURCE_GENERATE_HASHCODE_EQUALS));
}
 
Example #17
Source File: DocumentLifeCycleHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testRemoveDeadCodeAfterIf() throws Exception {
	IJavaProject javaProject = newEmptyProject();
	IPackageFragmentRoot sourceFolder = javaProject.getPackageFragmentRoot(javaProject.getProject().getFolder("src"));
	IPackageFragment pack1 = sourceFolder.createPackageFragment("test1", false, null);

	StringBuilder buf = new StringBuilder();
	buf.append("package test1;\n");
	buf.append("public class E {\n");
	buf.append("    public boolean foo(boolean b1) {\n");
	buf.append("        if (false) {\n");
	buf.append("            return true;\n");
	buf.append("        }\n");
	buf.append("        return false;\n");
	buf.append("    }\n");
	buf.append("}\n");
	ICompilationUnit cu = pack1.createCompilationUnit("E.java", buf.toString(), false, null);

	List<Either<Command, CodeAction>> codeActions = getCodeActions(cu);
	assertEquals(codeActions.size(), 1);
	assertEquals(codeActions.get(0).getRight().getKind(), CodeActionKind.QuickFix);
}
 
Example #18
Source File: JSONCodeActionService.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public List<Either<Command, CodeAction>> getCodeActions(Options options) {
	List<Either<Command, CodeAction>> result = new ArrayList<>();
	if (options.getCodeActionParams() != null && options.getCodeActionParams().getContext() != null) {
		List<Diagnostic> diagnostics = options.getCodeActionParams().getContext().getDiagnostics();
		for (Diagnostic diag : diagnostics) {
			if (IssueCodes.NON_EXISTING_PROJECT.equals(diag.getCode())) {
				Command cmd = createInstallNpmCommand(options, diag);
				if (cmd != null) {
					result.add(Either.forLeft(cmd));
				}
			}
		}
	}
	return result;
}
 
Example #19
Source File: src_import_1_2CodeAction.java    From lemminx with Eclipse Public License 2.0 6 votes vote down vote up
private CodeAction createNamespaceCodeAction(Diagnostic diagnostic, Range range, DOMDocument document, String prefix) throws BadLocationException {
	int offset = document.offsetAt(range.getStart());
	DOMNode node = document.findNodeAt(offset);

	if (node == null || !node.isElement()) {
		return null;
	}
	
	String message;
	if (prefix != null) {
		message = "Insert 'namespace' attribute in '" + prefix + ":import' element";
	} else {
		message = "Insert 'namespace' attribute in 'import' element";
	}

	return CodeActionFactory.insert(message, diagnostic.getRange().getEnd(), " namespace=\"\"", document.getTextDocument(), diagnostic);
}
 
Example #20
Source File: CodeActionFactory.java    From lemminx with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Makes a CodeAction to create a file and add content to the file.
 * 
 * @param title      The displayed name of the CodeAction
 * @param docURI     The file to create
 * @param content    The text to put into the newly created document.
 * @param diagnostic The diagnostic that this CodeAction will fix
 */
public static CodeAction createFile(String title, String docURI, String content, Diagnostic diagnostic) {

	List<Either<TextDocumentEdit, ResourceOperation>> actionsToTake = new ArrayList<>(2);

	// 1. create an empty file
	actionsToTake.add(Either.forRight(new CreateFile(docURI, new CreateFileOptions(false, true))));

	// 2. update the created file with the given content
	VersionedTextDocumentIdentifier identifier = new VersionedTextDocumentIdentifier(docURI, 0);
	TextEdit te = new TextEdit(new Range(new Position(0, 0), new Position(0, 0)), content);
	actionsToTake.add(Either.forLeft(new TextDocumentEdit(identifier, Collections.singletonList(te))));

	WorkspaceEdit createAndAddContentEdit = new WorkspaceEdit(actionsToTake);

	CodeAction codeAction = new CodeAction(title);
	codeAction.setEdit(createAndAddContentEdit);
	codeAction.setDiagnostics(Collections.singletonList(diagnostic));
	codeAction.setKind(CodeActionKind.QuickFix);

	return codeAction;
}
 
Example #21
Source File: LanguageServerImpl.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Compute the code action commands. Executed in a read request.
 * @since 2.20
 */
protected List<Either<Command, CodeAction>> codeAction(CodeActionParams params, CancelIndicator cancelIndicator) {
	URI uri = getURI(params.getTextDocument());
	IResourceServiceProvider serviceProvider = getResourceServiceProvider(uri);
	ICodeActionService2 service2 = getService(serviceProvider, ICodeActionService2.class);
	if (service2 == null) {
		return Collections.emptyList();
	}
	return workspaceManager.doRead(uri, (doc, resource) -> {
		List<Either<Command, CodeAction>> result = new ArrayList<>();
		if (service2 != null) {
			ICodeActionService2.Options options = new ICodeActionService2.Options();
			options.setDocument(doc);
			options.setResource(resource);
			options.setLanguageServerAccess(access);
			options.setCodeActionParams(params);
			options.setCancelIndicator(cancelIndicator);
			List<Either<Command, CodeAction>> actions = service2.getCodeActions(options);
			if (actions != null) {
				result.addAll(actions);
			}
		}
		return result;
	});
}
 
Example #22
Source File: GenerateConstructorsActionTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testGenerateConstructorsEnabled_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> constructorAction = CodeActionHandlerTest.findAction(codeActions, JavaCodeActionKind.SOURCE_GENERATE_CONSTRUCTORS);
	Assert.assertNotNull(constructorAction);
	Command constructorCommand = CodeActionHandlerTest.getCommand(constructorAction);
	Assert.assertNotNull(constructorCommand);
	Assert.assertEquals(CodeActionHandler.COMMAND_ID_APPLY_EDIT, constructorCommand.getCommand());
}
 
Example #23
Source File: GenerateDelegateMethodsActionTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testGenerateDelegateMethodsEnabled() 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> delegateMethodsAction = CodeActionHandlerTest.findAction(codeActions, JavaCodeActionKind.SOURCE_GENERATE_DELEGATE_METHODS);
	Assert.assertNotNull(delegateMethodsAction);
	Command delegateMethodsCommand = CodeActionHandlerTest.getCommand(delegateMethodsAction);
	Assert.assertNotNull(delegateMethodsCommand);
	Assert.assertEquals(SourceAssistProcessor.COMMAND_ID_ACTION_GENERATEDELEGATEMETHODSPROMPT, delegateMethodsCommand.getCommand());
}
 
Example #24
Source File: AdvancedExtractTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testExtractMethod() throws Exception {
	IPackageFragment pack1 = fSourceFolder.createPackageFragment("test1", false, null);

	StringBuilder buf = new StringBuilder();
	buf.append("package test1;\n");
	buf.append("\n");
	buf.append("public class E {\n");
	buf.append("    public int foo(boolean b1, boolean b2) {\n");
	buf.append("        int n = 0;\n");
	buf.append("        int i = 0;\n");
	buf.append("        /*[*/\n");
	buf.append("        if (b1)\n");
	buf.append("            i = 1;\n");
	buf.append("        if (b2)\n");
	buf.append("            n = n + i;\n");
	buf.append("        /*]*/\n");
	buf.append("        return n;\n");
	buf.append("    }\n");
	buf.append("}\n");

	ICompilationUnit cu = pack1.createCompilationUnit("E.java", buf.toString(), false, null);
	Range selection = getRange(cu, null);
	List<Either<Command, CodeAction>> codeActions = evaluateCodeActions(cu, selection);
	Assert.assertNotNull(codeActions);
	Either<Command, CodeAction> extractMethodAction = CodeActionHandlerTest.findAction(codeActions, JavaCodeActionKind.REFACTOR_EXTRACT_METHOD);
	Assert.assertNotNull(extractMethodAction);
	Command extractMethodCommand = CodeActionHandlerTest.getCommand(extractMethodAction);
	Assert.assertNotNull(extractMethodCommand);
	Assert.assertEquals(RefactorProposalUtility.APPLY_REFACTORING_COMMAND_ID, extractMethodCommand.getCommand());
	Assert.assertNotNull(extractMethodCommand.getArguments());
	Assert.assertEquals(2, extractMethodCommand.getArguments().size());
	Assert.assertEquals(RefactorProposalUtility.EXTRACT_METHOD_COMMAND, extractMethodCommand.getArguments().get(0));
}
 
Example #25
Source File: CodeActionService.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
private CodeAction fixUnsortedMembers(Diagnostic d, ICodeActionService2.Options options) {
	WorkspaceEdit wsEdit = recordWorkspaceEdit(options, (Resource copiedResource) -> {
		Model model = Iterables.getFirst(Iterables.filter(copiedResource.getContents(), Model.class), null);
		if (model != null) {
			for (TypeDeclaration type : Iterables.filter(model.getElements(), TypeDeclaration.class)) {
				ECollections.sort(type.getMembers(), (Member a, Member b) -> a.getName().compareTo(b.getName()));
			}
		}
	});
	CodeAction codeAction = new CodeAction();
	codeAction.setTitle("Sort Members");
	codeAction.setDiagnostics(Lists.newArrayList(d));
	codeAction.setEdit(wsEdit);
	return codeAction;
}
 
Example #26
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);
}
 
Example #27
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 #28
Source File: NonNullTest.java    From lsp4j with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testCodeAction2() {
	try {
		CodeAction codeAction = new CodeAction();
		codeAction.setTitle(null);
		fail("Expected an IllegalArgumentException");
	} catch (IllegalArgumentException exc) {
		assertEquals("Property must not be null: title", exc.getMessage());
	}
}
 
Example #29
Source File: UnknownPropertyQuickfixTest.java    From camel-language-server with 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, 33, 9, 37);
	assertThat(textEdit.getNewText()).isEqualTo("delay");
}
 
Example #30
Source File: CamelTextDocumentService.java    From camel-language-server with Apache License 2.0 5 votes vote down vote up
@Override
public CompletableFuture<List<Either<Command, CodeAction>>> codeAction(CodeActionParams params) {
	LOGGER.info("codeAction: {}", params.getTextDocument());
	CodeActionContext context = params.getContext();
	if (context != null && (context.getOnly() == null || context.getOnly().contains(CodeActionKind.QuickFix))) {
		return CompletableFuture.supplyAsync(() -> {
			List<Either<Command, CodeAction>> allQuickfixes = new ArrayList<>();
			allQuickfixes.addAll(new UnknownPropertyQuickfix(this).apply(params));
			allQuickfixes.addAll(new InvalidEnumQuickfix(this).apply(params));
			return allQuickfixes;
		});
	} else {
		return CompletableFuture.completedFuture(Collections.emptyList());
	}
}