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

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

Introduction

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

Prototype

int getEntryKind();

Source Link

Document

Returns the kind of this classpath entry.

Usage

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;//from  w  w w .  j  a v a2  s  . c o 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();/*from  w w  w.j  a  va  2s  .c  o m*/
    IPath op = ent.getOutputLocation();
    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.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();/*www  .j  a  va 2s. com*/
    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  . java2 s. c om
        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 {//  w  w  w .  jav a 2 s.  co 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 {//from  w w  w.  ja va 2  s .  co  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:es.bsc.servicess.ide.PackagingUtils.java

License:Apache License

/** Get the classpath of the project
 * @param project//w  ww  .j  ava2  s .c o  m
 * @return
 * @throws JavaModelException
 */
public static String getClasspath(IJavaProject project) throws JavaModelException {
    String classpath = new String();
    IPath path = project.getProject().getWorkspace().getRoot().getLocation();
    boolean first = true;
    for (IClasspathEntry e : project.getResolvedClasspath(true)) {
        if (!first) {
            classpath = classpath.concat(":");

        } else {
            first = false;
        }
        if (e.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
            IPath entryPath = e.getPath();
            path.isPrefixOf(entryPath);
            classpath = classpath.concat(path.append(entryPath.makeRelative()).toOSString());
        } else {
            classpath = classpath.concat(e.getPath().toOSString());
        }
    }
    return classpath;
}

From source file:es.optsicom.res.client.util.ProjectDependenciesResolver.java

License:Eclipse Public License

private void calculateDependencies(IClasspathEntry[] cpe, IProject project)
        throws DependenciesResolverException {
    try {/*w  w w  .  j  a  va  2s.  c  o  m*/

        IWorkspace workspace = project.getWorkspace();
        IPath workspacePath = workspace.getRoot().getLocation();
        String nombreWorkspace = workspacePath.toString();
        IJavaProject jp = JavaCore.create(project);

        if (!dependencies.contains(project.getLocation().toString())) {
            // Aadimos la carpeta bin
            classpathFiles.add(workspacePath.append(jp.getOutputLocation()).toFile());
            classpath.add(jp.getOutputLocation().toString());
        }

        for (IClasspathEntry cpEntry : cpe) {

            String path = cpEntry.getPath().toString();
            String dependency = nombreWorkspace.concat(path);

            if (!dependencies.contains(dependency)) {
                RESClientPlugin.log("Adding dependency: " + dependency);
                dependencies.add(dependency);

                if (cpEntry.getOutputLocation() != null) {
                    RESClientPlugin.log("Binarios: " + cpEntry.getOutputLocation().toString());
                    classpath.add(cpEntry.getOutputLocation().makeRelativeTo(workspacePath).toString());
                    classpathFiles.add(cpEntry.getOutputLocation().toFile());
                }

                int tipo = cpEntry.getEntryKind();

                //Si la dependencia es de una libreria(

                if (tipo == IClasspathEntry.CPE_LIBRARY) {

                    String dep = cpEntry.getPath().makeRelativeTo(workspacePath).toString();
                    //mgarcia: Optsicom res Evolution
                    if (new File(workspacePath.toFile(), cpEntry.getPath().toOSString()).exists()) {
                        classpathFiles.add(new File(workspacePath.toFile(), cpEntry.getPath().toOSString()));

                        //Aadimos las dependencias a las properties
                        RESClientPlugin.log("Adding library: " + dep);
                        classpath.add(cpEntry.getPath().toString());
                    } else {
                        throw new DependenciesResolverException();
                    }

                } else if (tipo == IClasspathEntry.CPE_PROJECT) {

                    //                  File[] files = new File(dependency).listFiles();
                    //                  for (File f : files){
                    //                     lista.add(f);
                    //                     String dep = f.getPath();
                    //                     RESClientPlugin.log("Adding dependency: " + dep);
                    //                     dependencies.add(dep);
                    //                  }

                    IProject p = workspace.getRoot().getProject(cpEntry.getPath().lastSegment());
                    IJavaProject projectDependency = JavaCore.create(p);
                    IClasspathEntry[] cp = projectDependency.getRawClasspath();

                    classpathFiles.add(workspacePath.append(projectDependency.getOutputLocation()).toFile());
                    classpath.add(projectDependency.getOutputLocation().toString());

                    RESClientPlugin.log("Populating files from: " + p.getName());
                    calculateDependencies(cp, p);

                } else if (tipo == IClasspathEntry.CPE_SOURCE) {

                    File f = new File(dependency);
                    classpathFiles.add(f);
                    RESClientPlugin.log("Adding source: " + dependency);

                } else if (tipo == IClasspathEntry.CPE_VARIABLE) {

                    IClasspathEntry[] clpe = new IClasspathEntry[1];
                    clpe[0] = JavaCore.getResolvedClasspathEntry(cpEntry);
                    if (clpe[0] != null) {
                        RESClientPlugin.log("Populating files from: " + clpe[0].getPath().toOSString());
                        calculateDependencies(clpe, project);
                    }

                } else if (tipo == IClasspathEntry.CPE_CONTAINER) {

                    if (cpEntry.getPath().toOSString().contains("JRE_CONTAINER")
                            || cpEntry.getPath().toOSString().contains("requiredPlugins")) {
                        continue;
                    }

                    IClasspathContainer cc = JavaCore.getClasspathContainer(cpEntry.getPath(), jp);
                    IClasspathEntry[] entradas = cc.getClasspathEntries();

                    RESClientPlugin.log("Populating files from: " + cc.getPath().toOSString());
                    calculateDependencies(entradas, project);

                }
            }
        }
    } catch (JavaModelException e) {
        RESClientPlugin.log(e);
    }

    for (String path : classpath) {
        RESClientPlugin.log("Classpath: " + path);
    }
    for (File file : classpathFiles) {
        RESClientPlugin.log("Classpath file: " + file.getAbsolutePath());
    }
}

From source file:fede.workspace.eclipse.composition.copy.exporter.JavaClassRefExporter.java

License:Apache License

protected Map<IPath, FolderExportedContent> findLocations(FolderExportedContent folderContent,
        String exporterType) throws JavaModelException, CoreException {
    IJavaProject javaProject = JavaProjectManager.getJavaProject(getItem());

    Map<IPath, FolderExportedContent> outputLocations = new HashMap<IPath, FolderExportedContent>();
    IClasspathEntry[] rawClasspath = javaProject.getRawClasspath();

    if (exporterType.equals(JAVA_REF_EXPORTER_TYPE)) {
        for (IClasspathEntry entry : rawClasspath) {
            if (entry.getEntryKind() != IClasspathEntry.CPE_SOURCE)
                continue;

            if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
                IPath outputPath = entry.getOutputLocation();
                if (outputPath == null)
                    outputPath = javaProject.getOutputLocation();

                outputLocations.put(getRelativePath(outputPath), folderContent);
            } else if (entry.getEntryKind() == IClasspathEntry.CPE_LIBRARY) {
                IPath outputPath = entry.getPath();
                if (outputPath != null)
                    outputLocations.put(getRelativePath(outputPath), folderContent);
            }//from  w  w w  .  ja  v  a 2  s  .c o m
        }
    } else {
        for (IClasspathEntry entry : rawClasspath) {
            if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
                IPath outputPath = entry.getPath();
                if (outputPath != null)
                    outputLocations.put(getRelativePath(outputPath), folderContent);
            } else if (entry.getEntryKind() == IClasspathEntry.CPE_LIBRARY) {
                IPath outputPath = entry.getSourceAttachmentPath();
                if (outputPath != null)
                    outputLocations.put(getRelativePath(outputPath), folderContent);
            }
        }
    }
    return outputLocations;
}

From source file:fede.workspace.eclipse.composition.java.JavaProjectExporter.java

License:Apache License

/**
 * Updates an existing packaged binary version of the content of the item in
 * this project.// w  w  w  .  j  ava2  s. c o  m
 * 
 * Scans all output directories of the java project and updates all modified
 * classes in the packaged item version.
 * 
 * If no resource delta is specified all the binary contents are copied to
 * the packaged version.
 * 
 * @param monitor
 *            the monitor
 * @param eclipseExportedContent
 *            the eclipse exported content
 * @param projectDelta
 *            the project delta
 * @param exporterType
 *            the exporter type
 * 
 * @throws CoreException
 *             the core exception
 */
@Override
protected void exportItem(EclipseExportedContent eclipseExportedContent, IResourceDelta projectDelta,
        IProgressMonitor monitor, String exporterType) throws CoreException {

    /*
     * skip empty notifications
     */
    if ((projectDelta != null) && (projectDelta.getKind() == IResourceDelta.NO_CHANGE)) {
        return;
    }

    /*
     * Verify this item is actually hosted in a Java Project
     */
    if (!JavaProjectManager.isJavaProject(MelusineProjectManager.getProject(getItem()))) {
        return;
    }

    IJavaProject javaProject = JavaProjectManager.getJavaProject(getItem());

    /*
     * TODO We scan all output directories, we should only scan the output
     * directory associated with the item.
     * 
     * We need to handle mapping variants in which there are many composites
     * in a single java project, this is the case for example when a
     * composite has parts that are themselves java composites.
     */
    Set<IPath> outputLocations = new HashSet<IPath>();
    for (IClasspathEntry entry : javaProject.getResolvedClasspath(true)) {
        if (entry.getEntryKind() != IClasspathEntry.CPE_SOURCE) {
            continue;
        }

        IPath outputPath = entry.getOutputLocation();
        if (outputPath == null) {
            outputPath = javaProject.getOutputLocation();
        }

        outputLocations.add(getRelativePath(outputPath));
    }

    Scanner scanner = new Scanner(eclipseExportedContent);
    for (IPath outputPath : outputLocations) {
        IFolder outputRoot = getFolder(outputPath);
        IResourceDelta outputDelta = (projectDelta != null)
                ? projectDelta.findMember(outputRoot.getProjectRelativePath())
                : null;

        // If no modification of the output location just skip it
        if ((projectDelta != null) && (outputDelta == null)) {
            return;
        }

        scanner.scan(outputRoot, outputDelta, monitor);
    }
}