Java Code Examples for org.eclipse.jdt.core.IJavaProject#getResolvedClasspath()

The following examples show how to use org.eclipse.jdt.core.IJavaProject#getResolvedClasspath() . 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: RefactoringScopeFactory.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private static IClasspathEntry getReferencingClassPathEntry(IJavaProject referencingProject, IJavaProject referencedProject) throws JavaModelException {
	IClasspathEntry result = null;
	IPath path = referencedProject.getProject().getFullPath();
	IClasspathEntry[] classpath = referencingProject.getResolvedClasspath(true);
	for (int i = 0; i < classpath.length; i++) {
		IClasspathEntry entry = classpath[i];
		if (entry.getEntryKind() == IClasspathEntry.CPE_PROJECT && path.equals(entry.getPath())) {
			if (entry.isExported()) {
				return entry;
			}
			// Consider it as a candidate. May be there is another entry that is
			// exported.
			result = entry;
		}
	}
	return result;
}
 
Example 2
Source File: XtendUIValidator.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
protected boolean isInSourceFolder(IJavaProject javaProject, IFile resource) {
	IPath path = resource.getFullPath();
	IClasspathEntry[] classpath;
	try {
		classpath = javaProject.getResolvedClasspath(true);
	} catch(JavaModelException e){
		return false; // not a Java project
	}
	for (int i = 0; i < classpath.length; i++) {
		IClasspathEntry entry = classpath[i];
		if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
			IPath entryPath = entry.getPath();
			if (entryPath.isPrefixOf(path)) {
				return true;
			}
		}
	}
	return false;
}
 
Example 3
Source File: XtendResourceUiServiceProvider.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
public boolean isInSourceFolder(IJavaProject javaProject, IFile resource) {
	IPath path = resource.getFullPath();
	IClasspathEntry[] classpath;
	try {
		classpath = javaProject.getResolvedClasspath(true);
	} catch(JavaModelException e){
		return false; // not a Java project
	}
	for (int i = 0; i < classpath.length; i++) {
		IClasspathEntry entry = classpath[i];
		if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
			IPath entryPath = entry.getPath();
			if (entryPath.isPrefixOf(path) && !isExcluded(entry, path)) {
				return true;
			}
		}
	}
	return false;
}
 
Example 4
Source File: RefactoringScopeFactory.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private static IClasspathEntry getReferencingClassPathEntry(IJavaProject referencingProject, IJavaProject referencedProject) throws JavaModelException {
	IClasspathEntry result= null;
	IPath path= referencedProject.getProject().getFullPath();
	IClasspathEntry[] classpath= referencingProject.getResolvedClasspath(true);
	for (int i= 0; i < classpath.length; i++) {
		IClasspathEntry entry= classpath[i];
		if (entry.getEntryKind() == IClasspathEntry.CPE_PROJECT && path.equals(entry.getPath())) {
			if (entry.isExported())
				return entry;
			// Consider it as a candidate. May be there is another entry that is
			// exported.
			result= entry;
		}
	}
	return result;
}
 
Example 5
Source File: DuplicatedCode.java    From JDeodorant with MIT License 6 votes vote down vote up
private ICompilationUnit getICompilationUnit(IJavaProject iJavaProject, String fullName) {
	try {
		IClasspathEntry[] classpathEntries = iJavaProject.getResolvedClasspath(true);
		for(int i = 0; i < classpathEntries.length; i++){
			IClasspathEntry entry = classpathEntries[i];

			if(entry.getContentKind() == IPackageFragmentRoot.K_SOURCE){
				IPath path = entry.getPath();  
				if (path.toString().length() > iJavaProject.getProject().getName().length() + 2) {
					String fullPath = path.toString().substring(iJavaProject.getProject().getName().length() + 2) + "/" + fullName;

					ICompilationUnit iCompilationUnit = (ICompilationUnit)JavaCore.create(iJavaProject.getProject().getFile(fullPath));
					if (iCompilationUnit != null && iCompilationUnit.exists())
						return iCompilationUnit;
				}
			}
		}
	} catch (JavaModelException e) {
		e.printStackTrace();
	}
	return null;
}
 
Example 6
Source File: CrySLBuilder.java    From CogniCrypt with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected IProject[] build(int kind, Map<String, String> args, IProgressMonitor monitor) throws CoreException {
	try {
		CrySLParser csmr = new CrySLParser(getProject());
		final IProject curProject = getProject();
		List<IPath> resourcesPaths = new ArrayList<IPath>();
		List<IPath> outputPaths = new ArrayList<IPath>();
		IJavaProject projectAsJavaProject = JavaCore.create(curProject);

		for (final IClasspathEntry entry : projectAsJavaProject.getResolvedClasspath(true)) {
			if (entry.getContentKind() == IPackageFragmentRoot.K_SOURCE) {
				IPath res = entry.getPath();
				if (!projectAsJavaProject.getPath().equals(res)) {
					resourcesPaths.add(res);
					IPath outputLocation = entry.getOutputLocation();
					outputPaths.add(outputLocation != null ? outputLocation : projectAsJavaProject.getOutputLocation());
				}
			}
		}
		for (int i = 0; i < resourcesPaths.size(); i++) {
			CrySLParserUtils.storeRulesToFile(csmr.readRulesWithin(resourcesPaths.get(i).toOSString()),
					ResourcesPlugin.getWorkspace().getRoot().findMember(outputPaths.get(i)).getLocation().toOSString());
		}
	}
	catch (IOException e) {
		Activator.getDefault().logError(e, "Build of CrySL rules failed.");
	}

	return null;
}
 
Example 7
Source File: ProjectAwareXtendXtext2EcorePostProcessor.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
protected ClassLoader createClassLoader(IJavaProject javaProject) throws CoreException {
	List<URL> urls = Lists.newArrayListWithExpectedSize(javaProject.getResolvedClasspath(true).length);
	try {
		IWorkspaceRoot workspaceRoot = getWorkspace().getRoot();
		urls.addAll(getOutputFolders(javaProject));
		for (IClasspathEntry entry : javaProject.getResolvedClasspath(true)) {
			IPath path = null;
			URL url = null;
			switch (entry.getEntryKind()) {
				case IClasspathEntry.CPE_SOURCE:
					break;
				case IClasspathEntry.CPE_PROJECT:
					IResource project = workspaceRoot.findMember(entry.getPath());
					urls.addAll(getOutputFolders(JavaCore.create(project.getProject())));
					break;
				default:
					path = entry.getPath();
					url = path.toFile().toURI().toURL();
					break;
			}
			if (url != null) {
				urls.add(url);
			}
		}
	} catch (MalformedURLException e) {
		logger.error("Error creating class loader for java project '" + javaProject.getProject().getName() + "'", e);
	}
	return new URLClassLoader(urls.toArray(new URL[urls.size()]), getClass().getClassLoader());
}
 
Example 8
Source File: JdtClasspathUriResolver.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
private URI findResourceInProjectRoot(IJavaProject javaProject, String path, Set<String> visited) throws CoreException {
	boolean includeAll = visited.isEmpty();
	if (visited.add(javaProject.getElementName())) {
		IProject project = javaProject.getProject();
		IResource resourceFromProjectRoot = project.findMember(path);
		if (resourceFromProjectRoot != null && resourceFromProjectRoot.exists()) {
			return createPlatformResourceURI(resourceFromProjectRoot);
		}
		for(IClasspathEntry entry: javaProject.getResolvedClasspath(true)) {
			if (entry.getEntryKind() == IClasspathEntry.CPE_PROJECT) {
				if (includeAll || entry.isExported()) {
					IResource referencedProject = project.getWorkspace().getRoot().findMember(entry.getPath());
					if (referencedProject != null && referencedProject.getType() == IResource.PROJECT) {
						IJavaProject referencedJavaProject = JavaCore.create((IProject) referencedProject);
						if (referencedJavaProject.exists()) {
							URI result = findResourceInProjectRoot(referencedJavaProject, path, visited);
							if (result != null) {
								return result;
							}
						}
					}
					break;
				}
			}
		}
	}
	return null;
}
 
Example 9
Source File: GeneratorSupport.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
private ResourceLoader createResourceLoader(final IProject project) {
  if (project != null) {
    IJavaProject javaProject = JavaCore.create(project);
    if (javaProject != null) {
      IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();
      try {
        IClasspathEntry[] classPathEntries = javaProject.getResolvedClasspath(true);
        URL[] urls = new URL[classPathEntries.length];
        for (int i = 0; i < classPathEntries.length; i++) {
          IClasspathEntry entry = classPathEntries[i];
          IPath path = null;
          switch (entry.getEntryKind()) {
          case IClasspathEntry.CPE_PROJECT:
            IJavaProject requiredProject = JavaCore.create((IProject) workspaceRoot.findMember(entry.getPath()));
            if (requiredProject != null) {
              path = workspaceRoot.findMember(requiredProject.getOutputLocation()).getLocation();
            }
            break;
          case IClasspathEntry.CPE_SOURCE:
            path = workspaceRoot.findMember(entry.getPath()).getLocation();
            break;
          default:
            path = entry.getPath();
            break;
          }
          if (path != null) {
            urls[i] = path.toFile().toURI().toURL();
          }
        }
        ClassLoader parentClassLoader = javaProject.getClass().getClassLoader();
        URLClassLoader classLoader = new URLClassLoader(urls, parentClassLoader);
        return new CustomResourceLoader(classLoader);
      } catch (MalformedURLException | CoreException e) {
        LOG.warn("Failed to create class loader for project " + project.getName(), e);
      }
    }
  }
  return new ResourceLoaderImpl(GeneratorSupport.class.getClassLoader());
}
 
Example 10
Source File: CompilationUnitDocumentProvider.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Creates a fake compilation unit.
 *
 * @param editorInput the URI editor input
 * @return the fake compilation unit
 * @since 3.3
 */
private ICompilationUnit createFakeCompiltationUnit(IURIEditorInput editorInput) {
	try {
		final URI uri= editorInput.getURI();
		final IFileStore fileStore= EFS.getStore(uri);
		final IPath path= URIUtil.toPath(uri);
		String fileStoreName= fileStore.getName();
		if (fileStoreName == null || path == null)
			return null;

		WorkingCopyOwner woc= new WorkingCopyOwner() {
			/*
			 * @see org.eclipse.jdt.core.WorkingCopyOwner#createBuffer(org.eclipse.jdt.core.ICompilationUnit)
			 * @since 3.2
			 */
			@Override
			public IBuffer createBuffer(ICompilationUnit workingCopy) {
				return new DocumentAdapter(workingCopy, fileStore, path);
			}
		};

		IClasspathEntry[] cpEntries= null;
		IJavaProject jp= findJavaProject(path);
		if (jp != null)
			cpEntries= jp.getResolvedClasspath(true);

		if (cpEntries == null || cpEntries.length == 0)
			cpEntries= new IClasspathEntry[] { JavaRuntime.getDefaultJREContainerEntry() };

		final ICompilationUnit cu= woc.newWorkingCopy(fileStoreName, cpEntries, getProgressMonitor());

		if (!isModifiable(editorInput))
			JavaModelUtil.reconcile(cu);

		return cu;
	} catch (CoreException ex) {
		return null;
	}
}
 
Example 11
Source File: MavenProjectSREProviderFactory.java    From sarl with Apache License 2.0 5 votes vote down vote up
@Override
public ProjectSREProvider getProjectSREProvider(IProject project) {
	try {
		if (project.hasNature(IMavenConstants.NATURE_ID)
				&& project.hasNature(JavaCore.NATURE_ID)
				&& project.hasNature(SARLEclipseConfig.NATURE_ID)) {
			final IMavenProjectFacade facade = MavenPluginActivator.getDefault()
					.getMavenProjectManager().getProject(project);
			if (facade == null) {
				return null;
			}
			final IJavaProject javaProject = JavaCore.create(project);
			final IClasspathEntry[] classpath = javaProject.getResolvedClasspath(true);
			if (classpath == null) {
				return null;
			}
			for (final IClasspathEntry dep : classpath) {
				final IPath depPath = dep.getPath();
				if (SARLRuntime.isPackedSRE(depPath)) {
					return new MavenProjectSREProvider(
							facade.getArtifactKey().toString()
							+ ":" + depPath.lastSegment(), //$NON-NLS-1$
							depPath);
				}
			}
		}
	} catch (CoreException e) {
		SARLMavenEclipsePlugin.getDefault().log(e);
	}
	return null;
}
 
Example 12
Source File: MockJavaProjectProviderTest.java    From xtext-eclipse with Eclipse Public License 2.0 4 votes vote down vote up
@Test public void testClasspathResolved() throws CoreException {
		IJavaProject javaProject = new MockJavaProjectProvider().getJavaProject(null);
		javaProject.getResolvedClasspath(false);
//		assertTrue(expandAndLookFor(javaProject, 0, ParameterizedTypes.class.getSimpleName() + ".class"));
		
	}
 
Example 13
Source File: JdtBasedProcessorProvider.java    From xtext-xtend with Eclipse Public License 2.0 4 votes vote down vote up
protected void collectClasspathURLs(final IJavaProject projectToUse, final LinkedHashSet<URL> result, final boolean includeOutputFolder, final Set<IJavaProject> visited) throws JavaModelException {
  try {
    if (((!projectToUse.getProject().isAccessible()) || (!visited.add(projectToUse)))) {
      return;
    }
    if (includeOutputFolder) {
      IPath path = projectToUse.getOutputLocation().addTrailingSeparator();
      String _string = URI.createPlatformResourceURI(path.toString(), true).toString();
      URL url = new URL(_string);
      result.add(url);
    }
    final IClasspathEntry[] resolvedClasspath = projectToUse.getResolvedClasspath(true);
    for (final IClasspathEntry entry : resolvedClasspath) {
      {
        URL url_1 = null;
        int _entryKind = entry.getEntryKind();
        switch (_entryKind) {
          case IClasspathEntry.CPE_SOURCE:
            if (includeOutputFolder) {
              final IPath path_1 = entry.getOutputLocation();
              if ((path_1 != null)) {
                String _string_1 = URI.createPlatformResourceURI(path_1.addTrailingSeparator().toString(), true).toString();
                URL _uRL = new URL(_string_1);
                url_1 = _uRL;
              }
            }
            break;
          case IClasspathEntry.CPE_PROJECT:
            IPath path_2 = entry.getPath();
            final IResource project = this.getWorkspaceRoot(projectToUse).findMember(path_2);
            final IJavaProject referencedProject = JavaCore.create(project.getProject());
            this.collectClasspathURLs(referencedProject, result, true, visited);
            break;
          case IClasspathEntry.CPE_LIBRARY:
            IPath path_3 = entry.getPath();
            final IResource library = this.getWorkspaceRoot(projectToUse).findMember(path_3);
            URL _xifexpression = null;
            if ((library != null)) {
              URL _xblockexpression = null;
              {
                final java.net.URI locationUri = library.getLocationURI();
                URL _xifexpression_1 = null;
                String _scheme = null;
                if (locationUri!=null) {
                  _scheme=locationUri.getScheme();
                }
                boolean _equals = Objects.equal(EFS.SCHEME_FILE, _scheme);
                if (_equals) {
                  java.net.URI _rawLocationURI = library.getRawLocationURI();
                  URL _uRL_1 = null;
                  if (_rawLocationURI!=null) {
                    _uRL_1=_rawLocationURI.toURL();
                  }
                  _xifexpression_1 = _uRL_1;
                } else {
                  _xifexpression_1 = null;
                }
                _xblockexpression = _xifexpression_1;
              }
              _xifexpression = _xblockexpression;
            } else {
              _xifexpression = path_3.toFile().toURI().toURL();
            }
            url_1 = _xifexpression;
            break;
          default:
            {
              IPath path_4 = entry.getPath();
              url_1 = path_4.toFile().toURI().toURL();
            }
            break;
        }
        if ((url_1 != null)) {
          result.add(url_1);
        }
      }
    }
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}
 
Example 14
Source File: JreServiceProjectSREProviderFactory.java    From sarl with Apache License 2.0 4 votes vote down vote up
private static ProjectSREProvider findOnClasspath(IJavaProject project) {
	try {
		final IClasspathEntry[] classpath = project.getResolvedClasspath(true);
		for (final IClasspathEntry entry : classpath) {
			final IPath path;
			final String id;
			final String name;
			switch (entry.getEntryKind()) {
			case IClasspathEntry.CPE_LIBRARY:
				path = entry.getPath();
				if (path != null) {
					id = path.makeAbsolute().toPortableString();
					name = path.lastSegment();
				} else {
					id  = null;
					name = null;
				}
				break;
			case IClasspathEntry.CPE_PROJECT:
				final IResource res = project.getProject().getParent().findMember(entry.getPath());
				if (res instanceof IProject) {
					final IProject dependency = (IProject) res;
					final IJavaProject javaDependency = JavaCore.create(dependency);
					path = javaDependency.getOutputLocation();
					id = javaDependency.getHandleIdentifier();
					name = javaDependency.getElementName();
					break;
				}
				continue;
			default:
				continue;
			}
			if (path != null && !SARLRuntime.isPackedSRE(path) && !SARLRuntime.isUnpackedSRE(path)) {
				final String bootstrap = SARLRuntime.getDeclaredBootstrap(path);
				if (!Strings.isEmpty(bootstrap)) {
					final List<IRuntimeClasspathEntry> 	classpathEntries = Collections.singletonList(new RuntimeClasspathEntry(entry));
					return new JreServiceProjectSREProvider(
							id, name,
							project.getPath().toPortableString(),
							bootstrap,
							classpathEntries);
				}
			}
		}
	} catch (JavaModelException exception) {
		//
	}
	return null;
}
 
Example 15
Source File: JavaModelUtility.java    From JDeodorant with MIT License 4 votes vote down vote up
public static Set<String> getAllSourceDirectories(IJavaProject jProject)
		throws JavaModelException {
	/*
	 * We sort the src paths by their character lengths in a non-increasing
	 * order, because we are going to see whether a Java file's path starts
	 * with a specific source path For example, if the Java file's path is
	 * "src/main/org/blah/blah", the "src/main" is considered the source
	 * path not "src/"
	 */
	Set<String> allSrcDirectories = new TreeSet<String>(new Comparator<String>() {
		public int compare(String o1, String o2) {
			if (o1.equals(o2))
				return 0;

			if (o1.length() == o2.length())
				return 1;

			return -Integer.compare(o1.length(), o2.length());
		}
	});

	IClasspathEntry[] classpathEntries = jProject
			.getResolvedClasspath(true);

	for (int i = 0; i < classpathEntries.length; i++) {
		IClasspathEntry entry = classpathEntries[i];
		if (entry.getContentKind() == IPackageFragmentRoot.K_SOURCE) {
			IPath path = entry.getPath();
			if (path.toString().equals(
					"/" + jProject.getProject().getName()))
				allSrcDirectories.add(path.toString());
			else if (path.toString().length() > jProject.getProject()
					.getName().length() + 2) {
				String srcDirectory = path.toString().substring(
						jProject.getProject().getName().length() + 2);
				allSrcDirectories.add(srcDirectory);
			}
		}
	}
	return allSrcDirectories;
}
 
Example 16
Source File: INSDEnvironmentPage.java    From uima-uimaj with Apache License 2.0 4 votes vote down vote up
/**
 * Gets the initial class path.
 *
 * @param classPath the class path
 * @return the initial class path
 */
private String getInitialClassPath(String classPath) {
  // do nothing if the container is not a project
  if (currentContainer.getType() != IResource.PROJECT) {
    return classPath;
  }

  try {
    IJavaProject javaProject = JavaCore.create((IProject) currentContainer);
    // if java project
    if (javaProject != null && javaProject.exists()) {

      MissingLibraries = new ArrayList();

      // get class path
      IClasspathEntry[] classPathEntries = javaProject.getResolvedClasspath(true);
      ArrayList resultStringEntries = tokenizeClassPath(classPath);

      // add classPathEntries
      addToClassPath(classPathEntries, resultStringEntries);

      // add output Location
      System.out.println("Output Location (normal): "
              + javaProject.getOutputLocation().toOSString());
      System.out.println("Output Location (relative): "
              + javaProject.getOutputLocation().makeRelative().toOSString());
      System.out.println("Output Location (absolute): "
              + javaProject.getOutputLocation().makeAbsolute().toOSString());
      String outputLocation = "$main_root/"
              + javaProject.getOutputLocation().makeRelative().removeFirstSegments(1)
                      .toOSString();
      outputLocation = outputLocation.replace('\\', '/');
      outputLocation = outputLocation.trim();
      System.out.println("Output Location (to class path): " + outputLocation);

      if (!contain(resultStringEntries, outputLocation)) {
        resultStringEntries.add(0, outputLocation);
        System.out.println("\tadded Output Location to ClassPath: " + outputLocation);
      }

      // convert class path a to String
      classPath = convertToString(resultStringEntries, ";");

      System.out.println("CLASSPATH: " + classPath);

      // warn about required projects (if any) javaProject.getRequiredProjectNames();
      if (MissingLibraries != null && MissingLibraries.size() > 0) {

        StringBuffer sb = new StringBuffer();
        Iterator itr = MissingLibraries.iterator();
        while (itr.hasNext())
          sb.append("\n- ").append((String) itr.next());
        MessageDialog
                .openWarning(
                        getShell(),
                        "Missing class path entries",
                        "The following class path entries corresponds to resources not included in your project. Please make sure all the required class path resources (except JRE and UIMA jars) are included in this project and in the PEAR class path (in the environment page of the wizard):"
                                + sb.toString());
      }
    }
  } catch (Throwable e) {
    MessageDialog
            .openWarning(
                    getShell(),
                    "Class Path Initialization",
                    "The class path could not be initialized properly. Please edit the class path variable in the environment page of the wizard.");
    e.printStackTrace();
  }

  return classPath;
}