org.eclipse.lsp4j.DocumentFormattingParams#org.eclipse.jdt.ls.core.internal.JDTUtils源码实例Demo

下面列出了org.eclipse.lsp4j.DocumentFormattingParams#org.eclipse.jdt.ls.core.internal.JDTUtils 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: eclipse.jdt.ls   文件: ProjectCommand.java
/**
 * Checks if the input uri is a test source file or not.
 *
 * @param uri
 *                Uri of the source file that needs to be queried.
 * @return <code>true</code> if the input uri is a test file in its belonging
 *         project, otherwise returns <code>false</code>.
 * @throws CoreException
 */
public static boolean isTestFile(String uri) throws CoreException {
	ICompilationUnit compilationUnit = JDTUtils.resolveCompilationUnit(uri);
	if (compilationUnit == null) {
		throw new CoreException(new Status(IStatus.ERROR, IConstants.PLUGIN_ID, "Given URI does not belong to an existing Java source file."));
	}
	IJavaProject javaProject = compilationUnit.getJavaProject();
	if (javaProject == null) {
		throw new CoreException(new Status(IStatus.ERROR, IConstants.PLUGIN_ID, "Given URI does not belong to an existing Java project."));
	}
	// Ignore default project
	if (ProjectsManager.DEFAULT_PROJECT_NAME.equals(javaProject.getProject().getName())) {
		return false;
	}
	final IPath compilationUnitPath = compilationUnit.getPath();
	for (IPath testpath : listTestSourcePaths(javaProject)) {
		if (testpath.isPrefixOf(compilationUnitPath)) {
			return true;
		}
	}
	return false;
}
 
private void assertNewProblemReported(ExpectedProblemReport... expectedReports) {
	List<PublishDiagnosticsParams> diags = getClientRequests("publishDiagnostics");
	assertEquals(expectedReports.length, diags.size());

	for (int i = 0; i < expectedReports.length; i++) {
		PublishDiagnosticsParams diag = diags.get(i);
		ExpectedProblemReport expected = expectedReports[i];
		assertEquals(JDTUtils.toURI(expected.cu), diag.getUri());
		if (expected.problemCount != diag.getDiagnostics().size()) {
			String message = "";
			for (Diagnostic d : diag.getDiagnostics()) {
				message += d.getMessage() + ", ";
			}
			assertEquals(message, expected.problemCount, diag.getDiagnostics().size());
		}

	}
	diags.clear();
}
 
源代码3 项目: eclipse.jdt.ls   文件: InvisibleProjectImporter.java
private static IPath inferSourceDirectory(java.nio.file.Path filePath, String packageName) {
	String packagePath = packageName.replace(JDTUtils.PERIOD, JDTUtils.PATH_SEPARATOR);
	java.nio.file.Path sourcePath = filePath.getParent();
	if (StringUtils.isBlank(packagePath)) {
		return ResourceUtils.filePathFromURI(sourcePath.toUri().toString());
	} else if (sourcePath.endsWith(Paths.get(packagePath))) { // package should match ancestor folders.
		int packageCount = packageName.split("\\" + JDTUtils.PERIOD).length;
		while (packageCount > 0) {
			sourcePath = sourcePath.getParent();
			packageCount--;
		}
		return ResourceUtils.filePathFromURI(sourcePath.toUri().toString());
	}

	return null;
}
 
源代码4 项目: eclipse.jdt.ls   文件: FormatterHandlerTest.java
@Test
public void testDisableFormattingOnType() throws Exception {
	//@formatter:off
	String text =  "package org.sample;\n"
				+ "\n"
				+ "    public      class     Baz {  \n"
				+ "String          name       ;\n"
				+ "}\n";
			//@formatter:on
	ICompilationUnit unit = getWorkingCopy("src/org/sample/Baz.java", text);

	String uri = JDTUtils.toURI(unit);
	TextDocumentIdentifier textDocument = new TextDocumentIdentifier(uri);
	FormattingOptions options = new FormattingOptions(4, true);// ident == 4 spaces

	DocumentOnTypeFormattingParams params = new DocumentOnTypeFormattingParams(new Position(3, 28), "\n");
	params.setTextDocument(textDocument);
	params.setOptions(options);
	//Check it's disabled by default
	List<? extends TextEdit> edits = server.onTypeFormatting(params).get();
	assertNotNull(edits);

	String newText = TextEditUtil.apply(unit, edits);
	assertEquals(text, newText);
}
 
源代码5 项目: eclipse.jdt.ls   文件: HoverHandlerTest.java
@Test
public void testHoverThrowable() throws Exception {
	String uriString = ClassFileUtil.getURI(project, "java.lang.Exception");
	IClassFile classFile = JDTUtils.resolveClassFile(uriString);
	String contents = JavaLanguageServerPlugin.getContentProviderManager().getSource(classFile, monitor);
	IDocument document = new Document(contents);
	IRegion region = new FindReplaceDocumentAdapter(document).find(0, "Throwable", true, false, false, false);
	int offset = region.getOffset();
	int line = document.getLineOfOffset(offset);
	int character = offset - document.getLineOffset(line);
	TextDocumentIdentifier textDocument = new TextDocumentIdentifier(uriString);
	Position position = new Position(line, character);
	TextDocumentPositionParams params = new TextDocumentPositionParams(textDocument, position);
	Hover hover = handler.hover(params, monitor);
	assertNotNull(hover);
	assertTrue("Unexpected hover ", !hover.getContents().getLeft().isEmpty());
}
 
@Test
public void testSemanticTokens_variables() throws JavaModelException {
	IPackageFragment pack1 = fSourceFolder.createPackageFragment("test1", false, null);
	StringBuilder buf = new StringBuilder();
	buf.append("package test1;\n");
	buf.append("\n");
	buf.append("public class E {\n");
	buf.append("\n");
	buf.append("    public static void foo() {\n");
	buf.append("      String bar1;\n");
	buf.append("      final String bar2 = \"test\";\n");
	buf.append("    }\n");
	buf.append("}\n");
	ICompilationUnit cu = pack1.createCompilationUnit("E.java", buf.toString(), false, null);
	SemanticTokensLegend legend = SemanticTokensCommand.getLegend();
	SemanticTokens tokens = SemanticTokensCommand.provide(JDTUtils.toURI(cu));
	Map<Integer, Map<Integer, int[]>> decodedTokens = decode(tokens);
	assertToken(decodedTokens, legend, 5, 13, 4, "variable", Arrays.asList());
	assertToken(decodedTokens, legend, 6, 19, 4, "variable", Arrays.asList("readonly"));
}
 
源代码7 项目: eclipse.jdt.ls   文件: CallHierarchyHandler.java
private CallHierarchyItem toCallHierarchyItem(IMember member) throws JavaModelException {
	Location fullLocation = getLocation(member, LocationType.FULL_RANGE);
	Range range = fullLocation.getRange();
	String uri = fullLocation.getUri();
	CallHierarchyItem item = new CallHierarchyItem();
	item.setName(JDTUtils.getName(member));
	item.setKind(DocumentSymbolHandler.mapKind(member));
	item.setRange(range);
	item.setSelectionRange(getLocation(member, LocationType.NAME_RANGE).getRange());
	item.setUri(uri);
	IType declaringType = member.getDeclaringType();
	item.setDetail(declaringType == null ? null : declaringType.getFullyQualifiedName());
	if (JDTUtils.isDeprecated(member)) {
		item.setTags(Arrays.asList(SymbolTag.Deprecated));
	}

	return item;
}
 
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());
	}
 
源代码9 项目: eclipse.jdt.ls   文件: BaseDiagnosticsHandler.java
@SuppressWarnings("restriction")
private static Range convertRange(IOpenable openable, IProblem problem) {
	try {
		return JDTUtils.toRange(openable, problem.getSourceStart(), problem.getSourceEnd() - problem.getSourceStart() + 1);
	} catch (CoreException e) {
		// In case failed to open the IOpenable's buffer, use the IProblem's information to calculate the range.
		Position start = new Position();
		Position end = new Position();

		start.setLine(problem.getSourceLineNumber() - 1);// The protocol is 0-based.
		end.setLine(problem.getSourceLineNumber() - 1);
		if (problem instanceof DefaultProblem) {
			DefaultProblem dProblem = (DefaultProblem) problem;
			start.setCharacter(dProblem.getSourceColumnNumber() - 1);
			int offset = 0;
			if (dProblem.getSourceStart() != -1 && dProblem.getSourceEnd() != -1) {
				offset = dProblem.getSourceEnd() - dProblem.getSourceStart() + 1;
			}
			end.setCharacter(dProblem.getSourceColumnNumber() - 1 + offset);
		}
		return new Range(start, end);
	}
}
 
@Test
public void testDidOpenNotOnClasspath() throws Exception {
	importProjects("eclipse/hello");
	IProject project = WorkspaceHelper.getProject("hello");
	URI uri = project.getFile("nopackage/Test2.java").getRawLocationURI();
	ICompilationUnit cu = JDTUtils.resolveCompilationUnit(uri);
	String source = FileUtils.readFileToString(FileUtils.toFile(uri.toURL()));
	openDocument(cu, source, 1);
	Job.getJobManager().join(DocumentLifeCycleHandler.DOCUMENT_LIFE_CYCLE_JOBS, monitor);
	assertEquals(project, cu.getJavaProject().getProject());
	assertEquals(source, cu.getSource());
	List<PublishDiagnosticsParams> diagnosticReports = getClientRequests("publishDiagnostics");
	assertEquals(1, diagnosticReports.size());
	PublishDiagnosticsParams diagParam = diagnosticReports.get(0);
	assertEquals(2, diagParam.getDiagnostics().size());
	closeDocument(cu);
	Job.getJobManager().join(DocumentLifeCycleHandler.DOCUMENT_LIFE_CYCLE_JOBS, monitor);
	diagnosticReports = getClientRequests("publishDiagnostics");
	assertEquals(2, diagnosticReports.size());
	diagParam = diagnosticReports.get(1);
	assertEquals(0, diagParam.getDiagnostics().size());
}
 
源代码11 项目: eclipse.jdt.ls   文件: SemanticHighlightingTest.java
protected void changeDocument(ICompilationUnit unit, String content, int version, Range range, int length) {
	DidChangeTextDocumentParams changeParms = new DidChangeTextDocumentParams();
	VersionedTextDocumentIdentifier textDocument = new VersionedTextDocumentIdentifier();
	textDocument.setUri(JDTUtils.toURI(unit));
	textDocument.setVersion(version);
	changeParms.setTextDocument(textDocument);
	TextDocumentContentChangeEvent event = new TextDocumentContentChangeEvent();
	if (range != null) {
		event.setRange(range);
		event.setRangeLength(length);
	}
	event.setText(content);
	List<TextDocumentContentChangeEvent> contentChanges = new ArrayList<>();
	contentChanges.add(event);
	changeParms.setContentChanges(contentChanges);
	lifeCycleHandler.didChange(changeParms);
}
 
源代码12 项目: eclipse.jdt.ls   文件: MoveHandler.java
public static PackageNode createPackageNode(IPackageFragment fragment) {
	if (fragment == null) {
		return null;
	}

	String projectName = fragment.getJavaProject().getProject().getName();
	String uri = null;
	if (fragment.getResource() != null) {
		uri = JDTUtils.getFileURI(fragment.getResource());
	}

	if (fragment.isDefaultPackage()) {
		return new PackageNode(DEFAULT_PACKAGE_DISPLAYNAME, uri, fragment.getPath().toPortableString(), projectName, true);
	}

	return new PackageNode(fragment.getElementName(), uri, fragment.getPath().toPortableString(), projectName, false);
}
 
源代码13 项目: eclipse.jdt.ls   文件: SaveActionHandlerTest.java
@Test
public void testWillSaveWaitUntil() throws Exception {

	URI srcUri = project.getFile("src/java/Foo4.java").getRawLocationURI();
	ICompilationUnit cu = JDTUtils.resolveCompilationUnit(srcUri);

	StringBuilder buf = new StringBuilder();
	buf.append("package java;\n");
	buf.append("\n");
	buf.append("public class Foo4 {\n");
	buf.append("}\n");

	WillSaveTextDocumentParams params = new WillSaveTextDocumentParams();
	TextDocumentIdentifier document = new TextDocumentIdentifier();
	document.setUri(srcUri.toString());
	params.setTextDocument(document);

	List<TextEdit> result = handler.willSaveWaitUntil(params, monitor);

	Document doc = new Document();
	doc.set(cu.getSource());
	assertEquals(TextEditUtil.apply(doc, result), buf.toString());
}
 
源代码14 项目: eclipse.jdt.ls   文件: AdvancedExtractTest.java
@Test
public void testMoveFile() throws Exception {
	when(preferenceManager.getClientPreferences().isMoveRefactoringSupported()).thenReturn(true);

	IPackageFragment pack1 = fSourceFolder.createPackageFragment("test1", false, null);
	StringBuilder buf = new StringBuilder();
	buf.append("package test1;\n");
	buf.append("\n");
	buf.append("public /*[*/class E /*]*/{\n");
	buf.append("}\n");

	ICompilationUnit cu = pack1.createCompilationUnit("E.java", buf.toString(), false, null);
	Range selection = getRange(cu, null);
	List<Either<Command, CodeAction>> codeActions = evaluateCodeActions(cu, selection);
	Assert.assertNotNull(codeActions);
	Either<Command, CodeAction> moveAction = CodeActionHandlerTest.findAction(codeActions, JavaCodeActionKind.REFACTOR_MOVE);
	Assert.assertNotNull(moveAction);
	Command moveCommand = CodeActionHandlerTest.getCommand(moveAction);
	Assert.assertNotNull(moveCommand);
	Assert.assertEquals(RefactorProposalUtility.APPLY_REFACTORING_COMMAND_ID, moveCommand.getCommand());
	Assert.assertNotNull(moveCommand.getArguments());
	Assert.assertEquals(3, moveCommand.getArguments().size());
	Assert.assertEquals(RefactorProposalUtility.MOVE_FILE_COMMAND, moveCommand.getArguments().get(0));
	Assert.assertTrue(moveCommand.getArguments().get(2) instanceof RefactorProposalUtility.MoveFileInfo);
	Assert.assertEquals(JDTUtils.toURI(cu), ((RefactorProposalUtility.MoveFileInfo) moveCommand.getArguments().get(2)).uri);
}
 
源代码15 项目: eclipse.jdt.ls   文件: FindLinksHandlerTest.java
@Test
public void testNoSuperMethod() throws JavaModelException {
	IPackageFragment pack1 = sourceFolder.createPackageFragment("test1", false, null);
	//@formatter:off
	ICompilationUnit unitA = pack1.createCompilationUnit("A.java", "package test1;\n" +
			"\n" +
			"public class A {\n" +
			"	public void run() {\n" +
			"	}\n" +
			"}", true, null);
	//@formatter:on

	String uri = JDTUtils.toURI(unitA);
	List<? extends Location> response = FindLinksHandler.findLinks("superImplementation", new TextDocumentPositionParams(new TextDocumentIdentifier(uri), new Position(3, 14)), new NullProgressMonitor());
	assertTrue(response == null || response.isEmpty());
}
 
private void changeDocument(ICompilationUnit cu, String content, int version, Range range, int length) throws JavaModelException {
	DidChangeTextDocumentParams changeParms = new DidChangeTextDocumentParams();
	VersionedTextDocumentIdentifier textDocument = new VersionedTextDocumentIdentifier();
	textDocument.setUri(JDTUtils.toURI(cu));
	textDocument.setVersion(version);
	changeParms.setTextDocument(textDocument);
	TextDocumentContentChangeEvent event = new TextDocumentContentChangeEvent();
	if (range != null) {
		event.setRange(range);
		event.setRangeLength(length);
	}
	event.setText(content);
	List<TextDocumentContentChangeEvent> contentChanges = new ArrayList<>();
	contentChanges.add(event);
	changeParms.setContentChanges(contentChanges);
	lifeCycleHandler.didChange(changeParms);
}
 
private Location computeDefinitionNavigation(ITypeRoot unit, int line, int column, IProgressMonitor monitor) {
	try {
		IJavaElement element = JDTUtils.findElementAtSelection(unit, line, column, this.preferenceManager, monitor);
		if (monitor.isCanceled()) {
			return null;
		}
		if (element == null) {
			return computeBreakContinue(unit, line, column);
		}
		return computeDefinitionNavigation(element, unit.getJavaProject());
	} catch (CoreException e) {
		JavaLanguageServerPlugin.logException("Problem computing definition for" + unit.getElementName(), e);
	}

	return null;
}
 
public static Location computeDefinitionNavigation(IJavaElement element, IJavaProject javaProject) throws JavaModelException {
	if (element == null) {
		return null;
	}

	ICompilationUnit compilationUnit = (ICompilationUnit) element.getAncestor(IJavaElement.COMPILATION_UNIT);
	IClassFile cf = (IClassFile) element.getAncestor(IJavaElement.CLASS_FILE);
	if (compilationUnit != null || (cf != null && cf.getSourceRange() != null)) {
		return fixLocation(element, JDTUtils.toLocation(element), javaProject);
	}

	if (element instanceof IMember && ((IMember) element).getClassFile() != null) {
		return fixLocation(element, JDTUtils.toLocation(((IMember) element).getClassFile()), javaProject);
	}

	return null;
}
 
private static Location fixLocation(IJavaElement element, Location location, IJavaProject javaProject) {
	if (location == null) {
		return null;
	}
	if (!javaProject.equals(element.getJavaProject()) && element.getJavaProject().getProject().getName().equals(ProjectsManager.DEFAULT_PROJECT_NAME)) {
		// see issue at: https://github.com/eclipse/eclipse.jdt.ls/issues/842 and https://bugs.eclipse.org/bugs/show_bug.cgi?id=541573
		// for jdk classes, jdt will reuse the java model by altering project to share the model between projects
		// so that sometimes the project for `element` is default project and the project is different from the project for `unit`
		// this fix is to replace the project name with non-default ones since default project should be transparent to users.
		if (location.getUri().contains(ProjectsManager.DEFAULT_PROJECT_NAME)) {
			String patched = StringUtils.replaceOnce(location.getUri(), ProjectsManager.DEFAULT_PROJECT_NAME, javaProject.getProject().getName());
			try {
				IClassFile cf = (IClassFile) JavaCore.create(JDTUtils.toURI(patched).getQuery());
				if (cf != null && cf.exists()) {
					location.setUri(patched);
				}
			} catch (Exception ex) {

			}
		}
	}
	return location;
}
 
@Override
public ICompilationUnit resolveCompilationUnit(String uri) {
	IFile resource = JDTUtils.findFile(uri);
	ICompilationUnit unit = JDTUtils.resolveCompilationUnit(resource);
	if (JDTUtils.isOnClassPath(unit)) {
		return unit;
	}

	// Open file not on the classpath.
	IPath filePath = ResourceUtils.canonicalFilePathFromURI(uri);
	Collection<IPath> rootPaths = preferenceManager.getPreferences().getRootPaths();
	Optional<IPath> belongedRootPath = rootPaths.stream().filter(rootPath -> rootPath.isPrefixOf(filePath)).findFirst();
	if (belongedRootPath.isPresent()) {
		if (tryUpdateClasspath(filePath, belongedRootPath.get())) {
			unit = JDTUtils.resolveCompilationUnit(uri);
			projectsManager.registerWatchers(true);;
		}
	}

	if (unit == null) {
		unit = JDTUtils.getFakeCompilationUnit(uri);
	}

	return unit;
}
 
源代码21 项目: eclipse.jdt.ls   文件: SyntaxProjectsManager.java
@Override
public void fileChanged(String uriString, CHANGE_TYPE changeType) {
	if (uriString == null) {
		return;
	}
	IResource resource = JDTUtils.getFileOrFolder(uriString);
	if (resource == null) {
		return;
	}

	try {
		Optional<IBuildSupport> bs = getBuildSupport(resource.getProject());
		if (bs.isPresent()) {
			IBuildSupport buildSupport = bs.get();
			buildSupport.fileChanged(resource, changeType, new NullProgressMonitor());
		}
	} catch (CoreException e) {
		JavaLanguageServerPlugin.logException("Problem refreshing workspace", e);
	}
}
 
源代码22 项目: eclipse.jdt.ls   文件: SemanticTokensCommandTest.java
@Test
public void testSemanticTokens_packages() throws JavaModelException {
	IPackageFragment pack1 = fSourceFolder.createPackageFragment("test1", false, null);
	StringBuilder buf = new StringBuilder();
	buf.append("package test1;\n");
	buf.append("import java.util.List;\n");
	buf.append("import java.nio.*;\n");
	buf.append("\n");
	buf.append("public class E {\n");
	buf.append("}\n");
	ICompilationUnit cu = pack1.createCompilationUnit("E.java", buf.toString(), false, null);
	SemanticTokensLegend legend = SemanticTokensCommand.getLegend();
	SemanticTokens tokens = SemanticTokensCommand.provide(JDTUtils.toURI(cu));
	Map<Integer, Map<Integer, int[]>> decodedTokens = decode(tokens);
	assertToken(decodedTokens, legend, 1, 7, 9, "namespace", Arrays.asList());
	assertToken(decodedTokens, legend, 2, 7, 8, "namespace", Arrays.asList());
}
 
private boolean isOnClasspath(List<Object> arguments) throws DebugException {
    if (arguments.size() < 1) {
        throw new DebugException("No file uri is specified.");
    }

    String uri = (String) arguments.get(0);
    final ICompilationUnit unit = JDTUtils.resolveCompilationUnit(uri);
    if (unit == null || unit.getResource() == null || !unit.getResource().exists()) {
        throw new DebugException("The compilation unit " + uri + " doesn't exist.");
    }

    IJavaProject javaProject = unit.getJavaProject();
    return javaProject == null || javaProject.isOnClasspath(unit);
}
 
源代码24 项目: java-debug   文件: ResolveElementHandler.java
/**
 * Resolve the Java element at the selected position.
 * @return the resolved Java element information.
 */
public static Object resolveElementAtSelection(List<Object> arguments, IProgressMonitor monitor) throws DebugException {
    if (arguments == null || arguments.size() < 3) {
        return Collections.emptyList();
    }

    String uri = (String) arguments.get(0);
    int line = (int) Math.round((double) arguments.get(1));
    int column = (int) Math.round((double) arguments.get(2));
    final ICompilationUnit unit = JDTUtils.resolveCompilationUnit(uri);
    try {
        IJavaElement element = JDTUtils.findElementAtSelection(unit, line, column,
                JavaLanguageServerPlugin.getPreferencesManager(), monitor);
        if (element instanceof IMethod) {
            return new JavaElement(((IMethod) element).getDeclaringType().getFullyQualifiedName(),
                element.getJavaProject().getProject().getName(),
                ((IMethod) element).isMainMethod());
        } else if (element instanceof IType) {
            return new JavaElement(((IType) element).getFullyQualifiedName(),
                element.getJavaProject().getProject().getName(),
                ResolveMainMethodHandler.getMainMethod((IType) element) != null);
        }
    } catch (JavaModelException e) {
        throw new DebugException("Failed to resolve the selected element information: " + e.getMessage(), e);
    }

    return null;
}
 
源代码25 项目: eclipse.jdt.ls   文件: CodeActionHandlerTest.java
@Test
public void test_noUnnecessaryCodeActions() throws Exception{
	//@formatter:off
	ICompilationUnit unit = getWorkingCopy(
			"src/org/sample/Foo.java",
			"package org.sample;\n"+
			"\n"+
			"public class Foo {\n"+
			"	private String foo;\n"+
			"	public String getFoo() {\n"+
			"	  return foo;\n"+
			"	}\n"+
			"   \n"+
			"	public void setFoo(String newFoo) {\n"+
			"	  foo = newFoo;\n"+
			"	}\n"+
			"}\n");
	//@formatter:on
	CodeActionParams params = new CodeActionParams();
	params.setTextDocument(new TextDocumentIdentifier(JDTUtils.toURI(unit)));
	final Range range = CodeActionUtil.getRange(unit, "String foo;");
	params.setRange(range);
	params.setContext(new CodeActionContext(Collections.emptyList()));
	List<Either<Command, CodeAction>> codeActions = getCodeActions(params);
	Assert.assertNotNull(codeActions);
	Assert.assertFalse("No need for organize imports action", containsKind(codeActions, CodeActionKind.SourceOrganizeImports));
	Assert.assertFalse("No need for generate getter and setter action", containsKind(codeActions, JavaCodeActionKind.SOURCE_GENERATE_ACCESSORS));
}
 
源代码26 项目: eclipse.jdt.ls   文件: RenameHandlerTest.java
@Test
public void testRenameMethod() throws JavaModelException, BadLocationException {
	IPackageFragment pack1 = sourceFolder.createPackageFragment("test1", false, null);

	String[] codes = {
			"package test1;\n",
			"public class E {\n",
			"   public int bar() {\n",
			"   }\n",
			"   public int foo() {\n",
			"		this.bar|*();\n",
			"   }\n",
			"}\n"
	};
	StringBuilder builder = new StringBuilder();
	Position pos = mergeCode(builder, codes);
	ICompilationUnit cu = pack1.createCompilationUnit("E.java", builder.toString(), false, null);

	WorkspaceEdit edit = getRenameEdit(cu, pos, "newname");
	assertNotNull(edit);
	assertEquals(edit.getChanges().size(), 1);
	assertEquals(TextEditUtil.apply(builder.toString(), edit.getChanges().get(JDTUtils.toURI(cu))),
			"package test1;\n" +
			"public class E {\n" +
			"   public int newname() {\n" +
			"   }\n" +
			"   public int foo() {\n" +
			"		this.newname();\n" +
			"   }\n" +
			"}\n"
			);
}
 
public void helpTestImageExtractionWithXJar(String testFolderName) throws Exception {
	setupMockMavenProject(testFolderName, "reactor.core.publisher.Mono");

	URI uri = project.getFile("src/main/java/foo/JavaDocJarTest.java").getLocationURI();
	ICompilationUnit cu = JDTUtils.resolveCompilationUnit(uri);

	assertTrue(cu.isStructureKnown());

	IJavaElement javaElement = JDTUtils.findElementAtSelection(cu, 10, 12, null, new NullProgressMonitor());

	File testExportFile = JavaDocHTMLPathHandler.EXTRACTED_JAR_IMAGES_FOLDER.append("reactor-core-3.2.10.RELEASE/error.svg").toFile();
	String testExportPath = testExportFile.toURI().toString();

	//@formatter:off
	// We don't use this. Just to show what it should look like
	String expectedOutput =
			"Create a [Mono](jdt://contents/reactor-core-3.2.10.RELEASE.jar/reactor.core.publisher/Mono.class?=javadoctest/%5C/home%5C/nkomonen%5C/.m2%5C/repository%5C/io%5C/projectreactor%5C/reactor-core%5C/3.2.10.RELEASE%5C/reactor-core-3.2.10.RELEASE.jar%3Creactor.core.publisher%28Mono.class#101) that terminates with the specified error immediately after being subscribed to.\n" +
			"\n" +
			"![Image](" + testExportPath + ")\n" +
			"\n" +
			" *  **Type Parameters:**\n" +
			"    \n" +
			"     *  **<T>** the reified [Subscriber](jdt://contents/reactive-streams-1.0.2.jar/org.reactivestreams/Subscriber.class?=javadoctest/%5C/home%5C/nkomonen%5C/.m2%5C/repository%5C/org%5C/reactivestreams%5C/reactive-streams%5C/1.0.2%5C/reactive-streams-1.0.2.jar%3Corg.reactivestreams%28Subscriber.class#29) type\n" +
			" *  **Parameters:**\n" +
			"    \n" +
			"     *  **error** the onError signal\n" +
			" *  **Returns:**\n" +
			"    \n" +
			"     *  a failing [Mono](jdt://contents/reactor-core-3.2.10.RELEASE.jar/reactor.core.publisher/Mono.class?=javadoctest/%5C/home%5C/nkomonen%5C/.m2%5C/repository%5C/io%5C/projectreactor%5C/reactor-core%5C/3.2.10.RELEASE%5C/reactor-core-3.2.10.RELEASE.jar%3Creactor.core.publisher%28Mono.class#101)";
	//@formatter:on

	String expectedImageMarkdown = "![Image](" + testExportPath + ")";

	String finalString = HoverInfoProvider.computeJavadoc(javaElement).getValue();

	assertTrue("Does finalString=\n\t\"" + finalString + "\"\nContain expectedImageMarkdown=\n\t\"" + expectedImageMarkdown + "\"", finalString.contains(expectedImageMarkdown));

	assertTrue(testExportFile.exists());
}
 
源代码28 项目: eclipse.jdt.ls   文件: FormatterHandlerTest.java
@Test // typing new_line should format the current line if previous character doesn't close a block
public void testFormattingOnTypeNewLine() throws Exception {
	ICompilationUnit unit = getWorkingCopy("src/org/sample/Baz.java",
	//@formatter:off
		  "package org.sample;\n"
		+ "\n"
		+ "    public      class     Baz {  \n"
		+ "String          name       ;\n"//typed \n here
		+ "}\n"
	//@formatter:on
	);

	String uri = JDTUtils.toURI(unit);
	TextDocumentIdentifier textDocument = new TextDocumentIdentifier(uri);
	FormattingOptions options = new FormattingOptions(4, true);// ident == 4 spaces

	DocumentOnTypeFormattingParams params = new DocumentOnTypeFormattingParams(new Position(3, 28), "\n");
	params.setTextDocument(textDocument);
	params.setOptions(options);

	preferenceManager.getPreferences().setJavaFormatOnTypeEnabled(true);
	List<? extends TextEdit> edits = server.onTypeFormatting(params).get();
	assertNotNull(edits);

	//@formatter:off
	String expectedText =
		  "package org.sample;\n"
		+ "\n"
		+ "    public      class     Baz {  \n"//this part won't be formatted
		+ "        String name;\n"
		+ "}\n";
	//@formatter:on

	String newText = TextEditUtil.apply(unit, edits);
	assertEquals(expectedText, newText);
}
 
源代码29 项目: eclipse.jdt.ls   文件: DiagnosticsCommandTest.java
@Test
public void testRefreshDiagnosticsWithReportSyntaxErrors() throws Exception {
	JavaLanguageServerPlugin.getNonProjectDiagnosticsState().setGlobalErrorLevel(ErrorLevel.COMPILATION_ERROR);
	IJavaProject javaProject = newDefaultProject();
	IPackageFragmentRoot sourceFolder = javaProject.getPackageFragmentRoot(javaProject.getProject().getFolder("src"));
	IPackageFragment pack1 = sourceFolder.createPackageFragment("java", false, null);

	// @formatter:off
	String standaloneFileContent =
			"package java;\n"+
			"public class Foo extends UnknownType {\n"+
			"	public void method1(){\n"+
			"		super.whatever()\n"+
			"	}\n"+
			"}";
	// @formatter:on

	ICompilationUnit cu1 = pack1.createCompilationUnit("Foo.java", standaloneFileContent, false, null);

	openDocument(cu1, cu1.getSource(), 1);

	List<PublishDiagnosticsParams> diagnosticReports = getClientRequests("publishDiagnostics");
	assertEquals(1, diagnosticReports.size());
	PublishDiagnosticsParams diagParam = diagnosticReports.get(0);
	assertEquals(4, diagParam.getDiagnostics().size());
	assertEquals("Foo.java is a non-project file, only JDK classes are added to its build path", diagParam.getDiagnostics().get(0).getMessage());
	assertEquals("UnknownType cannot be resolved to a type", diagParam.getDiagnostics().get(1).getMessage());
	assertEquals("UnknownType cannot be resolved to a type", diagParam.getDiagnostics().get(2).getMessage());
	assertEquals("Syntax error, insert \";\" to complete BlockStatements", diagParam.getDiagnostics().get(3).getMessage());

	DiagnosticsCommand.refreshDiagnostics(JDTUtils.toURI(cu1), "thisFile", true);

	diagnosticReports = getClientRequests("publishDiagnostics");
	assertEquals(2, diagnosticReports.size());
	diagParam = diagnosticReports.get(1);
	assertEquals(2, diagParam.getDiagnostics().size());
	assertEquals("Foo.java is a non-project file, only syntax errors are reported", diagParam.getDiagnostics().get(0).getMessage());
	assertEquals("Syntax error, insert \";\" to complete BlockStatements", diagParam.getDiagnostics().get(1).getMessage());
}
 
源代码30 项目: eclipse.jdt.ls   文件: OrganizeImportsCommand.java
public WorkspaceEdit organizeImportsInFile(String fileUri) {
	WorkspaceEdit rootEdit = new WorkspaceEdit();
	ICompilationUnit unit = null;
	if (JDTUtils.toURI(fileUri) != null) {
		unit = JDTUtils.resolveCompilationUnit(fileUri);
	}
	if (unit == null) {
		return rootEdit;
	}
	organizeImportsInCompilationUnit(unit, rootEdit);
	return rootEdit;
}