Example usage for org.eclipse.jdt.core IJavaProject getResolvedClasspath

List of usage examples for org.eclipse.jdt.core IJavaProject getResolvedClasspath

Introduction

In this page you can find the example usage for org.eclipse.jdt.core IJavaProject getResolvedClasspath.

Prototype

IClasspathEntry[] getResolvedClasspath(boolean ignoreUnresolvedEntry) throws JavaModelException;

Source Link

Document

This is a helper method returning the resolved classpath for the project as a list of simple (non-variable, non-container) classpath entries.

Usage

From source file:com.halware.nakedide.eclipse.core.util.JavaCoreUtils.java

License:Open Source License

public final static List<IClasspathEntry> getSourceFolders(IJavaProject javaProject) throws JavaModelException {
    IClasspathEntry[] classpathEntries = javaProject.getResolvedClasspath(false);
    List<IClasspathEntry> sourceFolders = new ArrayList<IClasspathEntry>();
    for (IClasspathEntry classpathEntry : classpathEntries) {
        if (classpathEntry.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
            sourceFolders.add(classpathEntry);
        }/*from   w w  w  .  j  av  a 2 s .c  om*/
    }
    return sourceFolders;
}

From source file:com.javadude.antxr.eclipse.core.builder.AntxrBuilder.java

License:Open Source License

/**
 * Compile a grammar//from  ww w. j  a va 2 s  .  c om
 *
 * @param aFile
 *            The grammar file to compile
 * @param aMonitor
 *            A progress monitor
 */
public void compileFile(IFile aFile, IProgressMonitor aMonitor) {
    String grammarFileName = aFile.getProjectRelativePath().toString();
    try {
        // delete the old generated files for this grammar
        aFile.getProject().accept(new CleaningVisitor(aMonitor, grammarFileName));

        // if it's in a java project, only build it if it's in a source dir
        if (AntxrCorePlugin.getUtil().hasNature(aFile.getProject(), AntxrNature.NATURE_ID)) {
            IProject project = aFile.getProject();
            IJavaProject javaProject = JavaCore.create(project);
            IPath path = aFile.getFullPath();
            boolean ok = false;
            IClasspathEntry[] resolvedClasspath = javaProject.getResolvedClasspath(true);
            for (int i = 0; i < resolvedClasspath.length; i++) {
                IClasspathEntry entry = resolvedClasspath[i];

                if (entry.getEntryKind() != IClasspathEntry.CPE_SOURCE) {
                    continue;
                }

                IPath entryPath = entry.getPath();
                if (entryPath.isPrefixOf(path)) {
                    ok = true;
                    break;
                }
            }
            if (!ok) {
                return;
            }
        }
    } catch (CoreException e1) {
        e1.printStackTrace();
    }

    fFile = aFile;

    aMonitor.beginTask(
            AntxrCorePlugin.getFormattedMessage("AntxrBuilder.compiling", aFile.getFullPath().toString()), 4);

    // Remove all markers from this file
    try {
        aFile.deleteMarkers(null, true, IResource.DEPTH_INFINITE);
    } catch (CoreException e) {
        AntxrCorePlugin.log(e);
    }

    // Prepare arguments for ANTXR compiler
    // read the settings for this grammar
    Map<String, Map<String, String>> map = SettingsPersister.readSettings(aFile.getProject());

    List<String> args = createArguments(map, aFile);
    if (AntxrBuilder.DEBUG) {
        System.out.println("Compiling ANTXR grammar '" + aFile.getName() + "': arguments=" + args);
    }

    // Monitor system out and err
    fOriginalOut = System.out;
    fOriginalErr = System.err;
    System.setOut(new PrintStream(new MonitoredOutputStream(this)));
    System.setErr(new PrintStream(new MonitoredOutputStream(this)));

    try {
        // Compile ANTXR grammar file
        AntxrTool tool = new AntxrTool();
        if (!tool.preprocess(args.toArray(new String[args.size()]))) {
            try {
                aMonitor.worked(1);
                if (!tool.parse()) {
                    aMonitor.worked(1);
                    if (!tool.generate()) {
                        aMonitor.worked(1);
                        refreshFolder(map, tool, args, aFile, grammarFileName,
                                ResourcesPlugin.getWorkspace().getRoot().findMember(fOutput), aMonitor,
                                tool.getSourceMaps());
                    } else {

                        // If errors during generate then delete all
                        // generated files
                        deleteFiles(tool, aFile.getParent(), aMonitor);
                    }
                    aMonitor.worked(1);
                }
            } catch (CoreException e) {
                AntxrCorePlugin.log(e);
            }
        }

    } catch (Throwable e) {
        if (!(e instanceof SecurityException)) {
            AntxrCorePlugin.log(e);
        }
    } finally {
        System.setOut(fOriginalOut);
        System.setErr(fOriginalErr);
        aMonitor.done();
    }
}

From source file:com.javadude.antxr.eclipse.smapinstaller.SMapInstallerBuilder.java

License:Open Source License

/**
 * Installs the modified smap into a generated classfile
 * @param resource//from  www  .  j  a  v a2 s .  co  m
 * @throws JavaModelException
 */
protected void installSmap(IResource resource) throws JavaModelException {
    // We only work on smap files -- skip everything else
    if (!(resource instanceof IFile)) {
        return;
    }
    IFile smapIFile = (IFile) resource;
    if (!"smap".equalsIgnoreCase(smapIFile.getFileExtension())) {
        return;
    }
    IJavaProject javaProject = JavaCore.create(smapIFile.getProject());

    // get the name of the corresponding java source file
    IPath smapPath = smapIFile.getFullPath();

    IClasspathEntry[] classpathEntries = javaProject.getResolvedClasspath(true);
    for (IClasspathEntry entry : classpathEntries) {
        if (entry.getEntryKind() != IClasspathEntry.CPE_SOURCE) {
            continue;
        }
        if (!entry.getPath().isPrefixOf(smapPath)) {
            continue;
        }

        // found the right source container
        IPath outputLocation = entry.getOutputLocation();
        if (outputLocation == null) {
            outputLocation = javaProject.getOutputLocation();
        }
        // strip the source dir and .smap suffix
        String sourceDir = entry.getPath().toString();
        String smapName = smapPath.toString();
        String javaSourceName = smapName.substring(0, smapName.length() - 5) + ".java";
        String className = smapName.substring(sourceDir.length(), smapName.length() - 5) + ".class";
        IPath path = outputLocation.append(className);
        IPath workspaceLoc = ResourcesPlugin.getWorkspace().getRoot().getLocation();
        IPath classFileLocation = workspaceLoc.append(path);
        IResource classResource = ResourcesPlugin.getWorkspace().getRoot().findMember(javaSourceName);

        File classFile = classFileLocation.toFile();
        File smapFile = smapIFile.getLocation().toFile();
        try {
            String installSmap = classResource.getPersistentProperty(AntxrBuilder.INSTALL_SMAP);
            if ("true".equals(installSmap)) {
                SDEInstaller.install(classFile, smapFile);
            }
        } catch (CoreException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.javapathfinder.vjp.DefaultProperties.java

License:Open Source License

/**
 * append all relevant paths from the target project settings to the vm.classpath 
 *//*w w w  .  j ava 2s.c o  m*/
private static void appendProjectClassPaths(IJavaProject project, StringBuilder cp) {
    try {
        // we need to maintain order
        LinkedHashSet<IPath> paths = new LinkedHashSet<IPath>();

        // append the default output folder
        IPath defOutputFolder = project.getOutputLocation();
        if (defOutputFolder != null) {
            paths.add(defOutputFolder);
        }
        // look for libraries and source root specific output folders
        for (IClasspathEntry e : project.getResolvedClasspath(true)) {
            IPath ePath = null;

            switch (e.getContentKind()) {
            case IClasspathEntry.CPE_LIBRARY:
                ePath = e.getPath();
                break;
            case IClasspathEntry.CPE_SOURCE:
                ePath = e.getOutputLocation();
                break;
            }

            if (ePath != null && !paths.contains(ePath)) {

                paths.add(ePath);
            }
        }

        for (IPath path : paths) {
            String absPath = getAbsolutePath(project, path).toOSString();

            //        if (cp.length() > 0) {
            //          cp.append(Config.LIST_SEPARATOR);
            //        }
            // only add classes that are found in bin
            if (absPath.contains("/bin"))
                cp.append(absPath);
        }
        System.out.println("cp is" + cp);
    } catch (JavaModelException jme) {
        VJP.logError("Could not append Project classpath", jme);
    }
}

From source file:com.javapathfinder.vjp.DefaultProperties.java

License:Open Source License

private static String getSourcepathEntry(IJavaProject project) {

    StringBuilder sourcepath = new StringBuilder();
    IClasspathEntry[] paths;//w w  w .j av a2  s . c  o m

    try {
        paths = project.getResolvedClasspath(true);
    } catch (JavaModelException e) {
        VJP.logError("Could not retrieve project classpaths.", e);
        return "";
    }

    for (IClasspathEntry entry : paths) {
        if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
            sourcepath.append(getAbsolutePath(project, entry.getPath()));
            sourcepath.append(Config.LIST_SEPARATOR);
        } else if (entry.getSourceAttachmentPath() != null) {
            IPath path = entry.getSourceAttachmentPath();
            if (path.getFileExtension() == null) { //null for a directory
                sourcepath.append(path);
                sourcepath.append(Config.LIST_SEPARATOR);
            }
        }
    }
    if (sourcepath.length() > 0)
        sourcepath.setLength(sourcepath.length() - 1); //remove that trailing separator
    // VJP.logInfo(sourcepath.toString());
    return sourcepath.toString();
}

From source file:com.liferay.ide.project.core.BaseValidator.java

License:Open Source License

protected IPath[] getSourceEntries(IJavaProject javaProject) {
    List<IPath> paths = new ArrayList<IPath>();

    try {//  w w w .ja va 2  s .c o  m
        final IClasspathEntry[] classpathEntries = javaProject.getResolvedClasspath(true);

        for (IClasspathEntry entry : classpathEntries) {
            if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
                paths.add(entry.getPath());
            }
        }
    } catch (JavaModelException e) {
        ProjectCore.logError("Error resolving classpath.", e);
    }

    return paths.toArray(new IPath[0]);
}

From source file:com.liferay.ide.server.remote.ModuleTraverser.java

License:Open Source License

private static Map getComponentClasspathDependencies(final IJavaProject javaProject, final boolean isWebApp)
        throws CoreException {

    // get the raw entries
    final Map referencedRawEntries = getRawComponentClasspathDependencies(javaProject);
    final Map<IClasspathEntry, IClasspathAttribute> validRawEntries = new HashMap<IClasspathEntry, IClasspathAttribute>();

    // filter out non-valid referenced raw entries
    final Iterator i = referencedRawEntries.keySet().iterator();
    while (i.hasNext()) {
        final IClasspathEntry entry = (IClasspathEntry) i.next();
        final IClasspathAttribute attrib = (IClasspathAttribute) referencedRawEntries.get(entry);
        if (isValid(entry, attrib, isWebApp, javaProject.getProject())) {
            validRawEntries.put(entry, attrib);
        }// w w  w  . ja v a2 s  . c o  m
    }

    // if we have no valid raw entries, return empty map
    if (validRawEntries.isEmpty()) {
        return Collections.EMPTY_MAP;
    }

    // XXX Would like to replace the code below with use of a public JDT API that returns
    // the raw IClasspathEntry for a given resolved IClasspathEntry (see see https://bugs.eclipse.org/bugs/show_bug.cgi?id=183995)
    // The code must currently leverage IPackageFragmentRoot to determine this
    // mapping and, because IPackageFragmentRoots do not maintain IClasspathEntry data, a prior
    // call is needed to getResolvedClasspath() and the resolved IClasspathEntries have to be stored in a Map from IPath-to-IClasspathEntry to
    // support retrieval using the resolved IPackageFragmentRoot

    // retrieve the resolved classpath
    final IClasspathEntry[] entries = javaProject.getResolvedClasspath(true);
    final Map<IPath, IClasspathEntry> pathToResolvedEntry = new HashMap<IPath, IClasspathEntry>();

    // store in a map from path to entry
    for (int j = 0; j < entries.length; j++) {
        pathToResolvedEntry.put(entries[j].getPath(), entries[j]);
    }

    final Map<IClasspathEntry, IClasspathAttribute> referencedEntries = new LinkedHashMap<IClasspathEntry, IClasspathAttribute>();

    // grab all IPackageFragmentRoots
    final IPackageFragmentRoot[] roots = javaProject.getPackageFragmentRoots();
    for (int j = 0; j < roots.length; j++) {
        final IPackageFragmentRoot root = roots[j];
        final IClasspathEntry rawEntry = root.getRawClasspathEntry();

        // is the raw entry valid?
        IClasspathAttribute attrib = validRawEntries.get(rawEntry);
        if (attrib == null) {
            continue;
        }

        final IPath pkgFragPath = root.getPath();
        final IClasspathEntry resolvedEntry = pathToResolvedEntry.get(pkgFragPath);
        final IClasspathAttribute resolvedAttrib = checkForComponentDependencyAttribute(resolvedEntry,
                DEPENDECYATTRIBUTETYPE_DEPENDENCY_OR_NONDEPENDENCY);
        // attribute for the resolved entry must either be unspecified or it must be the
        // dependency attribute for it to be included
        if (resolvedAttrib == null || resolvedAttrib.getName().equals(CLASSPATH_COMPONENT_DEPENDENCY)) {
            // filter out resolved entry if it doesn't pass the validation rules
            if (isValid(resolvedEntry, resolvedAttrib != null ? resolvedAttrib : attrib, isWebApp,
                    javaProject.getProject())) {
                if (resolvedAttrib != null) {
                    // if there is an attribute on the sub-entry, use that
                    attrib = resolvedAttrib;
                }
                referencedEntries.put(resolvedEntry, attrib);
            }
        }
    }

    return referencedEntries;
}

From source file:com.microsoft.javapkgbuild.Tasks.java

License:MIT License

public static void displayReferences(String projectName) throws JavaModelException {
    IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();
    IProject project = workspaceRoot.getProject(projectName);
    IJavaProject javaProject = JavaCore.create(project);

    IClasspathEntry[] classPathList = javaProject.getResolvedClasspath(true);
    for (IClasspathEntry cp : classPathList) {
        System.out.println(cp.toString());
    }//from  w  ww.  j av  a2 s .  c  o m
}

From source file:com.microsoft.javapkgbuild.Tasks.java

License:MIT License

public static void exportReferences(String projectName, String outputFileName) throws JavaModelException {
    try {/*from   w w w  .  ja  va2 s .c  o m*/
        IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();
        IProject project = workspaceRoot.getProject(projectName);
        IJavaProject javaProject = JavaCore.create(project);

        DocumentBuilderFactory xFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = xFactory.newDocumentBuilder();
        Document doc = builder.newDocument();

        Element mainRoot = doc.createElement("classpath");
        mainRoot.setAttribute("projectName", projectName);
        doc.appendChild(mainRoot);

        IClasspathEntry[] classPathList = javaProject.getResolvedClasspath(true);
        for (IClasspathEntry cp : classPathList) {
            Element cpNode = doc.createElement("classpathentry");
            cpNode.setAttribute("path", cp.getPath().toOSString());
            cpNode.setAttribute("kind", getClassPathType(cp));
            cpNode.setAttribute("exported", Boolean.toString(cp.isExported()));

            IPath sourceFolder = cp.getSourceAttachmentPath();
            if (cp.getEntryKind() == IClasspathEntry.CPE_LIBRARY && sourceFolder != null)
                cpNode.setAttribute("sourcepath", sourceFolder.toOSString());

            mainRoot.appendChild(cpNode);
        }

        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        DOMSource source = new DOMSource(doc);

        FileOutputStream fos = new FileOutputStream(outputFileName);
        StreamResult outFile = new StreamResult(fos);
        transformer.transform(source, outFile);
        fos.close();

        System.out.println("Output file is: " + outputFileName);
    } catch (Exception e) {
        e.printStackTrace(System.err);
    }
}

From source file:com.redhat.victims.plugin.eclipse.handler.ScanHandler.java

License:Open Source License

/**
 * Begins the life-cycle of the plugin. Finds the absolute path names of all
 * dependencies for a project in eclipse and creates the popup menu for
 * settings.//ww w .j av  a  2s  .  c  o m
 */
public Object execute(ExecutionEvent event) throws ExecutionException {
    Shell shell = HandlerUtil.getActiveShell(event);
    ISelection sel = HandlerUtil.getActiveMenuSelection(event);
    IStructuredSelection selection = (IStructuredSelection) sel;
    Object firstElement = selection.getFirstElement();

    if (firstElement instanceof IJavaProject) {
        IJavaProject jp = (IJavaProject) firstElement;
        optionMenu = new OptionMenuRunnable(this);
        EventQueue.invokeLater(optionMenu);

        try {
            IClasspathEntry[] cp = jp.getResolvedClasspath(true);
            /*
             * Extracts all .jar files from the classpath and adds them to a
             * list to be passed to VictimScan during the callback
             */
            for (IClasspathEntry entry : cp) {
                IPath path = entry.getPath();
                String ext = path.getFileExtension();
                // This condition seems weird but if it's the other way
                // around you open yourself up to null pointer exceptions!
                if (JAR_EXT.equals(ext)) {
                    paths.add(path);
                }
            }
        } catch (JavaModelException e) {
            log.log(new Status(Status.INFO, Activator.PLUGIN_ID, e.getLocalizedMessage()));
        }

    } else {
        MessageDialog.openInformation(shell, "Info", "Please select a Java Project");
    }
    return null;
}