org.eclipse.lsp4j.CodeActionKind Java Examples

The following examples show how to use org.eclipse.lsp4j.CodeActionKind. 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: GetterSetterCorrectionSubProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Proposes a getter for this field.
 *
 * @param context
 *            the proposal parameter
 * @param relevance
 *            relevance of this proposal
 * @return the proposal if available or null
 */
private static ChangeCorrectionProposal addGetterProposal(ProposalParameter context, int relevance) {
	IMethodBinding method = findGetter(context);
	if (method != null) {
		Expression mi = createMethodInvocation(context, method, null);
		context.astRewrite.replace(context.accessNode, mi, null);

		String label = Messages.format(CorrectionMessages.GetterSetterCorrectionSubProcessor_replacewithgetter_description, BasicElementLabels.getJavaCodeString(ASTNodes.asString(context.accessNode)));
		ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, CodeActionKind.QuickFix, context.compilationUnit, context.astRewrite, relevance);
		return proposal;
	} else {
		IJavaElement element = context.variableBinding.getJavaElement();
		if (element instanceof IField) {
			IField field = (IField) element;
			try {
				if (RefactoringAvailabilityTester.isSelfEncapsulateAvailable(field)) {
					return new SelfEncapsulateFieldProposal(relevance, field);
				}
			} catch (JavaModelException e) {
				JavaLanguageServerPlugin.log(e);
			}
		}
	}
	return null;
}
 
Example #2
Source File: JavadocTagsSubProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
public static void getInvalidQualificationProposals(IInvocationContext context, IProblemLocationCore problem,
		Collection<ChangeCorrectionProposal> proposals) {
	ASTNode node= problem.getCoveringNode(context.getASTRoot());
	if (!(node instanceof Name)) {
		return;
	}
	Name name= (Name) node;
	IBinding binding= name.resolveBinding();
	if (!(binding instanceof ITypeBinding)) {
		return;
	}
	ITypeBinding typeBinding= (ITypeBinding)binding;

	AST ast= node.getAST();
	ASTRewrite rewrite= ASTRewrite.create(ast);
	rewrite.replace(name, ast.newName(typeBinding.getQualifiedName()), null);

	String label= CorrectionMessages.JavadocTagsSubProcessor_qualifylinktoinner_description;
	ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, CodeActionKind.QuickFix, context.getCompilationUnit(),
			rewrite, IProposalRelevance.QUALIFY_INNER_TYPE_NAME);

	proposals.add(proposal);
}
 
Example #3
Source File: JavadocTagsSubProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
public static void getRemoveJavadocTagProposals(IInvocationContext context, IProblemLocationCore problem,
		Collection<ChangeCorrectionProposal> proposals) {
	ASTNode node= problem.getCoveringNode(context.getASTRoot());
	while (node != null && !(node instanceof TagElement)) {
		node= node.getParent();
	}
	if (node == null) {
		return;
	}
	ASTRewrite rewrite= ASTRewrite.create(node.getAST());
	rewrite.remove(node, null);

	String label= CorrectionMessages.JavadocTagsSubProcessor_removetag_description;
	proposals.add(new ASTRewriteCorrectionProposal(label, CodeActionKind.QuickFix, context.getCompilationUnit(), rewrite,
			IProposalRelevance.REMOVE_TAG));
}
 
Example #4
Source File: UnresolvedElementsSubProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
public static void getAmbiguousTypeReferenceProposals(IInvocationContext context, IProblemLocationCore problem,
		Collection<ChangeCorrectionProposal> proposals) throws CoreException {
	final ICompilationUnit cu= context.getCompilationUnit();
	int offset= problem.getOffset();
	int len= problem.getLength();

	IJavaElement[] elements= cu.codeSelect(offset, len);
	for (int i= 0; i < elements.length; i++) {
		IJavaElement curr= elements[i];
		if (curr instanceof IType && !TypeFilter.isFiltered((IType) curr)) {
			String qualifiedTypeName= ((IType) curr).getFullyQualifiedName('.');

			CompilationUnit root= context.getASTRoot();

			String label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_importexplicit_description, BasicElementLabels.getJavaElementName(qualifiedTypeName));
			ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, CodeActionKind.QuickFix, cu, ASTRewrite.create(root.getAST()), IProposalRelevance.IMPORT_EXPLICIT);

			ImportRewrite imports= proposal.createImportRewrite(root);
			imports.addImport(qualifiedTypeName);

			proposals.add(proposal);
		}
	}
}
 
Example #5
Source File: InvertVariableTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testRemovingNotPrefixWhenInvertVariable() throws Exception {
	IPackageFragment pack1 = testSourceFolder.createPackageFragment("test", false, null);

	StringBuilder buf = new StringBuilder();
	buf.append("package test;\n");
	buf.append("public class E {\n");
	buf.append("    public void foo() {\n");
	buf.append("        boolean notLie = 3 != 5;\n");
	buf.append("    }\n");
	buf.append("}\n");

	ICompilationUnit cu = pack1.createCompilationUnit("E.java", buf.toString(), false, null);

	buf = new StringBuilder();
	buf.append("package test;\n");
	buf.append("public class E {\n");
	buf.append("    public void foo() {\n");
	buf.append("        boolean lie = 3 == 5;\n");
	buf.append("    }\n");
	buf.append("}\n");

	Expected expected = new Expected(INVERT_BOOLEAN_VARIABLE, buf.toString(), CodeActionKind.Refactor);
	Range replacedRange = CodeActionUtil.getRange(cu, "notLie", 0);
	assertCodeActions(cu, replacedRange, expected);
}
 
Example #6
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 #7
Source File: OrganizeImportsCommand.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
public void organizeImportsInCompilationUnit(ICompilationUnit unit, WorkspaceEdit rootEdit) {
	try {
		InnovationContext context = new InnovationContext(unit, 0, unit.getBuffer().getLength() - 1);
		CUCorrectionProposal proposal = new CUCorrectionProposal("OrganizeImports", CodeActionKind.SourceOrganizeImports, unit, null, IProposalRelevance.ORGANIZE_IMPORTS) {
			@Override
			protected void addEdits(IDocument document, TextEdit editRoot) throws CoreException {
				CompilationUnit astRoot = context.getASTRoot();
				OrganizeImportsOperation op = new OrganizeImportsOperation(unit, astRoot, true, false, true, null);
				TextEdit edit = op.createTextEdit(null);
				TextEdit staticEdit = OrganizeImportsHandler.wrapStaticImports(edit, astRoot, unit);
				if (staticEdit.getChildrenSize() > 0) {
					editRoot.addChild(staticEdit);
				}
			}
		};

		addWorkspaceEdit(unit, proposal, rootEdit);
	} catch (CoreException e) {
		JavaLanguageServerPlugin.logException("Problem organize imports ", e);
	}
}
 
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_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 #9
Source File: CodeActionProvider.java    From vscode-as3mxml with Apache License 2.0 6 votes vote down vote up
private void createCodeActionsForUnusedImport(Path path, Diagnostic diagnostic, WorkspaceFolderData folderData, List<Either<Command, CodeAction>> codeActions)
{
    String fileText = fileTracker.getText(path);
    if(fileText == null)
    {
        return;
    }

    Range range = diagnostic.getRange();
    WorkspaceEdit edit = CodeActionsUtils.createWorkspaceEditForRemoveUnusedImport(fileText, path.toUri().toString(), diagnostic.getRange());
    if (edit == null)
    {
        return;
    }

    int startOffset = LanguageServerCompilerUtils.getOffsetFromPosition(new StringReader(fileText), range.getStart());
    int endOffset = LanguageServerCompilerUtils.getOffsetFromPosition(new StringReader(fileText), range.getEnd());

    String importText = fileText.substring(startOffset, endOffset);
    CodeAction codeAction = new CodeAction();
    codeAction.setTitle("Remove " + importText);
    codeAction.setEdit(edit);
    codeAction.setKind(CodeActionKind.QuickFix);
    codeAction.setDiagnostics(Collections.singletonList(diagnostic));
    codeActions.add(Either.forRight(codeAction));
}
 
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: LocalCorrectionsSubProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
public static void addCasesOmittedProposals(IInvocationContext context, IProblemLocationCore problem, Collection<ChangeCorrectionProposal> proposals) {
	ASTNode selectedNode = problem.getCoveringNode(context.getASTRoot());
	if (selectedNode instanceof Expression && selectedNode.getLocationInParent() == SwitchStatement.EXPRESSION_PROPERTY) {
		AST ast = selectedNode.getAST();
		SwitchStatement parent = (SwitchStatement) selectedNode.getParent();

		for (Statement statement : (List<Statement>) parent.statements()) {
			if (statement instanceof SwitchCase && ((SwitchCase) statement).isDefault()) {

				// insert //$CASES-OMITTED$:
				ASTRewrite rewrite = ASTRewrite.create(ast);
				rewrite.setTargetSourceRangeComputer(new NoCommentSourceRangeComputer());
				ListRewrite listRewrite = rewrite.getListRewrite(parent, SwitchStatement.STATEMENTS_PROPERTY);
				ASTNode casesOmittedComment = rewrite.createStringPlaceholder("//$CASES-OMITTED$", ASTNode.EMPTY_STATEMENT); //$NON-NLS-1$
				listRewrite.insertBefore(casesOmittedComment, statement, null);

				String label = CorrectionMessages.LocalCorrectionsSubProcessor_insert_cases_omitted;
				ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, CodeActionKind.QuickFix, context.getCompilationUnit(), rewrite, IProposalRelevance.INSERT_CASES_OMITTED);
				proposals.add(proposal);
				break;
			}
		}
	}
}
 
Example #12
Source File: CodeActionHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testCodeAction_removeUnterminatedString() throws Exception{
	ICompilationUnit unit = getWorkingCopy(
			"src/java/Foo.java",
			"public class Foo {\n"+
					"	void foo() {\n"+
					"String s = \"some str\n" +
					"	}\n"+
			"}\n");

	CodeActionParams params = new CodeActionParams();
	params.setTextDocument(new TextDocumentIdentifier(JDTUtils.toURI(unit)));
	final Range range = CodeActionUtil.getRange(unit, "some str");
	params.setRange(range);
	params.setContext(new CodeActionContext(Arrays.asList(getDiagnostic(Integer.toString(IProblem.UnterminatedString), range))));
	List<Either<Command, CodeAction>> codeActions = getCodeActions(params);
	Assert.assertNotNull(codeActions);
	Assert.assertFalse(codeActions.isEmpty());
	Assert.assertEquals(codeActions.get(0).getRight().getKind(), CodeActionKind.QuickFix);
	Command c = codeActions.get(0).getRight().getCommand();
	Assert.assertEquals(CodeActionHandler.COMMAND_ID_APPLY_EDIT, c.getCommand());
}
 
Example #13
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 #14
Source File: CodeActionsUtils.java    From vscode-as3mxml with Apache License 2.0 6 votes vote down vote up
private static void createCodeActionsForGenerateGetterAndSetter(IVariableNode variableNode, String uri, String fileText, Range codeActionsRange, List<Either<Command, CodeAction>> codeActions)
{
    WorkspaceEdit getSetEdit = createWorkspaceEditForGenerateGetterAndSetter(
        variableNode, uri, fileText, true, true);
    CodeAction getAndSetCodeAction = new CodeAction();
    getAndSetCodeAction.setTitle("Generate 'get' and 'set' accessors");
    getAndSetCodeAction.setEdit(getSetEdit);
    getAndSetCodeAction.setKind(CodeActionKind.RefactorRewrite);
    codeActions.add(Either.forRight(getAndSetCodeAction));
    
    WorkspaceEdit getterEdit = createWorkspaceEditForGenerateGetterAndSetter(
        variableNode, uri, fileText, true, false);
    CodeAction getterCodeAction = new CodeAction();
    getterCodeAction.setTitle("Generate 'get' accessor (make read-only)");
    getterCodeAction.setEdit(getterEdit);
    getterCodeAction.setKind(CodeActionKind.RefactorRewrite);
    codeActions.add(Either.forRight(getterCodeAction));

    WorkspaceEdit setterEdit = createWorkspaceEditForGenerateGetterAndSetter(
        variableNode, uri, fileText, false, true);
    CodeAction setterCodeAction = new CodeAction();
    setterCodeAction.setTitle("Generate 'set' accessor (make write-only)");
    setterCodeAction.setEdit(setterEdit);
    setterCodeAction.setKind(CodeActionKind.RefactorRewrite);
    codeActions.add(Either.forRight(setterCodeAction));
}
 
Example #15
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 #16
Source File: DocumentLifeCycleHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testUnimplementedMethods() throws Exception {
	IJavaProject javaProject = newEmptyProject();
	IPackageFragmentRoot sourceFolder = javaProject.getPackageFragmentRoot(javaProject.getProject().getFolder("src"));
	IPackageFragment pack1 = sourceFolder.createPackageFragment("test1", false, null);

	StringBuilder buf = new StringBuilder();
	buf.append("package test1;\n");
	buf.append("public interface E {\n");
	buf.append("    void foo();\n");
	buf.append("}\n");
	pack1.createCompilationUnit("E.java", buf.toString(), false, null);

	buf = new StringBuilder();
	buf.append("package test1;\n");
	buf.append("public class F implements E {\n");
	buf.append("}\n");
	ICompilationUnit cu = pack1.createCompilationUnit("F.java", buf.toString(), false, null);
	openDocument(cu, cu.getSource(), 1);

	List<Either<Command, CodeAction>> codeActions = getCodeActions(cu);
	assertEquals(codeActions.size(), 1);
	assertEquals(codeActions.get(0).getRight().getKind(), CodeActionKind.QuickFix);
}
 
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: 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 #19
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 #20
Source File: ExtractVariableTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Before
public void setup() throws Exception {
	fJProject1 = newEmptyProject();
	Hashtable<String, String> options = TestOptions.getDefaultOptions();

	fJProject1.setOptions(options);
	fSourceFolder = fJProject1.getPackageFragmentRoot(fJProject1.getProject().getFolder("src"));
	setOnly(CodeActionKind.Refactor);
	this.setIgnoredCommands("Extract to method");
}
 
Example #21
Source File: InvertConditionTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testInvertAndOperator() throws Exception {
	IPackageFragment pack1 = testSourceFolder.createPackageFragment("test", false, null);

	StringBuilder buf = new StringBuilder();
	buf.append("package test;\n");
	buf.append("public class E {\n");
	buf.append("    public void foo() {\n");
	buf.append("        if (true & true)\n");
	buf.append("            return;\n");
	buf.append("    }\n");
	buf.append("}\n");

	ICompilationUnit cu = pack1.createCompilationUnit("E.java", buf.toString(), false, null);

	buf = new StringBuilder();
	buf.append("package test;\n");
	buf.append("public class E {\n");
	buf.append("    public void foo() {\n");
	buf.append("        if (false | false)\n");
	buf.append("            return;\n");
	buf.append("    }\n");
	buf.append("}\n");

	Expected expected = new Expected("Invert conditions", buf.toString(), CodeActionKind.Refactor);
	Range replacedRange = CodeActionUtil.getRange(cu, "true & true", "true & true".length());
	assertCodeActions(cu, replacedRange, expected);

	Range nonSelectionRange = CodeActionUtil.getRange(cu, "true & true", 0);
	assertCodeActions(cu, nonSelectionRange, expected);
}
 
Example #22
Source File: CodeActionHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void test_filterTypes() throws Exception {
	//@formatter:off
	ICompilationUnit unit = getWorkingCopy(
			"src/org/sample/Foo.java",
			"package org.sample;\n"+
			"\n"+
			"public class Foo {\n"+
			"	List foo;\n"+
			"}\n");
	//@formatter:on
	CodeActionParams params = new CodeActionParams();
	params.setTextDocument(new TextDocumentIdentifier(JDTUtils.toURI(unit)));
	final Range range = CodeActionUtil.getRange(unit, "List");
	params.setRange(range);
	params.setContext(new CodeActionContext(Collections.emptyList()));
	List<Either<Command, CodeAction>> codeActions = getCodeActions(params);
	Assert.assertNotNull(codeActions);
	Assert.assertTrue("No organize imports action", containsKind(codeActions, CodeActionKind.SourceOrganizeImports));
	try {
		List<String> filteredTypes = new ArrayList<>();
		filteredTypes.add("java.util.*");
		PreferenceManager.getPrefs(null).setFilteredTypes(filteredTypes);
		codeActions = getCodeActions(params);
		assertNotNull(codeActions);
		Assert.assertFalse("No need for organize imports action", containsKind(codeActions, CodeActionKind.SourceOrganizeImports));
	} finally {
		PreferenceManager.getPrefs(null).setFilteredTypes(Collections.emptyList());
	}
}
 
Example #23
Source File: InvertConditionTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testInvertLessOperator() throws Exception {
	IPackageFragment pack1 = testSourceFolder.createPackageFragment("test", false, null);

	StringBuilder buf = new StringBuilder();
	buf.append("package test;\n");
	buf.append("public class E {\n");
	buf.append("    public void foo() {\n");
	buf.append("        if (3 < 5)\n");
	buf.append("            return;\n");
	buf.append("    }\n");
	buf.append("}\n");

	ICompilationUnit cu = pack1.createCompilationUnit("E.java", buf.toString(), false, null);

	buf = new StringBuilder();
	buf.append("package test;\n");
	buf.append("public class E {\n");
	buf.append("    public void foo() {\n");
	buf.append("        if (3 >= 5)\n");
	buf.append("            return;\n");
	buf.append("    }\n");
	buf.append("}\n");

	Expected expected = new Expected("Invert conditions", buf.toString(), CodeActionKind.Refactor);
	Range replacedRange = CodeActionUtil.getRange(cu, "3 < 5", "3 < 5".length());
	assertCodeActions(cu, replacedRange, expected);

	Range nonSelectionRange = CodeActionUtil.getRange(cu, "3 < 5", 0);
	assertCodeActions(cu, nonSelectionRange, expected);
}
 
Example #24
Source File: InvertConditionTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testInvertXorOperator() throws Exception {
	IPackageFragment pack1 = testSourceFolder.createPackageFragment("test", false, null);

	StringBuilder buf = new StringBuilder();
	buf.append("package test;\n");
	buf.append("public class E {\n");
	buf.append("    public void foo() {\n");
	buf.append("        if (true ^ true)\n");
	buf.append("            return;\n");
	buf.append("    }\n");
	buf.append("}\n");

	ICompilationUnit cu = pack1.createCompilationUnit("E.java", buf.toString(), false, null);

	buf = new StringBuilder();
	buf.append("package test;\n");
	buf.append("public class E {\n");
	buf.append("    public void foo() {\n");
	buf.append("        if (!(true ^ true))\n");
	buf.append("            return;\n");
	buf.append("    }\n");
	buf.append("}\n");

	Expected expected = new Expected("Invert conditions", buf.toString(), CodeActionKind.Refactor);
	Range replacedRange = CodeActionUtil.getRange(cu, "true ^ true", "true ^ true".length());
	assertCodeActions(cu, replacedRange, expected);

	Range nonSelectionRange = CodeActionUtil.getRange(cu, "true ^ true", 0);
	assertCodeActions(cu, nonSelectionRange, expected);
}
 
Example #25
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 #26
Source File: GetterSetterCorrectionSubProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Proposes a setter for this field.
 *
 * @param context
 *            the proposal parameter
 * @param relevance
 *            relevance of this proposal
 * @return the proposal if available or null
 */
private static ChangeCorrectionProposal addSetterProposal(ProposalParameter context, int relevance) {
	boolean isBoolean = isBoolean(context);
	String setterName = GetterSetterUtil.getSetterName(context.variableBinding, context.compilationUnit.getJavaProject(), null, isBoolean);
	ITypeBinding declaringType = context.variableBinding.getDeclaringClass();
	if (declaringType == null) {
		return null;
	}

	IMethodBinding method = Bindings.findMethodInHierarchy(declaringType, setterName, new ITypeBinding[] { context.variableBinding.getType() });
	if (method != null && Bindings.isVoidType(method.getReturnType()) && (Modifier.isStatic(method.getModifiers()) == Modifier.isStatic(context.variableBinding.getModifiers()))) {
		Expression assignedValue = getAssignedValue(context);
		if (assignedValue == null) {
			return null; //we don't know how to handle those cases.
		}
		Expression mi = createMethodInvocation(context, method, assignedValue);
		context.astRewrite.replace(context.accessNode.getParent(), mi, null);

		String label = Messages.format(CorrectionMessages.GetterSetterCorrectionSubProcessor_replacewithsetter_description, BasicElementLabels.getJavaCodeString(ASTNodes.asString(context.accessNode)));
		ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, CodeActionKind.QuickFix, context.compilationUnit, context.astRewrite, relevance);
		return proposal;
	} else {
		IJavaElement element = context.variableBinding.getJavaElement();
		if (element instanceof IField) {
			IField field = (IField) element;
			try {
				if (RefactoringAvailabilityTester.isSelfEncapsulateAvailable(field)) {
					return new SelfEncapsulateFieldProposal(relevance, field);
				}
			} catch (JavaModelException e) {
				JavaLanguageServerPlugin.log(e);
			}
		}
	}
	return null;
}
 
Example #27
Source File: MissingEnumQuickFixTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testMissingEnumConstant() throws Exception {
	IPackageFragment pack1 = fSourceFolder.createPackageFragment("test1", false, null);
	StringBuilder buf = new StringBuilder();
	buf.append("package test1;\n");
	buf.append("public class E {\n");
	buf.append("   public enum Numbers { One, Two};\n");
	buf.append("    public void testing() {\n");
	buf.append("        Numbers n = Numbers.One;\n");
	buf.append("        switch (n) {\n");
	buf.append("        case Two:\n");
	buf.append("            return;\n");
	buf.append("        }\n");
	buf.append("    }\n");
	buf.append("}\n");
	ICompilationUnit cu = pack1.createCompilationUnit("E.java", buf.toString(), false, null);
	Range range = new Range(new Position(5, 16), new Position(5, 17));
	setIgnoredCommands(ActionMessages.GenerateConstructorsAction_ellipsisLabel, ActionMessages.GenerateConstructorsAction_label);
	List<Either<Command, CodeAction>> codeActions = evaluateCodeActions(cu, range);
	assertEquals(2, codeActions.size());
	Either<Command, CodeAction> codeAction = codeActions.get(0);
	CodeAction action = codeAction.getRight();
	assertEquals(CodeActionKind.QuickFix, action.getKind());
	assertEquals("Add 'default' case", action.getTitle());
	TextEdit edit = getTextEdit(codeAction);
	assertEquals("\n        default:\n            break;", edit.getNewText());
	codeAction = codeActions.get(1);
	action = codeAction.getRight();
	assertEquals(CodeActionKind.QuickFix, action.getKind());
	assertEquals("Add missing case statements", action.getTitle());
	edit = getTextEdit(codeAction);
	assertEquals("\n        case One:\n            break;\n        default:\n            break;", edit.getNewText());
}
 
Example #28
Source File: InvertVariableTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testComplexInvertVariable() throws Exception {
	IPackageFragment pack1 = testSourceFolder.createPackageFragment("test", false, null);

	StringBuilder buf = new StringBuilder();
	buf.append("package test;\n");
	buf.append("public class E {\n");
	buf.append("    public boolean foo() {\n");
	buf.append("        boolean a = 3 != 5;\n");
	buf.append("        boolean b = !a;\n");
	buf.append("        boolean c = bar(a);\n");
	buf.append("        return a;\n");
	buf.append("    }\n");
	buf.append("    public boolean bar(boolean value) {\n");
	buf.append("        return !value;\n");
	buf.append("    }\n");
	buf.append("}\n");

	ICompilationUnit cu = pack1.createCompilationUnit("E.java", buf.toString(), false, null);

	buf = new StringBuilder();
	buf.append("package test;\n");
	buf.append("public class E {\n");
	buf.append("    public boolean foo() {\n");
	buf.append("        boolean notA = 3 == 5;\n");
	buf.append("        boolean b = notA;\n");
	buf.append("        boolean c = bar(!notA);\n");
	buf.append("        return !notA;\n");
	buf.append("    }\n");
	buf.append("    public boolean bar(boolean value) {\n");
	buf.append("        return !value;\n");
	buf.append("    }\n");
	buf.append("}\n");

	Expected expected = new Expected(INVERT_BOOLEAN_VARIABLE, buf.toString(), CodeActionKind.Refactor);
	Range replacedRange = CodeActionUtil.getRange(cu, "a = 3 != 5", 0);
	assertCodeActions(cu, replacedRange, expected);
}
 
Example #29
Source File: ImplementInterfaceProposal.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
public ImplementInterfaceProposal(ICompilationUnit targetCU, ITypeBinding binding, CompilationUnit astRoot, ITypeBinding newInterface, int relevance) {
	super("", CodeActionKind.QuickFix, targetCU, null, relevance); //$NON-NLS-1$

	Assert.isTrue(binding != null && Bindings.isDeclarationBinding(binding));

	fBinding= binding;
	fAstRoot= astRoot;
	fNewInterface= newInterface;

	String[] args= { BasicElementLabels.getJavaElementName(binding.getName()), BasicElementLabels.getJavaElementName(Bindings.getRawName(newInterface)) };
	setDisplayName(Messages.format(CorrectionMessages.ImplementInterfaceProposal_name, args));
}
 
Example #30
Source File: NewVariableCorrectionProposal.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
public NewVariableCorrectionProposal(String label, ICompilationUnit cu, int variableKind, SimpleName node,
		ITypeBinding senderBinding, int relevance) {
	super(label, CodeActionKind.QuickFix, cu, null, relevance);
	if (senderBinding == null) {
		Assert.isTrue(variableKind == PARAM || variableKind == LOCAL);
	} else {
		Assert.isTrue(Bindings.isDeclarationBinding(senderBinding));
	}

	fVariableKind= variableKind;
	fOriginalNode= node;
	fSenderBinding= senderBinding;
}