Java Code Examples for org.eclipse.jdt.ls.core.internal.JDTUtils#resolveCompilationUnit()

The following examples show how to use org.eclipse.jdt.ls.core.internal.JDTUtils#resolveCompilationUnit() . 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: ProjectCommand.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example 2
Source File: SemanticTokensCommand.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private static SemanticTokens doProvide(String uri) {
    IDocument document = null;

    ICompilationUnit cu = JDTUtils.resolveCompilationUnit(uri);
    if (cu != null) {
        try {
            document = JsonRpcHelpers.toDocument(cu.getBuffer());
        } catch (JavaModelException e) {
            JavaLanguageServerPlugin.logException("Failed to provide semantic tokens for " + uri, e);
        }
    }
    if (document == null) {
        return new SemanticTokens(Collections.emptyList());
    }

    SemanticTokensVisitor collector = new SemanticTokensVisitor(document, SemanticTokenManager.getInstance());
    CompilationUnit root = CoreASTProvider.getInstance().getAST(cu, CoreASTProvider.WAIT_YES, new NullProgressMonitor());
    root.accept(collector);
    return collector.getSemanticTokens();
}
 
Example 3
Source File: FormatterHandler.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private List<? extends org.eclipse.lsp4j.TextEdit> format(String uri, FormattingOptions options, Position position, String triggerChar, IProgressMonitor monitor) {
	if (!preferenceManager.getPreferences().isJavaFormatOnTypeEnabled()) {
		return Collections.emptyList();
	}

	ICompilationUnit cu = JDTUtils.resolveCompilationUnit(uri);
	if (cu == null) {
		return Collections.emptyList();
	}
	IRegion region = null;
	IDocument document = null;
	try {
		document = JsonRpcHelpers.toDocument(cu.getBuffer());
		if (document != null && position != null) {
			region = getRegion(cu, document, position, triggerChar);
		}
	} catch (JavaModelException e) {
		JavaLanguageServerPlugin.logException(e.getMessage(), e);
	}
	if (region == null) {
		return Collections.emptyList();
	}
	return format(cu, document, region, options, false, monitor);
}
 
Example 4
Source File: FormatterHandler.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private List<org.eclipse.lsp4j.TextEdit> format(String uri, FormattingOptions options, Range range, IProgressMonitor monitor) {
	if (!preferenceManager.getPreferences().isJavaFormatEnabled()) {
		return Collections.emptyList();
	}
	ICompilationUnit cu = JDTUtils.resolveCompilationUnit(uri);
	if (cu == null) {
		return Collections.emptyList();
	}
	IRegion region = null;
	IDocument document = null;
	try {
		document = JsonRpcHelpers.toDocument(cu.getBuffer());
		if (document != null) {
			region = (range == null ? new Region(0, document.getLength()) : getRegion(range, document));
		}
	} catch (JavaModelException e) {
		JavaLanguageServerPlugin.logException(e.getMessage(), e);
	}
	if (region == null) {
		return Collections.emptyList();
	}

	return format(cu, document, region, options, preferenceManager.getPreferences().isJavaFormatComments(), monitor);
}
 
Example 5
Source File: SyntaxDocumentLifeCycleHandler.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@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;
}
 
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: SyntaxServerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testDidOpen() throws Exception {
	URI fileURI = openFile("maven/salut4", "src/main/java/java/Foo.java");
	Job.getJobManager().join(SyntaxDocumentLifeCycleHandler.DOCUMENT_LIFE_CYCLE_JOBS, monitor);
	ICompilationUnit cu = JDTUtils.resolveCompilationUnit(fileURI);
	assertNotNull(cu);
	IPath rootPath = getWorkingTestPath("maven/salut4");
	String projectName = ProjectUtils.getWorkspaceInvisibleProjectName(rootPath);
	assertEquals(projectName, cu.getJavaProject().getProject().getName());

	IPath[] sourcePaths = ProjectUtils.listSourcePaths(cu.getJavaProject());
	assertEquals(2, sourcePaths.length);
	IPath basePath = ProjectUtils.getProject(projectName).getFolder(ProjectUtils.WORKSPACE_LINK).getFullPath();
	assertTrue(Objects.equals(basePath.append("src/main/java"), sourcePaths[0]));
	assertTrue(Objects.equals(basePath.append("src/test/java"), sourcePaths[1]));
}
 
Example 8
Source File: SyntaxServerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testCompletionOnQualifiedName() throws Exception{
	URI fileURI = openFile("maven/salut4", "src/main/java/java/Completion.java");
	ICompilationUnit cu = JDTUtils.resolveCompilationUnit(fileURI);
	assertNotNull(cu);
	cu.getBuffer().setContents("package java;\n\n" +
		"public class Completion {\n" +
		"	void foo() {\n" +
		"		String str = new String(\"hello\");\n" +
		"		str.starts" +
		"	}\n" +
		"}\n");
	cu.makeConsistent(null);

	int[] loc = findLocation(cu, "str.starts");
	String fileUri = ResourceUtils.fixURI(fileURI);
	TextDocumentIdentifier identifier = new TextDocumentIdentifier(fileUri);
	CompletionParams params = new CompletionParams(identifier, new Position(loc[0], loc[1]));
	CompletionList list = server.completion(params).join().getRight();
	assertNotNull(list);
	assertFalse("No proposals were found", list.getItems().isEmpty());

	List<CompletionItem> items = list.getItems();
	for (CompletionItem item : items) {
		assertTrue(StringUtils.isNotBlank(item.getLabel()));
		assertTrue(item.getLabel().startsWith("starts"));
		assertEquals(CompletionItemKind.Method, item.getKind());
		assertTrue(StringUtils.isNotBlank(item.getSortText()));
	}
}
 
Example 9
Source File: BaseDocumentLifeCycleHandler.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
public ICompilationUnit handleClosed(DidCloseTextDocumentParams params) {
	String uri = params.getTextDocument().getUri();
	ICompilationUnit unit = JDTUtils.resolveCompilationUnit(uri);
	if (unit == null) {
		return unit;
	}
	try {
		synchronized (toReconcile) {
			toReconcile.remove(unit);
		}
		if (isSyntaxMode(unit) || unit.getResource().isDerived()) {
			createDiagnosticsHandler(unit).clearDiagnostics();
		} else if (hasUnsavedChanges(unit)) {
			unit.discardWorkingCopy();
			unit.becomeWorkingCopy(new NullProgressMonitor());
			publishDiagnostics(unit, new NullProgressMonitor());
		}
		if (unit.equals(sharedASTProvider.getActiveJavaElement())) {
			sharedASTProvider.disposeAST();
		}
		unit.discardWorkingCopy();
		if (JDTUtils.isDefaultProject(unit)) {
			File f = new File(unit.getUnderlyingResource().getLocationURI());
			if (!f.exists()) {
				unit.delete(true, null);
			}
		}
	} catch (CoreException e) {
		JavaLanguageServerPlugin.logException("Error while handling document close. URI: " + uri, e);
	}

	return unit;
}
 
Example 10
Source File: PrepareRenameHandler.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
public Either<Range, PrepareRenameResult> prepareRename(TextDocumentPositionParams params, IProgressMonitor monitor) {

		final ICompilationUnit unit = JDTUtils.resolveCompilationUnit(params.getTextDocument().getUri());
		if (unit != null) {
			try {
				OccurrencesFinder finder = new OccurrencesFinder();
				CompilationUnit ast = CoreASTProvider.getInstance().getAST(unit, CoreASTProvider.WAIT_YES, monitor);

				if (ast != null) {
					int offset = JsonRpcHelpers.toOffset(unit.getBuffer(), params.getPosition().getLine(), params.getPosition().getCharacter());
					String error = finder.initialize(ast, offset, 0);
					if (error == null) {
						OccurrenceLocation[] occurrences = finder.getOccurrences();
						if (occurrences != null) {
							for (OccurrenceLocation loc : occurrences) {
								if (monitor.isCanceled()) {
									return Either.forLeft(new Range());
								}
								if (loc.getOffset() <= offset && loc.getOffset() + loc.getLength() >= offset) {
									InnovationContext context = new InnovationContext(unit, loc.getOffset(), loc.getLength());
									context.setASTRoot(ast);
									ASTNode node = context.getCoveredNode();
									// Rename package is not fully supported yet.
									if (!isBinaryOrPackage(node)) {
										return Either.forLeft(JDTUtils.toRange(unit, loc.getOffset(), loc.getLength()));
									}
								}
							}
						}
					}
				}

			} catch (CoreException e) {
				JavaLanguageServerPlugin.logException("Problem computing occurrences for" + unit.getElementName() + " in prepareRename", e);
			}
		}
		throw new ResponseErrorException(new ResponseError(ResponseErrorCode.InvalidRequest, "Renaming this element is not supported.", null));
	}
 
Example 11
Source File: MoveHandler.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private static MoveDestinationsResponse getInstanceMethodDestinations(CodeActionParams params) {
	final ICompilationUnit unit = JDTUtils.resolveCompilationUnit(params.getTextDocument().getUri());
	if (unit == null) {
		return new MoveDestinationsResponse("Cannot find the compilation unit associated with " + params.getTextDocument().getUri());
	}

	MethodDeclaration methodDeclaration = getSelectedMethodDeclaration(unit, params);
	if (methodDeclaration == null) {
		return new MoveDestinationsResponse("The selected element is not a method.");
	}

	IMethodBinding methodBinding = methodDeclaration.resolveBinding();
	if (methodBinding == null || !(methodBinding.getJavaElement() instanceof IMethod)) {
		return new MoveDestinationsResponse("The selected element is not a method.");
	}

	IMethod method = (IMethod) methodBinding.getJavaElement();
	MoveInstanceMethodProcessor processor = new MoveInstanceMethodProcessor(method, PreferenceManager.getCodeGenerationSettings(method.getJavaProject().getProject()));
	Refactoring refactoring = new MoveRefactoring(processor);
	CheckConditionsOperation check = new CheckConditionsOperation(refactoring, CheckConditionsOperation.INITIAL_CONDITONS);
	try {
		check.run(new NullProgressMonitor());
		if (check.getStatus().hasFatalError()) {
			return new MoveDestinationsResponse(check.getStatus().getMessageMatchingSeverity(RefactoringStatus.FATAL));
		}

		IVariableBinding[] possibleTargets = processor.getPossibleTargets();
		LspVariableBinding[] targets = Stream.of(possibleTargets).map(target -> new LspVariableBinding(target)).toArray(LspVariableBinding[]::new);
		return new MoveDestinationsResponse(targets);
	} catch (CoreException e) {
		JavaLanguageServerPlugin.log(e);
	}

	return new MoveDestinationsResponse("Cannot find any target to move the method to.");
}
 
Example 12
Source File: CodeLensHandler.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
public List<CodeLens> getCodeLensSymbols(String uri, IProgressMonitor monitor) {
	if (!preferenceManager.getPreferences().isCodeLensEnabled()) {
		return Collections.emptyList();
	}
	final ICompilationUnit unit = JDTUtils.resolveCompilationUnit(uri);
	IClassFile classFile = null;
	if (unit == null) {
		classFile = JDTUtils.resolveClassFile(uri);
		if (classFile == null) {
			return Collections.emptyList();
		}
	} else {
		if (!unit.getResource().exists() || monitor.isCanceled()) {
			return Collections.emptyList();
		}
	}
	try {
		ITypeRoot typeRoot = unit != null ? unit : classFile;
		IJavaElement[] elements = typeRoot.getChildren();
		LinkedHashSet<CodeLens> lenses = new LinkedHashSet<>(elements.length);
		collectCodeLenses(typeRoot, elements, lenses, monitor);
		if (monitor.isCanceled()) {
			lenses.clear();
		}
		return new ArrayList<>(lenses);
	} catch (JavaModelException e) {
		JavaLanguageServerPlugin.logException("Problem getting code lenses for" + unit.getElementName(), e);
	}
	return Collections.emptyList();
}
 
Example 13
Source File: SaveActionHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testStaticWillSaveWaitUntil() throws Exception {
	String[] favourites = JavaLanguageServerPlugin.getPreferencesManager().getPreferences().getJavaCompletionFavoriteMembers();
	try {
		List<String> list = new ArrayList<>();
		list.add("java.lang.Math.*");
		list.add("java.util.stream.Collectors.*");
		JavaLanguageServerPlugin.getPreferencesManager().getPreferences().setJavaCompletionFavoriteMembers(list);
		URI srcUri = project.getFile("src/org/sample/Foo6.java").getRawLocationURI();
		ICompilationUnit cu = JDTUtils.resolveCompilationUnit(srcUri);
		/* @formatter:off */
		String expected = "package org.sample;\n" +
				"\n" +
				"import static java.lang.Math.PI;\n" +
				"import static java.lang.Math.abs;\n" +
				"import static java.util.stream.Collectors.toList;\n" +
				"\n" +
				"import java.util.List;\n" +
				"\n" +
				"public class Foo6 {\n" +
				"    List list = List.of(1).stream().collect(toList());\n" +
				"    double i = abs(-1);\n" +
				"    double pi = PI;\n" +
				"}\n";
		//@formatter:on
		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(expected, TextEditUtil.apply(doc, result));
	} finally {
		JavaLanguageServerPlugin.getPreferencesManager().getPreferences().setJavaCompletionFavoriteMembers(Arrays.asList(favourites));
	}
}
 
Example 14
Source File: OrganizeImportsCommand.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
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;
}
 
Example 15
Source File: DiagnosticsCommand.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
public static Object refreshDiagnostics(String uri, String scope, boolean syntaxOnly) {
	DiagnosticsState state = JavaLanguageServerPlugin.getNonProjectDiagnosticsState();
	boolean refreshAll = false;
	if (Objects.equals(scope, "thisFile")) {
		state.setErrorLevel(uri, syntaxOnly);
	} else if (Objects.equals(scope, "anyNonProjectFile")) {
		state.setGlobalErrorLevel(syntaxOnly);
		refreshAll = true;
	}

	ICompilationUnit target = refreshAll ? null : JDTUtils.resolveCompilationUnit(uri);
	refreshDiagnostics(target);

	return null;
}
 
Example 16
Source File: SyntaxServerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
@Test
public void testResolveCompletion() throws Exception {
	URI fileURI = openFile("maven/salut4", "src/main/java/java/Completion.java");
	ICompilationUnit cu = JDTUtils.resolveCompilationUnit(fileURI);
	assertNotNull(cu);
	cu.getBuffer().setContents("package java;\n\n" +
		"public class Completion {\n" +
		"	public static void main(String[] args) {\n" +
		"		fo\n" +
		"		System.out.println(\"Hello World!\");\n" +
		"	}\n\n" +
		"	/**\n" +
		"	* This method has Javadoc\n" +
		"	*/\n" +
		"	public static void foo(String bar) {\n" +
		"	}\n" +
		"	/**\n" +
		"	* Another Javadoc\n" +
		"	*/\n" +
		"	public static void foo() {\n" +
		"	}\n" +
		"}\n");
	cu.makeConsistent(null);

	int[] loc = findLocation(cu, "\t\tfo");
	String fileUri = ResourceUtils.fixURI(fileURI);
	TextDocumentIdentifier identifier = new TextDocumentIdentifier(fileUri);
	CompletionParams params = new CompletionParams(identifier, new Position(loc[0], loc[1]));
	CompletionList list = server.completion(params).join().getRight();
	assertNotNull(list);
	CompletionItem ci = list.getItems().stream().filter(item -> item.getLabel().startsWith("foo(String bar) : void")).findFirst().orElse(null);
	assertNotNull(ci);
	CompletionItem resolvedItem = server.resolveCompletionItem(ci).join();
	assertNotNull(resolvedItem);
	assertNotNull(resolvedItem.getDocumentation());
	assertNotNull(resolvedItem.getDocumentation().getLeft());
	String javadoc = resolvedItem.getDocumentation().getLeft();
	assertEquals(javadoc, " This method has Javadoc ");
	ci = list.getItems().stream().filter(item -> item.getLabel().startsWith("foo() : void")).findFirst().orElse(null);
	assertNotNull(ci);
	resolvedItem = server.resolveCompletionItem(ci).join();
	assertNotNull(resolvedItem);
	assertNotNull(resolvedItem.getDocumentation());
	assertNotNull(resolvedItem.getDocumentation().getLeft());
	javadoc = resolvedItem.getDocumentation().getLeft();
	assertEquals(javadoc, " Another Javadoc ");
}
 
Example 17
Source File: SyntaxServerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
@Test
public void testCompletionOnSingleName() throws Exception{
	URI fileURI = openFile("maven/salut4", "src/main/java/java/Completion.java");
	ICompilationUnit cu = JDTUtils.resolveCompilationUnit(fileURI);
	assertNotNull(cu);
	cu.getBuffer().setContents("package java;\n\n" +
		"public class Completion {\n" +
		"	void foo() {\n" +
		"		Objec\n" +
		"	}\n" +
		"}\n");
	cu.makeConsistent(null);

	int[] loc = findLocation(cu, "Objec");
	String fileUri = ResourceUtils.fixURI(fileURI);
	TextDocumentIdentifier identifier = new TextDocumentIdentifier(fileUri);
	CompletionParams params = new CompletionParams(identifier, new Position(loc[0], loc[1]));
	CompletionList list = server.completion(params).join().getRight();
	assertNotNull(list);
	assertFalse("No proposals were found", list.getItems().isEmpty());

	List<CompletionItem> items = list.getItems();
	for (CompletionItem item : items) {
		assertTrue(StringUtils.isNotBlank(item.getLabel()));
		assertNotNull(item.getKind());
		assertTrue(StringUtils.isNotBlank(item.getSortText()));
		//text edits are set during calls to "completion"
		assertNotNull(item.getTextEdit());
		assertTrue(StringUtils.isNotBlank(item.getInsertText()));
		assertNotNull(item.getFilterText());
		assertFalse(item.getFilterText().contains(" "));
		assertTrue(item.getLabel().startsWith(item.getInsertText()));
		assertTrue(item.getFilterText().startsWith("Objec"));
		//Check contains data used for completionItem resolution
		@SuppressWarnings("unchecked")
		Map<String,String> data = (Map<String, String>) item.getData();
		assertNotNull(data);
		assertTrue(StringUtils.isNotBlank(data.get(CompletionResolveHandler.DATA_FIELD_URI)));
		assertTrue(StringUtils.isNotBlank(data.get(CompletionResolveHandler.DATA_FIELD_PROPOSAL_ID)));
		assertTrue(StringUtils.isNotBlank(data.get(CompletionResolveHandler.DATA_FIELD_REQUEST_ID)));
	}
}
 
Example 18
Source File: JavaDocImageExtractionTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
@Test
public void testImageExtractionWithoutAnyJars() throws Exception {
	testFolderName = "javadoc-image-extraction-without-any";
	setupMockMavenProject(testFolderName);

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

	assertTrue(cu.isStructureKnown());

	IJavaElement javaElement = JDTUtils.findElementAtSelection(cu, 12, 22, null, new NullProgressMonitor());
	String finalString = HoverInfoProvider.computeJavadoc(javaElement).getValue();

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

	assertTrue(finalString.contains(expectedImageMarkdown));

}
 
Example 19
Source File: BaseDocumentLifeCycleHandler.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
private ICompilationUnit checkPackageDeclaration(String uri, ICompilationUnit unit) {
	if (unit.getResource() != null && unit.getJavaProject() != null && unit.getJavaProject().getProject().getName().equals(ProjectsManager.DEFAULT_PROJECT_NAME)) {
		try {
			CompilationUnit astRoot = CoreASTProvider.getInstance().getAST(unit, CoreASTProvider.WAIT_YES, new NullProgressMonitor());
			IProblem[] problems = astRoot.getProblems();
			for (IProblem problem : problems) {
				if (problem.getID() == IProblem.PackageIsNotExpectedPackage) {
					IResource file = unit.getResource();
					boolean toRemove = file.isLinked();
					if (toRemove) {
						IPath path = file.getParent().getProjectRelativePath();
						if (path.segmentCount() > 0 && JDTUtils.SRC.equals(path.segments()[0])) {
							String packageNameResource = path.removeFirstSegments(1).toString().replace(JDTUtils.PATH_SEPARATOR, JDTUtils.PERIOD);
							path = file.getLocation();
							if (path != null && path.segmentCount() > 0) {
								path = path.removeLastSegments(1);
								String pathStr = path.toString().replace(JDTUtils.PATH_SEPARATOR, JDTUtils.PERIOD);
								if (pathStr.endsWith(packageNameResource)) {
									toRemove = false;
								}
							}
						}
					}
					if (toRemove) {
						file.delete(true, new NullProgressMonitor());
						if (unit.equals(sharedASTProvider.getActiveJavaElement())) {
							sharedASTProvider.disposeAST();
						}
						unit.discardWorkingCopy();
						unit = JDTUtils.resolveCompilationUnit(uri);
						unit.becomeWorkingCopy(new NullProgressMonitor());
						triggerValidation(unit);
					}
					break;
				}
			}

		} catch (CoreException e) {
			JavaLanguageServerPlugin.logException(e.getMessage(), e);
		}
	}
	return unit;
}
 
Example 20
Source File: JavaDocImageExtractionTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 3 votes vote down vote up
@Test
public void testImageRelativeToFile() throws Exception {

	testFolderName = "relative-image";
	setupMockMavenProject(testFolderName);


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

	assertTrue(cu.isStructureKnown());

	IJavaElement javaElement = JDTUtils.findElementAtSelection(cu, 7, 23, null, new NullProgressMonitor());

	Path pp = Paths.get(uri).getParent();
	URI parentURI = pp.toUri();

	String parentExportPath = parentURI.getPath();

	String relativeExportPath = "FolderWithPictures/red-hat-logo.png";

	String absoluteExportPath = parentExportPath + relativeExportPath;

	String expectedImageMarkdown = "![Image](file:" + absoluteExportPath + ")";

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

	assertTrue(finalString.contains(expectedImageMarkdown));

}