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:org.apache.metro.studio.eclipse.core.templateengine.Directory.java

License:Apache License

private void addClasspath(IProject project, IClasspathEntry entry) {
    try {//  w w  w  .  j  a  v a2  s  . c  o m
        Vector libraries = new Vector();

        IJavaProject javaProject = JavaCore.create(project);
        IClasspathEntry[] current = javaProject.getResolvedClasspath(true);

        for (int i = 0; i < current.length; i++) {
            // don't add the project to the classpath!
            IPath curPath = current[i].getPath();
            IPath projPath = project.getFullPath();

            // TODO: Shouldn't IPath.equals() work??
            if (!curPath.toString().equals(projPath.toString())) {
                libraries.add(current[i]);
            }
        }
        libraries.add(entry);

        int size = libraries.size();
        IClasspathEntry[] entries = new IClasspathEntry[size];
        libraries.toArray(entries);
        IPath location = javaProject.getOutputLocation();
        javaProject.setRawClasspath(entries, location, null);
    } catch (JavaModelException e) {
        MetroStudioCore.log(e, "could not add libraries to project");
    }
}

From source file:org.apache.metro.studio.eclipse.core.templateengine.ResourceTemplate.java

License:Apache License

/**
 * @param project//  www .j  a  v  a  2  s .c om
 */
private void addLibraries(IProject project) {
    try {
        Vector libs = new Vector();

        IJavaProject javaProject = JavaCore.create(project);

        // first retain already created libs
        IClasspathEntry[] entries = javaProject.getResolvedClasspath(true);
        for (int i = 0; i < entries.length; i++) {
            libs.add(entries[i]);
        }

        // allways add the java library
        libs.add(JavaRuntime.getJREVariableEntry());

        // now add custom libraries
        libs.addAll(getLibraryEntries());

        IClasspathEntry[] cpEntries = new IClasspathEntry[libraries.size()];
        libs.toArray(cpEntries);
        IPath location = javaProject.getOutputLocation();
        javaProject.setRawClasspath(cpEntries, location, null);
    } catch (JavaModelException e) {
        e.printStackTrace();
    }
}

From source file:org.cloudfoundry.ide.eclipse.server.core.internal.CloudFoundryProjectUtil.java

License:Open Source License

/**
 * //from w w w.  ja  va2 s .  c o m
 * 
 * Derived from org.springframework.ide.eclipse.boot.core.BootPropertyTester
 * 
 * FIXNS: Remove when boot detection is moved to a common STS plug-in that
 * can be shared with CF Eclipse.
 * @return true if the given project is a Spring boot project, false
 * otherwise
 */
public static boolean isSpringBoot(IProject project) {
    if (project != null && isSpringProject(project)) {
        try {
            IJavaProject javaProject = getJavaProject(project);

            if (javaProject != null) {
                IClasspathEntry[] classpath = javaProject.getResolvedClasspath(true);
                // Look for a 'spring-boot' jar entry
                for (IClasspathEntry e : classpath) {
                    if (hasBootDependencies(e)) {
                        return true;
                    }
                }
            }
        } catch (Exception e) {
            CloudFoundryPlugin.logError(e);
        }
    }
    return false;
}

From source file:org.cloudfoundry.ide.eclipse.server.core.internal.debug.DebugProvider.java

License:Open Source License

protected boolean containsDebugFiles(IJavaProject project) {
    try {/*  ww w  . ja  va2 s .  c om*/

        IClasspathEntry[] entries = project.getResolvedClasspath(true);

        if (entries != null) {
            for (IClasspathEntry entry : entries) {
                if (entry != null && entry.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
                    IPath projectPath = project.getPath();
                    IPath relativePath = entry.getPath().makeRelativeTo(projectPath);
                    IFolder folder = project.getProject().getFolder(relativePath);
                    if (getFile(folder, ".profile.d", "ngrok.sh") != null) {//$NON-NLS-1$ //$NON-NLS-2$
                        return true;
                    }
                }
            }
        }
    } catch (JavaModelException e) {
        CloudFoundryPlugin.logError(e);
    } catch (CoreException ce) {
        CloudFoundryPlugin.logError(ce);
    }
    return false;
}

From source file:org.cloudfoundry.ide.eclipse.server.ui.internal.CloudRebelUIHandler.java

License:Open Source License

protected List<String> getClasspathSourceOutputPaths(IProject project) {

    IJavaProject javaProject = CloudFoundryProjectUtil.getJavaProject(project);
    List<String> outputPaths = new ArrayList<String>();
    if (javaProject != null) {
        try {/*from   w  w w.j  a v  a  2s .c om*/
            IClasspathEntry[] classpath = javaProject.getResolvedClasspath(true);

            if (classpath != null) {
                for (IClasspathEntry entry : classpath) {
                    if (entry != null && entry.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
                        String outputPath = entry.getOutputLocation() != null
                                ? entry.getOutputLocation().toString()
                                : null;
                        if (outputPath != null && !outputPaths.contains(outputPath)
                                && !outputPath.contains("target/test-classes")) {//$NON-NLS-1$
                            outputPaths.add(outputPath);
                        }
                    }
                }
            }

            String outputPath = javaProject.getOutputLocation() != null
                    ? javaProject.getOutputLocation().toString()
                    : null;
            if (outputPath != null && !outputPaths.contains(outputPath)) {
                outputPaths.add(outputPath);
            }
        } catch (JavaModelException e) {
            CloudFoundryPlugin.logError(e);
        }
    }

    return outputPaths;
}

From source file:org.codecover.eclipse.builder.CodeCoverCompilationParticipant.java

License:Open Source License

/**
 * This method is called for each project separately.
 *//*from w  w w.  ja va2  s. com*/
@Override
public void buildStarting(BuildContext[] files, boolean isBatch) {
    if (files.length == 0) {
        return;
    }

    final IProject iProject = files[0].getFile().getProject();
    final IPath projectFullPath = iProject.getFullPath();
    final IPath projectLocation = iProject.getLocation();
    final String projectFolderLocation = iProject.getLocation().toOSString();
    final Queue<SourceTargetContainer> sourceTargetContainers = new LinkedList<SourceTargetContainer>();
    final String instrumentedFolderLocation = CodeCoverPlugin.getDefault()
            .getPathToInstrumentedSources(iProject).toOSString();

    // try to get all source folders
    final Queue<String> possibleSourceFolders = new LinkedList<String>();
    try {
        final IJavaProject javaProject = JavaCore.create(iProject);
        for (IPackageFragmentRoot thisRoot : javaProject.getAllPackageFragmentRoots()) {
            IResource resource = thisRoot.getCorrespondingResource();
            if (resource != null) {
                possibleSourceFolders.add(resource.getLocation().toOSString());
            }
        }
    } catch (JavaModelException e) {
        eclipseLogger.fatal("JavaModelException in CompilationParticipant", e); //$NON-NLS-1$
        return;
    }

    InstrumentableItemsManager instrumentableItemsManager = CodeCoverPlugin.getDefault()
            .getInstrumentableItemsManager();
    TSContainerManager tscManager = CodeCoverPlugin.getDefault().getTSContainerManager();

    // //////////////////////////////////////////////////////////////////////
    // CREATE THE SOURCE TARGET CONTAINERS AND COPY THE UNINSTRUMENTED
    // FILES TO THE INSTRUMENTEDFOLDERLOCATION
    // //////////////////////////////////////////////////////////////////////
    fillSourceTargetContainers(files, possibleSourceFolders, sourceTargetContainers, instrumentedFolderLocation,
            eclipseLogger, instrumentableItemsManager);

    // //////////////////////////////////////////////////////////////////////
    // SEARCH IN ALL TSC OF THIS PROJECT IF A TSC CAN BE REUSED
    // //////////////////////////////////////////////////////////////////////

    TestSessionContainer tsc;
    if (SEARCH_IN_ALL_TSC) {
        tsc = searchUseableTSC(iProject, files, instrumentableItemsManager, tscManager);
    } else {
        tsc = getUseableTSC(files, instrumentableItemsManager, tscManager);
    }

    // //////////////////////////////////////////////////////////////////////
    // PREPARE INSTRUMENTATION
    // //////////////////////////////////////////////////////////////////////
    InstrumenterDescriptor descriptor = new org.codecover.instrumentation.java15.InstrumenterDescriptor();
    if (descriptor == null) {
        eclipseLogger.fatal("NullPointerException in CompilationParticipant"); //$NON-NLS-1$
    }

    // check whether TSC's criteria match
    // with the selected criteria of the project
    if (tsc != null) {
        Set<Criterion> tscCriteria = tsc.getCriteria();

        for (Criterion criterion : tscCriteria) {
            if (!CodeCoverPlugin.getCriterionSelectedState(iProject, criterion)) {
                // the TSC uses a criterion which is not selected for the project
                // therefore it can't be used
                tsc = null;
            }
        }

        // all selected criteria must be active for the TSC
        for (Criterion criterion : descriptor.getSupportedCriteria()) {
            if (CodeCoverPlugin.getCriterionSelectedState(iProject, criterion)) {
                if (!tscCriteria.contains(criterion)) {
                    // the TSC doesn't use a criterion which is selected
                    // for the project, this means we can't use the TSC
                    tsc = null;
                }
            }
        }
    }

    eclipseLogger.debug("can reuse TSC: " + (tsc != null ? tsc : "no")); //$NON-NLS-1$ //$NON-NLS-2$

    InstrumenterFactory factory = new DefaultInstrumenterFactory();
    factory.setDescriptor(descriptor);

    // only instrument with the selected criteria
    for (Criterion criterion : descriptor.getSupportedCriteria()) {
        if (CodeCoverPlugin.getCriterionSelectedState(iProject, criterion)) {
            factory.addCriterion(criterion);
        }
    }

    factory.setCharset(DEFAULT_CHARSET_FOR_COMPILING);

    Instrumenter instrumenter = null;
    try {
        instrumenter = factory.getInstrumenter();
    } catch (FactoryMisconfigurationException e) {
        eclipseLogger.fatal("FactoryMisconfigurationException in CompilationParticipant"); //$NON-NLS-1$
    }

    // //////////////////////////////////////////////////////////////////////
    // INSTRUMENT
    // //////////////////////////////////////////////////////////////////////
    File rootFolder = new File(projectFolderLocation);
    File targetFolder = new File(instrumentedFolderLocation);
    MASTBuilder builder = new MASTBuilder(eclipseLogger);
    Map<String, Object> instrumenterDirectives = descriptor.getDefaultDirectiveValues();
    CodeCoverPlugin plugin = CodeCoverPlugin.getDefault();
    eclipseLogger.debug("Plugin: " + plugin);
    IPath coverageLogPath = CodeCoverPlugin.getDefault().getPathToCoverageLogs(iProject);
    coverageLogPath = coverageLogPath.append("coverage-log-file.clf"); //$NON-NLS-1$

    instrumenterDirectives.put(
            org.codecover.instrumentation.java15.InstrumenterDescriptor.CoverageLogPathDirective.KEY,
            coverageLogPath.toOSString());

    if (tsc != null) {
        // we can reuse the TSC
        instrumenterDirectives.put(org.codecover.instrumentation.UUIDDirective.KEY, tsc.getId());
    }

    TestSessionContainer testSessionContainer;
    try {
        testSessionContainer = instrumenter.instrument(rootFolder, targetFolder, sourceTargetContainers,
                builder, instrumenterDirectives);
    } catch (InstrumentationIOException e) {
        eclipseLogger.fatal("InstrumentationIOException in CompilationParticipant", e); //$NON-NLS-1$
        return;
    } catch (InstrumentationException e) {
        eclipseLogger.fatal("InstrumentationException in CompilationParticipant", e); //$NON-NLS-1$
        return;
    }

    // //////////////////////////////////////////////////////////////////////
    // SAVE TSC
    // //////////////////////////////////////////////////////////////////////
    if (tsc == null) {
        // we have to create a new TSC
        try {
            tscManager.addTestSessionContainer(testSessionContainer, iProject, false, null, null);
        } catch (FileSaveException e) {
            eclipseLogger.fatal("FileSaveException in CompilationParticipant", e); //$NON-NLS-1$
        } catch (TSCFileCreateException e) {
            eclipseLogger.fatal("CoreException in CompilationParticipant", e); //$NON-NLS-1$
        } catch (FileLoadException e) {
            eclipseLogger.fatal("CoreException in CompilationParticipant", e); //$NON-NLS-1$
        } catch (InvocationTargetException e) {
            // can't happen because we didn't pass a runnable
            eclipseLogger.warning("InvocationTargetException in CompilationParticipant", e); //$NON-NLS-1$
        } catch (CancelException e) {
            eclipseLogger.warning("User canceled writing of" + //$NON-NLS-1$
                    " new test session container in" + //$NON-NLS-1$
                    " CompilationParticipant"); //$NON-NLS-1$
        }
    }

    // TODO handle compilation errors
    IJavaProject javaProject = JavaCore.create(iProject);

    // set up classpath
    StringBuilder runCommand = new StringBuilder(1024);
    IClasspathEntry[] cpEntries;
    try {
        cpEntries = javaProject.getResolvedClasspath(true);
    } catch (JavaModelException e) {
        eclipseLogger.fatal("JavaModelException in CompilationParticipant", e); //$NON-NLS-1$
        return;
    }

    for (int i = 0; i < cpEntries.length; i++) {
        IClasspathEntry thisEntry = cpEntries[i];
        if (thisEntry.getEntryKind() == IClasspathEntry.CPE_LIBRARY) {
            if (runCommand.length() == 0) {
                // this is the first entry -> create the class path option
                runCommand.append("-cp "); //$NON-NLS-1$
            } else {
                // this is not the first -> we need a separator
                runCommand.append(File.pathSeparatorChar);
            }
            runCommand.append("\""); //$NON-NLS-1$
            IPath itsIPath = thisEntry.getPath();
            if (projectFullPath.isPrefixOf(itsIPath)) {
                itsIPath = itsIPath.removeFirstSegments(1);
                itsIPath = projectLocation.append(itsIPath);
            }
            runCommand.append(itsIPath.toOSString());
            runCommand.append("\""); //$NON-NLS-1$
        }
    }

    // check java version related options
    String targetVersion = javaProject.getOption(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, true);
    runCommand.append(" -target "); //$NON-NLS-1$
    runCommand.append(targetVersion);
    String sourceVersion = javaProject.getOption(JavaCore.COMPILER_SOURCE, true);
    runCommand.append(" -source "); //$NON-NLS-1$
    runCommand.append(sourceVersion);

    // no warnings
    runCommand.append(" -nowarn"); //$NON-NLS-1$

    // use the default charset for the encoding
    // all files have been instrumented or copied using this charset
    runCommand.append(" -encoding "); //$NON-NLS-1$
    runCommand.append(DEFAULT_CHARSET_FOR_COMPILING.toString());

    // the directory to compile
    // put the path in "", because the commandline tokenizes this path
    runCommand.append(" \""); //$NON-NLS-1$
    runCommand.append(instrumentedFolderLocation);
    runCommand.append("\""); //$NON-NLS-1$

    eclipseLogger.debug("I run this compile command now:\n" + runCommand); //$NON-NLS-1$
    StringWriter out = new StringWriter();
    StringWriter err = new StringWriter();
    boolean result;
    result = org.eclipse.jdt.internal.compiler.batch.Main.compile(runCommand.toString(), new PrintWriter(out),
            new PrintWriter(err));

    eclipseLogger.debug("ECJ Output: " + out.toString()); //$NON-NLS-1$
    eclipseLogger.debug("ECJ Error Output: " + err.toString()); //$NON-NLS-1$

    if (!result) {
        eclipseLogger.fatal("An error occured when trying to compile the instrumented sources."); //$NON-NLS-1$
    }

    super.buildStarting(files, isBatch);
}

From source file:org.codehaus.aspectwerkz.ide.eclipse.core.AwCorePlugin.java

License:Open Source License

/**
 * Build the list of URL for the given project
 * Resolve container (ie JRE jars) and dependancies and project output folder
 * //from w ww .  j ava  2s  .c om
 * @param project
 * @return
 */
public List getProjectClassPathURLs(IJavaProject project) {
    List paths = new ArrayList();
    try {
        // configured classpath
        IClasspathEntry classpath[] = project.getResolvedClasspath(false);
        for (int i = 0; i < classpath.length; i++) {
            IClasspathEntry path = classpath[i];
            URL urlEntry = null;

            if (path.getEntryKind() == IClasspathEntry.CPE_LIBRARY) {
                IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();
                Object target = JavaModel.getTarget(workspaceRoot, path.getPath(), false);
                if (target != null) {
                    // inside the workspace
                    if (target instanceof IResource) {
                        urlEntry = ((IResource) target).getLocation().toFile().toURL();
                    } else if (target instanceof File) {
                        urlEntry = ((File) target).toURL();
                    }
                }
            } else if (path.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
                IPath outPath = path.getOutputLocation();
                if (outPath != null) {
                    //TODO : don't know if I ll have absolute path here
                    urlEntry = outPath.toFile().toURL();
                }
            }
            if (urlEntry != null) {
                paths.add(urlEntry);
            } else {
                AwLog.logTrace("project loader - ignored " + path.toString());
            }
        }
        // project build output
        IPath location = getProjectLocation(project.getProject());
        IPath outputPath = location.append(project.getOutputLocation().removeFirstSegments(1));
        paths.add(outputPath.toFile().toURL());
    } catch (Exception e) {
        AwLog.logError("Could not build project path", e);
    }
    return paths;
}

From source file:org.codehaus.groovy.eclipse.dsl.tests.BuiltInDSLInferencingTests.java

License:Open Source License

public void testSanity() throws Exception {
    IJavaProject javaProject = JavaCore.create(project);
    assertTrue("Should have DSL support classpath container",
            GroovyRuntime.hasClasspathContainer(javaProject, GroovyDSLCoreActivator.CLASSPATH_CONTAINER_ID));

    IClasspathContainer container = JavaCore
            .getClasspathContainer(GroovyDSLCoreActivator.CLASSPATH_CONTAINER_ID, javaProject);
    IClasspathEntry[] cpes = container.getClasspathEntries();
    assertEquals("Wrong number of classpath entries found: " + Arrays.toString(cpes), 2, cpes.length);

    IClasspathEntry pluginEntry = null;//from   w  w  w  .jav  a  2 s.  c  om
    IClasspathEntry[] entries = javaProject.getResolvedClasspath(true);
    for (IClasspathEntry entry : entries) {
        if (entry.getPath().toString().contains("plugin_dsld")) {
            pluginEntry = entry;
        }
    }

    IPackageFragmentRoot root = null;
    List<String> elements = new ArrayList<String>();
    for (IJavaElement elt : javaProject.getChildren()) {
        elements.add(elt.getElementName());
        if (elt.getElementName().contains("plugin_dsld")) {
            root = (IPackageFragmentRoot) elt;
        }
    }

    List<String> possibleFrags = new ArrayList<String>();
    for (IPackageFragment frag : javaProject.getPackageFragments()) {
        if (frag.getElementName().equals("dsld")) {
            possibleFrags.add(frag.toString());
            possibleFrags.add("  [");
            for (IJavaElement child : frag.getChildren()) {
                possibleFrags.add("    " + child.getElementName());
            }
            possibleFrags.add("  ]");
        }
    }

    assertNotNull("Did not find the Plugin DSLD classpath entry.  Exsting resolved roots:\n"
            + printList(elements) + "\nOther DSLD fragments:\n" + printList(possibleFrags), pluginEntry);
    assertNotNull("Plugin DSLD classpath entry should exist.  Exsting resolved roots:\n" + printList(elements)
            + "\nOther DSLD fragments:\n" + printList(possibleFrags), root);
    assertTrue("Plugin DSLD classpath entry should exist", root.exists());

    ExternalPackageFragmentRoot ext = (ExternalPackageFragmentRoot) root;
    ext.resource().refreshLocal(IResource.DEPTH_INFINITE, null);
    root.close();
    root.open(null);

    IPackageFragment frag = root.getPackageFragment("dsld");
    assertTrue("DSLD package fragment should exist", frag.exists());
}

From source file:org.drools.eclipse.builder.DroolsBuilder.java

License:Apache License

private IProject[] getRequiredProjects(IProject project) {
    IJavaProject javaProject = JavaCore.create(project);
    List projects = new ArrayList();
    try {/*from w  w w .j a  v a2s  .co  m*/
        IClasspathEntry[] entries = javaProject.getResolvedClasspath(true);
        for (int i = 0, l = entries.length; i < l; i++) {
            IClasspathEntry entry = entries[i];
            if (entry.getEntryKind() == IClasspathEntry.CPE_PROJECT) {
                IProject p = project.getWorkspace().getRoot().getProject(entry.getPath().lastSegment()); // missing projects are considered too
                if (p != null && !projects.contains(p)) {
                    projects.add(p);
                }
            }
        }
    } catch (JavaModelException e) {
        return new IProject[0];
    }
    return (IProject[]) projects.toArray(new IProject[projects.size()]);
}

From source file:org.drools.eclipse.util.ProjectClassLoader.java

License:Apache License

public static List<URL> getProjectClassPathURLs(IJavaProject project, List<String> alreadyLoadedProjects) {
    List<URL> pathElements = new ArrayList<URL>();
    try {/*from  w  w w . j a  va2s  . c o  m*/
        IClasspathEntry[] paths = project.getResolvedClasspath(true);
        Set<IPath> outputPaths = new HashSet<IPath>();
        if (paths != null) {
            for (int i = 0; i < paths.length; i++) {
                IClasspathEntry path = paths[i];
                if (path.getEntryKind() == IClasspathEntry.CPE_LIBRARY) {
                    URL url = getRawLocationURL(path.getPath());
                    pathElements.add(url);
                } else if (path.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
                    IPath output = path.getOutputLocation();
                    if (path.getOutputLocation() != null) {
                        outputPaths.add(output);
                    }
                }
            }
        }
        IPath location = getProjectLocation(project.getProject());
        IPath outputPath = location.append(project.getOutputLocation().removeFirstSegments(1));
        pathElements.add(0, outputPath.toFile().toURI().toURL());
        for (IPath path : outputPaths) {
            outputPath = location.append(path.removeFirstSegments(1));
            pathElements.add(0, outputPath.toFile().toURI().toURL());
        }

        // also add classpath of required projects
        for (String projectName : project.getRequiredProjectNames()) {
            if (!alreadyLoadedProjects.contains(projectName)) {
                alreadyLoadedProjects.add(projectName);
                IProject reqProject = project.getProject().getWorkspace().getRoot().getProject(projectName);
                if (reqProject != null) {
                    IJavaProject reqJavaProject = JavaCore.create(reqProject);
                    pathElements.addAll(getProjectClassPathURLs(reqJavaProject, alreadyLoadedProjects));
                }
            }
        }
    } catch (JavaModelException e) {
        DroolsEclipsePlugin.log(e);
    } catch (MalformedURLException e) {
        DroolsEclipsePlugin.log(e);
    } catch (Throwable t) {
        DroolsEclipsePlugin.log(t);
    }
    return pathElements;
}