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

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

Introduction

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

Prototype

IPath getPath();

Source Link

Document

Returns the path of this classpath entry.

Usage

From source file:de.tobject.findbugs.builder.PDEClassPathGenerator.java

License:Open Source License

private static void appendBundleToClasspath(BundleDescription bd, List<String> pdeClassPath,
        IPath defaultOutputLocation) {/* w  w w .j  av  a 2  s.  c  o m*/
    IPluginModelBase model = PluginRegistry.findModel(bd);
    if (model == null) {
        return;
    }
    ArrayList<IClasspathEntry> classpathEntries = new ArrayList<IClasspathEntry>();
    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);
        }
    }
}

From source file:edu.brown.cs.bubbles.bedrock.BedrockOpenEditorBubbleActionDelegate.java

License:Open Source License

@Override
public void run(IAction action) {
    IWorkbenchPage page = our_window.getActivePage();

    if (page != null) {
        if (!(page.getActiveEditor() instanceof ITextEditor))
            return;

        ITextEditor fileEditor = (ITextEditor) page.getActiveEditor();

        IFileEditorInput fileEditorInput = (IFileEditorInput) fileEditor.getEditorInput();
        String path = fileEditorInput.getFile().getProjectRelativePath().toOSString();
        String filePath = path;// w w w  . j a  v a  2 s .  co m
        IProject project = fileEditorInput.getFile().getProject();

        IJavaProject javaProject = JavaModelManager.getJavaModelManager().getJavaModel()
                .getJavaProject(project.getName());

        try {
            for (IClasspathEntry entry : javaProject.getRawClasspath()) {
                if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
                    String sourcePath = entry.getPath().toOSString().substring(project.getName().length() + 2);

                    if (path.startsWith(sourcePath)) {
                        path = path.substring(sourcePath.length() + 1);
                        path = path.replace(File.separatorChar, '$');
                        path = path.substring(0, path.indexOf("."));

                        filePath = filePath.substring(sourcePath.length() + 1);

                        break;
                    }
                }
            }
        } catch (Exception e1) {
            BedrockPlugin.log("Exception : " + e1.getMessage() + ", " + e1.getClass().toString());
        }

        try {
            IJavaElement javaElement = javaProject.findElement(new Path(filePath));

            if (!(javaElement instanceof ICompilationUnit))
                return;

            ICompilationUnit icu = (ICompilationUnit) javaElement;

            ISelectionProvider selectionProvider = fileEditor.getSelectionProvider();
            ISelection selection = selectionProvider.getSelection();

            if (selection instanceof ITextSelection) {
                ITextSelection textSelection = (ITextSelection) selection;
                int offset = textSelection.getOffset();

                IJavaElement element = icu.getElementAt(offset);

                IvyXmlWriter xw = BedrockPlugin.getPlugin().beginMessage("OPENEDITOR");
                xw.field("PROJECT", project.getName());

                if (element == null) {
                    xw.field("RESOURCEPATH", path);
                } else {
                    boolean isFirstElement = true;
                    boolean isMethod = false;

                    String fileName = path.substring(path.lastIndexOf('$') + 1);

                    List<String> list = new ArrayList<String>();

                    while (element != null && (!element.getElementName().equals(fileName)
                            || element.getElementType() == IJavaElement.METHOD)) {
                        if (isFirstElement && (element.getElementType() == IJavaElement.METHOD
                                || element.getElementType() == IJavaElement.TYPE)) {
                            list.add(element.getElementName());

                            if (element.getElementType() == IJavaElement.METHOD) {
                                isMethod = true;
                            }

                            isFirstElement = false;
                        } else if (!isFirstElement) {
                            list.add(element.getElementName());
                        }

                        element = element.getParent();

                        if ("".equals(element.getElementName())) {
                            xw.field("RESOURCEPATH", path);
                            BedrockPlugin.getPlugin().finishMessage(xw);

                            return;
                        }
                    }

                    String[] aryPath = new String[list.size()];
                    list.toArray(aryPath);

                    for (int i = aryPath.length - 1; i >= 0; i--) {
                        path += ("$" + aryPath[i]);
                    }

                    xw.field("RESOURCEPATH", path);

                    if (isMethod)
                        xw.field("RESOURCETYPE", "Function");
                }

                BedrockPlugin.getPlugin().finishMessage(xw);
            }
        } catch (Exception e2) {
            BedrockPlugin.log("Exception : " + e2.getMessage() + ", " + e2.getClass().toString());
        }
    }
}

From source file:edu.brown.cs.bubbles.bedrock.BedrockProject.java

License:Open Source License

private void addPath(IvyXmlWriter xw, IJavaProject jp, IClasspathEntry ent, boolean nest) {
    IPath p = ent.getPath();
    IPath op = ent.getOutputLocation();/* www  .  j a  va2 s .c o m*/
    IPath sp = ent.getSourceAttachmentPath();
    IProject ip = jp.getProject();

    String jdp = null;
    boolean opt = false;
    IClasspathAttribute[] atts = ent.getExtraAttributes();
    for (IClasspathAttribute att : atts) {
        if (att.getName().equals(IClasspathAttribute.JAVADOC_LOCATION_ATTRIBUTE_NAME))
            jdp = att.getValue();
        else if (att.getName().equals(IClasspathAttribute.OPTIONAL)) {
            String v = att.getValue();
            if (v.equals("true"))
                opt = true;
        }
    }

    if (p == null && op == null)
        return;
    File f1 = null;
    if (p != null) {
        f1 = BedrockUtil.getFileForPath(p, ip);
        if (!f1.exists()) {
            BedrockPlugin.logD("Path file " + p + " not found as " + f1);
            // f1 = null;
        }
    }
    File f2 = null;
    if (op != null) {
        f2 = BedrockUtil.getFileForPath(op, ip);
        if (!f2.exists()) {
            BedrockPlugin.logD("Path file " + op + " not found");
            f2 = null;
        }
    }
    File f3 = null;
    if (sp != null) {
        f3 = BedrockUtil.getFileForPath(sp, ip);
        if (!f3.exists()) {
            BedrockPlugin.logD("Path file " + sp + " not found");
            f3 = null;
        }
    }
    if (f1 == null && f2 == null)
        return;

    // references to nested projects are handled in addClassPaths
    if (ent.getEntryKind() == IClasspathEntry.CPE_PROJECT)
        return;

    xw.begin("PATH");
    xw.field("ID", ent.hashCode());
    if (nest)
        xw.field("NESTED", "TRUE");

    switch (ent.getEntryKind()) {
    case IClasspathEntry.CPE_SOURCE:
        xw.field("TYPE", "SOURCE");
        f3 = f1;
        f1 = null;
        break;
    case IClasspathEntry.CPE_PROJECT:
        xw.field("TYPE", "BINARY");
        break;
    case IClasspathEntry.CPE_LIBRARY:
        xw.field("TYPE", "LIBRARY");
        break;
    }
    if (ent.isExported())
        xw.field("EXPORTED", true);
    if (opt)
        xw.field("OPTIONAL", true);

    if (f1 != null)
        xw.textElement("BINARY", f1.getAbsolutePath());
    if (f2 != null)
        xw.textElement("OUTPUT", f2.getAbsolutePath());
    if (f3 != null)
        xw.textElement("SOURCE", f3.getAbsolutePath());
    if (jdp != null)
        xw.textElement("JAVADOC", jdp);

    IAccessRule[] rls = ent.getAccessRules();
    for (IAccessRule ar : rls) {
        xw.begin("ACCESS");
        xw.field("KIND", ar.getKind());
        xw.field("PATTERN", ar.getPattern().toString());
        xw.field("IGNOREIFBETTER", ar.ignoreIfBetter());
        xw.end("ACCESS");
    }

    xw.end("PATH");
}

From source file:edu.clarkson.serl.critic.loader.SootClasspath.java

License:Open Source License

public static URL[] projectClassPath(IJavaProject javaProject) {
    IWorkspace workspace = CriticPlugin.getWorkspaceRoot().getWorkspace();
    IClasspathEntry[] cp;//  w ww  .j a v a  2 s.  c om
    try {
        cp = javaProject.getResolvedClasspath(true);
        Set<URL> urls = new HashSet<URL>();
        String uriString = workspace.getRoot().getFile(javaProject.getOutputLocation()).getLocationURI()
                .toString() + "/";
        urls.add(new URI(uriString).toURL());
        for (IClasspathEntry entry : cp) {
            File file = entry.getPath().toFile();
            URL url = file.toURI().toURL();
            urls.add(url);
        }
        URL[] array = new URL[urls.size()];
        urls.toArray(array);
        return array;
    } catch (JavaModelException e) {
        e.printStackTrace();
        return new URL[0];
    } catch (MalformedURLException e) {
        e.printStackTrace();
        return new URL[0];
    } catch (URISyntaxException e) {
        e.printStackTrace();
        return new URL[0];
    }
}

From source file:edu.clarkson.serl.critic.loader.SootClasspath.java

License:Open Source License

/**
 * This is an addition to the original SootClasspath class where
 * bug due to '\\' in the path string has been resolved.
 * (Added By: Ryan Edgar)//  ww w . ja va 2 s .  co  m
 *  
 * @param javaProject The JavaProject to be analyzed.
 * @return An array of {@link URL}s corresponding to the classpath of the supplied project.
 */
public static URL[] projectClassPath2(IJavaProject javaProject) {
    IWorkspace workspace = CriticPlugin.getWorkspaceRoot().getWorkspace();
    IClasspathEntry[] cp;
    try {
        cp = javaProject.getResolvedClasspath(true);
        Set<URL> urls = new HashSet<URL>();
        String uriString = workspace.getRoot().getFile(javaProject.getOutputLocation()).getLocationURI()
                .toString() + "/";
        urls.add(new URI(uriString).toURL());
        for (IClasspathEntry entry : cp) {
            File file = entry.getPath().toFile();
            if (file.getPath().startsWith("\\")) {
                file = workspace.getRoot().getLocation().append(file.getPath()).toFile();
            }
            URL url = file.toURI().toURL();
            urls.add(url);
        }
        URL[] array = new URL[urls.size()];
        urls.toArray(array);
        return array;
    } catch (JavaModelException e) {
        e.printStackTrace();

        return new URL[0];
    } catch (MalformedURLException e) {
        e.printStackTrace();
        return new URL[0];
    } catch (URISyntaxException e) {
        e.printStackTrace();
        return new URL[0];
    }
}

From source file:edu.rice.cs.drjava.plugins.eclipse.repl.EclipseInteractionsModel.java

License:BSD License

private void _addProjectToClasspath(IJavaProject jProj, IJavaModel jModel, IWorkspaceRoot root)
        throws CoreException {
    // Get the project's location on disk
    IProject proj = jProj.getProject();/*w  ww .  j  av  a 2s. c  o  m*/
    URI projRoot = proj.getDescription().getLocationURI();
    // Note: getLocation returns null if the default location is used
    //  (brilliant...)

    // Get the resolved classpath entries - this should filter out
    //   all CPE_VARIABLE and CPE_CONTAINER entries.
    IClasspathEntry entries[] = jProj.getResolvedClasspath(true);

    // For each of the classpath entries...
    for (int j = 0; j < entries.length; j++) {
        IClasspathEntry entry = entries[j];

        // Check what kind of entry it is...
        int kind = entry.getEntryKind();

        // And get the appropriate path.
        IPath path;
        switch (kind) {
        case IClasspathEntry.CPE_LIBRARY:
            // The raw location of a JAR.
            path = entry.getPath();
            //System.out.println("Adding library: " + path.toOSString());
            addToClassPath(path.toOSString());
            break;
        case IClasspathEntry.CPE_SOURCE:
            // The output location of source.
            // Need to append it to the user's workspace directory.
            path = entry.getOutputLocation();
            if (path == null) {
                path = jProj.getOutputLocation();
                //System.out.println(" output location from proj: " + path);
            }

            // At this point, the output location contains the project
            //  name followed by the actual output folder name

            if (projRoot != null && (!projRoot.isAbsolute() || projRoot.getScheme().equals("file"))) {
                // We have a custom project location, so the project name
                //  is not part of the *actual* output directory.  We need
                //  to remove the project name (first segment) and then
                //  append the rest of the output location to projRoot.
                path = path.removeFirstSegments(1);
                path = new Path(projRoot.getPath()).append(path);
            } else {
                // A null projRoot means use the default location, which
                //  *does* include the project name in the output directory.
                path = root.getLocation().append(path);
            }

            //System.out.println("Adding source: " + path.toOSString());
            //addToClassPath(path.toOSString());
            addBuildDirectoryClassPath(path.toOSString());
            break;
        case IClasspathEntry.CPE_PROJECT:
            // In this case, just the project name is given.
            // We don't actually need to add anything to the classpath,
            //  since the project is open and we will get its classpath
            //  on another pass.
            break;
        default:
            // This should never happen.
            throw new RuntimeException("Unsupported classpath entry type.");
        }
    }
}

From source file:edu.uci.lighthouse.core.util.WorkbenchUtility.java

License:Open Source License

public static String[] getSourceFolders(IJavaProject project) {
    List<String> result = new LinkedList<String>();
    try {/*  w w w.j  av  a  2s  .  c  o m*/
        IClasspathEntry[] classPaths = project.getRawClasspath();
        for (IClasspathEntry cp : classPaths) {
            if (cp.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
                result.add(cp.getPath().toPortableString());
            }
        }
    } catch (JavaModelException e) {
        logger.error(e, e);
    }
    return result.toArray(new String[0]);
}

From source file:edu.uci.lighthouse.services.persistence.ThreadTest.java

License:Open Source License

public static String[] getSourceFolders(IJavaProject project) {
    List<String> result = new LinkedList<String>();
    try {/*  ww  w .j  a va  2s . c o m*/
        IClasspathEntry[] classPaths = project.getRawClasspath();
        for (IClasspathEntry cp : classPaths) {
            if (cp.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
                result.add(cp.getPath().toString());
            }
        }
    } catch (JavaModelException e) {
        //logger.error(e,e);
    }
    return result.toArray(new String[0]);
}

From source file:edu.washington.cs.cupid.scripting.java.internal.UpdateClasspathJob.java

License:Open Source License

@Override
public IStatus runInWorkspace(final IProgressMonitor monitor) {
    try {/*  www.ja  v  a2  s  . c o m*/
        IJavaProject project = CupidScriptingPlugin.getDefault().getCupidJavaProject();

        int classpathSize = project.getRawClasspath().length;

        monitor.beginTask("Update Cupid Classpath", classpathSize + 2);

        List<IClasspathEntry> updatedClasspath = Lists.newArrayList();
        List<IClasspathEntry> updatedEntries = Lists.newArrayList();

        List<String> allResolved = Lists.newArrayList();

        for (IClasspathEntry entry : project.getRawClasspath()) {

            if (entry.getEntryKind() == IClasspathEntry.CPE_LIBRARY) {
                File file = entry.getPath().toFile();

                if (file.exists()) {
                    // the entry is valid
                    allResolved.add(entry.getPath().toString());
                    updatedClasspath.add(entry);

                } else {
                    // try to find bundle with same name
                    IPath path = entry.getPath();
                    String filename = path.segment(path.segmentCount() - 1);

                    String[] parts = filename.split("_");
                    if (parts.length == 2) {
                        Bundle bundle = Platform.getBundle(parts[0]);
                        if (bundle != null) {
                            // we found a bundle with the same name
                            IPath replacement = ClasspathUtil.bundlePath(bundle);
                            IClasspathEntry newEntry = JavaCore.newLibraryEntry(replacement, null, null);
                            updatedClasspath.add(newEntry);
                            updatedEntries.add(newEntry);
                        } else {
                            CupidScriptingPlugin.getDefault()
                                    .logWarning("Can't find updated bundle for Cupid Project classpath entry: "
                                            + entry.getPath());

                            updatedClasspath.add(entry);
                        }
                    } else if (filename.startsWith("guava")) {
                        CodeSource guavaSrc = Lists.class.getProtectionDomain().getCodeSource();
                        IClasspathEntry newEntry = JavaCore
                                .newLibraryEntry(ClasspathUtil.urlToPath(guavaSrc.getLocation()), null, null);
                        updatedClasspath.add(newEntry);
                        updatedEntries.add(newEntry);

                    } else {
                        // TODO handle other internal JARs besides Guava

                        CupidScriptingPlugin.getDefault()
                                .logWarning("Can't find updated library for Cupid Project classpath entry: "
                                        + entry.getPath());

                        // we don't know how to find the name
                        updatedClasspath.add(entry);
                    }
                }
            } else {
                // don't try to handle variables / projects
                updatedClasspath.add(entry);
                allResolved.add(entry.getPath().toString());
            }

            monitor.worked(1);
        }

        CupidScriptingPlugin.getDefault().logInformation("Found " + allResolved.size()
                + " valid Cupid classpath entries (see log for details)" + System.getProperty("line.separator")
                + Joiner.on(System.getProperty("line.separator")).join(allResolved));

        if (!updatedEntries.isEmpty()) {
            // perform update
            project.setRawClasspath(updatedClasspath.toArray(new IClasspathEntry[] {}),
                    new SubProgressMonitor(monitor, 1));

            for (IClasspathEntry entry : updatedEntries) {
                CupidScriptingPlugin.getDefault()
                        .logInformation("Updated Cupid classpath entry " + entry.getPath());
            }
        } else {
            CupidScriptingPlugin.getDefault().logInformation("Cupid Project classpath is up-to-date");
        }

        return Status.OK_STATUS;
    } catch (Exception ex) {
        return new Status(IStatus.ERROR, CupidScriptingPlugin.PLUGIN_ID,
                "Error updating Cupid scripting classpath", ex);
    } finally {
        monitor.done();
    }
}

From source file:edu.washington.cs.cupid.scripting.java.JavaProjectManager.java

License:Open Source License

/**
 * Add the JAR providing <tt>inputType</tt> to the Cupid project classpath, if it is not already present
 * @param inputType/*from  w  w w . j a  va2 s .com*/
 * @throws JavaModelException
 * @throws IOException
 * @throws ClassNotFoundException
 */
public static void ensureClasspath(TypeToken<?> inputType)
        throws JavaModelException, IOException, ClassNotFoundException {
    IJavaProject project = CupidScriptingPlugin.getDefault().getCupidJavaProject();

    Bundle bundle = ClasspathUtil.bundleForClass(inputType.getRawType().getName());

    if (bundle == null)
        return; // Java core classes don't have bundles

    IPath path = ClasspathUtil.bundlePath(bundle);

    if (!path.toFile().exists()) {
        CupidScriptingPlugin.getDefault()
                .logInformation("Bundle path for " + bundle.getSymbolicName() + " does not exist: " + path);
        return;
    }

    List<IClasspathEntry> cp = Lists.newArrayList(project.getRawClasspath());
    for (IClasspathEntry old : cp) {
        if (old.getPath().equals(path)) {
            return;
        }
    }

    if (path != null) {
        cp.add(JavaCore.newLibraryEntry(path, null, null));
    }

    project.setRawClasspath(cp.toArray(new IClasspathEntry[] {}), null);
}