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.ebayopensource.turmeric.eclipse.errorlibrary.buildsystem.core.ErrorLibraryBuildSystemConfigurer.java

License:Open Source License

/**
 * Adds the java support./*from   w ww. j  a va 2 s  .  c o m*/
 *
 * @param errorLibraryProject the error library project
 * @param outputLocation the output location
 * @param monitor the monitor
 * @throws CoreException the core exception
 */
public static void addJavaSupport(SOAErrorLibraryProject errorLibraryProject, String outputLocation,
        IProgressMonitor monitor) throws CoreException {
    final IProject project = errorLibraryProject.getProject();
    boolean changedClasspath = false;
    if (JDTUtil.addJavaNature(project, monitor)) {
        changedClasspath = true;
    }
    // Configuring the Java Project
    final IJavaProject javaProject = JavaCore.create(project);
    final List<IClasspathEntry> classpath = JDTUtil.rawClasspath(javaProject, true);
    final List<IClasspathEntry> classpathContainers = new ArrayList<IClasspathEntry>();
    // TODO Lets see if we need this
    if (outputLocation.equals(javaProject.getOutputLocation()) == false) {
        final IFolder outputDirClasses = project.getFolder(outputLocation);
        javaProject.setOutputLocation(outputDirClasses.getFullPath(), monitor);
        changedClasspath = true;
    }

    // Dealing with the case where the root of the project is set to be the
    // src and bin destinations... bad... bad...
    for (final Iterator<IClasspathEntry> iterator = classpath.iterator(); iterator.hasNext();) {
        final IClasspathEntry entry = iterator.next();
        if (entry.getEntryKind() == IClasspathEntry.CPE_CONTAINER) {
            classpathContainers.add(entry);
        }
        if (entry.getEntryKind() != IClasspathEntry.CPE_SOURCE
                || !entry.getPath().equals(new Path("/" + project.getName())))
            continue;
        iterator.remove();
        changedClasspath |= true;
    }
    for (final SOAProjectSourceDirectory dir : errorLibraryProject.getSourceDirectories()) {
        if (!WorkspaceUtil.isDotDirectory(dir.getLocation())) {
            final IFolder source = project.getFolder(dir.getLocation());
            // If the Java project existed previously, checking if
            // directories
            // already exist in
            // its classpath.
            boolean found = false;
            for (final IClasspathEntry entry : classpath) {
                if (!entry.getPath().equals(source.getFullPath()))
                    continue;
                found = true;
                break;
            }
            if (found)
                continue;
            changedClasspath |= true;
            IPath[] excludePatterns = ClasspathEntry.EXCLUDE_NONE;
            if (dir.getExcludePatterns() != null) {
                int length = dir.getExcludePatterns().length;
                excludePatterns = new Path[length];
                for (int i = 0; i < length; i++) {
                    excludePatterns[i] = new Path(dir.getExcludePatterns()[i]);
                }
            }
            IPath outputPath = dir.getOutputLocation() != null
                    ? project.getFolder(dir.getOutputLocation()).getFullPath()
                    : null;
            final IClasspathEntry entry = JavaCore.newSourceEntry(source.getFullPath(), excludePatterns,
                    outputPath);
            classpath.add(entry);
        }
    }
    ProgressUtil.progressOneStep(monitor);
    // Adding the runtime library
    boolean found = false;
    for (final IClasspathEntry entry : classpath) {
        // All JRE Containers should have a prefix of
        // org.eclipse.jdt.launching.JRE_CONTAINER
        if (JavaRuntime.newDefaultJREContainerPath().isPrefixOf(entry.getPath())
                && JavaRuntime.newDefaultJREContainerPath().equals(entry.getPath())) {
            found = true;
            break;
        }
    }
    if (!found) {
        changedClasspath = true;
        classpath.add(JavaRuntime.getDefaultJREContainerEntry());
    }
    // we want all classpath containers to be the end of .classpath file
    classpath.removeAll(classpathContainers);
    classpath.addAll(classpathContainers);

    ProgressUtil.progressOneStep(monitor);
    // Configuring the classpath of the Java Project
    if (changedClasspath) {
        javaProject.setRawClasspath(classpath.toArray(new IClasspathEntry[0]), null);
    }
}

From source file:org.ebayopensource.turmeric.eclipse.maven.core.m2eclipse.MavenProjectConfigurator.java

License:Open Source License

@Override
public void configure(ProjectConfigurationRequest request, IProgressMonitor monitor) throws CoreException {
    if (request == null) {
        return;//from  w w  w.ja  v a 2  s . com
    }

    if (request.isProjectImport() == true) {
        IProject project = request.getProject();
        SupportedProjectType projectType = null;
        if (isValidInterfaceProject(project) && TurmericServiceUtils.isSOAInterfaceProject(project) == false) {
            projectType = SupportedProjectType.INTERFACE;
        } else if (isValidImplementationProject(project)
                && TurmericServiceUtils.isSOAImplProject(project) == false) {
            projectType = SupportedProjectType.IMPL;
        } else if (isValidConsumerProject(project)
                && TurmericServiceUtils.isSOAConsumerProject(project) == false) {
            projectType = SupportedProjectType.CONSUMER;
        } else if (isValidTypeLibraryProject(project)
                && TurmericServiceUtils.isSOATypeLibraryProject(project) == false) {
            projectType = SupportedProjectType.TYPE_LIBRARY;
        } else if (isValidErrorLibraryProject(project)
                && TurmericServiceUtils.isSOAErrorLibraryProject(project) == false) {
            projectType = SupportedProjectType.ERROR_LIBRARY;
        } else {
            //OK this is not a Turmeric project after all.
            return;
        }

        String natureId = GlobalRepositorySystem.instanceOf().getActiveRepositorySystem()
                .getProjectNatureId(projectType);

        if (StringUtils.isNotBlank(natureId)) {
            //it is a SOA project
            JDTUtil.addNatures(project, monitor, natureId);
            InputStream input = null;
            try {
                input = request.getPom().getContents();
                Model model = MavenCoreUtils.mavenEclipseAPI().parsePom(input);
                Build build = model.getBuild();
                final IJavaProject javaProject = JavaCore.create(project);
                List<IPath> srcDirs = JDTUtil.getSourceDirectories(project);
                List<IPath> additionalSrcDirs = new ArrayList<IPath>();
                Plugin: for (Plugin plugin : build.getPlugins()) {
                    if (plugin.getArtifactId().equals("build-helper-maven-plugin")) {
                        for (PluginExecution exec : plugin.getExecutions()) {
                            if ("add-source".equals(exec.getId()) && exec.getConfiguration() != null) {
                                String xml = exec.getConfiguration().toString();
                                InputStream ins = null;
                                try {
                                    ins = new ByteArrayInputStream(xml.getBytes());
                                    Document doc = JDOMUtil.readXML(ins);
                                    Element elem = doc.getRootElement().getChild("sources");
                                    if (elem != null) {
                                        for (Object obj : elem.getChildren("source")) {
                                            if (obj instanceof Element) {
                                                IPath src = new Path(((Element) obj).getTextTrim());
                                                if (srcDirs.contains(src) == false) {
                                                    additionalSrcDirs.add(src);
                                                }
                                            }
                                        }
                                    }

                                } finally {
                                    IOUtils.closeQuietly(ins);
                                }
                                break Plugin;
                            }
                        }
                    }
                }

                if (additionalSrcDirs.isEmpty() == false) {
                    final List<IClasspathEntry> entries = ListUtil.arrayList(javaProject.readRawClasspath());
                    IPath outputDir = project.getFolder(build.getOutputDirectory()).getFullPath();
                    List<String> missingDirs = new ArrayList<String>();
                    for (IPath path : additionalSrcDirs) {
                        IFolder folder = project.getFolder(path);
                        if (folder.exists() == false) {
                            missingDirs.add(path.toString());
                        }
                        IPath srcPath = project.getFolder(path).getFullPath();
                        if (containsSourcePath(entries, srcPath) == false) {
                            entries.add(JavaCore.newSourceEntry(srcPath, new IPath[0], new IPath[0],
                                    outputDir.makeAbsolute()));
                        }
                    }
                    if (missingDirs.isEmpty() == false) {
                        WorkspaceUtil.createFolders(project, missingDirs, monitor);
                    }

                    javaProject.setRawClasspath(entries.toArray(new IClasspathEntry[0]), monitor);
                }
            } catch (Exception e) {
                throw new CoreException(EclipseMessageUtils.createErrorStatus(e));
            } finally {
                IOUtils.closeQuietly(input);
            }
        }
    }
}

From source file:org.ebayopensource.turmeric.eclipse.maven.sconfig.TurmerStandardProjectConfigurator.java

License:Open Source License

@Override
public void configure(ProjectConfigurationRequest projRequest, IProgressMonitor monitor) throws CoreException {

    if (projRequest == null) {
        return;//  ww w.  ja va 2s . c o  m
    }

    SupportedProjectType projectType = null;
    IProject project = projRequest.getProject();
    if (isInterfaceProject(projRequest)) {
        projectType = SupportedProjectType.INTERFACE;
    } else if (isImplementationProject(projRequest)) {
        projectType = SupportedProjectType.IMPL;
    } else if (isErrorLibProject(projRequest)) {
        projectType = SupportedProjectType.ERROR_LIBRARY;
    } else if (isTypeLibProject(projRequest)) {
        projectType = SupportedProjectType.TYPE_LIBRARY;
    } else if (isConsumerLibProject(projRequest)) {
        projectType = SupportedProjectType.CONSUMER;
    } else {
        return;
    }

    String natureId = GlobalRepositorySystem.instanceOf().getActiveRepositorySystem()
            .getProjectNatureId(projectType);

    JDTUtil.addNatures(project, monitor, natureId);

    List<IPath> additionalSrcDirs = new ArrayList<IPath>();
    additionalSrcDirs.add(new Path("target/generated-sources/codegen"));
    additionalSrcDirs.add(new Path("target/generated-resources/codegen"));

    final IJavaProject javaProject = JavaCore.create(project);

    final List<IClasspathEntry> entries = ListUtil.arrayList(javaProject.readRawClasspath());
    for (IPath path : additionalSrcDirs) {
        IFolder folder = project.getFolder(path);
        if (folder.exists()) {
            IPath srcPath = project.getFolder(path).getFullPath();
            if (containsSourcePath(entries, srcPath) == false) {
                entries.add(JavaCore.newSourceEntry(srcPath, new IPath[0]));
            }
        }
    }
    javaProject.setRawClasspath(entries.toArray(new IClasspathEntry[0]), monitor);

}

From source file:org.ebayopensource.turmeric.eclipse.utils.plugin.JDTUtil.java

License:Open Source License

/**
 * Adds the java support to eclipse project.
 * ie soa nature is added here./* w  ww. jav  a 2s . c  o  m*/
 * Class Path container related linking etc..
 *
 * @param project the project
 * @param sourceDirectories the source directories
 * @param defaultCompilerLevel the default compiler level
 * @param outputLocation the output location
 * @param monitor the monitor
 * @throws CoreException the core exception
 */
public static void addJavaSupport(IProject project, List<String> sourceDirectories, String defaultCompilerLevel,
        String outputLocation, IProgressMonitor monitor) throws CoreException {

    boolean changedClasspath = false;
    if (addJavaNature(project, monitor)) {
        changedClasspath = true;
    }
    // Configuring the Java Project
    final IJavaProject javaProject = JavaCore.create(project);
    final List<IClasspathEntry> classpath = JDTUtil.rawClasspath(javaProject, true);
    if (outputLocation.equals(javaProject.getOutputLocation()) == false) {
        final IFolder outputDirClasses = project.getFolder(outputLocation);
        javaProject.setOutputLocation(outputDirClasses.getFullPath(), monitor);
        changedClasspath = true;
    }

    // Dealing with the case where the root of the project is set to be the
    // src and bin destinations... bad... bad...
    for (final Iterator<IClasspathEntry> iterator = classpath.iterator(); iterator.hasNext();) {
        final IClasspathEntry entry = iterator.next();
        if (entry.getEntryKind() != IClasspathEntry.CPE_SOURCE
                || !entry.getPath().equals(new Path("/" + project.getName())))
            continue;
        iterator.remove();
        changedClasspath |= true;
    }
    for (final String dir : sourceDirectories) {

        final IFolder source = project.getFolder(dir);
        // If the Java project existed previously, checking if directories
        // already exist in
        // its classpath.
        boolean found = false;
        for (final IClasspathEntry entry : classpath) {
            if (!entry.getPath().equals(source.getFullPath()))
                continue;
            found = true;
            break;
        }
        if (found)
            continue;
        changedClasspath |= true;
        classpath.add(JavaCore.newSourceEntry(source.getFullPath()));
    }
    ProgressUtil.progressOneStep(monitor, 10);
    // Adding the runtime library
    boolean found = false;
    for (final IClasspathEntry entry : classpath) {
        // All JRE Containers should have a prefix of
        // org.eclipse.jdt.launching.JRE_CONTAINER
        if (JavaRuntime.newDefaultJREContainerPath().isPrefixOf(entry.getPath())
                && JavaRuntime.newDefaultJREContainerPath().equals(entry.getPath())) {
            found = true;
            break;
        }
    }
    if (!found) {
        changedClasspath = true;
        classpath.add(JavaRuntime.getDefaultJREContainerEntry());
    }
    ProgressUtil.progressOneStep(monitor);
    // Configuring the classpath of the Java Project
    if (changedClasspath) {
        javaProject.setRawClasspath(classpath.toArray(new IClasspathEntry[0]), null);
    }

    IProjectFacetVersion projectFacetVersion = JavaFacetUtils.JAVA_60;
    if (StringUtils.isNotBlank(defaultCompilerLevel)) {
        try {
            projectFacetVersion = JavaFacetUtils.compilerLevelToFacet(defaultCompilerLevel);
        } catch (Exception e) {
            Logger.getLogger(JDTUtil.class.getName()).throwing(JDTUtil.class.getName(), "addJavaSupport", e);
        }
    }

    JavaFacetUtils.setCompilerLevel(project, projectFacetVersion);
}

From source file:org.ebayopensource.turmeric.repositorysystem.imp.impl.TurmericProjectConfigurer.java

License:Open Source License

private void mavenizeAndCleanUp(final IProject project, final ProjectMavenizationRequest request,
        final IProgressMonitor monitor)
        throws CoreException, MavenEclipseApiException, IOException, InterruptedException, TemplateException {
    if (SOALogger.DEBUG)
        logger.entering(project, request);
    final IMavenEclipseApi api = MavenCoreUtils.mavenEclipseAPI();
    try {/*from w  w w .  jav  a  2  s  .  c om*/
        //         It seems that the pom.xml is not updated in the Eclipse Workspace by the mavenize project operation
        //         Util.refresh( project.getFile( "pom.xml" ) );
        //         Project Mavenization doesn't seem to care that the output directory is set here and set in the pom.xml
        //         it will use the maven default of target-eclipse no matter what.
        IJavaProject javaProject = null;
        try {
            api.mavenizeProject(request, monitor);
            logger.info("Mavenization finished->" + project);
            ProgressUtil.progressOneStep(monitor);
            javaProject = JavaCore.create(project);
            //javaProject.setOutputLocation( project.getFolder( SOAProjectConstants.FOLDER_OUTPUT_DIR).getFullPath(), null );
            FileUtils.deleteDirectory(project.getFolder("target-eclipse").getLocation().toFile());
            //Util.delete( project.getFolder( "target-eclipse" ), null );
            final Map<?, ?> options = javaProject.getOptions(false);
            options.clear();
            javaProject.setOptions(options);
        } catch (NullPointerException e) {
            throw new CoreException(EclipseMessageUtils.createErrorStatus(
                    "NPE occured during projects mavenization.\n\n"
                            + "The possible cause is that the M2Eclipse Maven indexes in your current workspace might be corrupted. "
                            + "Please remove folder {workspace}/.metadata/.plugins/org.maven.ide.eclipse/, and then restart your IDE.",
                    e));
        }
        //         The Mavenization also seemed to take the META-SRC src directory and add an exclusion pattern along with
        //         setting its output location to itself.  Maybe they wanted to do a class library folder?  Either way its
        //         no good for us.  Secondly, we are setting the Maven classpath container to have its entries exported by default.
        //         Finally, we are adding the classpath entry attribute 'org.eclipse.jst.component.dependency' in case the project
        //         is a WTP web project so that WTP will use the maven classpath container when deploying to its runtime servers.
        boolean changed = false;
        final List<IClasspathEntry> newEntries = ListUtil.list();
        final IPath containerPath = new Path(SOAMavenConstants.MAVEN_CLASSPATH_CONTAINER_ID);
        for (final IClasspathEntry cpEntry : JDTUtil.rawClasspath(javaProject, true)) {
            if (cpEntry.getEntryKind() == IClasspathEntry.CPE_CONTAINER) {
                if (cpEntry.getPath().equals(containerPath)) {
                    newEntries.add(JavaCore.newContainerEntry(containerPath, true));
                    changed |= true;
                }
            } else if (cpEntry.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
                if (!ArrayUtils.isEmpty(cpEntry.getExclusionPatterns())
                        || cpEntry.getOutputLocation() != null) {
                    newEntries.add(JavaCore.newSourceEntry(cpEntry.getPath()));
                    changed |= true;
                } else {
                    newEntries.add(cpEntry);
                }
            } else {
                newEntries.add(cpEntry);
            }
        }
        ProgressUtil.progressOneStep(monitor, 15);
        if (changed) {
            javaProject.setRawClasspath(newEntries.toArray(new IClasspathEntry[0]), null);
            ProgressUtil.progressOneStep(monitor);
            //This is a hot fix for the Maven classpath container issue,
            //should be removed as soon as the M2Eclipse guys fix it
            int count = 0; //we only go to sleep 5 times.
            while (MavenCoreUtils.getMaven2ClasspathContainer(javaProject).getClasspathEntries().length == 0
                    && count < 5) {
                logger.warning("Maven Classpath is empty->", SOAMavenConstants.MAVEN_CLASSPATH_CONTAINER_ID,
                        ", going to sleep...");
                Thread.sleep(1000);
                ProgressUtil.progressOneStep(monitor, 10);
                count++;
            }
        }
    } finally {
        if (SOALogger.DEBUG)
            logger.exiting();
    }
}

From source file:org.ebayopensource.turmeric.repositorysystem.imp.impl.TurmericProjectConfigurer.java

License:Open Source License

/**
 * {@inheritDoc}// w  w  w .j av a  2 s.  c  om
 * 
 */
public void addBuildSystemClasspathContainer(IJavaProject javaProject, IProgressMonitor monitor)
        throws CoreException {
    boolean found = false;
    final List<IClasspathEntry> newEntries = JDTUtil.rawClasspath(javaProject, true);
    final IPath containerPath = new Path(SOAMavenConstants.MAVEN_CLASSPATH_CONTAINER_ID);
    for (final IClasspathEntry cpEntry : newEntries) {
        if (cpEntry.getEntryKind() == IClasspathEntry.CPE_CONTAINER) {
            if (cpEntry.getPath().equals(containerPath)) {
                found = true;
                break;
            }
        }
    }
    ProgressUtil.progressOneStep(monitor, 15);
    if (found == false) {
        newEntries.add(JavaCore.newContainerEntry(containerPath, true));
        javaProject.setRawClasspath(newEntries.toArray(new IClasspathEntry[0]), null);
        ProgressUtil.progressOneStep(monitor);
    }

}

From source file:org.ebayopensource.vjet.eclipse.core.test.bug.BugVerifyTests.java

License:Open Source License

/**
 * verify bug 2519//  w  w  w.ja  v a 2s.  co  m
 * 
 * @throws Exception
 */
public void test2519() throws Exception {
    IWorkspaceRunnable workspaceRunnable = new IWorkspaceRunnable() {
        @Override
        public void run(IProgressMonitor monitor) throws CoreException {
            // create project
            IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject("JavaProject");
            if (project.exists())
                project.delete(false, monitor);
            project.create(monitor);

            if (!project.isOpen())
                project.open(monitor);

            // add nature
            IProjectDescription description = project.getDescription();
            String[] prevNatures = description.getNatureIds();
            String[] newNatures = new String[prevNatures.length + 1];
            System.arraycopy(prevNatures, 0, newNatures, 0, prevNatures.length);
            newNatures[prevNatures.length] = JavaCore.NATURE_ID;
            description.setNatureIds(newNatures);
            project.setDescription(description, monitor);

            // add src
            project.getFolder("src").create(false, true, monitor);
            IClasspathEntry srcEntry = JavaCore.newSourceEntry(project.getFullPath().append("src"));
            IClasspathEntry[] entries = new IClasspathEntry[] { srcEntry };
            IJavaProject javaProject = JavaCore.create(project);
            javaProject.setRawClasspath(entries, monitor);

            // add VJET Nature
            IAddVjoNaturePolicy policy = AddVjoNaturePolicyManager.getInstance().getPolicy(project);
            policy.addVjoNature(project);

            // verify VJET .buildpath
            IFile buildPathFile = project.getFile(ScriptProject.BUILDPATH_FILENAME);
            if (!buildPathFile.exists())
                assertTrue("VJET .buildpath file not exist!", false);

            ScriptProject scriptProject = new ScriptProject(project, null);
            IBuildpathEntry buildpathEntry = scriptProject
                    .getBuildpathEntryFor(project.getFullPath().append("src"));

            // delete java project
            project.delete(true, null);

            if (buildpathEntry == null)
                assertTrue("no src build path entry", false);
        }
    };
    ResourcesPlugin.getWorkspace().run(workspaceRunnable, null);
}

From source file:org.ecipse.che.plugin.testing.testng.server.TestNGRunnerTest.java

License:Open Source License

@Test()
public void testName() throws Exception {
    String name = "Test";
    FolderEntry folder = pm.getProjectsRoot().createFolder(name);
    FolderEntry testsFolder = folder.createFolder("src/tests");
    StringBuilder b = new StringBuilder("package tests;\n");
    b.append("public class TestNGTest {}");
    testsFolder.createFile("TestNGTest.java", b.toString().getBytes());
    projectRegistry.setProjectType(folder.getPath().toString(), "java", false);

    //inform DeltaProcessingStat about new project
    JavaModelManager.getJavaModelManager().deltaState
            .resourceChanged(new ResourceChangedEvent(root, new ProjectCreatedEvent("", "/Test")));

    IJavaProject javaProject = JavaModelManager.getJavaModelManager().getJavaModel().getJavaProject("/Test");
    IClasspathEntry testNg = JavaCore.newLibraryEntry(new Path(ClasspathUtil.getJarPathForClass(Test.class)),
            null, null);/*from w  w w. j a  va  2 s  .  co m*/
    IClasspathEntry source = JavaCore.newSourceEntry(new Path("/Test/src"), null,
            new Path(ClasspathUtil.getJarPathForClass(TestNGRunnerTest.class)));
    IClasspathEntry jre = JavaCore.newContainerEntry(new Path(JREContainerInitializer.JRE_CONTAINER));

    javaProject.setRawClasspath(new IClasspathEntry[] { testNg, source, jre }, null);

    DtoServerImpls.TestExecutionContextImpl context = new DtoServerImpls.TestExecutionContextImpl();
    context.setDebugModeEnable(false);
    context.setContextType(TestExecutionContext.ContextType.FILE);
    context.setProjectPath("/Test");
    context.setFilePath("/Test/src/tests/TestNGTest.java");
    assertEquals("testng", runner.getName());
}

From source file:org.ecipse.che.plugin.testing.testng.server.TestSetUpUtil.java

License:Open Source License

/**
 * Creates a IJavaProject./*from  ww w.j  a  v a 2  s  . c om*/
 *
 * @param projectName The name of the project
 * @param binFolderName Name of the output folder
 * @return Returns the Java project handle
 * @throws CoreException Project creation failed
 */
public static IJavaProject createJavaProject(String projectName, String binFolderName) throws CoreException {
    IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
    IProject project = root.getProject(projectName);
    if (!project.exists()) {
        project.create(null);
    } else {
        project.refreshLocal(IResource.DEPTH_INFINITE, null);
    }

    if (!project.isOpen()) {
        project.open(null);
    }

    IPath outputLocation;
    if (binFolderName != null && binFolderName.length() > 0) {
        IFolder binFolder = project.getFolder(binFolderName);
        if (!binFolder.exists()) {
            CoreUtility.createFolder(binFolder, false, true, null);
        }
        outputLocation = binFolder.getFullPath();
    } else {
        outputLocation = project.getFullPath();
    }

    IFolder codenvyFolder = project.getFolder(".che");
    if (!codenvyFolder.exists()) {
        CoreUtility.createFolder(codenvyFolder, false, true, null);
    }

    //      if (!project.hasNature(JavaCore.NATURE_ID)) {
    //         addNatureToProject(project, JavaCore.NATURE_ID, null);
    //      }

    IJavaProject jproject = JavaCore.create(project);
    //      jproject.setOutputLocation(outputLocation, null);
    jproject.setRawClasspath(new IClasspathEntry[0], null);
    IFolder folder = project.getFolder(JavaProject.INNER_DIR);
    CoreUtility.createFolder(folder, true, true, null);

    return jproject;
}

From source file:org.eclim.plugin.jdt.project.JavaProjectManager.java

License:Open Source License

/**
 * Creates a new project.//w  w  w.  j  a v  a  2  s  . com
 *
 * @param project The project.
 * @param depends Comma separated project names this project depends on.
 */
protected void create(IProject project, String depends) throws Exception {
    // with scala-ide installed, apparently this needs to be explicitly done
    IProjectDescription desc = project.getDescription();
    if (!desc.hasNature(PluginResources.NATURE)) {
        String[] natures = desc.getNatureIds();
        String[] newNatures = new String[natures.length + 1];
        System.arraycopy(natures, 0, newNatures, 0, natures.length);
        newNatures[natures.length] = PluginResources.NATURE;
        desc.setNatureIds(newNatures);
        project.setDescription(desc, new NullProgressMonitor());
    }

    IJavaProject javaProject = JavaCore.create(project);
    ((JavaProject) javaProject).configure();

    if (!project.getFile(CLASSPATH).exists()) {
        ArrayList<IClasspathEntry> classpath = new ArrayList<IClasspathEntry>();
        boolean source = false;
        boolean container = false;

        ClassPathDetector detector = new ClassPathDetector(project, null);
        for (IClasspathEntry entry : detector.getClasspath()) {
            if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
                source = true;
            } else if (entry.getEntryKind() == IClasspathEntry.CPE_CONTAINER) {
                container = true;
            }
            classpath.add(entry);
        }

        // default source folder
        if (!source) {
            IResource src;
            IPreferenceStore store = PreferenceConstants.getPreferenceStore();
            String name = store.getString(PreferenceConstants.SRCBIN_SRCNAME);
            boolean srcBinFolders = store.getBoolean(PreferenceConstants.SRCBIN_FOLDERS_IN_NEWPROJ);
            if (srcBinFolders && name.length() > 0) {
                src = javaProject.getProject().getFolder(name);
            } else {
                src = javaProject.getProject();
            }

            classpath.add(new CPListElement(javaProject, IClasspathEntry.CPE_SOURCE, src.getFullPath(), src)
                    .getClasspathEntry());

            File srcPath = new File(ProjectUtils.getFilePath(project, src.getFullPath().toString()));
            if (!srcPath.exists()) {
                srcPath.mkdirs();
            }
        }

        // default containers
        if (!container) {
            for (IClasspathEntry entry : PreferenceConstants.getDefaultJRELibrary()) {
                classpath.add(entry);
            }
        }

        // dependencies on other projects
        for (IClasspathEntry entry : createOrUpdateDependencies(javaProject, depends)) {
            classpath.add(entry);
        }

        javaProject.setRawClasspath(classpath.toArray(new IClasspathEntry[classpath.size()]), null);

        // output location
        IPath output = detector.getOutputLocation();
        if (output == null) {
            output = BuildPathsBlock.getDefaultOutputLocation(javaProject);
        }
        javaProject.setOutputLocation(output, null);
    }
    javaProject.makeConsistent(null);
    javaProject.save(null, false);
}