Example usage for org.eclipse.jdt.core IJavaElement getPath

List of usage examples for org.eclipse.jdt.core IJavaElement getPath

Introduction

In this page you can find the example usage for org.eclipse.jdt.core IJavaElement getPath.

Prototype

IPath getPath();

Source Link

Document

Returns the path to the innermost resource enclosing this element.

Usage

From source file:com.blackducksoftware.integration.eclipseplugin.internal.listeners.ProjectDependenciesChangedListener.java

License:Apache License

public void removeDependency(final IJavaElement el) throws CoreException, MalformedURLException {
    final String projName = getProjectNameFromElement(el);
    if (projName != null) {
        final URL projectUrl = el.getPath().toFile().toURI().toURL();
        if (depService.isGradleDependency(projectUrl)) {
            final Gav gav = extractor.getGradlePathGav(projectUrl);
            // TODO: No hardcoded strings.
            information.removeComponentFromProject(projName,
                    new Gav("maven", gav.getGroupId(), gav.getArtifactId(), gav.getVersion()));
        } else if (depService.isMavenDependency(projectUrl)) {
            final URL mavenURL = JavaCore.getClasspathVariable(ClasspathVariables.MAVEN).toFile().toURI()
                    .toURL();/*w  w  w  .j  a va  2  s  . c  o m*/
            final Gav gav = extractor.getMavenPathGav(projectUrl, mavenURL);
            information.removeComponentFromProject(projName,
                    new Gav("maven", gav.getGroupId(), gav.getArtifactId(), gav.getVersion()));
        }
    }

}

From source file:com.blackducksoftware.integration.eclipseplugin.internal.listeners.ProjectDependenciesChangedListener.java

License:Apache License

public void addDependency(final IJavaElement el) throws CoreException, MalformedURLException {
    final String projName = getProjectNameFromElement(el);
    if (projName != null) {
        final URL projectUrl = el.getPath().toFile().toURI().toURL();
        if (depService.isGradleDependency(projectUrl)) {
            final Gav gav = extractor.getGradlePathGav(projectUrl);
            // TODO: No hardcoded strings.
            information.addComponentToProject(projName,
                    new Gav("maven", gav.getGroupId(), gav.getArtifactId(), gav.getVersion()));
        } else if (depService.isMavenDependency(projectUrl)) {
            final URL mavenURL = JavaCore.getClasspathVariable(ClasspathVariables.MAVEN).toFile().toURI()
                    .toURL();/*from   www.j  a  va2  s .  c  om*/
            final Gav gav = extractor.getMavenPathGav(projectUrl, mavenURL);
            information.addComponentToProject(projName,
                    new Gav("maven", gav.getGroupId(), gav.getArtifactId(), gav.getVersion()));
        }
    }
}

From source file:com.codenvy.ide.ext.java.server.internal.core.DeltaProcessor.java

License:Open Source License

private boolean createExternalArchiveDelta(HashSet refreshedElements, IProgressMonitor monitor) {

    HashMap externalArchivesStatus = new HashMap();
    boolean hasDelta = false;

    // find JARs to refresh
    HashSet archivePathsToRefresh = new HashSet();
    Iterator iterator = refreshedElements.iterator();
    while (iterator.hasNext()) {
        IJavaElement element = (IJavaElement) iterator.next();
        switch (element.getElementType()) {
        case IJavaElement.PACKAGE_FRAGMENT_ROOT:
            archivePathsToRefresh.add(element.getPath());
            break;
        case IJavaElement.JAVA_PROJECT:
            JavaProject javaProject = (JavaProject) element;
            if (!JavaProject.hasJavaNature(javaProject.getProject())) {
                // project is not accessible or has lost its Java nature
                break;
            }/*from   w ww .  j a  v  a 2  s  .  c o m*/
            IClasspathEntry[] classpath;
            try {
                classpath = javaProject.getResolvedClasspath();
                for (int j = 0, cpLength = classpath.length; j < cpLength; j++) {
                    if (classpath[j].getEntryKind() == IClasspathEntry.CPE_LIBRARY) {
                        archivePathsToRefresh.add(classpath[j].getPath());
                    }
                }
            } catch (JavaModelException e) {
                // project doesn't exist -> ignore
            }
            break;
        case IJavaElement.JAVA_MODEL:
            //               Iterator projectNames = this.state.getOldJavaProjecNames().iterator();
            //               while (projectNames.hasNext()) {
            //                  String projectName = (String) projectNames.next();
            //                  IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
            //                  if (!JavaProject.hasJavaNature(project)) {
            //                     // project is not accessible or has lost its Java nature
            //                     continue;
            //                  }
            //                  javaProject = (JavaProject) JavaCore.create(project);
            //                  try {
            //                     classpath = javaProject.getResolvedClasspath();
            //                     for (int k = 0, cpLength = classpath.length; k < cpLength; k++){
            //                        if (classpath[k].getEntryKind() == IClasspathEntry.CPE_LIBRARY){
            //                           archivePathsToRefresh.add(classpath[k].getPath());
            //                        }
            //                     }
            //                  } catch (JavaModelException e2) {
            //                     // project doesn't exist -> ignore
            //                     continue;
            //                  }
            //               }
            throw new UnsupportedOperationException();
            //               break;
        }
    }

    //      // perform refresh
    //      Iterator projectNames = this.state.getOldJavaProjecNames().iterator();
    //      IWorkspaceRoot wksRoot = ResourcesPlugin.getWorkspace().getRoot();
    //      while (projectNames.hasNext()) {
    //
    //         if (monitor != null && monitor.isCanceled()) break;
    //
    //         String projectName = (String) projectNames.next();
    //         IProject project = wksRoot.getProject(projectName);
    //         if (!JavaProject.hasJavaNature(project)) {
    //            // project is not accessible or has lost its Java nature
    //            continue;
    //         }
    //         JavaProject javaProject = (JavaProject) JavaCore.create(project);
    //         IClasspathEntry[] entries;
    //         try {
    //            entries = javaProject.getResolvedClasspath();
    //         } catch (JavaModelException e1) {
    //            // project does not exist -> ignore
    //            continue;
    //         }
    //         boolean deltaContainsModifiedJar = false;
    //         for (int j = 0; j < entries.length; j++){
    //            if (entries[j].getEntryKind() == IClasspathEntry.CPE_LIBRARY) {
    //               IPath entryPath = entries[j].getPath();
    //
    //               if (!archivePathsToRefresh.contains(entryPath)) continue; // not supposed to be refreshed
    //
    //               String status = (String)externalArchivesStatus.get(entryPath);
    //               if (status == null){
    //
    //                  // Clear the external file state for this path, since this method is responsible for updating it.
    //                  this.manager.clearExternalFileState(entryPath);
    //
    //                  // compute shared status
    //                  Object targetLibrary = JavaModel.getTarget(entryPath, true);
    //
    //                  if (targetLibrary == null){ // missing JAR
    //                     if (this.state.getExternalLibTimeStamps().remove(entryPath) != null /* file was known*/
    //                           && this.state.roots.get(entryPath) != null /* and it was on the classpath*/) {
    //                        externalArchivesStatus.put(entryPath, EXTERNAL_JAR_REMOVED);
    //                        // the jar was physically removed: remove the index
    //                        this.manager.indexManager.removeIndex(entryPath);
    //                     }
    //
    //                  } else if (targetLibrary instanceof File){ // external JAR
    //
    //                     File externalFile = (File)targetLibrary;
    //
    //                     // check timestamp to figure if JAR has changed in some way
    //                     Long oldTimestamp =(Long) this.state.getExternalLibTimeStamps().get(entryPath);
    //                     long newTimeStamp = getTimeStamp(externalFile);
    //                     if (oldTimestamp != null){
    //
    //                        if (newTimeStamp == 0){ // file doesn't exist
    //                           externalArchivesStatus.put(entryPath, EXTERNAL_JAR_REMOVED);
    //                           this.state.getExternalLibTimeStamps().remove(entryPath);
    //                           // remove the index
    //                           this.manager.indexManager.removeIndex(entryPath);
    //
    //                        } else if (oldTimestamp.longValue() != newTimeStamp){
    //                           externalArchivesStatus.put(entryPath, EXTERNAL_JAR_CHANGED);
    //                           this.state.getExternalLibTimeStamps().put(entryPath, new Long(newTimeStamp));
    //                           // first remove the index so that it is forced to be re-indexed
    //                           this.manager.indexManager.removeIndex(entryPath);
    //                           // then index the jar
    //                           this.manager.indexManager.indexLibrary(entryPath, project.getProject(), ((ClasspathEntry)entries[j]).getLibraryIndexLocation(), true);
    //                        } else {
    //                           URL indexLocation = ((ClasspathEntry)entries[j]).getLibraryIndexLocation();
    //                           if (indexLocation != null) { // force reindexing, this could be faster rather than maintaining the list
    //                              this.manager.indexManager.indexLibrary(entryPath, project.getProject(), indexLocation);
    //                           }
    //                           externalArchivesStatus.put(entryPath, EXTERNAL_JAR_UNCHANGED);
    //                        }
    //                     } else {
    //                        if (newTimeStamp == 0){ // jar still doesn't exist
    //                           externalArchivesStatus.put(entryPath, EXTERNAL_JAR_UNCHANGED);
    //                        } else {
    //                           externalArchivesStatus.put(entryPath, EXTERNAL_JAR_ADDED);
    //                           this.state.getExternalLibTimeStamps().put(entryPath, new Long(newTimeStamp));
    //                           // index the new jar
    //                           this.manager.indexManager.removeIndex(entryPath);
    //                           this.manager.indexManager.indexLibrary(entryPath, project.getProject(), ((ClasspathEntry)entries[j]).getLibraryIndexLocation());
    //                        }
    //                     }
    //                  } else { // internal JAR
    //                     externalArchivesStatus.put(entryPath, INTERNAL_JAR_IGNORE);
    //                  }
    //               }
    //               // according to computed status, generate a delta
    //               status = (String)externalArchivesStatus.get(entryPath);
    //               if (status != null){
    //                  if (status == EXTERNAL_JAR_ADDED){
    //                     PackageFragmentRoot root = (PackageFragmentRoot) javaProject.getPackageFragmentRoot(entryPath.toString());
    //                     if (VERBOSE){
    //                        System.out.println("- External JAR ADDED, affecting root: "+root.getElementName()); //$NON-NLS-1$
    //                     }
    //                     elementAdded(root, null, null);
    //                     deltaContainsModifiedJar = true;
    //                     this.state.addClasspathValidation(javaProject); // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=185733
    //                     hasDelta = true;
    //                  } else if (status == EXTERNAL_JAR_CHANGED) {
    //                     PackageFragmentRoot root = (PackageFragmentRoot) javaProject.getPackageFragmentRoot(entryPath.toString());
    //                     if (VERBOSE){
    //                        System.out.println("- External JAR CHANGED, affecting root: "+root.getElementName()); //$NON-NLS-1$
    //                     }
    //                     contentChanged(root);
    //                     deltaContainsModifiedJar = true;
    //                     hasDelta = true;
    //                  } else if (status == EXTERNAL_JAR_REMOVED) {
    //                     PackageFragmentRoot root = (PackageFragmentRoot) javaProject.getPackageFragmentRoot(entryPath.toString());
    //                     if (VERBOSE){
    //                        System.out.println("- External JAR REMOVED, affecting root: "+root.getElementName()); //$NON-NLS-1$
    //                     }
    //                     elementRemoved(root, null, null);
    //                     deltaContainsModifiedJar = true;
    //                     this.state.addClasspathValidation(javaProject); // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=185733
    //                     hasDelta = true;
    //                  }
    //               }
    //            }
    //         }
    //
    //         if (deltaContainsModifiedJar) {
    //            javaProject.resetResolvedClasspath();
    //         }
    //      }
    //
    //      if (hasDelta){
    //         // flush jar type cache
    //         JavaModelManager.getJavaModelManager().resetJarTypeCache();
    //      }
    return hasDelta;
}

From source file:com.codenvy.ide.ext.java.server.internal.core.search.BasicSearchEngine.java

License:Open Source License

public void searchDeclarations(IJavaElement enclosingElement, SearchRequestor requestor, SearchPattern pattern,
        IProgressMonitor monitor) throws JavaModelException {
    if (VERBOSE) {
        Util.verbose("   - java element: " + enclosingElement); //$NON-NLS-1$
    }//from   w w w. j  ava  2 s  .c  o  m
    IJavaSearchScope scope = createJavaSearchScope(new IJavaElement[] { enclosingElement });
    IResource resource = ((JavaElement) enclosingElement).resource();
    if (enclosingElement instanceof IMember) {
        IMember member = (IMember) enclosingElement;
        ICompilationUnit cu = member.getCompilationUnit();
        if (cu != null) {
            resource = cu.getResource();
        } else if (member.isBinary()) {
            // binary member resource cannot be used as this
            // see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=148215
            resource = null;
        }
    }
    try {
        if (resource instanceof IFile) {
            try {
                requestor.beginReporting();
                if (VERBOSE) {
                    Util.verbose("Searching for " + pattern + " in " + resource.getFullPath()); //$NON-NLS-1$//$NON-NLS-2$
                }
                SearchParticipant participant = getDefaultSearchParticipant(indexManager);
                SearchDocument[] documents = MatchLocator.addWorkingCopies(pattern,
                        new SearchDocument[] {
                                new JavaSearchDocument(enclosingElement.getPath().toString(), participant) },
                        getWorkingCopies(enclosingElement), participant);
                participant.locateMatches(documents, pattern, scope, requestor, monitor);
            } finally {
                requestor.endReporting();
            }
        } else {
            search(pattern, new SearchParticipant[] { getDefaultSearchParticipant(indexManager) }, scope,
                    requestor, monitor);
        }
    } catch (CoreException e) {
        if (e instanceof JavaModelException)
            throw (JavaModelException) e;
        throw new JavaModelException(e);
    }
}

From source file:com.codenvy.ide.ext.java.server.internal.core.search.IndexSelector.java

License:Open Source License

private static boolean canSeeFocus(IJavaElement focus, JavaProject javaProject,
        char[][][] focusQualifiedNames) {
    try {//  w  ww.ja  v a 2  s .  com
        if (focus == null)
            return false;
        if (focus.equals(javaProject))
            return true;

        if (focus instanceof JarPackageFragmentRoot) {
            // focus is part of a jar
            IPath focusPath = focus.getPath();
            IClasspathEntry[] entries = javaProject.getExpandedClasspath();
            for (int i = 0, length = entries.length; i < length; i++) {
                IClasspathEntry entry = entries[i];
                if (entry.getEntryKind() == IClasspathEntry.CPE_LIBRARY && entry.getPath().equals(focusPath))
                    return true;
            }
            return false;
        }
        // look for dependent projects
        IPath focusPath = ((JavaProject) focus).getProject().getFullPath();
        IClasspathEntry[] entries = javaProject.getExpandedClasspath();
        for (int i = 0, length = entries.length; i < length; i++) {
            IClasspathEntry entry = entries[i];
            if (entry.getEntryKind() == IClasspathEntry.CPE_PROJECT && entry.getPath().equals(focusPath)) {
                if (focusQualifiedNames != null) { // builder state is usable, hence use it to try to reduce project which can see the focus...
                    State projectState = (State) JavaModelManager.getJavaModelManager()
                            .getLastBuiltState(javaProject.getProject(), null);
                    if (projectState != null) {
                        Object[] values = projectState.getReferences().valueTable;
                        int vLength = values.length;
                        for (int j = 0; j < vLength; j++) {
                            if (values[j] == null)
                                continue;
                            ReferenceCollection references = (ReferenceCollection) values[j];
                            if (references.includes(focusQualifiedNames, null, null)) {
                                return true;
                            }
                        }
                        return false;
                    }
                }
                return true;
            }
        }
        return false;
    } catch (JavaModelException e) {
        return false;
    }
}

From source file:com.codenvy.ide.ext.java.server.internal.core.search.JavaSearchScope.java

License:Open Source License

private IPath getPath(IJavaElement element, boolean relativeToRoot) {
    switch (element.getElementType()) {
    case IJavaElement.JAVA_MODEL:
        return Path.EMPTY;
    case IJavaElement.JAVA_PROJECT:
        return element.getPath();
    case IJavaElement.PACKAGE_FRAGMENT_ROOT:
        if (relativeToRoot)
            return Path.EMPTY;
        return element.getPath();
    case IJavaElement.PACKAGE_FRAGMENT:
        String relativePath = Util.concatWith(((PackageFragment) element).names, '/');
        return getPath(element.getParent(), relativeToRoot).append(new Path(relativePath));
    case IJavaElement.COMPILATION_UNIT:
    case IJavaElement.CLASS_FILE:
        return getPath(element.getParent(), relativeToRoot).append(new Path(element.getElementName()));
    default://from w  w  w. jav  a  2  s . c o  m
        return getPath(element.getParent(), relativeToRoot);
    }
}

From source file:com.drgarbage.bytecodevisualizer.compare.CompareElement.java

License:Apache License

/**
 * Returns the class name for the given java element.
 * @param javaElement/* w ww  . j  a  v  a 2s  . c om*/
 * @return class name
 */
private static String getClassName(IJavaElement javaElement) {
    String name;
    IClassFile classFile = (IClassFile) javaElement.getAncestor(IJavaElement.CLASS_FILE);
    if (classFile != null) {
        name = classFile.getPath().toOSString();
    } else {
        if (javaElement.getPath() != null) {
            name = javaElement.getPath().toOSString();
        } else {
            name = javaElement.getElementName();
        }
    }

    return name;
}

From source file:com.github.ajaxsys.jdtx.utils.JDTUtils.java

License:Open Source License

public static String getFilePath(IJavaElement javaElt) {
    if (javaElt == null) {
        throw new IllegalArgumentException("javaElt is null");
    }/*from w w  w. j  ava 2  s . c o  m*/
    try {
        IPath p = javaElt.getPath();
        if (p == null) {
            throw new IllegalArgumentException("javaElt has null path");
        }
        String filePath = p.toString();
        return filePath;
    } catch (Exception e) {
        throw new IllegalArgumentException("malformed javaElt: " + javaElt, e);
    }
}

From source file:com.google.gwt.eclipse.devtoolsgen.actions.PopulateGwtDevTools.java

License:Open Source License

public void run(IAction action) {
    try {//from ww  w  . j a va  2  s. co m
        if (gwtDev == null) {
            System.err.println("Must import the gwt-dev project");
            return;
        }

        if (gwtUser == null) {
            System.err.println("Must import the gwt-user project");
            return;
        }

        if (gwtDevTools == null) {
            System.err.println("Must import the gwt-dev-tools project");
            return;
        }

        System.out.println("Searching for dependecies in GWT source projects...");

        deps.clear();
        IType searchRoot = gwtDevTools.findType("Deps");

        // Find compilation units and resources we depend on
        findAllDependencies(searchRoot.getCompilationUnit(), 0);
        int totalDepsCount = deps.size();

        // Prune out files already in gwt-dev-tools. This eliminates most of the
        // bulk copy when you've already run this tool at least once.
        Iterator<IFile> iter = deps.iterator();
        while (iter.hasNext()) {
            IFile dep = iter.next();

            IJavaElement srcRoot = JavaCore.create(dep.getParent())
                    .getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);
            IPath srcPathRelativePath = dep.getFullPath().removeFirstSegments(srcRoot.getPath().segmentCount());
            IFile existingFile = findFileOnClasspath(gwtDevTools, srcPathRelativePath);

            if (existingFile != null) {
                iter.remove();
            }
        }

        System.out.format("Finished dependency search (%d files found; %d new)\n", totalDepsCount, deps.size());

        if (!deps.isEmpty()) {
            IWorkspaceRunnable op = new CopyDepsToGwtDevTools();
            ISchedulingRule lock = ResourcesPlugin.getWorkspace().getRoot();
            ResourcesPlugin.getWorkspace().run(op, lock, IWorkspace.AVOID_UPDATE, null);
        } else {
            System.out.println("Done");
        }
    } catch (CoreException e) {
        e.printStackTrace();
    }
}

From source file:com.legstar.eclipse.plugin.cixsmap.dialogs.LegacyStructureDialog.java

License:Open Source License

/**
 * Examines packages in a given project and adds segments which contain the
 * .bind suffix to the package list table. ".bind" suffix identify segments
 * that correspond to COXB binding packages.
 * //from www .  ja  v  a2 s . c o m
 * @param project the java project to get packages from
 * @return map of java package names to fragments
 * @throws CoreException if the given project is not a Java project
 */
private Map<String, IPackageFragment> createPackageList(final IProject project) throws CoreException {
    Map<String, IPackageFragment> packageMap = new HashMap<String, IPackageFragment>();
    IJavaProject jproject = JavaCore.create(project);
    IPackageFragmentRoot[] pkgRoots = jproject.getPackageFragmentRoots();
    for (int j = 0; j < pkgRoots.length; j++) {
        IPackageFragmentRoot pkgRoot = pkgRoots[j];
        if (pkgRoot.getKind() == IPackageFragmentRoot.K_SOURCE) {
            for (int k = 0; k < pkgRoot.getChildren().length; k++) {
                IJavaElement el = pkgRoot.getChildren()[k];
                if (el.getPath().lastSegment().compareTo(BIND_FRAG) == 0) {
                    packageMap.put(el.getElementName(), (IPackageFragment) el);
                }
            }
        }
    }
    return packageMap;
}