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

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

Introduction

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

Prototype

void setRawClasspath(IClasspathEntry[] entries, IProgressMonitor monitor) throws JavaModelException;

Source Link

Document

Sets the classpath of this project using a list of classpath entries.

Usage

From source file:org.evosuite.eclipse.popup.actions.TestGenerationAction.java

License:Open Source License

/**
 * Main action: check if evosuite-tests exists, and add test generation job
 * /* w  w w  .j  a v a 2 s  . c o m*/
 * @param target
 */
public void generateTests(IResource target) {
    Boolean disabled = System.getProperty("evosuite.disable") != null; //  && System.getProperty("evosuite.disable").equals("1")
    if (disabled) {
        MessageDialog.openInformation(shell, "Sorry!", "The EvoSuite Plugin is disabled :(");
        return;
    }
    System.out.println("EvoSuite Plugin is enabled");
    System.out.println("[TestGenerationAction] Generating tests for " + target.toString());
    IFolder folder = target.getProject().getFolder("evosuite-tests");
    if (!folder.exists()) {
        // Create evosuite-tests directory and add as source folder
        try {
            folder.create(false, true, null);
            IJavaProject jProject = JavaCore.create(target.getProject());

            IPackageFragmentRoot root = jProject.getPackageFragmentRoot(folder);
            IClasspathEntry[] oldEntries = jProject.getRawClasspath();
            IClasspathEntry[] newEntries = new IClasspathEntry[oldEntries.length + 1];
            System.arraycopy(oldEntries, 0, newEntries, 0, oldEntries.length);
            newEntries[oldEntries.length] = JavaCore.newSourceEntry(root.getPath());
            jProject.setRawClasspath(newEntries, null);

        } catch (Throwable t) {
            t.printStackTrace();
        }
    }
    addTestJob(target);
}

From source file:org.evosuite.eclipse.popup.actions.TestGenerationAction.java

License:Open Source License

/**
 * If we generate JUnit tests, we need to make sure that JUnit is on the
 * classpath of the project, otherwise we will see compile errors
 * //from w w  w  .j a  va 2 s. com
 * @param project
 */
public void fixJUnitClassPath(IJavaProject project) {
    IPath junitPath = JUnitCore.JUNIT4_CONTAINER_PATH;

    boolean hasJUnit = false;
    boolean hasEvoSuite = false;
    boolean hasOldEvoSuite = false;

    try {
        Path containerPath = new Path("org.evosuite.eclipse.classpathContainerInitializer");
        IClasspathContainer container = JavaCore.getClasspathContainer(containerPath, project);
        System.out.println("EvoSuite JAR at: " + container.getPath().toOSString());

        IClasspathEntry[] oldEntries = project.getRawClasspath();
        ArrayList<IClasspathEntry> newEntries = new ArrayList<IClasspathEntry>(oldEntries.length + 1);

        IClasspathEntry cpentry = JavaCore.newContainerEntry(junitPath);

        for (int i = 0; i < oldEntries.length; i++) {
            IClasspathEntry curr = oldEntries[i];

            // Check if JUnit is already in the build path
            if (curr.getEntryKind() == IClasspathEntry.CPE_CONTAINER) {
                IPath path = curr.getPath();
                if (path.equals(cpentry.getPath())) {
                    hasJUnit = true;
                }
                if (path.equals(container.getPath())) {
                    hasEvoSuite = true;
                }
            } else if (curr.getEntryKind() == IClasspathEntry.CPE_LIBRARY) {
                // Check for older EvoSuite entries
                IPath path = curr.getPath();
                if (path.toFile().getName().equals(Activator.EVOSUITE_JAR)) {
                    if (path.equals(container.getPath())) {
                        System.out.println("Is current evosuite!");
                        hasEvoSuite = true;
                    } else {
                        System.out.println("Is NOT current evosuite!");
                        hasOldEvoSuite = true;
                        continue;
                    }
                }
                if (path.equals(cpentry.getPath())) {
                    hasJUnit = true;
                }
                if (path.equals(container.getPath())) {
                    hasEvoSuite = true;
                }
            }

            if (curr != null) {
                newEntries.add(curr);
            }
        }

        if (hasJUnit && hasEvoSuite && !hasOldEvoSuite) {
            return;
        }

        // add the entry
        if (!hasJUnit) {
            newEntries.add(cpentry);
        }

        if (!hasEvoSuite && container != null) {
            for (IClasspathEntry entry : container.getClasspathEntries()) {
                newEntries.add(entry);
            }
        }

        System.out.println("New classpath: " + newEntries);

        // newEntries.add(JavaCore.newContainerEntry(EvoSuiteClasspathContainer.ID));

        // Convert newEntries to an array
        IClasspathEntry[] newCPEntries = newEntries.toArray(new IClasspathEntry[newEntries.size()]);
        project.setRawClasspath(newCPEntries, null);
    } catch (JavaModelException e) {
        e.printStackTrace();
    }

}

From source file:org.flowerplatform.editor.java.propertypage.remote.JavaProjectPropertyPageService.java

License:Open Source License

/**
 * @author Cristina Constantinescu/*  w ww . j  av a2 s . co m*/
 * @author Mariana Gheorghe - added linked source folders and JRE container
 */
public boolean setClasspathEntries(ServiceInvocationContext context, List<PathFragment> path,
        List<String> srcFolders, List<String> projects, List<String> libraries) {
    @SuppressWarnings("unchecked")
    Pair<File, String> node = (Pair<File, String>) GenericTreeStatefulService.getNodeByPathFor(path, null);
    File projectFile = node.a;

    IProject project = ProjectsService.getInstance().getProjectToWorkingDirectoryAndIProjectMap()
            .get(projectFile).b;
    IJavaProject javaProject = JavaCore.create(project);
    File wd = ProjectsService.getInstance().getProjectToWorkingDirectoryAndIProjectMap().get(projectFile).a;

    List<IClasspathEntry> entries = new ArrayList<IClasspathEntry>();
    for (String srcFolder : srcFolders) {
        entries.add(JavaCore.newSourceEntry(
                project.getFolder(ProjectsService.LINK_TO_PROJECT).getFullPath().append(srcFolder)));
    }
    for (String projectName : projects) {
        entries.add(JavaCore.newProjectEntry(ProjectsService.getInstance()
                .getProjectWrapperResourceFromFile(new File(wd, projectName)).getFullPath()));
    }
    for (String library : libraries) {
        entries.add(JavaCore.newLibraryEntry(ProjectsService.getInstance()
                .getProjectWrapperResourceFromFile(new File(wd, library)).getFullPath(), null, null));
    }
    // default entry
    entries.add(JavaRuntime.getDefaultJREContainerEntry());

    try {
        javaProject.setRawClasspath(entries.toArray(new IClasspathEntry[entries.size()]),
                new NullProgressMonitor());
    } catch (JavaModelException e) {
        logger.error("Exception thrown while setting java classpath entries for {}", project.getName(), e);
        return false;
    }

    return true;
}

From source file:org.fornax.cartridges.sculptor.wizard.util.EclipseHelper.java

License:Apache License

public static IProject createRichClientProject(final String projectName,
        final List<IProject> referencedProjects, final Set<String> requiredBundles,
        final IProgressMonitor progressMonitor, final Shell theShell) {
    IProject project = null;//from  w ww . j  a va  2 s  . com
    try {
        progressMonitor.beginTask("", 10);
        progressMonitor.subTask("Creating project " + projectName);
        IWorkspace workspace = ResourcesPlugin.getWorkspace();
        project = workspace.getRoot().getProject(projectName);

        // Clean up any old project information.
        if (project.exists()) {
            final boolean[] result = new boolean[1];
            PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable() {
                public void run() {
                    result[0] = MessageDialog.openQuestion(theShell, "Existing project " + projectName + "?",
                            "Do you want to overwrite the project '" + projectName
                                    + "' \nNote that everything inside the project '" + projectName
                                    + "' will be deleted if you confirm this dialog.");
                }
            });
            if (result[0]) {
                project.delete(true, true, new SubProgressMonitor(progressMonitor, 1));
            } else {
                return null;
            }
        }

        IJavaProject javaProject = JavaCore.create(project);
        IProjectDescription projectDescription = ResourcesPlugin.getWorkspace()
                .newProjectDescription(projectName);
        projectDescription.setLocation(null);
        project.create(projectDescription, new SubProgressMonitor(progressMonitor, 1));
        List<IClasspathEntry> classpathEntries = new ArrayList<IClasspathEntry>();
        if (referencedProjects.size() != 0) {
            projectDescription
                    .setReferencedProjects(referencedProjects.toArray(new IProject[referencedProjects.size()]));
            for (IProject referencedProject : referencedProjects) {
                IClasspathEntry referencedProjectClasspathEntry = JavaCore
                        .newProjectEntry(referencedProject.getFullPath());
                classpathEntries.add(referencedProjectClasspathEntry);
            }
        }

        projectDescription.setNatureIds(new String[] { JavaCore.NATURE_ID, "org.eclipse.pde.PluginNature" });

        ICommand java = projectDescription.newCommand();
        java.setBuilderName(JavaCore.BUILDER_ID);

        ICommand manifest = projectDescription.newCommand();
        manifest.setBuilderName("org.eclipse.pde.ManifestBuilder");

        ICommand schema = projectDescription.newCommand();
        schema.setBuilderName("org.eclipse.pde.SchemaBuilder");

        projectDescription.setBuildSpec(new ICommand[] { java, manifest, schema });

        project.open(new SubProgressMonitor(progressMonitor, 1));
        project.setDescription(projectDescription, new SubProgressMonitor(progressMonitor, 1));

        addSrcFolders(progressMonitor, project, classpathEntries);

        classpathEntries.add(JavaCore.newContainerEntry(new Path("org.eclipse.jdt.launching.JRE_CONTAINER")));
        classpathEntries.add(JavaCore.newContainerEntry(new Path("org.eclipse.pde.core.requiredPlugins")));

        javaProject.setRawClasspath(classpathEntries.toArray(new IClasspathEntry[classpathEntries.size()]),
                new SubProgressMonitor(progressMonitor, 1));

        javaProject.setOutputLocation(new Path("/" + projectName + "/target/classes"),
                new SubProgressMonitor(progressMonitor, 1));
    } catch (RuntimeException e) {
        throw e;
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        progressMonitor.done();
    }

    return project;
}

From source file:org.grails.ide.eclipse.commands.GrailsCommandUtils.java

License:Open Source License

/**
 * Recompute the Grails class path container. Essentially this performs the
 * same action as the "Refresh Dependencies" Grails menu command.
 * <p>/*from w  w w  .  j a v  a 2  s.c o  m*/
 * This is a potentially long running process and so it should not be called
 * directly from the UI thread. When running in the UI thread you should
 * wrap calls to this (and other work you are possibly doing alongside with
 * this in some type of background Job.).
 */
public static void refreshDependencies(final IJavaProject javaProject, boolean showOutput)
        throws CoreException {
    debug("Refreshing dependencies for " + javaProject.getElementName() + " ...");

    // This job is a no-op for maven projects since maven handles the source folders
    if (isMavenProject(javaProject)) {
        // don't do refresh dependencies on maven projects.  This is handled by project configurator
        debug("Not refreshing dependencies because this is a maven project.");
        return;
    }

    GroovyCompilerVersionCheck.check(javaProject);
    deleteOutOfSynchPlugins(javaProject.getProject());

    // Create the external process part and launch it synchronously...
    GrailsCommand refreshFileCmd = GrailsCommandFactory.refreshDependencyFile(javaProject.getProject());
    refreshFileCmd.setShowOutput(showOutput);
    ILaunchResult result = refreshFileCmd.synchExec();
    debug(result.toString());

    //TODO: KDV: (depend) if we do it right, we should be able to remove the call to the refreshFileCmd below. However, this
    //   assumes that 
    //    a) we ensure that any command that may change the state of the dependencies also forces
    //      the regeneration of the data file as part of its own execution. (Currently this isn't the case)
    //    b) RefreshGrailsDependencyActionDelegate also forces the data file to be regenerated somehow
    // Making this change is desirable (executing the command below takes a long time).
    // Making this change is difficult at the moment because many commands do not go via the GrailsCommand
    // class. In particular, commands executed via the command prompt still directly use the old GrailsLaunchConfigurationDelegate,

    //      ILaunchConfiguration configuration = GrailsDependencyLaunchConfigurationDelegate
    //      .getLaunchConfiguration(javaProject.getProject());
    //      SynchLaunch sl = new SynchLaunch(configuration, GrailsCoreActivator.getDefault().getGrailsCommandTimeOut());
    //      sl.setShowOutput(showOutput);
    //      sl.synchExec();

    // ensure that this operation runs without causing multiple builds
    IWorkspace workspace = ResourcesPlugin.getWorkspace();
    workspace.run(new IWorkspaceRunnable() {

        public void run(IProgressMonitor monitor) throws CoreException {
            // Grails "compile" command may have changed resources...?
            // TODO: KDV: (depend) find out why this refresh is necessary. See STS-1263.
            // Note: if this line is removed, it *will* break STS-1270. We should revisit
            // where calls are being made to refresh the resource tree. Suspect we may doing this more than 
            // once in some cases.
            javaProject.getProject().refreshLocal(IResource.DEPTH_INFINITE, monitor);

            // Now that we got here the data file should be available and 
            // we can ask GrailsClasspathContainer to refresh its dependencies.
            GrailsClasspathContainer container = GrailsClasspathUtils.getClasspathContainer(javaProject);
            // reparse classpath entries from dependencies file on next request
            if (container != null) {
                container.invalidate();
            }

            // ensure that the dependency and plugin data is forgotten
            GrailsCore.get().connect(javaProject.getProject(), PerProjectDependencyDataCache.class)
                    .refreshData();
            GrailsCore.get().connect(javaProject.getProject(), PerProjectPluginCache.class)
                    .refreshDependencyCache();

            // recompute source folders now
            SourceFolderJob updateSourceFolders = new SourceFolderJob(javaProject);
            updateSourceFolders.refreshSourceFolders(new NullProgressMonitor());

            // This will force the JDT to re-resolve the CP, even if only the "contents" of class path container changed see STS-1347
            javaProject.setRawClasspath(javaProject.getRawClasspath(), monitor);
        }

    }, new NullProgressMonitor());
    debug("Refreshing dependencies for " + javaProject.getElementName() + " DONE");
}

From source file:org.grails.ide.eclipse.maven.GrailsProjectConfigurator.java

License:Open Source License

@Override
public void configure(ProjectConfigurationRequest request, IProgressMonitor monitor) throws CoreException {
    IProject project = request.getProject();
    addJavaNature(project, monitor);//  ww  w  . j  a v a 2 s  . c  om
    IJavaProject javaProject = JavaCore.create(project);
    boolean noContainer = !GrailsClasspathUtils.hasClasspathContainer(javaProject);
    boolean hasOldContainer = GrailsClasspathUtils.hasOldClasspathContainer(javaProject);
    IClasspathEntry[] rawClasspath = javaProject.getRawClasspath();
    List<IClasspathEntry> entries = new ArrayList<IClasspathEntry>(Arrays.asList(rawClasspath));
    if (hasOldContainer) {
        for (Iterator<IClasspathEntry> entryIter = entries.iterator(); entryIter.hasNext();) {
            IClasspathEntry entry = entryIter.next();
            if (entry.getPath().toPortableString().equals(IConversionConstants.GRAILS_OLD_CONTAINER)) {
                entryIter.remove();
                break;
            }
        }
    }
    if (noContainer) {
        entries.add(JavaCore.newContainerEntry(GrailsClasspathContainer.CLASSPATH_CONTAINER_PATH, null, null,
                false));
    }

    // also remove any grails source folders that have the grails classpath attribute
    for (Iterator<IClasspathEntry> entryIter = entries.iterator(); entryIter.hasNext();) {
        IClasspathEntry entry = entryIter.next();
        if (GrailsResourceUtil.isGrailsClasspathEntry(entry)
                && !GrailsResourceUtil.hasClasspathAttribute(entry, IClasspathManager.POMDERIVED_ATTRIBUTE)) {
            entryIter.remove();
        }
    }
    javaProject.setRawClasspath(entries.toArray(new IClasspathEntry[entries.size()]), monitor);
    super.configure(request, monitor);
}

From source file:org.grails.ide.eclipse.test.MockGrailsTestProjectUtils.java

License:Apache License

/**
 * FIXADE move to {@link TestProject}/*  w w w. ja  v  a2s .c  o  m*/
 */
public static void setClasspath(IProject project, IClasspathEntry[] entries) throws JavaModelException {
    IJavaProject javaProject = JavaCore.create(project);
    javaProject.setRawClasspath(entries, null);
}

From source file:org.gw4e.eclipse.facade.ClasspathManager.java

License:Open Source License

/**
 * Add GraphWalker libraries to the passed project
 * /*from   www  .j a v a2  s .c o m*/
 * @param project
 * @throws JavaModelException
 */
public static void addGW4EClassPathContainer(IProject project) throws JavaModelException {
    if (hasGW4EClassPathContainer(project)) {
        return;
    }
    IJavaProject javaProject = JavaCore.create(project);
    IClasspathEntry[] entries = javaProject.getRawClasspath();
    IClasspathEntry[] newEntries = new IClasspathEntry[entries.length + 1];
    System.arraycopy(entries, 0, newEntries, 0, entries.length);
    Path lcp = new Path(GW4ELibrariesContainer.ID);
    IClasspathEntry libEntry = JavaCore.newContainerEntry(lcp, true);
    newEntries[entries.length] = JavaCore.newContainerEntry(libEntry.getPath(), true);
    javaProject.setRawClasspath(newEntries, null);

    addJunit4Libraries(project);
}

From source file:org.gw4e.eclipse.facade.ClasspathManager.java

License:Open Source License

/**
 * Add JUnit libraries to the passed project
 * /*from  w  w w.  j  a va 2s  .  c om*/
 * @param project
 * @throws JavaModelException
 */
private static void addJunit4Libraries(IProject project) throws JavaModelException {
    IClasspathEntry entry = JavaCore.newContainerEntry(JUnitCore.JUNIT4_CONTAINER_PATH);
    IJavaProject javaProject = JavaCore.create(project);
    IClasspathEntry[] entries = javaProject.getRawClasspath();
    boolean junitFound = false;
    String s = entry.getPath().toString();
    for (int i = 0; i < entries.length; i++) {
        if (entries[i].getPath().toString().indexOf(s) != -1) {
            junitFound = true;
            break;
        }
    }
    if (!junitFound) {
        IClasspathEntry[] newEntries = new IClasspathEntry[entries.length + 1];
        System.arraycopy(entries, 0, newEntries, 0, entries.length);
        newEntries[entries.length] = entry;
        javaProject.setRawClasspath(newEntries, null);
    }
}

From source file:org.gw4e.eclipse.facade.ClasspathManager.java

License:Open Source License

/**
 * Manage source folders exclusion//from  w  ww  . j  ava  2 s . co m
 * 
 * @param project
 * @param rootSrcEntry
 * @param relative
 * @return
 * @throws JavaModelException
 */
private static IClasspathEntry ensureExcludedPath(IProject project, IClasspathEntry rootSrcEntry,
        String relative) throws JavaModelException {
    if (rootSrcEntry == null)
        return rootSrcEntry;
    IJavaProject javaProject = JavaCore.create(project);
    IClasspathEntry[] entries = javaProject.getRawClasspath();
    IPath[] excluded = rootSrcEntry.getExclusionPatterns();
    boolean entryFound = false;
    for (int i = 0; i < excluded.length; i++) {
        if (excluded[i].toString().equalsIgnoreCase(relative)) {
            entryFound = true;
            break;
        }
    }
    if (!entryFound) {
        IPath rootSrcPath = javaProject.getPath().append("src");
        IPath[] newEntries = new IPath[excluded.length + 1];
        System.arraycopy(excluded, 0, newEntries, 0, excluded.length);
        newEntries[excluded.length] = new Path(relative);
        rootSrcEntry = JavaCore.newSourceEntry(rootSrcPath, newEntries);
        entries = javaProject.getRawClasspath();
        List<IClasspathEntry> temp = new ArrayList<IClasspathEntry>();
        temp.add(rootSrcEntry);
        for (int i = 0; i < entries.length; i++) {
            if (!(entries[i].getPath().equals(rootSrcPath))) {
                temp.add(entries[i]);
            }
        }
        IClasspathEntry[] array = new IClasspathEntry[temp.size()];
        temp.toArray(array);
        javaProject.setRawClasspath(array, null);
    }
    return rootSrcEntry;
}