org.eclipse.lsp4j.CodeActionParams Java Examples

The following examples show how to use org.eclipse.lsp4j.CodeActionParams. 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: RefactorProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private boolean getConvertAnonymousToNestedProposals(CodeActionParams params, IInvocationContext context, final ASTNode node, Collection<ChangeCorrectionProposal> proposals) throws CoreException {
	if (!(node instanceof Name)) {
		return false;
	}

	if (proposals == null) {
		return false;
	}

	RefactoringCorrectionProposal proposal = null;
	if (this.preferenceManager.getClientPreferences().isAdvancedExtractRefactoringSupported()) {
		proposal = getConvertAnonymousToNestedProposal(params, context, node, true /*returnAsCommand*/);
	} else {
		proposal = getConvertAnonymousToNestedProposal(params, context, node, false /*returnAsCommand*/);
	}

	if (proposal == null) {
		return false;
	}

	proposals.add(proposal);
	return true;
}
 
Example #2
Source File: GenerateToStringActionTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testGenerateToStringEnabled_emptyFields() throws JavaModelException {
	//@formatter:off
	ICompilationUnit unit = fPackageP.createCompilationUnit("A.java", "package p;\r\n" +
			"\r\n" +
			"public class A {\r\n" +
			"	private static 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(CodeActionHandler.COMMAND_ID_APPLY_EDIT, toStringCommand.getCommand());
}
 
Example #3
Source File: UnknownPropertyQuickfixTest.java    From camel-language-server with Apache License 2.0 6 votes vote down vote up
@Test
void testNoErrorWithDiagnosticWithoutCode() throws FileNotFoundException, InterruptedException, ExecutionException {
	TextDocumentIdentifier textDocumentIdentifier = initAnLaunchDiagnostic();
	
	Diagnostic diagnostic = lastPublishedDiagnostics.getDiagnostics().get(0);

	List<Diagnostic> diagnostics = new ArrayList<Diagnostic>();
	Diagnostic diagnosticWithoutCode = new Diagnostic(new Range(new Position(9,33), new Position(9,37)), "a different diagnostic coming without code.");
	diagnostics.add(diagnosticWithoutCode);
	diagnostics.addAll(lastPublishedDiagnostics.getDiagnostics());
	
	CodeActionContext context = new CodeActionContext(diagnostics, Collections.singletonList(CodeActionKind.QuickFix));
	CompletableFuture<List<Either<Command,CodeAction>>> codeActions = camelLanguageServer.getTextDocumentService().codeAction(new CodeActionParams(textDocumentIdentifier, diagnostic.getRange(), context));
	
	checkRetrievedCodeAction(textDocumentIdentifier, diagnostic, codeActions);
}
 
Example #4
Source File: CodeActionHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testCodeAction_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 #5
Source File: MoveHandler.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private static BodyDeclaration getSelectedMemberDeclaration(ICompilationUnit unit, CodeActionParams params) {
	int start = DiagnosticsHelper.getStartOffset(unit, params.getRange());
	int end = DiagnosticsHelper.getEndOffset(unit, params.getRange());
	InnovationContext context = new InnovationContext(unit, start, end - start);
	context.setASTRoot(CodeActionHandler.getASTRoot(unit));

	ASTNode node = context.getCoveredNode();
	if (node == null) {
		node = context.getCoveringNode();
	}

	while (node != null && !(node instanceof BodyDeclaration)) {
		node = node.getParent();
	}

	if (node != null && (node instanceof MethodDeclaration || node instanceof FieldDeclaration || node instanceof AbstractTypeDeclaration) && JdtFlags.isStatic((BodyDeclaration) node)) {
		return (BodyDeclaration) node;
	}

	return null;
}
 
Example #6
Source File: MoveHandler.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private static RefactorWorkspaceEdit moveTypeToClass(CodeActionParams params, String destinationTypeName, IProgressMonitor monitor) {
	final ICompilationUnit unit = JDTUtils.resolveCompilationUnit(params.getTextDocument().getUri());
	if (unit == null) {
		return new RefactorWorkspaceEdit("Failed to move type to another class because cannot find the compilation unit associated with " + params.getTextDocument().getUri());
	}

	IType type = getSelectedType(unit, params);
	if (type == null) {
		return new RefactorWorkspaceEdit("Failed to move type to another class because no type is selected.");
	}

	try {
		if (RefactoringAvailabilityTesterCore.isMoveStaticAvailable(type)) {
			return moveStaticMember(new IMember[] { type }, destinationTypeName, monitor);
		}

		return new RefactorWorkspaceEdit("Moving non-static type to another class is not supported.");
	} catch (JavaModelException e) {
		return new RefactorWorkspaceEdit("Failed to move type to another class. Reason: " + e.toString());
	}
}
 
Example #7
Source File: HashCodeEqualsHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testCheckHashCodeEqualsStatus_methodsExist() throws JavaModelException {
	//@formatter:off
	ICompilationUnit unit = fPackageP.createCompilationUnit("B.java", "package p;\r\n" +
			"\r\n" +
			"public class B {\r\n" +
			"	private static String UUID = \"23434343\";\r\n" +
			"	String name;\r\n" +
			"	int id;\r\n" +
			"   public int hashCode() {\r\n" +
			"	}\r\n" +
			"	public boolean equals(Object a) {\r\n" +
			"		return true;\r\n" +
			"	}\r\n" +
			"}"
			, true, null);
	//@formatter:on
	CodeActionParams params = CodeActionUtil.constructCodeActionParams(unit, "String name");
	CheckHashCodeEqualsResponse response = HashCodeEqualsHandler.checkHashCodeEqualsStatus(params);
	assertEquals("B", response.type);
	assertNotNull(response.fields);
	assertEquals(2, response.fields.length);
	assertNotNull(response.existingMethods);
	assertEquals(2, response.existingMethods.length);
}
 
Example #8
Source File: SourceAssistProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private Optional<Either<Command, CodeAction>> getGetterSetterAction(CodeActionParams params, IInvocationContext context, IType type) {
	try {
		AccessorField[] accessors = GenerateGetterSetterOperation.getUnimplementedAccessors(type);
		if (accessors == null || accessors.length == 0) {
			return Optional.empty();
		} else if (accessors.length == 1 || !preferenceManager.getClientPreferences().isAdvancedGenerateAccessorsSupported()) {
			GenerateGetterSetterOperation operation = new GenerateGetterSetterOperation(type, context.getASTRoot(), preferenceManager.getPreferences().isCodeGenerationTemplateGenerateComments());
			TextEdit edit = operation.createTextEdit(null, accessors);
			return convertToWorkspaceEditAction(params.getContext(), context.getCompilationUnit(), ActionMessages.GenerateGetterSetterAction_label, JavaCodeActionKind.SOURCE_GENERATE_ACCESSORS, edit);
		} else {
			Command command = new Command(ActionMessages.GenerateGetterSetterAction_ellipsisLabel, COMMAND_ID_ACTION_GENERATEACCESSORSPROMPT, Collections.singletonList(params));
			if (preferenceManager.getClientPreferences().isSupportedCodeActionKind(JavaCodeActionKind.SOURCE_GENERATE_ACCESSORS)) {
				CodeAction codeAction = new CodeAction(ActionMessages.GenerateGetterSetterAction_ellipsisLabel);
				codeAction.setKind(JavaCodeActionKind.SOURCE_GENERATE_ACCESSORS);
				codeAction.setCommand(command);
				codeAction.setDiagnostics(Collections.EMPTY_LIST);
				return Optional.of(Either.forRight(codeAction));
			} else {
				return Optional.of(Either.forLeft(command));
			}
		}
	} catch (OperationCanceledException | CoreException e) {
		JavaLanguageServerPlugin.logException("Failed to generate Getter and Setter source action", e);
		return Optional.empty();
	}
}
 
Example #9
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 #10
Source File: MoveHandler.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private static MethodDeclaration getSelectedMethodDeclaration(ICompilationUnit unit, CodeActionParams params) {
	int start = DiagnosticsHelper.getStartOffset(unit, params.getRange());
	int end = DiagnosticsHelper.getEndOffset(unit, params.getRange());
	InnovationContext context = new InnovationContext(unit, start, end - start);
	context.setASTRoot(CodeActionHandler.getASTRoot(unit));

	ASTNode node = context.getCoveredNode();
	if (node == null) {
		node = context.getCoveringNode();
	}

	while (node != null && !(node instanceof BodyDeclaration)) {
		node = node.getParent();
	}

	if (node != null && node instanceof MethodDeclaration) {
		return (MethodDeclaration) node;
	}

	return null;
}
 
Example #11
Source File: CodeActionHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testCodeAction_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 #12
Source File: RefactorProposalUtility.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private static List<CUCorrectionProposal> getExtractVariableProposals(CodeActionParams params, IInvocationContext context, boolean problemsAtLocation, boolean returnAsCommand) throws CoreException {
	if (!supportsExtractVariable(context)) {
		return null;
	}

	List<CUCorrectionProposal> proposals = new ArrayList<>();
	CUCorrectionProposal proposal = getExtractVariableAllOccurrenceProposal(params, context, problemsAtLocation, null, returnAsCommand);
	if (proposal != null) {
		proposals.add(proposal);
	}

	proposal = getExtractVariableProposal(params, context, problemsAtLocation, null, returnAsCommand);
	if (proposal != null) {
		proposals.add(proposal);
	}

	proposal = getExtractConstantProposal(params, context, problemsAtLocation, null, returnAsCommand);
	if (proposal != null) {
		proposals.add(proposal);
	}

	return proposals;
}
 
Example #13
Source File: GenerateConstructorsActionTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testGenerateConstructorsEnabled() throws JavaModelException {
	//@formatter:off
	ICompilationUnit unit = fPackageP.createCompilationUnit("A.java", "package p;\r\n" +
			"\r\n" +
			"public class A {\r\n" +
			"	String name;\r\n" +
			"}"
			, true, null);
	//@formatter:on
	CodeActionParams params = CodeActionUtil.constructCodeActionParams(unit, "String name");
	List<Either<Command, CodeAction>> codeActions = server.codeAction(params).join();
	Assert.assertNotNull(codeActions);
	Either<Command, CodeAction> constructorAction = CodeActionHandlerTest.findAction(codeActions, JavaCodeActionKind.SOURCE_GENERATE_CONSTRUCTORS);
	Assert.assertNotNull(constructorAction);
	Command constructorCommand = CodeActionHandlerTest.getCommand(constructorAction);
	Assert.assertNotNull(constructorCommand);
	Assert.assertEquals(SourceAssistProcessor.COMMAND_ID_ACTION_GENERATECONSTRUCTORSPROMPT, constructorCommand.getCommand());
}
 
Example #14
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 #15
Source File: HashCodeEqualsHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testCheckHashCodeEqualsStatus() throws JavaModelException {
	//@formatter:off
	ICompilationUnit unit = fPackageP.createCompilationUnit("B.java", "package p;\r\n" +
			"\r\n" +
			"public class B {\r\n" +
			"	private static String UUID = \"23434343\";\r\n" +
			"	String name;\r\n" +
			"	int id;\r\n" +
			"}"
			, true, null);
	//@formatter:on
	CodeActionParams params = CodeActionUtil.constructCodeActionParams(unit, "String name");
	CheckHashCodeEqualsResponse response = HashCodeEqualsHandler.checkHashCodeEqualsStatus(params);
	assertEquals("B", response.type);
	assertNotNull(response.fields);
	assertEquals(2, response.fields.length);
	assertTrue(response.existingMethods == null || response.existingMethods.length == 0);
}
 
Example #16
Source File: NonProjectFixProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
public List<Either<Command, CodeAction>> getCorrections(CodeActionParams params, IInvocationContext context, IProblemLocationCore[] locations) {
	if (locations == null || locations.length == 0) {
		return Collections.emptyList();
	}

	List<Either<Command, CodeAction>> $ = new ArrayList<>();
	String uri = JDTUtils.toURI(context.getCompilationUnit());
	for (int i = 0; i < locations.length; i++) {
		IProblemLocationCore curr = locations[i];
		Integer id = Integer.valueOf(curr.getProblemId());
		if (id == DiagnosticsHandler.NON_PROJECT_JAVA_FILE
			|| id == DiagnosticsHandler.NOT_ON_CLASSPATH) {
			if (this.nonProjectDiagnosticsState.isOnlySyntaxReported(uri)) {
				$.add(getDiagnosticsFixes(ActionMessages.ReportAllErrorsForThisFile, uri, "thisFile", false));
				$.add(getDiagnosticsFixes(ActionMessages.ReportAllErrorsForAnyNonProjectFile, uri, "anyNonProjectFile", false));
			} else {
				$.add(getDiagnosticsFixes(ActionMessages.ReportSyntaxErrorsForThisFile, uri, "thisFile", true));
				$.add(getDiagnosticsFixes(ActionMessages.ReportSyntaxErrorsForAnyNonProjectFile, uri, "anyNonProjectFile", true));
			}
		}
	}

	return $;
}
 
Example #17
Source File: GenerateConstructorsActionTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testGenerateConstructorsDisabled_anonymous() throws JavaModelException {
	//@formatter:off
	ICompilationUnit unit = fPackageP.createCompilationUnit("A.java", "package p;\r\n" +
			"\r\n" +
			"public class A {\r\n" +
			"	public Runnable getRunnable() {\r\n" +
			"		return new Runnable() {\r\n" +
			"			@Override\r\n" +
			"			public void run() {\r\n" +
			"			}\r\n" +
			"		};\r\n" +
			"	}\r\n" +
			"}"
			, true, null);
	//@formatter:on
	CodeActionParams params = CodeActionUtil.constructCodeActionParams(unit, "run()");
	List<Either<Command, CodeAction>> codeActions = server.codeAction(params).join();
	Assert.assertNotNull(codeActions);
	Assert.assertFalse("The operation is not applicable to anonymous", CodeActionHandlerTest.containsKind(codeActions, JavaCodeActionKind.SOURCE_GENERATE_CONSTRUCTORS));
}
 
Example #18
Source File: GenerateConstructorsHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testCheckConstructorStatus_enum() throws JavaModelException {
	//@formatter:off
	ICompilationUnit unit = fPackageP.createCompilationUnit("B.java", "package p;\r\n" +
			"\r\n" +
			"public enum B {\r\n" +
			"}"
			, true, null);
	//@formatter:on
	CodeActionParams params = CodeActionUtil.constructCodeActionParams(unit, "enum B");
	CheckConstructorsResponse response = GenerateConstructorsHandler.checkConstructorsStatus(params);
	assertNotNull(response.constructors);
	assertEquals(1, response.constructors.length);
	assertEquals("Object", response.constructors[0].name);
	assertNotNull(response.constructors[0].parameters);
	assertEquals(0, response.constructors[0].parameters.length);
	assertNotNull(response.fields);
	assertEquals(0, response.fields.length);
}
 
Example #19
Source File: CodeActionHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testCodeAction_removeUnusedImport() throws Exception{
	ICompilationUnit unit = getWorkingCopy(
			"src/java/Foo.java",
			"import java.sql.*; \n" +
					"public class Foo {\n"+
					"	void foo() {\n"+
					"	}\n"+
			"}\n");

	CodeActionParams params = new CodeActionParams();
	params.setTextDocument(new TextDocumentIdentifier(JDTUtils.toURI(unit)));
	final Range range = CodeActionUtil.getRange(unit, "java.sql");
	params.setRange(range);
	params.setContext(new CodeActionContext(Arrays.asList(getDiagnostic(Integer.toString(IProblem.UnusedImport), range))));
	List<Either<Command, CodeAction>> codeActions = getCodeActions(params);
	Assert.assertNotNull(codeActions);
	Assert.assertTrue(codeActions.size() >= 3);
	Assert.assertEquals(codeActions.get(0).getRight().getKind(), CodeActionKind.QuickFix);
	Assert.assertEquals(codeActions.get(1).getRight().getKind(), CodeActionKind.QuickFix);
	Assert.assertEquals(codeActions.get(2).getRight().getKind(), CodeActionKind.SourceOrganizeImports);
	Command c = codeActions.get(0).getRight().getCommand();
	Assert.assertEquals(CodeActionHandler.COMMAND_ID_APPLY_EDIT, c.getCommand());
}
 
Example #20
Source File: GenerateToStringHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testGenerateToStringStatus() throws JavaModelException {
	//@formatter:off
	ICompilationUnit unit = fPackageP.createCompilationUnit("B.java", "package p;\r\n" +
			"\r\n" +
			"public class B {\r\n" +
			"	private static String UUID = \"23434343\";\r\n" +
			"	String name;\r\n" +
			"	int id;\r\n" +
			"}"
			, true, null);
	//@formatter:on
	CodeActionParams params = CodeActionUtil.constructCodeActionParams(unit, "String name");
	CheckToStringResponse response = GenerateToStringHandler.checkToStringStatus(params);
	assertEquals("B", response.type);
	assertNotNull(response.fields);
	assertEquals(2, response.fields.length);
	assertFalse(response.exists);
}
 
Example #21
Source File: NonProjectFixTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private List<Either<Command, CodeAction>> getCodeActions(ICompilationUnit cu, IProblem problem) throws JavaModelException {		
	CodeActionParams parms = new CodeActionParams();
	Range range = JDTUtils.toRange(cu, problem.getSourceStart(), 0);

	TextDocumentIdentifier textDocument = new TextDocumentIdentifier();
	textDocument.setUri(JDTUtils.toURI(cu));
	parms.setTextDocument(textDocument);
	parms.setRange(range);
	CodeActionContext context = new CodeActionContext();
	context.setDiagnostics(DiagnosticsHandler.toDiagnosticsArray(cu, Arrays.asList(problem), true));
	context.setOnly(Arrays.asList(CodeActionKind.QuickFix));
	parms.setContext(context);

	return new CodeActionHandler(this.preferenceManager).getCodeActionCommands(parms, new NullProgressMonitor());
}
 
Example #22
Source File: RefactorProposalUtility.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
public static CUCorrectionProposal getAssignFieldProposal(CodeActionParams params, IInvocationContext context, boolean problemsAtLocation, Map formatterOptions, boolean returnAsCommand,
		IProblemLocationCore[] locations) throws CoreException {
	ASTNode node = context.getCoveringNode();
	Statement statement = ASTResolving.findParentStatement(node);
	if (!(statement instanceof ExpressionStatement)) {
		return null;
	}
	ExpressionStatement expressionStatement = (ExpressionStatement) statement;
	Expression expression = expressionStatement.getExpression();
	if (expression.getNodeType() == ASTNode.ASSIGNMENT) {
		return null;
	}
	ITypeBinding typeBinding = expression.resolveTypeBinding();
	typeBinding = Bindings.normalizeTypeBinding(typeBinding);
	if (typeBinding == null) {
		return null;
	}
	if (containsMatchingProblem(locations, IProblem.UnusedObjectAllocation)) {
		return null;
	}
	final ICompilationUnit cu = context.getCompilationUnit();
	ASTNode type = ASTResolving.findParentType(expression);
	if (type != null) {
		int relevance;
		if (context.getSelectionLength() == 0) {
			relevance = IProposalRelevance.EXTRACT_LOCAL_ZERO_SELECTION;
		} else if (problemsAtLocation) {
			relevance = IProposalRelevance.EXTRACT_LOCAL_ERROR;
		} else {
			relevance = IProposalRelevance.EXTRACT_LOCAL;
		}
		if (returnAsCommand) {
			return new AssignToVariableAssistCommandProposal(cu, JavaCodeActionKind.REFACTOR_ASSIGN_FIELD, AssignToVariableAssistProposal.FIELD, expressionStatement, typeBinding, relevance, APPLY_REFACTORING_COMMAND_ID,
					Arrays.asList(ASSIGN_FIELD_COMMAND, params));
		} else {
			return new AssignToVariableAssistProposal(cu, JavaCodeActionKind.REFACTOR_ASSIGN_FIELD, AssignToVariableAssistProposal.FIELD, expressionStatement, typeBinding, relevance);
		}
	}
	return null;
}
 
Example #23
Source File: GetRefactorEditHandler.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private static CUCorrectionProposal getExtractVariableProposal(CodeActionParams params, IInvocationContext context, boolean problemsAtLocation, String refactorType, Map formatterOptions) throws CoreException {
	if (RefactorProposalUtility.EXTRACT_VARIABLE_ALL_OCCURRENCE_COMMAND.equals(refactorType)) {
		return RefactorProposalUtility.getExtractVariableAllOccurrenceProposal(params, context, problemsAtLocation, formatterOptions, false);
	}

	if (RefactorProposalUtility.EXTRACT_VARIABLE_COMMAND.equals(refactorType)) {
		return RefactorProposalUtility.getExtractVariableProposal(params, context, problemsAtLocation, formatterOptions, false);
	}

	if (RefactorProposalUtility.EXTRACT_CONSTANT_COMMAND.equals(refactorType)) {
		return RefactorProposalUtility.getExtractConstantProposal(params, context, problemsAtLocation, formatterOptions, false);
	}

	return null;
}
 
Example #24
Source File: RefactorProposalUtility.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
public static CUCorrectionProposal getExtractVariableProposal(CodeActionParams params, IInvocationContext context, boolean problemsAtLocation, Map formatterOptions, boolean returnAsCommand) throws CoreException {
	final ICompilationUnit cu = context.getCompilationUnit();
	ExtractTempRefactoring extractTempRefactoringSelectedOnly = new ExtractTempRefactoring(context.getASTRoot(), context.getSelectionOffset(), context.getSelectionLength(), formatterOptions);
	extractTempRefactoringSelectedOnly.setReplaceAllOccurrences(false);
	if (extractTempRefactoringSelectedOnly.checkInitialConditions(new NullProgressMonitor()).isOK()) {
		String label = CorrectionMessages.QuickAssistProcessor_extract_to_local_description;
		int relevance;
		if (context.getSelectionLength() == 0) {
			relevance = IProposalRelevance.EXTRACT_LOCAL_ZERO_SELECTION;
		} else if (problemsAtLocation) {
			relevance = IProposalRelevance.EXTRACT_LOCAL_ERROR;
		} else {
			relevance = IProposalRelevance.EXTRACT_LOCAL;
		}

		if (returnAsCommand) {
			return new CUCorrectionCommandProposal(label, JavaCodeActionKind.REFACTOR_EXTRACT_VARIABLE, cu, relevance, APPLY_REFACTORING_COMMAND_ID, Arrays.asList(EXTRACT_VARIABLE_COMMAND, params));
		}

		LinkedProposalModelCore linkedProposalModel = new LinkedProposalModelCore();
		extractTempRefactoringSelectedOnly.setLinkedProposalModel(linkedProposalModel);
		extractTempRefactoringSelectedOnly.setCheckResultForCompileProblems(false);
		RefactoringCorrectionProposal proposal = new RefactoringCorrectionProposal(label, JavaCodeActionKind.REFACTOR_EXTRACT_VARIABLE, cu, extractTempRefactoringSelectedOnly, relevance) {
			@Override
			protected void init(Refactoring refactoring) throws CoreException {
				ExtractTempRefactoring etr = (ExtractTempRefactoring) refactoring;
				etr.setTempName(etr.guessTempName()); // expensive
			}
		};
		proposal.setLinkedProposalModel(linkedProposalModel);
		return proposal;
	}

	return null;
}
 
Example #25
Source File: HashCodeEqualsActionTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testHashCodeEqualsDisabled_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_HASHCODE_EQUALS));
}
 
Example #26
Source File: AbstractCodeActionTest.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected void performTest(Project project, String moduleName, N4JSTestCodeActionConfiguration tcac)
		throws InterruptedException, ExecutionException {

	CodeActionParams codeActionParams = new CodeActionParams();
	Range range = new Range();
	Position posStart = new Position(tcac.getLine(), tcac.getColumn());
	Position posEnd = tcac.getEndLine() >= 0 && tcac.getEndColumn() >= 0
			? new Position(tcac.getEndLine(), tcac.getEndColumn())
			: posStart;
	range.setStart(posStart);
	range.setEnd(posEnd);
	codeActionParams.setRange(range);

	CodeActionContext context = new CodeActionContext();
	FileURI uri = getFileURIFromModuleName(moduleName);
	context.setDiagnostics(Lists.newArrayList(getIssues(uri)));
	codeActionParams.setContext(context);

	TextDocumentIdentifier textDocument = new TextDocumentIdentifier();
	textDocument.setUri(uri.toString());
	codeActionParams.setTextDocument(textDocument);

	CompletableFuture<List<Either<Command, CodeAction>>> future = languageServer.codeAction(codeActionParams);
	List<Either<Command, CodeAction>> result = future.get();
	if (tcac.getAssertCodeActions() != null) {
		tcac.getAssertCodeActions().apply(result);
	} else {
		String resultStr = result.stream()
				.map(cmdOrAction -> getStringLSP4J().toString3(cmdOrAction))
				.collect(Collectors.joining("\n-----\n"));
		assertEquals(tcac.getExpectedCodeActions().trim(), resultStr.trim());
	}
}
 
Example #27
Source File: GenerateConstructorsHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testCheckConstructorStatus() throws JavaModelException {
	//@formatter:off
	fPackageP.createCompilationUnit("B.java", "package p;\r\n" +
			"\r\n" +
			"public class B {\r\n" +
			"	public B(String name) {\r\n" +
			"	}\r\n" +
			"	public B(String name, int id) {\r\n" +
			"	}\r\n" +
			"	private B() {\r\n" +
			"	}\r\n" +
			"}"
			, true, null);
	ICompilationUnit unit = fPackageP.createCompilationUnit("C.java", "package p;\r\n" +
			"\r\n" +
			"public class C extends B {\r\n" +
			"	private static String logger;\r\n" +
			"	private final String uuid = \"123\";\r\n" +
			"	private final String instance;\r\n" +
			"	private String address;\r\n" +
			"}"
			, true, null);
	//@formatter:on
	CodeActionParams params = CodeActionUtil.constructCodeActionParams(unit, "String address");
	CheckConstructorsResponse response = GenerateConstructorsHandler.checkConstructorsStatus(params);
	assertNotNull(response.constructors);
	assertEquals(2, response.constructors.length);
	assertEquals("B", response.constructors[0].name);
	assertTrue(Arrays.equals(new String[] { "String" }, response.constructors[0].parameters));
	assertEquals("B", response.constructors[1].name);
	assertTrue(Arrays.equals(new String[] { "String", "int" }, response.constructors[1].parameters));
	assertNotNull(response.fields);
	assertEquals(2, response.fields.length);
	assertEquals("instance", response.fields[0].name);
	assertEquals("String", response.fields[0].type);
	assertEquals("address", response.fields[1].name);
	assertEquals("String", response.fields[1].type);
}
 
Example #28
Source File: AbstractOrganizeImportsTest.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected void performTest(Project project, String moduleName, TestOrganizeImportsConfiguration config)
		throws Exception {
	FileURI uri = getFileURIFromModuleName(moduleName);

	if (config.expectedIssues.isEmpty()) {
		assertNoIssues();
	} else {
		assertIssues(Collections.singletonMap(uri, config.expectedIssues));
	}

	TextDocumentIdentifier id = new TextDocumentIdentifier(uri.toString());
	Range range = new Range(new Position(0, 0), new Position(0, 0));
	CodeActionContext context = new CodeActionContext();
	CodeActionParams params = new CodeActionParams(id, range, context);
	CompletableFuture<List<Either<Command, CodeAction>>> codeActionFuture = languageServer.codeAction(params);

	List<Either<Command, CodeAction>> result = codeActionFuture.join();
	Command organizeImportsCommand = result.stream()
			.map(e -> e.isLeft() ? e.getLeft() : e.getRight().getCommand())
			.filter(cmd -> cmd != null
					&& Objects.equals(cmd.getCommand(), N4JSCommandService.N4JS_ORGANIZE_IMPORTS))
			.findFirst().orElse(null);
	Assert.assertNotNull("code action for organize imports not found", organizeImportsCommand);

	ExecuteCommandParams execParams = new ExecuteCommandParams(
			organizeImportsCommand.getCommand(),
			organizeImportsCommand.getArguments());
	CompletableFuture<Object> execFuture = languageServer.executeCommand(execParams);
	execFuture.join();

	joinServerRequests();
	assertContentOfFileOnDisk(uri, config.expectedCode);
}
 
Example #29
Source File: CodeActionHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Test
@Ignore
public void testCodeAction_superfluousSemicolon() throws Exception{
	ICompilationUnit unit = getWorkingCopy(
			"src/java/Foo.java",
			"public class Foo {\n"+
					"	void foo() {\n"+
					";" +
					"	}\n"+
			"}\n");

	CodeActionParams params = new CodeActionParams();
	params.setTextDocument(new TextDocumentIdentifier(JDTUtils.toURI(unit)));
	final Range range = CodeActionUtil.getRange(unit, ";");
	params.setRange(range);
	params.setContext(new CodeActionContext(Arrays.asList(getDiagnostic(Integer.toString(IProblem.SuperfluousSemicolon), range))));
	List<Either<Command, CodeAction>> codeActions = getCodeActions(params);
	Assert.assertNotNull(codeActions);
	Assert.assertEquals(1, codeActions.size());
	Assert.assertEquals(codeActions.get(0), CodeActionKind.QuickFix);
	Command c = getCommand(codeActions.get(0));
	Assert.assertEquals(CodeActionHandler.COMMAND_ID_APPLY_EDIT, c.getCommand());
	Assert.assertNotNull(c.getArguments());
	Assert.assertTrue(c.getArguments().get(0) instanceof WorkspaceEdit);
	WorkspaceEdit we = (WorkspaceEdit) c.getArguments().get(0);
	List<org.eclipse.lsp4j.TextEdit> edits = we.getChanges().get(JDTUtils.toURI(unit));
	Assert.assertEquals(1, edits.size());
	Assert.assertEquals("", edits.get(0).getNewText());
	Assert.assertEquals(range, edits.get(0).getRange());
}
 
Example #30
Source File: JDTLanguageServer.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public CompletableFuture<List<Either<Command, CodeAction>>> codeAction(CodeActionParams params) {
	logInfo(">> document/codeAction");
	CodeActionHandler handler = new CodeActionHandler(this.preferenceManager);
	return computeAsync((monitor) -> {
		waitForLifecycleJobs(monitor);
		return handler.getCodeActionCommands(params, monitor);
	});
}