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, IPath outputLocation, IProgressMonitor monitor)
        throws JavaModelException;

Source Link

Document

Sets the both the classpath of this project and its default output location at once.

Usage

From source file:fede.workspace.eclipse.java.JavaProjectManager.java

License:Apache License

/**
 * Creates an empty Java project associated with the eclipse project
 * corresponding to the item.//from w ww .  j  ava  2 s.c  om
 * 
 * Automatically creates a source directory and default ouptut location.
 * 
 * @param item
 *            the item
 * @param monitor
 *            the monitor
 * @param project
 *            the project
 * @param cxt
 *            the cxt
 * @param defaultSourceFolder
 *            the default source folder
 * @param defaultClassFolder
 *            the default class folder
 * 
 * @return the created java project
 * 
 * @throws CoreException
 *             the core exception
 */
public static IJavaProject createJavaProject(IProject project, Item item, IProgressMonitor monitor,
        ContextVariable cxt, Variable defaultSourceFolder, Variable defaultClassFolder) throws CoreException {

    /*
     * Create empty project if needed
     */

    if (project == null) {
        return null;
    }

    if (!project.exists()) {
        project.create(monitor);
    }
    project.open(monitor);

    IJavaProject javaProject = JavaCore.create(project);

    /*
     * Add Java nature and initialize classpath
     */
    IProjectDescription description = project.getDescription();
    List<String> natures = new ArrayList<String>(Arrays.asList(description.getNatureIds()));

    if (!description.hasNature(JavaCore.NATURE_ID)) {
        IClasspathEntry[] classpath = null;
        String sourceFolder = defaultSourceFolder.compute(cxt, item);
        String classFolder = defaultClassFolder.compute(cxt, item);
        if (sourceFolder != null && classFolder != null) {
            IFolder sources = project.getFolder(sourceFolder);
            if (!sources.exists()) {
                sources.create(false, true, monitor);
            }
            IFolder output = project.getFolder(classFolder);
            if (!output.exists()) {
                output.create(false, true, monitor);
            }
        }

        natures.add(JavaCore.NATURE_ID);
        description.setNatureIds(natures.toArray(new String[natures.size()]));
        project.setDescription(description, monitor);

        if (sourceFolder != null && classFolder != null) {
            IFolder sources = project.getFolder(sourceFolder);
            IFolder output = project.getFolder(classFolder);

            classpath = new IClasspathEntry[] { JavaCore.newSourceEntry(sources.getFullPath()),
                    JavaCore.newContainerEntry(new Path(JavaRuntime.JRE_CONTAINER), false),
                    ItemDependenciesClasspathEntry.CLASSPATH_ENTRY };
            javaProject.setRawClasspath(classpath, output.getFullPath(), monitor);
        } else {
            classpath = new IClasspathEntry[] {
                    JavaCore.newContainerEntry(new Path(JavaRuntime.JRE_CONTAINER), false),
                    ItemDependenciesClasspathEntry.CLASSPATH_ENTRY };
            javaProject.setRawClasspath(classpath, monitor);
        }

    }

    return javaProject;
}

From source file:fede.workspace.eclipse.java.JavaProjectManager.java

License:Apache License

/**
 * Adds the source folder associated with the item to the source entries in
 * the classpath of the java project./* w w  w . j a  v  a 2  s.  c om*/
 * 
 * @param item
 *            the item
 * @param monitor
 *            the monitor
 * @param sourceFolder
 *            the source folder
 * @param specificOutputFolder
 *            the specific output folder
 * 
 * @throws CoreException
 *             the core exception
 */
public static void createJavaSourceFolder(Item item, IFolder sourceFolder, IFolder specificOutputFolder,
        IProgressMonitor monitor) throws CoreException {

    if (sourceFolder == null) {
        return;
    }

    IProject project = sourceFolder.getProject();

    IJavaProject javaProject = JavaCore.create(project);
    if (javaProject == null) {
        return;
    }

    if (!sourceFolder.exists()) {
        sourceFolder.create(false, true, monitor);
    }

    IFolder defaultOutputFolder = project
            .getFolder(DEFAULT_OUTPUT_FOLDER_NAME.compute(ContextVariableImpl.DEFAULT, item));
    if (!defaultOutputFolder.exists()) {
        defaultOutputFolder.create(false, true, monitor);
    }

    IPath specificOutputPath = null;
    if (specificOutputFolder != null) {
        specificOutputPath = specificOutputFolder.getFullPath();
        if (!specificOutputFolder.exists()) {
            specificOutputFolder.create(false, true, monitor);
        }
    }

    List<IClasspathEntry> classpath = new ArrayList<IClasspathEntry>(
            Arrays.asList(javaProject.getRawClasspath()));
    IClasspathEntry sourceEntry = JavaCore.newSourceEntry(sourceFolder.getFullPath(),
            ClasspathEntry.INCLUDE_ALL, ClasspathEntry.EXCLUDE_NONE, specificOutputPath);

    if (!classpath.contains(sourceEntry)) {
        classpath.add(sourceEntry);
        javaProject.setRawClasspath(classpath.toArray(new IClasspathEntry[classpath.size()]),
                defaultOutputFolder.getFullPath(), monitor);
    }

}

From source file:metabup.annotations.wizards.NewAnnotationWizard.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.
 *//*from   w  w  w. j a  v a  2 s . co  m*/

private void doFinish(String projectName, String fileName, String annotationName, String description,
        IProgressMonitor monitor) throws CoreException {
    // create a sample file
    monitor.beginTask("Creating " + fileName, 2);
    IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
    IResource resource = root.findMember(new Path(projectName));
    if (!resource.exists() || !(resource instanceof IProject))
        throwCoreException("Project \"" + projectName + "\" does not exist.");

    monitor.worked(1);

    IProject project = (IProject) resource;

    /*
     * Turn project into a Java project, if not yet
     */

    IProjectDescription projectDescription = project.getDescription();
    String javaNature[] = { JavaCore.NATURE_ID };
    String projectNatures[] = projectDescription.getNatureIds();

    boolean isJavaEnabled = false;

    for (int i = 0; i < projectNatures.length; i++) {
        if (projectNatures[i].equals(javaNature[0])) {
            isJavaEnabled = true;
            i = projectNatures.length;
        }
    }

    IJavaProject javaProject = JavaCore.create(project);

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

        IFolder binFolder = project.getFolder("bin");
        if (!binFolder.exists())
            binFolder.create(false, true, monitor);
        javaProject.setOutputLocation(binFolder.getFullPath(), monitor);

    }

    monitor.worked(1);

    //Import Activator library

    Bundle plugin = Activator.getDefault().getBundle();

    IPath relativePagePath = new Path(AnnotationsPluginPreferenceConstants.P_ANNOTATIONS_LIB_FILES);
    URL fileInPlugin = FileLocator.find(plugin, relativePagePath, null);

    if (fileInPlugin != null) {
        // the file exists         
        URL fileUrl;
        try {
            fileUrl = FileLocator.toFileURL(fileInPlugin);

            File file = new File(fileUrl.getPath());

            IClasspathEntry libEntry[] = { JavaCore.newLibraryEntry(new Path(file.getAbsolutePath()), null, // no source
                    null, // no source
                    false) }; // not exported

            monitor.worked(1);

            //set the build path      
            IClasspathEntry[] buildPath = { JavaCore.newSourceEntry(project.getFullPath().append("src")),
                    JavaRuntime.getDefaultJREContainerEntry(), libEntry[0] };

            javaProject.setRawClasspath(buildPath, project.getFullPath().append("bin"), null);

            IFolder srcFolder = project.getFolder("src");
            if (!srcFolder.exists())
                srcFolder.create(true, true, monitor);
            project.refreshLocal(IResource.DEPTH_INFINITE, monitor);

            monitor.worked(1);

            //Add folder to Java element
            IPackageFragmentRoot folder = javaProject.getPackageFragmentRoot(srcFolder);
            //create package fragment
            IPackageFragment fragment = folder.createPackageFragment(
                    AnnotationsPluginPreferenceConstants.P_ANNOTATIONS_PACKAGE, true, monitor);
            StringBuffer buffer = new StringBuffer();
            ICompilationUnit cu = fragment.createCompilationUnit(fileName,
                    AnnotationHandler.generateInstanceCode(buffer, annotationName, description).toString(),
                    false, monitor);
            project.refreshLocal(IResource.DEPTH_INFINITE, monitor);

            monitor.worked(1);

            project.refreshLocal(IResource.DEPTH_INFINITE, monitor);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            Activator.log(IStatus.ERROR, "Activator library couldn't be added to the java build path.");
        }
    } else {
        Activator.log(IStatus.ERROR, "Activator library couldn't be added to the java build path.");
    }

    /*final IFile file = container.getFile(new Path(fileName));
    try {
       InputStream stream = openContentStream();
       if (file.exists()) {
    file.setContents(stream, true, true, monitor);
       } else {
    file.create(stream, true, monitor);
       }
       stream.close();
    } catch (IOException e) {
    }*/

    /*monitor.setTaskName("Opening file for editing...");
    getShell().getDisplay().asyncExec(new Runnable() {
       public void run() {
    IWorkbenchPage page =
       PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
    try {
       IDE.openEditor(page, file, true);
    } catch (PartInitException e) {
    }
       }
    });*/

    monitor.worked(1);
}

From source file:org.apache.buildr.eclipse.BuildrNature.java

License:Apache License

@Override
public void configure() throws CoreException {
    if (project.hasNature(JavaCore.NATURE_ID)) {
        IJavaProject targetProject = JavaCore.create(project);
        IClasspathEntry[] entries = targetProject.getRawClasspath();
        Path buildrContainer = new Path("org.apache.buildr.eclipse.BUILDR_CONTAINER/dependencies");
        for (IClasspathEntry entry : entries) {
            if (entry.getPath().equals(buildrContainer)) {
                return;
            }//ww w  .j a  va2s.  c o  m
        }

        IClasspathEntry entry = JavaCore.newContainerEntry(buildrContainer);
        IClasspathEntry[] newEntries = new IClasspathEntry[entries.length + 1];
        System.arraycopy(entries, 0, newEntries, 0, entries.length);
        newEntries[entries.length] = entry;
        targetProject.setRawClasspath(newEntries, true, new NullProgressMonitor());
    }
}

From source file:org.apache.buildr.eclipse.BuildrNature.java

License:Apache License

@Override
public void deconfigure() throws CoreException {
    if (project.hasNature(JavaCore.NATURE_ID)) {
        IJavaProject targetProject = JavaCore.create(project);
        IClasspathEntry[] entries = targetProject.getRawClasspath();
        Path buildrContainer = new Path("org.apache.buildr.eclipse.BUILDR_CONTAINER/dependencies");
        List<IClasspathEntry> newEntries = new ArrayList<>();
        for (IClasspathEntry entry : entries) {
            if (!entry.getPath().equals(buildrContainer)) {
                newEntries.add(entry);/*from  ww w.  j a  v a 2 s  .com*/
            }
        }

        targetProject.setRawClasspath(newEntries.toArray(new IClasspathEntry[newEntries.size()]), true,
                new NullProgressMonitor());
    }
}

From source file:org.apache.easyant4e.natures.EasyAntNature.java

License:Apache License

private void addClassPathEntry(IJavaProject javaProject, IClasspathEntry newEntry) {
    try {//from www  .  j a  v  a2 s  . c o m
        IClasspathEntry[] entries = javaProject.getRawClasspath();
        List newEntries = new ArrayList(Arrays.asList(entries));
        newEntries.add(newEntry);
        entries = (IClasspathEntry[]) newEntries.toArray(new IClasspathEntry[newEntries.size()]);

        javaProject.setRawClasspath(entries, javaProject.getOutputLocation(), null);
    } catch (CoreException e) {
        // unless there are issues with the JDT, this should never happen
        Activator.getEasyAntPlugin().log(IStatus.ERROR, "Cannot add ClassPath entry", e);
    }
}

From source file:org.apache.ivyde.internal.eclipse.cpcontainer.IvyClasspathInitializer.java

License:Apache License

private void updateIvyDEContainerPath(final IJavaProject project, final IClasspathEntry entry,
        final IClasspathAttribute[] attributes, final boolean exported, final IPath updatedPath) {
    Display.getDefault().asyncExec(new Runnable() {
        public void run() {
            try {
                // update the classpath of the project by updating the IvyDE container
                IClasspathEntry newEntry = JavaCore.newContainerEntry(updatedPath, null, attributes, exported);
                IClasspathEntry[] entries;
                entries = project.getRawClasspath();
                List newEntries = new ArrayList(Arrays.asList(entries));
                for (int i = 0; i < newEntries.size(); i++) {
                    IClasspathEntry e = (IClasspathEntry) newEntries.get(i);
                    if (e == entry) {
                        newEntries.set(i, newEntry);
                        break;
                    }//from  w w w . j av  a  2 s  .  c  om
                }
                entries = (IClasspathEntry[]) newEntries.toArray(new IClasspathEntry[newEntries.size()]);
                project.setRawClasspath(entries, project.getOutputLocation(), null);
            } catch (JavaModelException e) {
                IvyPlugin.logError("Unable to update the container path", e);
            }
        }
    });
}

From source file:org.apache.ivyde.internal.eclipse.ui.NewIvyDEContainerWizard.java

License:Apache License

public boolean performFinish() {
    containerPage.finish();/* w ww .  j a  v a2 s  .  c  o m*/
    IClasspathEntry newEntry = containerPage.getSelection();
    IPath path = newEntry.getPath();
    IJavaProject project = containerPage.getProject();
    try {
        IvyClasspathContainerImpl ivycp = new IvyClasspathContainerImpl(project, path, new IClasspathEntry[0],
                new IClasspathAttribute[0]);
        JavaCore.setClasspathContainer(path, new IJavaProject[] { project },
                new IClasspathContainer[] { ivycp }, null);
        IClasspathEntry[] entries = project.getRawClasspath();
        List newEntries = new ArrayList(Arrays.asList(entries));
        newEntries.add(newEntry);
        entries = (IClasspathEntry[]) newEntries.toArray(new IClasspathEntry[newEntries.size()]);
        project.setRawClasspath(entries, project.getOutputLocation(), null);
        ivycp.launchResolve(false, null);
    } catch (JavaModelException e) {
        IvyPlugin.log(e);
        return false;
    }
    return true;
}

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

License:Apache License

private void addClasspath(IProject project, IClasspathEntry entry) {
    try {//  ww  w.jav  a  2 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//from w  w w .  j a v  a  2  s . com
 */
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();
    }
}