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

The following examples show how to use org.eclipse.jdt.ls.core.internal.JDTUtils#findElementAtSelection() . 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: NavigateToDefinitionHandler.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
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;
}
 
Example 2
Source File: JavaDocImageExtractionTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testHyperlinkImage() throws Exception {
	testFolderName = "javadoc-image-extraction-with-hyperlink";
	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, 14, 22, null, new NullProgressMonitor());
	String finalString = HoverInfoProvider.computeJavadoc(javaElement).getValue();

	String expectedImageMarkdown = "![Image](https://www.redhat.com/cms/managed-files/Logo-redhat-color-375.png)";

	assertTrue(finalString.contains(expectedImageMarkdown));
}
 
Example 3
Source File: ResolveElementHandler.java    From java-debug with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * 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;
}
 
Example 4
Source File: FindLinksHandler.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
public static List<? extends Location> findLinks(String linkType, TextDocumentPositionParams position, IProgressMonitor monitor) {
	if (monitor.isCanceled()) {
		return Collections.emptyList();
	}
	ITypeRoot unit = JDTUtils.resolveTypeRoot(position.getTextDocument().getUri());
	if (unit != null && !monitor.isCanceled()) {
		PreferenceManager preferenceManager = JavaLanguageServerPlugin.getInstance().getPreferencesManager();
		try {
			IJavaElement element = JDTUtils.findElementAtSelection(unit, position.getPosition().getLine(), position.getPosition().getCharacter(), preferenceManager, monitor);
			if (!monitor.isCanceled() && Objects.equals(linkType, "superImplementation")) {
				IMethod overriddenMethod = findOverriddenMethod(element, monitor);
				if (!monitor.isCanceled() && overriddenMethod != null) {
					Location location = NavigateToDefinitionHandler.computeDefinitionNavigation(overriddenMethod, element.getJavaProject());
					if (!monitor.isCanceled() && location != null) {
						String declaringTypeName = overriddenMethod.getDeclaringType().getFullyQualifiedName();
						String methodName = overriddenMethod.getElementName();
						String displayName = declaringTypeName + "." + methodName;
						return Collections.singletonList(new LinkLocation(displayName, "method", location));
					}
				}
			}
		} catch (JavaModelException e) {
			// do nothing
		}
	}

	return Collections.emptyList();
}
 
Example 5
Source File: JavaDocImageExtractionTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
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());
}
 
Example 6
Source File: ReferencesHandler.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
public List<Location> findReferences(ReferenceParams param, IProgressMonitor monitor) {

		final List<Location> locations = new ArrayList<>();
		try {
			IJavaElement elementToSearch = JDTUtils.findElementAtSelection(JDTUtils.resolveTypeRoot(param.getTextDocument().getUri()), param.getPosition().getLine(), param.getPosition().getCharacter(), this.preferenceManager, monitor);

			if (elementToSearch == null) {
				return locations;
			}

			boolean includeClassFiles = preferenceManager.isClientSupportsClassFileContent();
			SearchEngine engine = new SearchEngine();
			SearchPattern pattern = SearchPattern.createPattern(elementToSearch, IJavaSearchConstants.REFERENCES);

			engine.search(pattern, new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() }, createSearchScope(), new SearchRequestor() {

				@Override
				public void acceptSearchMatch(SearchMatch match) throws CoreException {
					Object o = match.getElement();
					if (o instanceof IJavaElement) {
						IJavaElement element = (IJavaElement) o;
						ICompilationUnit compilationUnit = (ICompilationUnit) element.getAncestor(IJavaElement.COMPILATION_UNIT);
						Location location = null;
						if (compilationUnit != null) {
							location = JDTUtils.toLocation(compilationUnit, match.getOffset(), match.getLength());
						} else if (includeClassFiles) {
							IClassFile cf = (IClassFile) element.getAncestor(IJavaElement.CLASS_FILE);
							if (cf != null && cf.getSourceRange() != null) {
								location = JDTUtils.toLocation(cf, match.getOffset(), match.getLength());
							}
						}
						if (location != null) {
							locations.add(location);
						}
					}
				}
			}, monitor);

		} catch (CoreException e) {
			JavaLanguageServerPlugin.logException("Find references failure ", e);
		}
		return locations;
	}
 
Example 7
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 8
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));

}