Java Code Examples for org.eclipse.jdt.core.IClasspathEntry#getPath()

The following examples show how to use org.eclipse.jdt.core.IClasspathEntry#getPath() . 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: GWTMavenRuntime.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Maven-based GWT SDKs do not have a clear installation path. So, we say that the installation path corresponds to:
 * <code><repository path>/<group path></code>.
 */
@Override
public IPath getInstallationPath() {

  try {
    IClasspathEntry classpathEntry = findGwtUserClasspathEntry();
    if (classpathEntry == null) {
      return null;
    }

    IPath p = classpathEntry.getPath();
    if (p.segmentCount() < 4) {
      return null;
    }
    return p.removeLastSegments(3);
  } catch (JavaModelException e) {
    Activator.getDefault().getLog().log(new Status(IStatus.ERROR, Activator.PLUGIN_ID,
        "Unable to determine installation path for the maven-based GWT runtime.", e));
  }

  return null;
}
 
Example 2
Source File: BuildPathsBlock.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private CPListElement findElement(IClasspathEntry entry) {
	CPListElement prefixMatch= null;
	int entryKind= entry.getEntryKind();
	for (int i= 0, len= fClassPathList.getSize(); i < len; i++) {
		CPListElement curr= fClassPathList.getElement(i);
		if (curr.getEntryKind() == entryKind) {
			IPath entryPath= entry.getPath();
			IPath currPath= curr.getPath();
			if (currPath.equals(entryPath)) {
				return curr;
			}
			// in case there's no full match, look for a similar container (same ID segment):
			if (prefixMatch == null && entryKind == IClasspathEntry.CPE_CONTAINER) {
				int n= entryPath.segmentCount();
				if (n > 0) {
					IPath genericContainerPath= n == 1 ? entryPath : entryPath.removeLastSegments(n - 1);
					if (n > 1 && genericContainerPath.isPrefixOf(currPath)) {
						prefixMatch= curr;
					}
				}
			}
		}
	}
	return prefixMatch;
}
 
Example 3
Source File: EclipseBuildSupport.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public boolean fileChanged(IResource resource, CHANGE_TYPE changeType, IProgressMonitor monitor) throws CoreException {
	if (resource == null || !applies(resource.getProject())) {
		return false;
	}
	refresh(resource, changeType, monitor);
	IProject project = resource.getProject();
	if (ProjectUtils.isJavaProject(project)) {
		IJavaProject javaProject = JavaCore.create(project);
		IClasspathEntry[] classpath = javaProject.getRawClasspath();
		for (IClasspathEntry entry : classpath) {
			if (entry.getEntryKind() == IClasspathEntry.CPE_LIBRARY) {
				IPath path = entry.getPath();
				IFile r = ResourcesPlugin.getWorkspace().getRoot().getFile(path);
				if (r != null && r.equals(resource)) {
					IClasspathEntry[] rawClasspath = javaProject.getRawClasspath();
					javaProject.setRawClasspath(new IClasspathEntry[0], monitor);
					javaProject.setRawClasspath(rawClasspath, monitor);
					break;
				}
			}
		}
	}
	return false;
}
 
Example 4
Source File: BuildPathSupport.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static void updateProjectClasspath(Shell shell, IJavaProject jproject, IClasspathEntry newEntry, String[] changedAttributes, IProgressMonitor monitor) throws JavaModelException {
	IClasspathEntry[] oldClasspath= jproject.getRawClasspath();
	int nEntries= oldClasspath.length;
	ArrayList<IClasspathEntry> newEntries= new ArrayList<IClasspathEntry>(nEntries + 1);
	int entryKind= newEntry.getEntryKind();
	IPath jarPath= newEntry.getPath();
	boolean found= false;
	for (int i= 0; i < nEntries; i++) {
		IClasspathEntry curr= oldClasspath[i];
		if (curr.getEntryKind() == entryKind && curr.getPath().equals(jarPath)) {
			// add modified entry
			newEntries.add(getUpdatedEntry(curr, newEntry, changedAttributes, jproject));
			found= true;
		} else {
			newEntries.add(curr);
		}
	}
	if (!found) {
		if (!putJarOnClasspathDialog(shell)) {
			return;
		}
		// add new
		newEntries.add(newEntry);
	}
	IClasspathEntry[] newClasspath= newEntries.toArray(new IClasspathEntry[newEntries.size()]);
	jproject.setRawClasspath(newClasspath, monitor);
}
 
Example 5
Source File: GwtSdk.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
private IPath computeInstallPathFromProjectOrSourceClasspathEntry(IClasspathEntry classpathEntry)
    throws JavaModelException {
  IPath installPath;
  IPath entryPath = classpathEntry.getPath();
  // First segment should be project name
  String projectName = entryPath.segment(0);
  IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
  IJavaProject jProject = JavaCore.create(project);
  installPath = computeInstallPathFromProject(jProject);
  return installPath;
}
 
Example 6
Source File: AbstractGWTRuntimeTest.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
protected boolean assertGWTRuntimeEntry(IPath runtimePath,
    IClasspathEntry[] entries) {
  boolean hasGWTRuntime = false;

  for (IClasspathEntry entry : entries) {
    IPath entryPath = entry.getPath();

    if (entry.getEntryKind() == IClasspathEntry.CPE_CONTAINER) {
      if (GWTRuntimeContainer.isPathForGWTRuntimeContainer(entryPath)) {
        // Make sure we have only one GWT runtime
        if (hasGWTRuntime) {
          return false;
        }

        // We found at a GWT runtime
        hasGWTRuntime = true;

        // Make sure it's the one we're looking for
        if (!entryPath.equals(runtimePath)) {
          return false;
        }
      }
    }

    // Make sure we don't have any gwt-user.jar dependencies
    if (entry.getEntryKind() == IClasspathEntry.CPE_LIBRARY) {
      String jarName = entryPath.lastSegment();
      if (jarName.equals(GwtSdk.GWT_USER_JAR)) {
        return false;
      }
    }
  }

  return hasGWTRuntime;
}
 
Example 7
Source File: SARLClasspathContainerTest.java    From sarl with Apache License 2.0 5 votes vote down vote up
private static boolean isReferenceLibrary(String reference, IClasspathEntry entry) {
	IPath path = entry.getPath();
	String str = path.lastSegment();
	if ("classes".equals(str)) {
		str = path.segment(path.segmentCount() - 3);
		return str.equals(reference);
	}
	return str.startsWith(reference + "_");
}
 
Example 8
Source File: JavaProject.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public boolean isOnClasspath(IResource resource) {
	IPath exactPath = resource.getFullPath();
	IPath path = exactPath;

	// ensure that folders are only excluded if all of their children are excluded
	int resourceType = resource.getType();
	boolean isFolderPath = resourceType == IResource.FOLDER || resourceType == IResource.PROJECT;

	IClasspathEntry[] classpath;
	try {
		classpath = this.getResolvedClasspath();
	} catch(JavaModelException e){
		return false; // not a Java project
	}
	for (int i = 0; i < classpath.length; i++) {
		IClasspathEntry entry = classpath[i];
		IPath entryPath = entry.getPath();
		if (entryPath.equals(exactPath)) { // package fragment roots must match exactly entry pathes (no exclusion there)
			return true;
		}
		// https://bugs.eclipse.org/bugs/show_bug.cgi?id=276373
		// When a classpath entry is absolute, convert the resource's relative path to a file system path and compare
		// e.g - /P/lib/variableLib.jar and /home/P/lib/variableLib.jar when compared should return true
		if (entryPath.isAbsolute()
				&& entryPath.equals(ResourcesPlugin.getWorkspace().getRoot().getLocation().append(exactPath))) {
			return true;
		}
		if (entryPath.isPrefixOf(path)
				&& !Util.isExcluded(path, ((ClasspathEntry)entry).fullInclusionPatternChars(), ((ClasspathEntry)entry).fullExclusionPatternChars(), isFolderPath)) {
			return true;
		}
	}
	return false;
}
 
Example 9
Source File: JDTAwareSourceFolderProvider.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public List<? extends IContainer> getSourceFolders(IProject project) {
	List<IContainer> sourceFolders = Lists.newArrayList();
	IJavaProject javaProject = JavaCore.create(project);
	IClasspathEntry[] classpath;
	if (!javaProject.exists()) {
		return Collections.emptyList();
	}
	try {
		classpath = javaProject.getRawClasspath();
	} catch (JavaModelException e) {
		log.error("Error determining source folders for project " + project.getName(), e);
		return Collections.emptyList();
	}
	for (IClasspathEntry entry : classpath) {
		if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
			IPath path = entry.getPath();
			// see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=436371
			if (path.segmentCount() == 1) {
				sourceFolders.add(project);
			} else {
				sourceFolders.add(project.getWorkspace().getRoot().getFolder(entry.getPath()));
			}
		}
	}
	return sourceFolders;
}
 
Example 10
Source File: NativeLibrariesPropertyPage.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * @see org.eclipse.jface.dialogs.IDialogPage#createControl(org.eclipse.swt.widgets.Composite)
 */
@Override
public void createControl(Composite parent) {
	IJavaElement elem= getJavaElement();
	try {
		if (elem instanceof IPackageFragmentRoot) {
			IPackageFragmentRoot root= (IPackageFragmentRoot) elem;

			IClasspathEntry entry= JavaModelUtil.getClasspathEntry(root);
			if (entry == null) {
				fIsValidElement= false;
				setDescription(PreferencesMessages.NativeLibrariesPropertyPage_invalidElementSelection_desription);
			} else {
				if (entry.getEntryKind() == IClasspathEntry.CPE_CONTAINER) {
					fContainerPath= entry.getPath();
					fEntry= handleContainerEntry(fContainerPath, elem.getJavaProject(), root.getPath());
					fIsValidElement= fEntry != null && !fIsReadOnly;
				} else {
					fContainerPath= null;
					fEntry= entry;
					fIsValidElement= true;
				}
			}
		} else {
			fIsValidElement= false;
			setDescription(PreferencesMessages.NativeLibrariesPropertyPage_invalidElementSelection_desription);
		}
	} catch (JavaModelException e) {
		fIsValidElement= false;
		setDescription(PreferencesMessages.NativeLibrariesPropertyPage_invalidElementSelection_desription);
	}
	super.createControl(parent);
}
 
Example 11
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 12
Source File: JavaProject.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public boolean contains(IResource resource) {

		IClasspathEntry[] classpath;
		IPath output;
		try {
			classpath = getResolvedClasspath();
			output = getOutputLocation();
		} catch (JavaModelException e) {
			return false;
		}

		IPath fullPath = resource.getFullPath();
		IPath innerMostOutput = output.isPrefixOf(fullPath) ? output : null;
		IClasspathEntry innerMostEntry = null;
		ExternalFoldersManager foldersManager = JavaModelManager.getExternalManager();
		for (int j = 0, cpLength = classpath.length; j < cpLength; j++) {
			IClasspathEntry entry = classpath[j];

			IPath entryPath = entry.getPath();
			if (entry.getEntryKind() == IClasspathEntry.CPE_LIBRARY) {
				IResource linkedFolder = foldersManager.getFolder(entryPath);
				if (linkedFolder != null)
					entryPath = linkedFolder.getFullPath();
			}
			if ((innerMostEntry == null || innerMostEntry.getPath().isPrefixOf(entryPath))
					&& entryPath.isPrefixOf(fullPath)) {
				innerMostEntry = entry;
			}
			IPath entryOutput = classpath[j].getOutputLocation();
			if (entryOutput != null && entryOutput.isPrefixOf(fullPath)) {
				innerMostOutput = entryOutput;
			}
		}
		if (innerMostEntry != null) {
			// special case prj==src and nested output location
			if (innerMostOutput != null && innerMostOutput.segmentCount() > 1 // output isn't project
					&& innerMostEntry.getPath().segmentCount() == 1) { // 1 segment must be project name
				return false;
			}
			if  (resource instanceof IFolder) {
				 // folders are always included in src/lib entries
				 return true;
			}
			switch (innerMostEntry.getEntryKind()) {
				case IClasspathEntry.CPE_SOURCE:
					// .class files are not visible in source folders
					return !org.eclipse.jdt.internal.compiler.util.Util.isClassFileName(fullPath.lastSegment());
				case IClasspathEntry.CPE_LIBRARY:
					// .java files are not visible in library folders
					return !org.eclipse.jdt.internal.core.util.Util.isJavaLikeFileName(fullPath.lastSegment());
			}
		}
		if (innerMostOutput != null) {
			return false;
		}
		return true;
	}
 
Example 13
Source File: SourceAttachmentPropertyPage.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private Control createPageContent(Composite composite) {
	try {
		fContainerPath= null;
		fEntry= null;
		fRoot= getJARPackageFragmentRoot();
		if (fRoot == null || fRoot.getKind() != IPackageFragmentRoot.K_BINARY) {
			return createMessageContent(composite, PreferencesMessages.SourceAttachmentPropertyPage_noarchive_message, null);
		}

		IPath containerPath= null;
		IJavaProject jproject= fRoot.getJavaProject();
		IClasspathEntry entry= JavaModelUtil.getClasspathEntry(fRoot);
		boolean canEditEncoding= true;
		if (entry.getEntryKind() == IClasspathEntry.CPE_CONTAINER) {
			containerPath= entry.getPath();
			ClasspathContainerInitializer initializer= JavaCore.getClasspathContainerInitializer(containerPath.segment(0));
			IClasspathContainer container= JavaCore.getClasspathContainer(containerPath, jproject);
			if (initializer == null || container == null) {
				return createMessageContent(composite, Messages.format(PreferencesMessages.SourceAttachmentPropertyPage_invalid_container, BasicElementLabels.getPathLabel(containerPath, false)), fRoot);
			}
			String containerName= container.getDescription();

			IStatus status= initializer.getSourceAttachmentStatus(containerPath, jproject);
			if (status.getCode() == ClasspathContainerInitializer.ATTRIBUTE_NOT_SUPPORTED) {
				return createMessageContent(composite, Messages.format(PreferencesMessages.SourceAttachmentPropertyPage_not_supported, containerName), null);
			}
			if (status.getCode() == ClasspathContainerInitializer.ATTRIBUTE_READ_ONLY) {
				return createMessageContent(composite, Messages.format(PreferencesMessages.SourceAttachmentPropertyPage_read_only, containerName), fRoot);
			}
			IStatus attributeStatus= initializer.getAttributeStatus(containerPath, jproject, IClasspathAttribute.SOURCE_ATTACHMENT_ENCODING);
			canEditEncoding= !(attributeStatus.getCode() == ClasspathContainerInitializer.ATTRIBUTE_NOT_SUPPORTED || attributeStatus.getCode() == ClasspathContainerInitializer.ATTRIBUTE_READ_ONLY);

			entry= JavaModelUtil.findEntryInContainer(container, fRoot.getPath());
		}
		fContainerPath= containerPath;
		fEntry= entry;

		fSourceAttachmentBlock= new SourceAttachmentBlock(this, entry, canEditEncoding);
		return fSourceAttachmentBlock.createControl(composite);
	} catch (CoreException e) {
		JavaPlugin.log(e);
		return createMessageContent(composite, PreferencesMessages.SourceAttachmentPropertyPage_noarchive_message, null);
	}
}
 
Example 14
Source File: JdtTypeProvider.java    From xtext-eclipse with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * @see JavaProject computePackageFragmentRoots(IClasspathEntry, ObjectVector, HashSet, IClasspathEntry, boolean, boolean, java.util.Map)
 */
private void collectSourcePackageFragmentRoots(JavaProject javaProject, HashSet<String> rootIDs, IClasspathEntry referringEntry, ObjectVector result) throws JavaModelException {
	if (referringEntry == null){
		rootIDs.add(javaProject.rootID());
	} else if (rootIDs.contains(javaProject.rootID())) {
		return;
	}
	IWorkspaceRoot workspaceRoot = javaProject.getProject().getWorkspace().getRoot();
	for(IClasspathEntry entry: javaProject.getResolvedClasspath()) {
		switch(entry.getEntryKind()) {
			case IClasspathEntry.CPE_PROJECT:
				if (referringEntry != null && !entry.isExported())
					return;
				
				IPath pathToProject = entry.getPath();
				IResource referencedProject = workspaceRoot.findMember(pathToProject);
				if (referencedProject != null && referencedProject.getType() == IResource.PROJECT) {
					IProject casted = (IProject) referencedProject;
					if (JavaProject.hasJavaNature(casted)) {
						rootIDs.add(javaProject.rootID());
						JavaProject referencedJavaProject = (JavaProject) JavaCore.create(casted);
						collectSourcePackageFragmentRoots(referencedJavaProject, rootIDs, entry, result);
					}
				}
				break;
			case IClasspathEntry.CPE_SOURCE:
				// inlined from org.eclipse.jdt.internal.core.JavaProject
				// .computePackageFragmentRoots(IClasspathEntry, ObjectVector, HashSet, IClasspathEntry, boolean, boolean, Map)
				IPath projectPath = javaProject.getProject().getFullPath();
				IPath entryPath = entry.getPath();
				if (projectPath.isPrefixOf(entryPath)){
					Object target = JavaModel.getTarget(entryPath, true/*check existency*/);
					if (target != null) {
						if (target instanceof IFolder || target instanceof IProject){
							IPackageFragmentRoot root = javaProject.getPackageFragmentRoot((IResource)target);
							result.add(root);
						}
					}
				}
				break;
		}
	}
}
 
Example 15
Source File: PDEClassPathGenerator.java    From spotbugs with GNU Lesser General Public License v2.1 4 votes vote down vote up
private static void appendBundleToClasspath(BundleDescription bd, List<String> pdeClassPath, IPath defaultOutputLocation) {
    IPluginModelBase model = PluginRegistry.findModel(bd);
    if (model == null) {
        return;
    }
    ArrayList<IClasspathEntry> classpathEntries = new ArrayList<>();
    ClasspathUtilCore.addLibraries(model, classpathEntries);

    for (IClasspathEntry cpe : classpathEntries) {
        IPath location;
        if (cpe.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
            location = ResourceUtils.getOutputLocation(cpe, defaultOutputLocation);
        } else {
            location = cpe.getPath();
        }
        if (location == null) {
            continue;
        }
        String locationStr = location.toOSString();
        if (pdeClassPath.contains(locationStr)) {
            continue;
        }
        // extra cleanup for some directories on classpath
        String bundleLocation = bd.getLocation();
        if (bundleLocation != null && !"jar".equals(location.getFileExtension()) &&
                new File(bundleLocation).isDirectory()) {
            if (bd.getSymbolicName().equals(location.lastSegment())) {
                // ignore badly resolved plugin directories inside workspace
                // ("." as classpath is resolved as plugin root directory)
                // which is, if under workspace, NOT a part of the classpath
                continue;
            }
        }
        if (!location.isAbsolute()) {
            location = ResourceUtils.relativeToAbsolute(location);
        }
        if (!isValidPath(location)) {
            continue;
        }
        locationStr = location.toOSString();
        if (!pdeClassPath.contains(locationStr)) {
            pdeClassPath.add(locationStr);
        }
    }
}
 
Example 16
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 17
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 18
Source File: CPListElement.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public static CPListElement create(Object parent, IClasspathEntry curr, boolean newElement, IJavaProject project) {
	IPath path= curr.getPath();
	IWorkspaceRoot root= ResourcesPlugin.getWorkspace().getRoot();

	// get the resource
	IResource res= null;
	boolean isMissing= false;
	IPath linkTarget= null;

	switch (curr.getEntryKind()) {
		case IClasspathEntry.CPE_CONTAINER:
			try {
				isMissing= project != null && (JavaCore.getClasspathContainer(path, project) == null);
			} catch (JavaModelException e) {
				isMissing= true;
			}
			break;
		case IClasspathEntry.CPE_VARIABLE:
			IPath resolvedPath= JavaCore.getResolvedVariablePath(path);
			isMissing=  root.findMember(resolvedPath) == null && !resolvedPath.toFile().exists();
			break;
		case IClasspathEntry.CPE_LIBRARY:
			res= root.findMember(path);
			if (res == null) {
				if (!ArchiveFileFilter.isArchivePath(path, true)) {
					if (root.getWorkspace().validatePath(path.toString(), IResource.FOLDER).isOK()
							&& root.getProject(path.segment(0)).exists()) {
						res= root.getFolder(path);
					}
				}

				IPath rawPath= path;
				if (project != null) {
					IPackageFragmentRoot[] roots= project.findPackageFragmentRoots(curr);
					if (roots.length == 1)
						rawPath= roots[0].getPath();
				}
				isMissing= !rawPath.toFile().exists(); // look for external JARs and folders
			} else if (res.isLinked()) {
				linkTarget= res.getLocation();
			}
			break;
		case IClasspathEntry.CPE_SOURCE:
			path= path.removeTrailingSeparator();
			res= root.findMember(path);
			if (res == null) {
				if (root.getWorkspace().validatePath(path.toString(), IResource.FOLDER).isOK()) {
					res= root.getFolder(path);
				}
				isMissing= true;
			} else if (res.isLinked()) {
				linkTarget= res.getLocation();
			}
			break;
		case IClasspathEntry.CPE_PROJECT:
			res= root.findMember(path);
			isMissing= (res == null);
			break;
	}
	CPListElement elem= new CPListElement(parent, project, curr.getEntryKind(), path, newElement, res, linkTarget);
	elem.setExported(curr.isExported());
	elem.setAttribute(SOURCEATTACHMENT, curr.getSourceAttachmentPath());
	elem.setAttribute(OUTPUT, curr.getOutputLocation());
	elem.setAttribute(EXCLUSION, curr.getExclusionPatterns());
	elem.setAttribute(INCLUSION, curr.getInclusionPatterns());
	elem.setAttribute(ACCESSRULES, curr.getAccessRules());
	elem.setAttribute(COMBINE_ACCESSRULES, new Boolean(curr.combineAccessRules()));

	IClasspathAttribute[] extraAttributes= curr.getExtraAttributes();
	for (int i= 0; i < extraAttributes.length; i++) {
		IClasspathAttribute attrib= extraAttributes[i];
		CPListElementAttribute attribElem= elem.findAttributeElement(attrib.getName());
		if (attribElem == null) {
			elem.createAttributeElement(attrib.getName(), attrib.getValue(), false);
		} else {
			attribElem.setValue(attrib.getValue());
		}
	}

	elem.setIsMissing(isMissing);
	return elem;
}
 
Example 19
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 20
Source File: GWTProjectsRuntime.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * FIXME - Were it not for the super source stuff, we would need this method. Can't we provide a
 * way for users to state which folders are super-source, etc?
 */
public static List<IRuntimeClasspathEntry> getGWTRuntimeProjectSourceEntries(
    IJavaProject project, boolean includeTestSourceEntries) throws SdkException {

  assert (isGWTRuntimeProject(project) && project.exists());

  String projectName = project.getProject().getName();
  List<IRuntimeClasspathEntry> sourceEntries = new ArrayList<IRuntimeClasspathEntry>();

  IClasspathEntry[] gwtUserJavaProjClasspathEntries = null;

  try {
    gwtUserJavaProjClasspathEntries = project.getRawClasspath();
  } catch (JavaModelException e) {
    throw new SdkException("Cannot extract raw classpath from " + projectName + " project.");
  }

  Set<IPath> absoluteSuperSourcePaths = new HashSet<IPath>();

  for (IClasspathEntry curClasspathEntry : gwtUserJavaProjClasspathEntries) {
    if (curClasspathEntry.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
      IPath sourcePath = curClasspathEntry.getPath();

      if (isJavadocPath(sourcePath)) {
        // Ignore javadoc paths.
        continue;
      }

      if (GWTProjectUtilities.isTestPath(sourcePath) && !includeTestSourceEntries) {
        // Ignore test paths, unless it is specified explicitly that we should
        // include them.
        continue;
      }

      sourceEntries.add(JavaRuntime.newArchiveRuntimeClasspathEntry(sourcePath));

      // Figure out the location of the super source path.

      IPath absoluteSuperSourcePath =
          sourcePath.removeLastSegments(1).append(SUPER_SOURCE_FOLDER_NAME);
      IPath relativeSuperSourcePath = absoluteSuperSourcePath.removeFirstSegments(1);

      if (absoluteSuperSourcePaths.contains(absoluteSuperSourcePath)) {
        // I've already included this path.
        continue;
      }

      if (project.getProject().getFolder(relativeSuperSourcePath).exists()) {
        /*
         * We've found the super source path, and we've not added it already. The existence test
         * uses a relative path, but the creation of a runtime classpath entry requires an
         * absolute path.
         */
        sourceEntries.add(JavaRuntime.newArchiveRuntimeClasspathEntry(absoluteSuperSourcePath));
        absoluteSuperSourcePaths.add(absoluteSuperSourcePath);
      }

      IPath absoluteTestSuperSourcePath =
          sourcePath.removeLastSegments(1).append(TEST_SUPER_SOURCE_FOLDER_NAME);
      IPath relativeTestSuperSourcePath = absoluteTestSuperSourcePath.removeFirstSegments(1);
      if (absoluteSuperSourcePaths.contains(absoluteTestSuperSourcePath)) {
        // I've already included this path.
        continue;
      }

      if (includeTestSourceEntries
          && project.getProject().getFolder(relativeTestSuperSourcePath).exists()) {
        /*
         * We've found the super source path, and we've not added it already. The existence test
         * uses a relative path, but the creation of a runtime classpath entry requires an
         * absolute path.
         */
        sourceEntries.add(JavaRuntime
            .newArchiveRuntimeClasspathEntry(absoluteTestSuperSourcePath));
        absoluteSuperSourcePaths.add(absoluteTestSuperSourcePath);
      }
    }
  }

  if (absoluteSuperSourcePaths.isEmpty()) {
    GWTPluginLog.logError("There were no super source folders found for the project '{0}'",
        project.getProject().getName());
  }

  return sourceEntries;
}