org.eclipse.lsp4j.jsonrpc.services.JsonRequest#org.eclipse.lsp4j.CodeActionParams源码实例Demo

下面列出了org.eclipse.lsp4j.jsonrpc.services.JsonRequest#org.eclipse.lsp4j.CodeActionParams 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。


@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);
}
 

@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());
}
 

@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);
}
 

@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);
}
 

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();
	}
}
 

@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());
}
 

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));
	}
}
 

@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));
	}
}
 

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;
}
 

@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());
}
 

@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());
}
 

@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);
}
 

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 $;
}
 

@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));
}
 

@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);
}
 
源代码16 项目: eclipse.jdt.ls   文件: RefactorProcessor.java

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;
}
 
源代码17 项目: eclipse.jdt.ls   文件: MoveHandler.java

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;
}
 
源代码18 项目: eclipse.jdt.ls   文件: MoveHandler.java

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());
	}
}
 
源代码19 项目: eclipse.jdt.ls   文件: MoveHandler.java

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;
}
 

@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();
	}
}
 

@Test
public void testExtractVariableAllOccurrence() throws Exception {
	IPackageFragment pack1 = fSourceFolder.createPackageFragment("test1", false, null);

	StringBuilder buf = new StringBuilder();
	buf.append("package test1;\n");
	buf.append("class A{\n");
	buf.append("	void m(int i){\n");
	buf.append("		int x= /*]*/0/*[*/;\n");
	buf.append("	}\n");
	buf.append("}\n");

	ICompilationUnit cu = pack1.createCompilationUnit("E.java", buf.toString(), false, null);
	Range selection = getRange(cu, null);
	CodeActionParams params = CodeActionUtil.constructCodeActionParams(cu, selection);
	GetRefactorEditParams editParams = new GetRefactorEditParams(RefactorProposalUtility.EXTRACT_VARIABLE_ALL_OCCURRENCE_COMMAND, params);
	RefactorWorkspaceEdit refactorEdit = GetRefactorEditHandler.getEditsForRefactor(editParams);
	Assert.assertNotNull(refactorEdit);
	Assert.assertNotNull(refactorEdit.edit);
	String actual = evaluateChanges(refactorEdit.edit.getChanges());

	buf = new StringBuilder();
	buf.append("package test1;\n");
	buf.append("class A{\n");
	buf.append("	void m(int i){\n");
	buf.append("		int j = 0;\n");
	buf.append("        int x= /*]*/j/*[*/;\n");
	buf.append("	}\n");
	buf.append("}\n");
	AbstractSourceTestCase.compareSource(buf.toString(), actual);

	Assert.assertNotNull(refactorEdit.command);
	Assert.assertEquals(GetRefactorEditHandler.RENAME_COMMAND, refactorEdit.command.getCommand());
	Assert.assertNotNull(refactorEdit.command.getArguments());
	Assert.assertEquals(1, refactorEdit.command.getArguments().size());
}
 

@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);
}
 

@Test
void testReturnCodeActionForQuickfixWhenNoCodeActionKindSpecified() throws FileNotFoundException, InterruptedException, ExecutionException {
	TextDocumentIdentifier textDocumentIdentifier = initAnLaunchDiagnostic();

	Diagnostic diagnostic = lastPublishedDiagnostics.getDiagnostics().get(0);
	CodeActionContext context = new CodeActionContext(lastPublishedDiagnostics.getDiagnostics());
	CompletableFuture<List<Either<Command,CodeAction>>> codeActions = camelLanguageServer.getTextDocumentService().codeAction(new CodeActionParams(textDocumentIdentifier, diagnostic.getRange(), context));
	
	checkRetrievedCodeAction(textDocumentIdentifier, diagnostic, codeActions);
}
 

@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));
}
 
源代码25 项目: n4js   文件: AbstractCodeActionTest.java

@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());
	}
}
 
源代码26 项目: n4js   文件: AbstractOrganizeImportsTest.java

@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);
}
 

@Test
public void testGenerateConstructorsDisabled_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_CONSTRUCTORS));
}
 
源代码28 项目: n4js   文件: XLanguageServerImpl.java

/**
 * Convert the given params to an enriched instance of options.
 */
public ICodeActionService2.Options toOptions(CodeActionParams params, XDocument doc, XtextResource res,
		CancelIndicator cancelIndicator) {

	ICodeActionService2.Options options = new ICodeActionService2.Options();
	options.setDocument(doc);
	options.setResource(res);
	options.setLanguageServerAccess(access);
	options.setCodeActionParams(params);
	options.setCancelIndicator(cancelIndicator);
	return options;
}
 
源代码29 项目: n4js   文件: N4JSCommandService.java

/**
 * Fix the issues of the same kind in the entire file.
 */
@ExecutableCommandHandler(COMPOSITE_FIX_FILE)
public Void fixAllInFile(String title, String code, String fixId, CodeActionParams codeActionParams,
		ILanguageServerAccess access, CancelIndicator cancelIndicator) {

	String uriString = codeActionParams.getTextDocument().getUri();
	URI uri = uriExtensions.toUri(uriString);

	WorkspaceEdit edit = codeActionService.applyToFile(uri, code, fixId, cancelIndicator);
	access.getLanguageClient().applyEdit(new ApplyWorkspaceEditParams(edit, title));
	return null;
}
 

@Test
public void testGenerateConstructors_enum() throws ValidateEditException, CoreException, IOException {
	//@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);
	assertNotNull(response.fields);
	assertEquals(0, response.fields.length);

	CodeGenerationSettings settings = new CodeGenerationSettings();
	settings.createComments = false;
	TextEdit edit = GenerateConstructorsHandler.generateConstructors(unit.findPrimaryType(), response.constructors, response.fields, settings);
	assertNotNull(edit);
	JavaModelUtil.applyEdit(unit, edit, true, null);

	/* @formatter:off */
	String expected = "package p;\r\n" +
			"\r\n" +
			"public enum B {\r\n" +
			"	;\r\n" +
			"\r\n" +
			"	private B() {\r\n" +
			"	}\r\n" +
			"}";
	/* @formatter:on */

	compareSource(expected, unit.getSource());
}