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

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

Introduction

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

Prototype

IClasspathEntry[] getRawClasspath() throws JavaModelException;

Source Link

Document

Returns the raw classpath for the project, as a list of classpath entries.

Usage

From source file:org.codehaus.groovy.eclipse.core.model.GroovyRuntime.java

License:Apache License

/**
 * Removes a classpath entry to a project
 *
 * @param project//w ww . j a  v a 2  s.  c om
 *            The project to remove the entry.
 * @param newEntry
 *            The entry to remove.
 * @throws JavaModelException
 */
public static void removeClassPathEntry(IJavaProject project, IClasspathEntry newEntry)
        throws JavaModelException {
    IClasspathEntry[] newEntries = (IClasspathEntry[]) ArrayUtils.removeElement(project.getRawClasspath(),
            newEntry);
    project.setRawClasspath(newEntries, null);
}

From source file:org.codehaus.groovy.eclipse.core.model.GroovyRuntime.java

License:Apache License

/**
 * Looks through a set of classpath entries and checks to see if the path is
 * in them./*from   w w  w  .j a va  2 s . co m*/
 *
 * @param project
 *            The project to search.
 * @param possiblePath
 *            The path to check the entries for.
 * @return If possiblePath is included in entries returns true, otherwise
 *         returns false.
 * @throws JavaModelException
 */
private static boolean includesClasspathEntry(IJavaProject project, String entryName)
        throws JavaModelException {
    IClasspathEntry[] entries = project.getRawClasspath();
    for (int i = 0; i < entries.length; i++) {
        IClasspathEntry entry = entries[i];
        if (entry.getPath().lastSegment().equals(entryName)) {
            return true;
        }
    }
    return false;
}

From source file:org.codehaus.groovy.eclipse.launchers.AbstractGroovyLaunchShortcut.java

License:Apache License

/**
 * Need to recursively walk the classpath and visit all dependent projects
 * Not looking at classpath containers yet.
 *
 * @param javaProject/*w w  w  . j a  v a  2  s  .  co m*/
 * @param entries
 */
private void addClasspathEntriesForProject(IJavaProject javaProject, SortedSet<String> sourceEntries,
        SortedSet<String> binEntries) {
    List<IJavaProject> dependingProjects = new ArrayList<IJavaProject>();
    try {
        IClasspathEntry[] entries = javaProject.getRawClasspath();
        for (IClasspathEntry entry : entries) {
            int kind = entry.getEntryKind();
            switch (kind) {
            case IClasspathEntry.CPE_LIBRARY:
                IPath libPath = entry.getPath();
                if (!isPathInWorkspace(libPath)) {
                    sourceEntries.add(libPath.toOSString());
                    break;
                }
                //$FALL-THROUGH$
            case IClasspathEntry.CPE_SOURCE:
                IPath srcPath = entry.getPath();
                String sloc = getProjectLocation(srcPath);
                if (srcPath.segmentCount() > 1) {
                    sloc += File.separator + srcPath.removeFirstSegments(1).toOSString();
                }
                sourceEntries.add(sloc);

                IPath outPath = entry.getOutputLocation();
                if (outPath != null) {
                    String bloc = getProjectLocation(outPath);
                    if (outPath.segmentCount() > 1) {
                        bloc += File.separator + outPath.removeFirstSegments(1).toOSString();
                    }
                    binEntries.add(bloc);
                }
                break;

            case IClasspathEntry.CPE_PROJECT:
                dependingProjects.add(javaProject.getJavaModel().getJavaProject(entry.getPath().lastSegment()));
                break;
            }
        }
        IPath defaultOutPath = javaProject.getOutputLocation();
        if (defaultOutPath != null) {
            String bloc = getProjectLocation(javaProject);
            if (defaultOutPath.segmentCount() > 1) {
                bloc += File.separator + defaultOutPath.removeFirstSegments(1).toOSString();
            }
            binEntries.add(bloc);
        }
    } catch (JavaModelException e) {
        GroovyCore.logException("Exception generating classpath for launching groovy script", e);
    }
    // recur through dependent projects
    for (IJavaProject dependingProject : dependingProjects) {
        if (dependingProject.getProject().isAccessible()) {
            addClasspathEntriesForProject(dependingProject, sourceEntries, binEntries);
        }
    }
}

From source file:org.codehaus.groovy.eclipse.refactoring.test.RefactoringTest.java

License:Open Source License

private void restoreTestProject() throws Exception {
    IJavaProject javaProject = getRoot().getJavaProject();
    if (javaProject.exists()) {
        IClasspathEntry srcEntry = getRoot().getRawClasspathEntry();
        try {/*from   w  w w. j av  a 2  s  .c om*/
            IClasspathEntry[] jreEntries = RefactoringTestSetup.getJRELibrariesAsRawClasspathEntry();
            IClasspathEntry[] cpes = javaProject.getRawClasspath();
            ArrayList newCPEs = new ArrayList();
            boolean cpChanged = false;
            for (int i = 0; i < cpes.length; i++) {
                IClasspathEntry cpe = cpes[i];
                boolean isJREEntry = false;
                for (int j = 0; j < jreEntries.length; j++) {
                    if (cpe.equals(jreEntries[j])) {
                        isJREEntry = true;
                        break;
                    }
                }
                if (cpe.equals(srcEntry) || isJREEntry) {
                    newCPEs.add(cpe);
                } else {
                    cpChanged = true;
                }
            }
            if (cpChanged) {
                IClasspathEntry[] newCPEsArray = (IClasspathEntry[]) newCPEs
                        .toArray(new IClasspathEntry[newCPEs.size()]);
                javaProject.setRawClasspath(newCPEsArray, null);
            }
        } catch (JavaModelException e) {
            System.err.println(
                    "Exception thrown when trying to restore project to original state.  We can probable ignore this.");
            e.printStackTrace();
        }

        Object[] nonJavaResources = javaProject.getNonJavaResources();
        for (int i = 0; i < nonJavaResources.length; i++) {
            Object kid = nonJavaResources[i];
            if (kid instanceof IResource) {
                IResource resource = (IResource) kid;
                if (!PROJECT_RESOURCE_CHILDREN.contains(resource.getName())) {
                    JavaProjectHelper.delete(resource);
                }
            }
        }
    }
}

From source file:org.codehaus.groovy.m2eclipse.GroovyProjectConfigurator.java

License:Open Source License

public void configureClasspath(IMavenProjectFacade facade, IClasspathDescriptor classpath,
        IProgressMonitor monitor) throws CoreException {
    SourceType sourceType = getSourceType(facade);
    if (sourceType != null) {
        // add source folders
        IJavaProject javaProject = JavaCore.create(facade.getProject());
        IPath projectPath = facade.getFullPath();

        if (sourceType == SourceType.TEST || sourceType == SourceType.BOTH) {
            IPath testPath = projectPath.append("src/test/groovy"); //$NON-NLS-1$
            IPath testOutPath = projectPath.append("target/test-classes"); //$NON-NLS-1$
            if (!hasEntry(javaProject, testPath)) {
                GroovyRuntime.addClassPathEntryToFront(javaProject,
                        JavaCore.newSourceEntry(testPath, new Path[0], testOutPath));
            }/*  w  w  w  . ja va 2s  . c  om*/
        }

        if (sourceType == SourceType.MAIN || sourceType == SourceType.BOTH) {
            IPath sourcePath = projectPath.append("src/main/groovy"); //$NON-NLS-1$
            IPath sourceOutPath = projectPath.append("target/classes"); //$NON-NLS-1$
            if (!hasEntry(javaProject, sourcePath)) {
                GroovyRuntime.addClassPathEntryToFront(javaProject,
                        JavaCore.newSourceEntry(sourcePath, new Path[0], sourceOutPath));
            }
        }

        // now remove the generated sources from the classpath if it exists
        IClasspathEntry[] allEntries = javaProject.getRawClasspath();
        for (IClasspathEntry entry : allEntries) {
            if (entry.getPath().equals(javaProject.getProject()
                    .getFolder("target/generated-sources/groovy-stubs/main").getFullPath())) {
                GroovyRuntime.removeClassPathEntry(javaProject, entry);
                break;
            }
        }
    }
}

From source file:org.codehaus.groovy.m2eclipse.GroovyProjectConfigurator.java

License:Open Source License

private boolean hasEntry(IJavaProject javaProject, IPath path) throws JavaModelException {
    IClasspathEntry[] entries = javaProject.getRawClasspath();
    for (IClasspathEntry entry : entries) {
        if (entry.getPath().equals(path)) {
            return true;
        }//from  w  ww  .  ja  v a  2  s . c om
    }
    return false;
}

From source file:org.codehaus.jdt.groovy.internal.compiler.ScriptFolderCompilationParticipant.java

License:Open Source License

private Map<IContainer, IContainer> generateSourceToOut(IJavaProject project) throws JavaModelException {
    IProject p = project.getProject();//from w w  w.j  ava  2 s.c  o  m
    IWorkspaceRoot root = (IWorkspaceRoot) p.getParent();
    IClasspathEntry[] cp = project.getRawClasspath();

    // determine default out folder
    IPath defaultOutPath = project.getOutputLocation();
    IContainer defaultOutContainer;
    if (defaultOutPath.segmentCount() > 1) {
        defaultOutContainer = root.getFolder(defaultOutPath);
    } else {
        defaultOutContainer = p;
    }

    Map<IContainer, IContainer> sourceToOut = new TreeMap<IContainer, IContainer>(comparator);
    for (IClasspathEntry cpe : cp) {
        if (cpe.getEntryKind() == IClasspathEntry.CPE_SOURCE) {

            // determine source folder
            IContainer sourceContainer;
            IPath sourcePath = cpe.getPath();
            if (sourcePath.segmentCount() > 1) {
                sourceContainer = root.getFolder(sourcePath);
            } else {
                sourceContainer = p;
            }

            // determine out folder
            IPath outPath = cpe.getOutputLocation();
            IContainer outContainer;
            if (outPath == null) {
                outContainer = defaultOutContainer;
            } else if (outPath.segmentCount() > 1) {
                outContainer = root.getFolder(outPath);
            } else {
                outContainer = p;
            }

            // if the two containers are equal, that means no copying should be done
            // do not add to map
            if (!sourceContainer.equals(outContainer)) {
                sourceToOut.put(sourceContainer, outContainer);
            }
        }

    }
    return sourceToOut;
}

From source file:org.compiere.mfg_scm.eclipse.db.DbfBootstrap.java

License:Apache License

private void getClassPathEntries(IJavaProject prj, ArrayList data, List selectedPaths,
        ArrayList visitedProjects) {
    IClasspathEntry[] entries = null;//w ww  .  j a  va 2  s  . c o m

    IPath outputPath = null;
    try {
        outputPath = prj.getOutputLocation();
        if (selectedPaths.contains(outputPath.toFile().toString().replace('\\', '/'))) {
            add(data, prj.getProject().getWorkspace().getRoot().findMember(outputPath));
        }
        entries = prj.getRawClasspath();
    } catch (JavaModelException e) {
        DbfLauncherPlugin.log(e);
    }
    if (entries == null)
        return;
    for (int i = 0; i < entries.length; i++) {
        IClasspathEntry entry = entries[i];
        IPath path = entry.getPath();
        if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
            path = entry.getOutputLocation();
            if (path == null)
                continue;
        }
        if (entry.getEntryKind() == IClasspathEntry.CPE_PROJECT) {
            String prjName = entry.getPath().lastSegment();
            if (!visitedProjects.contains(prjName)) {
                visitedProjects.add(prjName);
                getClassPathEntries(prj.getJavaModel().getJavaProject(prjName), data, selectedPaths,
                        visitedProjects);
            }
            continue;
        } else if (!selectedPaths.contains(path.toFile().toString().replace('\\', '/')))
            continue;

        IClasspathEntry[] tmpEntry = null;
        if (entry.getEntryKind() == IClasspathEntry.CPE_CONTAINER) {
            try {
                tmpEntry = JavaCore.getClasspathContainer(path, prj).getClasspathEntries();
            } catch (JavaModelException e1) {
                DbfLauncherPlugin.log(e1);
                continue;
            }
        } else {
            tmpEntry = new IClasspathEntry[1];
            tmpEntry[0] = JavaCore.getResolvedClasspathEntry(entry);
        }

        for (int j = 0; j < tmpEntry.length; j++) {
            if (entry.getEntryKind() == IClasspathEntry.CPE_LIBRARY) {
                IResource res = prj.getProject().getWorkspace().getRoot().findMember(tmpEntry[j].getPath());
                if (res != null)
                    add(data, res);
                else
                    add(data, tmpEntry[j].getPath());
            } else if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
                IPath srcPath = entry.getOutputLocation();
                if (srcPath != null && !srcPath.equals(outputPath)) {
                    add(data, prj.getProject().getWorkspace().getRoot().findMember(srcPath));
                }
            } else {
                add(data, tmpEntry[j].getPath());
            }
        }
    }
}

From source file:org.continuousassurance.swamp.eclipse.ImprovedClasspathHandler.java

License:Apache License

/**
 * Constructor for ImprovedClasspathHandler
 * @param project the Java project that we will generate a build file for
 * @param root the ImprovedClasspathHandler object for the project (this is the root of the recursive tree that we build from projects having dependencies)
 * @param exclSysLibs if true, Java system libraries get copied into the package at submission
 * @param subMonitor submonitor for tracking progress
 *//*  w w w  . j  a  va 2 s  .  co  m*/
public ImprovedClasspathHandler(IJavaProject project, ImprovedClasspathHandler root, boolean exclSysLibs,
        SubMonitor subMonitor) {
    this.excludeSysLibs = exclSysLibs;
    sources = new ArrayList<IClasspathEntry>();
    libs = new ArrayList<IClasspathEntry>();
    systemLibs = new ArrayList<IClasspathEntry>();
    dependentProjects = new ArrayList<ImprovedClasspathHandler>();
    exportedEntries = new ArrayList<IClasspathEntry>();

    this.project = project;
    this.srcVersion = this.project.getOption(SOURCE_VERSION_OPTION, true);
    this.targetVersion = this.project.getOption(TARGET_VERSION_OPTION, true);

    if (root == null) {
        this.root = this;
        this.subMonitor = subMonitor;
        this.subMonitor.setWorkRemaining(100);
        visitedProjects = new HashMap<String, ImprovedClasspathHandler>();
        SWAMPBIN_PATH = setupBinDir(project.getProject());
        filesToArchive = new HashSet<String>();
    } else {
        this.root = root;
        visitedProjects = root.visitedProjects;
        SWAMPBIN_PATH = root.SWAMPBIN_PATH;
        filesToArchive = root.filesToArchive;
    }

    try {
        project.getProject().build(IncrementalProjectBuilder.CLEAN_BUILD, null);
    } catch (CoreException e1) {
        // TODO Auto-generated catch block
        System.err.println("Unable to do a clean build on the project for some reason");
        e1.printStackTrace();
    }

    IClasspathEntry[] entries = null;
    try {
        entries = project.getRawClasspath();
        if (entries == null || entries.length == 0) {
            return;
        }
    } catch (JavaModelException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return;
    }
    IWorkspaceRoot wsRoot = ResourcesPlugin.getWorkspace().getRoot();
    try {
        for (IClasspathEntry entry : entries) {
            int kind = entry.getEntryKind();
            if (this.subMonitor != null) {
                if (this.subMonitor.isCanceled()) {
                    System.out.println("Sub monitor got cancelled!");
                }
                this.subMonitor.split(100 / SwampSubmitter.CLASSPATH_ENTRY_TICKS);
            }
            if (kind == IClasspathEntry.CPE_SOURCE) {
                handleSource(entry, wsRoot);
            } else if (kind == IClasspathEntry.CPE_LIBRARY) {
                handleLibrary(entry, wsRoot);
            } else if (kind == IClasspathEntry.CPE_PROJECT) {
                handleProject(entry, wsRoot);
            } else if (kind == IClasspathEntry.CPE_VARIABLE) {
                handleVariable(entry, wsRoot);
            } else { // kind == IClasspathEntry.CPE_CONTAINER
                handleContainer(entry, wsRoot);
            }
        }
    } catch (IOException | JavaModelException e) {
        // TODO Report this error! This is very bad
        e.printStackTrace();
    }
    if (hasSwampbinDependencies) {
        filesToArchive.add(SWAMPBIN_PATH.toOSString());
    }
}

From source file:org.continuousassurance.swamp.eclipse.SwampSubmitter.java

License:Apache License

/**
 * Generates build file for an Eclipse project and submits it to the SWAMP.
 * This can all happen in the background
 * @param si SubmissionInfo object with information about the submission
 *//*from  w ww  .  j a  v  a2s.com*/
private void submitAutoGenJob(SubmissionInfo si) {
    Job job = new Job(SWAMP_JOB_TITLE) {

        @Override
        public boolean belongsTo(Object family) {
            return family.equals(SWAMP_FAMILY);
        }

        @Override
        protected IStatus run(IProgressMonitor monitor) {
            IJavaProject jp = JavaCore.create(si.getProject());
            int total = 0;
            int numClasspathEntries = 0;
            IClasspathEntry[] entries = null;
            try {
                entries = jp.getRawClasspath();
                numClasspathEntries = entries.length;
            } catch (Exception e) {
                printToConsole(Utils.getBracketedTimestamp() + "Error: Unable to parse classpath.");
                Status status = new Status(IStatus.ERROR, "eclipsepluin", UNABLE_TO_GENERATE_BUILD,
                        "Unable to generate build for this project", null);
                done(status);
                return status;
            }

            total = calculateTotalTicks(false, numClasspathEntries, si.getSelectedToolIDs().size());
            SubMonitor subMonitor = SubMonitor.convert(monitor, total);

            if (subMonitor.isCanceled()) {
                IStatus status = Status.CANCEL_STATUS;
                done(status);
                return status;
            }

            if (jp.hasClasspathCycle(entries)) {
                printToConsole(Utils.getBracketedTimestamp()
                        + "Error: Classpath has cyclical dependencies. Please resolve these issues and resubmit.");
                Status status = new Status(IStatus.ERROR, "org.continuousassurance.swamp.eclipse",
                        CYCLICAL_DEPENDENCIES, "Project has cyclical dependencies", null);
                done(status);
                return status;
            }

            if (subMonitor.isCanceled()) {
                IStatus status = Status.CANCEL_STATUS;
                done(status);
                return status;
            }

            printToConsole(Utils.getBracketedTimestamp() + "Status: Generating build file");
            SubMonitor childSubMonitor = subMonitor.split(numClasspathEntries * CLASSPATH_ENTRY_TICKS);
            ImprovedClasspathHandler ich = new ImprovedClasspathHandler(jp, null, !si.packageSystemLibraries(),
                    childSubMonitor);
            Set<String> files = ich.getFilesToArchive();

            // TODO: Modularize these into a function call
            if (subMonitor.isCanceled()) {
                IStatus status = Status.CANCEL_STATUS;
                done(status);
                return status;
            }

            System.out.println("Java Classpath: " + System.getProperty("java.classpath"));
            BuildfileGenerator.generateBuildFile(ich, files);

            try {
                cleanProjects(si.getProject());
            } catch (CoreException e) {
                printToConsole(Utils.getBracketedTimestamp()
                        + "Error: Unable to clean project or dependent projects. The tools may be unable to assess this package.");
            }

            subMonitor.split(ZIP_TICKS);
            printToConsole(Utils.getBracketedTimestamp() + "Status: Packaging project " + si.getProjectName());
            String pluginLoc = ich.getRootProjectPluginLocation();
            Date date = new Date();
            String timestamp = date.toString();
            //String filename = timestamp + "-" + si.getPackageName() + ".zip";
            String filename = timestamp + "-" + si.getPackageName() + ".tar.gz";
            String archiveName = filename.replace(" ", "-").replace(":", "").toLowerCase();
            //Path archivePath = Utils.zipFiles(files, ich.getRootProjectPluginLocation(), archiveName);
            Path archivePath = null;
            try {
                archivePath = TarUtils.createTarGzip(files, ich.getRootProjectPluginLocation(), archiveName);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                IStatus status = Status.CANCEL_STATUS;
                done(status);
                return status;
            }

            if (subMonitor.isCanceled()) {
                IStatus status = Status.CANCEL_STATUS;
                done(status);
                return status;
            }

            subMonitor.split(PKG_CONF_TICKS);
            File pkgConf = PackageInfo.generatePkgConfFile(archivePath, pluginLoc, si.getPackageName(),
                    si.getPackageVersion(), ".", "Java", si.getPkgConfPackageType(), si.getBuildSystem(),
                    si.getBuildDirectory(), si.getBuildFile(), si.getBuildTarget(), si.getBuildOpts(),
                    si.getConfigDir(), si.getConfigCmd(), si.getConfigOpts());

            if (subMonitor.isCanceled()) {
                IStatus status = Status.CANCEL_STATUS;
                done(status);
                return status;
            }

            printToConsole(Utils.getBracketedTimestamp() + "Status: Uploading package " + si.getPackageName()
                    + " to SWAMP");
            String prjUUID = si.getSelectedProjectID();
            String pkgVersUUID = uploadPackage(pkgConf.getPath(), archivePath.toString(), prjUUID,
                    si.isNewPackage());
            String pkgThingUUID = api.getPackageVersion(pkgVersUUID, prjUUID).getPackageThing().getUUIDString();
            si.setPackageThing(api.getPackageVersion(pkgVersUUID, prjUUID).getPackageThing());
            // Always do this in case there were problems setting up these directories before
            doNewPackageResultsSetup(pkgThingUUID);

            setEclipseProjectToPackageThingMapping(pkgThingUUID, ich.getRootProjectPluginLocation());
            for (ImprovedClasspathHandler i : ich.getDependentProjects()) {
                setEclipseProjectToPackageThingMapping(pkgThingUUID, i.getProjectPluginLocation());
            }

            /*
            // Delete ant buildfile
            // Delete swampbin
            // Delete archive
            // Delete package.conf
            try {
               // TODO Uncomment these before release, also delete build file
               //FileUtils.forceDelete(pkgConf);
               //FileUtils.forceDelete(archivePath.toFile());
               ich.deleteSwampBin();
            } catch (IOException e) {
               // This isn't really a problem but why?
               e.printStackTrace();
            }
            */

            if (subMonitor.isCanceled()) {
                IStatus status = Status.CANCEL_STATUS;
                done(status);
                return status;
            }

            printToConsole(Utils.getBracketedTimestamp() + "Status: Submitting assessments");
            AssessmentDetails details = new AssessmentDetails(prjUUID, si.getPackageName(),
                    si.getPackageVersion(), si.getProjectName());

            for (String toolUUID : si.getSelectedToolIDs()) {
                for (String platformUUID : si.getSelectedPlatformIDs()) {
                    subMonitor.split(SUBMISSION_TICKS);
                    details.setResultsFilepath(
                            ResultsUtils.constructFilepath(prjUUID, pkgThingUUID, toolUUID, platformUUID));
                    details.setToolName(api.getTool(toolUUID, prjUUID).getName());
                    details.setPlatformName(api.getPlatformVersion(platformUUID).getName());
                    submitAssessment(pkgVersUUID, toolUUID, prjUUID, platformUUID, details);
                }
            }

            IStatus status = Status.OK_STATUS;
            done(status);
            return status;
        }
    };
    String pluginLocation = si.getProject().getWorkingLocation(PLUGIN_ID).toOSString();
    job.addJobChangeListener(new JobCancellationListener(pluginLocation, SwampSubmitter.FILE_PATTERNS, out));
    job.setRule(ResourcesPlugin.getWorkspace().getRoot()); // we have to lock the root for building projects (i.e. cleaning them). We could potentially get the set of projects, clean the set of projects, and then get a lesser project-scoped rule?
    job.setUser(true);
    job.schedule();

}