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:edu.brown.cs.bubbles.bedrock.BedrockProject.java

License:Open Source License

void localEditProject(Element pxml, IvyXmlWriter xw) throws BedrockException {
    String pnm = IvyXml.getAttrString(pxml, "NAME");
    IProject ip = findProject(pnm);/*from w  ww. j a v  a2 s .c o  m*/
    IJavaProject ijp = JavaCore.create(ip);
    List<IClasspathEntry> ents = new ArrayList<IClasspathEntry>();
    try {
        for (Element oe : IvyXml.children(pxml, "OPTION")) {
            String k = IvyXml.getAttrString(oe, "NAME");
            String v = IvyXml.getAttrString(oe, "VALUE");
            if (k.startsWith("edu.brown.cs.bubbles.bedrock.")) {
                String sfx = k.substring(29);
                QualifiedName qn = new QualifiedName("edu.brown.cs.bubbles.bedrock", sfx);
                try {
                    ip.setPersistentProperty(qn, v);
                } catch (CoreException e) {
                    BedrockPlugin.logD("Problem setting property " + qn + ": " + e);
                }
            } else
                ijp.setOption(k, v);
        }

        for (Element xe : IvyXml.children(pxml, "XPREF")) {
            String q = IvyXml.getAttrString(xe, "NODE");
            String k = IvyXml.getAttrString(xe, "KEY");
            String v = IvyXml.getAttrString(xe, "VALUE");
            IPreferencesService ps = Platform.getPreferencesService();
            Preferences rn = ps.getRootNode();
            Preferences qn = rn.node(q);
            qn.put(k, v);
        }

        for (IClasspathEntry cpe : ijp.getRawClasspath())
            ents.add(cpe);
        for (Element pe : IvyXml.children(pxml, "PATH")) {
            updatePathElement(ents, pe);
        }
        IClasspathEntry[] enta = new IClasspathEntry[ents.size()];
        enta = ents.toArray(enta);
        ijp.setRawClasspath(enta, new BedrockProgressMonitor(our_plugin, "Update Paths"));
        ijp.save(null, false);
    } catch (CoreException e) {
        throw new BedrockException("Problem editing project", e);
    }
}

From source file:edu.ubc.mirrors.test.SanityTest.java

License:Open Source License

public void testExpressionQuery() throws Exception {
    ConsoleProgressListener listener = new ConsoleProgressListener(System.out);
    ISnapshot snapshot = SnapshotFactory.openSnapshot(new File(
            "/Users/robinsalkeld/Documents/UBC/Code/RetrospectData/snapshots/cdt_oom_bug/java_pid7720.hprof"),
            listener);// w ww . ja  va  2  s  .co  m
    int objectID = snapshot.getClassesByName(CDTBugTest.CPPASTName, false).iterator().next().getObjectIds()[0];

    // Need to generate a JavaProject for this to work
    IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject("dummy");
    IProgressMonitor monitor = new NullProgressMonitor();
    if (!project.exists()) {
        project.create(monitor);
        project.open(monitor);
    }
    IJavaProject javaProject = JavaCore.create(project);

    IProjectDescription description = project.getDescription();
    description.setNatureIds(new String[] { JavaCore.NATURE_ID });
    project.setDescription(description, monitor);

    List<IClasspathEntry> entries = new ArrayList<IClasspathEntry>();
    entries.add(JavaCore.newLibraryEntry(
            new Path("/Library/Java/JavaVirtualMachines/1.7.0.jdk/Contents/Home/jre/lib/rt.jar"), null, null));
    javaProject.setRawClasspath(entries.toArray(new IClasspathEntry[entries.size()]), null);

    ExpressionQuery query = new ExpressionQuery();
    query.expression = "toString()";
    query.snapshot = snapshot;
    query.objects = new int[] { objectID };
    query.execute(listener);
}

From source file:edu.washington.cs.cupid.scripting.java.internal.UpdateClasspathJob.java

License:Open Source License

@Override
public IStatus runInWorkspace(final IProgressMonitor monitor) {
    try {/* w w  w  . j a v a  2s. co m*/
        IJavaProject project = CupidScriptingPlugin.getDefault().getCupidJavaProject();

        int classpathSize = project.getRawClasspath().length;

        monitor.beginTask("Update Cupid Classpath", classpathSize + 2);

        List<IClasspathEntry> updatedClasspath = Lists.newArrayList();
        List<IClasspathEntry> updatedEntries = Lists.newArrayList();

        List<String> allResolved = Lists.newArrayList();

        for (IClasspathEntry entry : project.getRawClasspath()) {

            if (entry.getEntryKind() == IClasspathEntry.CPE_LIBRARY) {
                File file = entry.getPath().toFile();

                if (file.exists()) {
                    // the entry is valid
                    allResolved.add(entry.getPath().toString());
                    updatedClasspath.add(entry);

                } else {
                    // try to find bundle with same name
                    IPath path = entry.getPath();
                    String filename = path.segment(path.segmentCount() - 1);

                    String[] parts = filename.split("_");
                    if (parts.length == 2) {
                        Bundle bundle = Platform.getBundle(parts[0]);
                        if (bundle != null) {
                            // we found a bundle with the same name
                            IPath replacement = ClasspathUtil.bundlePath(bundle);
                            IClasspathEntry newEntry = JavaCore.newLibraryEntry(replacement, null, null);
                            updatedClasspath.add(newEntry);
                            updatedEntries.add(newEntry);
                        } else {
                            CupidScriptingPlugin.getDefault()
                                    .logWarning("Can't find updated bundle for Cupid Project classpath entry: "
                                            + entry.getPath());

                            updatedClasspath.add(entry);
                        }
                    } else if (filename.startsWith("guava")) {
                        CodeSource guavaSrc = Lists.class.getProtectionDomain().getCodeSource();
                        IClasspathEntry newEntry = JavaCore
                                .newLibraryEntry(ClasspathUtil.urlToPath(guavaSrc.getLocation()), null, null);
                        updatedClasspath.add(newEntry);
                        updatedEntries.add(newEntry);

                    } else {
                        // TODO handle other internal JARs besides Guava

                        CupidScriptingPlugin.getDefault()
                                .logWarning("Can't find updated library for Cupid Project classpath entry: "
                                        + entry.getPath());

                        // we don't know how to find the name
                        updatedClasspath.add(entry);
                    }
                }
            } else {
                // don't try to handle variables / projects
                updatedClasspath.add(entry);
                allResolved.add(entry.getPath().toString());
            }

            monitor.worked(1);
        }

        CupidScriptingPlugin.getDefault().logInformation("Found " + allResolved.size()
                + " valid Cupid classpath entries (see log for details)" + System.getProperty("line.separator")
                + Joiner.on(System.getProperty("line.separator")).join(allResolved));

        if (!updatedEntries.isEmpty()) {
            // perform update
            project.setRawClasspath(updatedClasspath.toArray(new IClasspathEntry[] {}),
                    new SubProgressMonitor(monitor, 1));

            for (IClasspathEntry entry : updatedEntries) {
                CupidScriptingPlugin.getDefault()
                        .logInformation("Updated Cupid classpath entry " + entry.getPath());
            }
        } else {
            CupidScriptingPlugin.getDefault().logInformation("Cupid Project classpath is up-to-date");
        }

        return Status.OK_STATUS;
    } catch (Exception ex) {
        return new Status(IStatus.ERROR, CupidScriptingPlugin.PLUGIN_ID,
                "Error updating Cupid scripting classpath", ex);
    } finally {
        monitor.done();
    }
}

From source file:edu.washington.cs.cupid.scripting.java.JavaProjectManager.java

License:Open Source License

/**
 * Setup the Cupid script project. Creates source directory, bin directory, and constructs the
 * classpath./*from   ww w .ja  va2 s .com*/
 * @param project the project
 * @param monitor a progress monitor
 * @throws CoreException if project creation fails
 * @throws IOException if a file system error occurs
 */
public static void populateCupidProject(final IProject project, final IProgressMonitor monitor)
        throws CoreException, IOException {
    // http://www.pushing-pixels.org/2008/11/18/extending-eclipse-creating-a-java-project-without-displaying-a-wizard.html
    // http://www.stateofflow.com/journal/66/creating-java-projects-programmatically

    final int totalWork = 6;

    monitor.beginTask("Populate Cupid Project", totalWork);

    // create source directory
    IPath srcPath = new Path("src");
    IFolder srcFolder = project.getFolder(srcPath);
    srcFolder.create(true, true, new SubProgressMonitor(monitor, 1));

    // create bin directory
    IPath binPath = new Path(
            PreferenceConstants.getPreferenceStore().getString(PreferenceConstants.SRCBIN_BINNAME));
    IFolder binFolder = project.getFolder(binPath);
    binFolder.create(IResource.FORCE | IResource.DERIVED, true, new SubProgressMonitor(monitor, 1));
    binFolder.setDerived(true, new SubProgressMonitor(monitor, 1));

    IFolder libFolder = project.getFolder(new Path("lib"));
    libFolder.create(IResource.FORCE, true, new SubProgressMonitor(monitor, 1));

    // refresh directories
    project.refreshLocal(IResource.DEPTH_INFINITE, new SubProgressMonitor(monitor, 1));

    // load the project 
    IJavaProject javaProject = JavaCore.create(project);

    // Add a Java nature to the project
    IProjectDescription description = project.getDescription();
    String[] natures = description.getNatureIds();
    String[] newNatures = new String[natures.length + 1];
    System.arraycopy(natures, 0, newNatures, 0, natures.length);
    newNatures[natures.length] = JAVA_NATURE;
    description.setNatureIds(newNatures);
    project.setDescription(description, null);

    List<IClasspathEntry> classpath = Lists.newArrayList();

    classpath.add(JavaCore.newSourceEntry(project.getFullPath().append(srcPath)));

    IPath containerPath = new Path(JavaRuntime.JRE_CONTAINER);
    classpath.add(JavaCore.newContainerEntry(containerPath));

    for (String symbolicName : ECLIPSE_BUNDLES) {
        Bundle bundle = Platform.getBundle(symbolicName);

        if (bundle == null) {
            throw new RuntimeException("Cannot locate bundle " + symbolicName);
        }

        classpath.add(JavaCore.newLibraryEntry(ClasspathUtil.bundlePath(bundle), null, null));
    }

    // Add Google Guava
    CodeSource guavaSrc = Lists.class.getProtectionDomain().getCodeSource();
    classpath.add(JavaCore.newLibraryEntry(ClasspathUtil.urlToPath(guavaSrc.getLocation()), null, null));

    Bundle cupid = Platform.getBundle("edu.washington.cs.cupid");
    classpath.add(JavaCore.newLibraryEntry(ClasspathUtil.bundlePath(cupid), null, null));

    javaProject.setRawClasspath(classpath.toArray(new IClasspathEntry[] {}),
            new SubProgressMonitor(monitor, 1));

    monitor.done();
}

From source file:edu.washington.cs.cupid.scripting.java.JavaProjectManager.java

License:Open Source License

/**
 * Add the JAR providing <tt>inputType</tt> to the Cupid project classpath, if it is not already present
 * @param inputType/*  w w  w . ja  v a 2s. co m*/
 * @throws JavaModelException
 * @throws IOException
 * @throws ClassNotFoundException
 */
public static void ensureClasspath(TypeToken<?> inputType)
        throws JavaModelException, IOException, ClassNotFoundException {
    IJavaProject project = CupidScriptingPlugin.getDefault().getCupidJavaProject();

    Bundle bundle = ClasspathUtil.bundleForClass(inputType.getRawType().getName());

    if (bundle == null)
        return; // Java core classes don't have bundles

    IPath path = ClasspathUtil.bundlePath(bundle);

    if (!path.toFile().exists()) {
        CupidScriptingPlugin.getDefault()
                .logInformation("Bundle path for " + bundle.getSymbolicName() + " does not exist: " + path);
        return;
    }

    List<IClasspathEntry> cp = Lists.newArrayList(project.getRawClasspath());
    for (IClasspathEntry old : cp) {
        if (old.getPath().equals(path)) {
            return;
        }
    }

    if (path != null) {
        cp.add(JavaCore.newLibraryEntry(path, null, null));
    }

    project.setRawClasspath(cp.toArray(new IClasspathEntry[] {}), null);
}

From source file:edu.washington.cs.cupid.scripting.java.wizards.JavaCapabilityWizard.java

License:Open Source License

/**
 * The worker method. It will find the container, create the
 * file if missing or just replace its contents, and open
 * the editor on the newly created file.
 * @throws IOException //from   ww  w  .  j  ava2  s .  co  m
 */
private void doFinish(final String name, final String description, final Class<?> parameterType,
        final Class<?> returnType, final List<IPath> classpath, final IProgressMonitor monitor)
        throws Exception {

    CupidEventBuilder event = new CupidEventBuilder(EventConstants.FINISH_WHAT, getClass(),
            CupidScriptingPlugin.getDefault()).addData("name", name)
                    .addData("parameterType", parameterType.getName())
                    .addData("returnType", returnType.getName());
    CupidDataCollector.record(event.create());

    // create a sample file
    String className = formClassName(name);

    monitor.beginTask("Creating " + name, 2);

    IProject cupid = CupidScriptingPlugin.getDefault().getCupidProject();

    final IFile file = cupid.getFolder("src").getFile(new Path(className + ".java"));

    file.create(openContents(name, description, parameterType, returnType, cupid.getDefaultCharset()), true,
            monitor);

    IJavaProject proj = JavaCore.create(cupid);
    List<IClasspathEntry> cp = Lists.newArrayList(proj.getRawClasspath());
    for (IPath path : classpath) {
        if (path != null && !inClasspath(cp, path)) {
            cp.add(JavaCore.newLibraryEntry(path, null, null));
        }
    }
    proj.setRawClasspath(cp.toArray(new IClasspathEntry[] {}), null);

    monitor.worked(1);

    monitor.setTaskName("Opening file for editing...");
    getShell().getDisplay().asyncExec(new Runnable() {
        public void run() {
            IWorkbenchPage active = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
            try {
                IDE.openEditor(active, file);
            } catch (PartInitException e) {
                throw new RuntimeException("Error opening script editor", e);
            }
        }
    });

    monitor.done();
}

From source file:egovframework.hdev.imp.ide.common.DeviceAPIIdeUtils.java

License:Apache License

/**
 * ?  ?/* w  ww.j a va2 s. c  o  m*/
 * @param classpathEntry
 * @param append
 * @throws CoreException
 */
public static void assignClasspathEntryToJavaProject(IProject project, IClasspathEntry classpathEntry,
        boolean append) throws CoreException {
    IJavaProject javaProject = JavaCore.create(project);
    if ((javaProject == null) || (!javaProject.exists()))
        return;
    try {

        IClasspathEntry[] classpath;
        ArrayList<IClasspathEntry> entries;
        if (append) {
            classpath = javaProject.getRawClasspath();
            entries = new ArrayList<IClasspathEntry>(Arrays.asList(classpath));
        } else {
            entries = new ArrayList<IClasspathEntry>();
        }

        entries.add(classpathEntry);

        classpath = entries.toArray(new IClasspathEntry[entries.size()]);
        javaProject.setRawClasspath(classpath, null);
    } catch (JavaModelException e) {
        DeviceAPIIdeLog.logError(e);
    }
}

From source file:egovframework.hdev.imp.ide.common.DeviceAPIIdeUtils.java

License:Apache License

/**
 * ?  ?//from  ww  w  .  j a  va  2s.c  o m
 * @param project
 * @param collection
 * @param append
 * @throws CoreException
 */
public static void assignClasspathEntryToJavaProject(IProject project, Collection<IClasspathEntry> collection,
        boolean append) throws CoreException {
    IJavaProject javaProject = JavaCore.create(project);
    if ((javaProject == null) || (!javaProject.exists()))
        return;
    try {
        IClasspathEntry[] classpath;
        ArrayList<IClasspathEntry> entries;
        if (append) {
            classpath = javaProject.getRawClasspath();
            entries = new ArrayList<IClasspathEntry>(Arrays.asList(classpath));
        } else {
            entries = new ArrayList<IClasspathEntry>();
        }

        entries.addAll(collection);

        classpath = entries.toArray(new IClasspathEntry[entries.size()]);
        javaProject.setRawClasspath(classpath, null);
    } catch (JavaModelException e) {
        DeviceAPIIdeLog.logError(e);
    }
}

From source file:egovframework.hdev.imp.ide.common.DeviceAPIIdeUtils.java

License:Apache License

/**
 * ?  /*w  w w.j  a v a2s . c  o m*/
 * @param project
 * @throws CoreException
 */
@SuppressWarnings("unchecked")
public static void sortClasspathEntry(IProject project) throws CoreException {
    IJavaProject javaProject = JavaCore.create(project);

    if ((javaProject == null) || (!javaProject.exists()))
        return;
    try {
        IClasspathEntry[] classpath;
        ArrayList<IClasspathEntry> entries;

        classpath = javaProject.getRawClasspath();
        entries = new ArrayList<IClasspathEntry>(Arrays.asList(classpath));

        DeviceAPIIdeUtils utils = new DeviceAPIIdeUtils();
        ClasspathComparator classpathComparator = utils.new ClasspathComparator();
        Collections.sort(entries, classpathComparator);

        classpath = entries.toArray(new IClasspathEntry[entries.size()]);
        javaProject.setRawClasspath(classpath, null);
    } catch (JavaModelException e) {
        DeviceAPIIdeLog.logError(e);
    }
}

From source file:egovframework.hdev.imp.ide.common.DeviceAPIIdeUtils.java

License:Apache License

/**
 * ?  /*from w  w  w  .  j av a2s.c o m*/
 * @param project
 * @throws CoreException
 */
public static void removeClasspathEntry(IProject project, IClasspathEntry classpathEntry) throws CoreException {
    IJavaProject javaProject = JavaCore.create(project);

    if ((javaProject == null) || (!javaProject.exists()))
        return;

    try {
        IClasspathEntry[] classpath;
        ArrayList<IClasspathEntry> entries;

        classpath = javaProject.getRawClasspath();
        entries = new ArrayList<IClasspathEntry>(Arrays.asList(classpath));

        for (int i = 0; i < entries.size(); i++) {

            if (entries.get(i).getPath().toString().compareTo(classpathEntry.getPath().toString()) == 0) {

                entries.remove(i);
            }
        }

        classpath = entries.toArray(new IClasspathEntry[entries.size()]);
        javaProject.setRawClasspath(classpath, null);
    } catch (JavaModelException e) {
        DeviceAPIIdeLog.logError(e);
    }
}