Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support resolving stacktrace to uri #1584

Merged
merged 3 commits into from
Nov 3, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions org.eclipse.jdt.ls.core/plugin.xml
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,9 @@
<command
id="java.project.import">
</command>
<command
id="java.project.resolveStackTraceLocation">
</command>
</delegateCommandHandler>
</extension>
<extension
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
import org.eclipse.jdt.ls.core.internal.commands.OrganizeImportsCommand;
import org.eclipse.jdt.ls.core.internal.commands.ProjectCommand;
import org.eclipse.jdt.ls.core.internal.commands.ProjectCommand.ClasspathOptions;
import org.eclipse.jdt.ls.core.internal.handlers.ResolveSourceMappingHandler;
import org.eclipse.jdt.ls.core.internal.commands.SemanticTokensCommand;
import org.eclipse.jdt.ls.core.internal.commands.SourceAttachmentCommand;
import org.eclipse.jdt.ls.core.internal.semantictokens.SemanticTokensLegend;
Expand Down Expand Up @@ -79,6 +80,12 @@ public Object executeCommand(String commandId, List<Object> arguments, IProgress
case "java.project.import":
ProjectCommand.importProject(monitor);
return null;
case "java.project.resolveStackTraceLocation":
List<String> projectNames = null;
if (arguments.size() > 1) {
projectNames = (ArrayList<String>) arguments.get(1);
}
return ResolveSourceMappingHandler.resolveStackTraceLocation((String) arguments.get(0), projectNames);
default:
break;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*******************************************************************************
* Copyright (c) 2016-2019 Red Hat Inc. and others.
* Copyright (c) 2016-2020 Red Hat Inc. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License 2.0
* which accompanies this distribution, and is available at
Expand Down Expand Up @@ -139,6 +139,10 @@ public static IProject getProject(String projectName) {

public static IJavaProject getJavaProject(String projectName) {
IProject project = getProject(projectName);
return getJavaProject(project);
}

public static IJavaProject getJavaProject(IProject project) {
if (project != null && isJavaProject(project)) {
return JavaCore.create(project);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
/*******************************************************************************
* Copyright (c) 2020 Microsoft Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Microsoft Corporation - initial API and implementation
*******************************************************************************/

package org.eclipse.jdt.ls.core.internal.handlers;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.debug.core.sourcelookup.ISourceContainer;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.launching.IRuntimeClasspathEntry;
import org.eclipse.jdt.launching.JavaRuntime;
import org.eclipse.jdt.launching.sourcelookup.containers.JavaProjectSourceContainer;
import org.eclipse.jdt.ls.core.internal.JDTUtils;
import org.eclipse.jdt.ls.core.internal.JavaLanguageServerPlugin;
import org.eclipse.jdt.ls.core.internal.ProjectUtils;

public class JdtSourceLookUpProvider {

/**
* Resolve the uri of the source file or class file by the class fully qualified name, the source path
* and the interested projects.
*
* @param fullyQualifiedName
* the fully qualified name of the class.
* @param sourcePath
* the source path of the class.
* @param projectNames
* A list of the project names that needs to search in. If the given list is empty,
* All the projects in the workspace will be searched.
*
* @return the uri of the associated source file or class file.
*/
public String getSourceFileURI(String fullyQualifiedName, String sourcePath, List<String> projectNames) {
if (sourcePath == null) {
return null;
}

Object sourceElement = findSourceElement(sourcePath, getSourceContainers(projectNames));
if (sourceElement instanceof IResource) {
return JDTUtils.getFileURI((IResource) sourceElement);
} else if (sourceElement instanceof IClassFile) {
return JDTUtils.toUri((IClassFile) sourceElement);
}
return null;
}

/**
* Given a source name info, search the associated source file or class file from the source container list.
*
* @param sourcePath
* the target source name (e.g. org\eclipse\jdt\ls\xxx.java).
* @param containers
* the source container list.
* @return the associated source file or class file.
*/
private Object findSourceElement(String sourcePath, ISourceContainer[] containers) {
if (containers == null) {
return null;
}
for (ISourceContainer container : containers) {
try {
Object[] objects = container.findSourceElements(sourcePath);
if (objects.length > 0 && (objects[0] instanceof IResource || objects[0] instanceof IClassFile)) {
return objects[0];
}
} catch (CoreException e) {
JavaLanguageServerPlugin.logException("Failed to find the source elements", e);
}
}
return null;
}

private ISourceContainer[] getSourceContainers(List<String> projectNames) {
List<IProject> projects = new ArrayList<>();
if (projectNames == null || projectNames.size() == 0) {
projects.addAll(Arrays.asList(ProjectUtils.getAllProjects()));
} else {
for (String projectName : projectNames) {
projects.add(ProjectUtils.getProject(projectName));
}
}

Set<ISourceContainer> containers = new LinkedHashSet<>();
Set<IRuntimeClasspathEntry> calculated = new LinkedHashSet<>();
projects.stream().map(project -> ProjectUtils.getJavaProject(project))
.filter(javaProject -> javaProject != null && javaProject.exists())
.forEach(javaProject -> {
// Add source containers associated with the project's runtime classpath entries.
containers.addAll(Arrays.asList(getSourceContainers(javaProject, calculated)));
// Add source containers associated with the project's source folders.
containers.add(new JavaProjectSourceContainer(javaProject));
});

return containers.toArray(new ISourceContainer[0]);
}

private ISourceContainer[] getSourceContainers(IJavaProject project, Set<IRuntimeClasspathEntry> calculated) {
if (project == null || !project.exists()) {
return new ISourceContainer[0];
}

try {
IRuntimeClasspathEntry[] unresolved = JavaRuntime.computeUnresolvedRuntimeClasspath(project);
List<IRuntimeClasspathEntry> resolved = new ArrayList<>();
for (IRuntimeClasspathEntry entry : unresolved) {
for (IRuntimeClasspathEntry resolvedEntry : JavaRuntime.resolveRuntimeClasspathEntry(entry, project)) {
if (!calculated.contains(resolvedEntry)) {
calculated.add(resolvedEntry);
resolved.add(resolvedEntry);
}
}
}
Set<ISourceContainer> containers = new LinkedHashSet<>();
containers.addAll(Arrays.asList(
JavaRuntime.getSourceContainers(resolved.toArray(new IRuntimeClasspathEntry[0]))));
Copy link
Contributor

@rgrunber rgrunber Oct 30, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think there may be an issue here when JavaSourceLookupUtil#translate(..) creates a PackageFragmentRootSourceContainer(..) for the archive entries. The PackageFragmentRootSourceContainer class doesn't seem to use the source attachment to figure the source location. It ends up just returning a reference in the classfile.

Update : Come to think of it, I could be wrong here. I mean if the stacktrace reference is meant to just resolve to the artifact that ran that code then I think this is fine.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, here we mean to resolve a uri for a given stack trace line, and the uri comes from the classfile's reference.

To resolve the content(source code) of the uri, we have a content provider to do this: https://github.com/eclipse/eclipse.jdt.ls/blob/master/org.eclipse.jdt.ls.core/src/org/eclipse/jdt/ls/core/internal/DisassemblerContentProvider.java#L52

return containers.toArray(new ISourceContainer[0]);
} catch (CoreException e) {
JavaLanguageServerPlugin.logException("Failed to find the source elements for project: " + project.getElementName(), e);
}

return new ISourceContainer[0];
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
/*******************************************************************************
* Copyright (c) 2020 Microsoft Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Microsoft Corporation - initial API and implementation
*******************************************************************************/

package org.eclipse.jdt.ls.core.internal.handlers;

import java.io.File;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang3.StringUtils;

public class ResolveSourceMappingHandler {
private static final Pattern SOURCE_PATTERN = Pattern.compile("([\\w$\\.]+\\/)?(([\\w$]+\\.)+[<\\w$>]+)\\(([\\w-$]+\\.java:\\d+)\\)");
private static final JdtSourceLookUpProvider sourceProvider = new JdtSourceLookUpProvider();

/**
* Given a line of stacktrace, resolve the uri of the source file or class file.
*
* @param lineText
* the line of the stacktrace.
* @param projectNames
* A list of the project names that needs to search in. If the given list is empty,
* All the projects in the workspace will be searched.
*
* @return the uri of the associated source file or class file.
*/
public static String resolveStackTraceLocation(String lineText, List<String> projectNames) {
if (lineText == null) {
return null;
}

Matcher matcher = SOURCE_PATTERN.matcher(lineText);
if (matcher.find()) {
String methodField = matcher.group(2);
String locationField = matcher.group(matcher.groupCount());
String fullyQualifiedName = methodField.substring(0, methodField.lastIndexOf("."));
String packageName = fullyQualifiedName.lastIndexOf(".") > -1 ? fullyQualifiedName.substring(0, fullyQualifiedName.lastIndexOf(".")) : "";
String[] locations = locationField.split(":");
String sourceName = locations[0];
String sourcePath = StringUtils.isBlank(packageName) ? sourceName
: packageName.replace('.', File.separatorChar) + File.separatorChar + sourceName;
return sourceProvider.getSourceFileURI(fullyQualifiedName, sourcePath, projectNames);
}

return null;
}
}
75 changes: 75 additions & 0 deletions org.eclipse.jdt.ls.tests/projects/maven/quickstart2/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>quickstart</groupId>
<artifactId>quickstart2</artifactId>
<version>1.0-SNAPSHOT</version>

<name>quickstart2</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
</properties>

<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
<scope>test</scope>
</dependency>
</dependencies>

<build>
<pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
<plugins>
<!-- clean lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#clean_Lifecycle -->
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.1.0</version>
</plugin>
<!-- default lifecycle, jar packaging: see https://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_jar_packaging -->
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.1</version>
</plugin>
<plugin>
<artifactId>maven-jar-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
</plugin>
<!-- site lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#site_Lifecycle -->
<plugin>
<artifactId>maven-site-plugin</artifactId>
<version>3.7.1</version>
</plugin>
<plugin>
<artifactId>maven-project-info-reports-plugin</artifactId>
<version>3.0.0</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package quickstart;

public class App {
public String getName() {
return "App";
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package quickstart;

import static org.junit.Assert.assertEquals;

import org.junit.Test;

public class AppTest {
@Test
public void shouldAnswerWithTrue() {
assertEquals("app", new App().getName());
}

public static void main(String[] args) throws Exception {
Class<?> clazz = Class.forName("com.baeldung.reflection.Goat");
// assertEquals("app", new App().getName());
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
/*******************************************************************************
* Copyright (c) 2020 Microsoft Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Microsoft Corporation - initial API and implementation
*******************************************************************************/

package org.eclipse.jdt.ls.core.internal.handlers;

import static org.junit.Assert.assertTrue;

import java.util.Arrays;

import org.eclipse.jdt.ls.core.internal.managers.AbstractProjectsManagerBasedTest;
import org.junit.Before;
import org.junit.Test;

public class ResolveSourceMappingHandlerTest extends AbstractProjectsManagerBasedTest {

@Before
public void setup() throws Exception {
importProjects("maven/quickstart2");
}

@Test
public void testResolveSourceUri() {
String uri = ResolveSourceMappingHandler.resolveStackTraceLocation("at quickstart.AppTest.shouldAnswerWithTrue(AppTest.java:10)", Arrays.asList("quickstart2"));
assertTrue(uri.startsWith("file://"));
assertTrue(uri.contains("quickstart2/src/test/java/quickstart/AppTest.java"));
}

@Test
public void testResolveDependencyUri() {
String uri = ResolveSourceMappingHandler.resolveStackTraceLocation("at org.junit.Assert.assertEquals(Assert.java:117)", Arrays.asList("quickstart2"));
assertTrue(uri.startsWith("jdt://contents/junit-4.13.jar/org.junit/Assert.class"));
assertTrue(uri.contains("junit%5C/junit%5C/4.13%5C/junit-4.13.jar=/maven.pomderived=/true=/=/maven.pomderived=/true=/=/test=/true=/=/maven.groupId=/junit=/=/maven.artifactId=/junit=/=/maven.version=/4.13=/=/maven.scope=/test=/%3Corg.junit(Assert.class"));
}

@Test
public void testResolveDependencyUriWithoutGivingProjectNames() {
String uri = ResolveSourceMappingHandler.resolveStackTraceLocation("at org.junit.Assert.assertEquals(Assert.java:117)", null);
assertTrue(uri.startsWith("jdt://contents/junit-4.13.jar/org.junit/Assert.class"));
assertTrue(uri.contains("junit%5C/junit%5C/4.13%5C/junit-4.13.jar=/maven.pomderived=/true=/=/maven.pomderived=/true=/=/test=/true=/=/maven.groupId=/junit=/=/maven.artifactId=/junit=/=/maven.version=/4.13=/=/maven.scope=/test=/%3Corg.junit(Assert.class"));
}
}