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

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

Introduction

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

Prototype

void setOutputLocation(IPath path, IProgressMonitor monitor) throws JavaModelException;

Source Link

Document

Sets the default output location of this project to the location described by the given workspace-relative absolute path.

Usage

From source file:at.bestsolution.efxclipse.tooling.rrobot.impl.JDTProjectHandler.java

License:Open Source License

protected IStatus customizeProject(IProgressMonitor monitor, IProject project, P model) {
    try {//ww  w.j a v  a2  s .  c o m
        addNatureToProject(project, JavaCore.NATURE_ID, monitor);

        IJavaProject javaProject = JavaCore.create(project);

        javaProject.setOutputLocation(project.getFullPath().append("bin"), monitor); //FIXME has to come from model
        IClasspathEntry[] tmpEntries = createClasspathEntries(model);
        IClasspathEntry[] entries = new IClasspathEntry[tmpEntries.length + model.getSourceFragments().size()];
        int i = 0;
        for (SourceFragment f : model.getSourceFragments()) {
            StringBuilder b = new StringBuilder();
            Folder folder = f.getFolder();
            while (folder != null) {
                if (b.length() > 0) {
                    b.insert(0, "/");
                }
                b.insert(0, folder.getName());
                if (folder.eContainer() instanceof Folder) {
                    folder = (Folder) folder.eContainer();
                } else {
                    break;
                }
            }

            entries[i] = JavaCore.newSourceEntry(project.getProject().getFullPath().append(b.toString()));
        }

        System.arraycopy(tmpEntries, 0, entries, model.getSourceFragments().size(), tmpEntries.length);
        javaProject.setRawClasspath(entries, monitor);

    } catch (CoreException e) {
        return new Status(IStatus.ERROR, PLUGIN_ID, "Unable to add nature", e);
    }
    return super.customizeProject(monitor, project, model);
}

From source file:at.bestsolution.fxide.jdt.maven.MavenModuleTypeService.java

License:Open Source License

@Override
public Status createModule(IProject project, IResource resource) {
    IProjectDescription description = project.getWorkspace().newProjectDescription(project.getName());
    description.setNatureIds(new String[] { JavaCore.NATURE_ID, "org.eclipse.m2e.core.maven2Nature" });

    ICommand[] commands = new ICommand[2];

    {/*from   w ww.  j  a v  a  2  s.c o m*/
        ICommand cmd = description.newCommand();
        cmd.setBuilderName(JavaCore.BUILDER_ID);
        commands[0] = cmd;
    }

    {
        ICommand cmd = description.newCommand();
        cmd.setBuilderName("org.eclipse.m2e.core.maven2Builder");
        commands[1] = cmd;
    }

    if (resource != null) {
        // If we get a parent path we create a nested project
        try {
            if (resource.getProject().getNature("org.eclipse.m2e.core.maven2Nature") != null) {
                IFolder folder = resource.getProject().getFolder(project.getName());
                if (folder.exists()) {
                    return Status.status(State.ERROR, -1, "Folder already exists", null);
                }
                folder.create(true, true, null);

                description.setLocation(folder.getLocation());
            }
        } catch (CoreException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
            return Status.status(State.ERROR, -1, "Could not create parent relation", e1);
        }
    }

    description.setBuildSpec(commands);

    try {
        project.create(description, null);
        project.open(null);

        project.getFolder(new Path("target")).create(true, true, null);
        project.getFolder(new Path("target").append("classes")).create(true, true, null);

        project.getFolder(new Path("target")).setDerived(true, null);
        project.getFolder(new Path("target").append("classes")).setDerived(true, null);

        project.getFolder(new Path("src")).create(true, true, null);

        project.getFolder(new Path("src").append("main")).create(true, true, null);
        project.getFolder(new Path("src").append("main").append("java")).create(true, true, null);
        project.getFolder(new Path("src").append("main").append("resources")).create(true, true, null);

        project.getFolder(new Path("src").append("test")).create(true, true, null);
        project.getFolder(new Path("src").append("test").append("java")).create(true, true, null);
        project.getFolder(new Path("src").append("test").append("resources")).create(true, true, null);

        {
            IFile file = project.getFile(new Path("pom.xml"));
            try (InputStream templateStream = getClass().getResourceAsStream("template-pom.xml")) {
                String pomContent = IOUtils.readToString(templateStream, Charset.forName("UTF-8"));
                Map<String, String> map = new HashMap<>();
                map.put("groupId", project.getName());
                map.put("artifactId", project.getName());
                map.put("version", "1.0.0");

                file.create(new ByteArrayInputStream(StrSubstitutor.replace(pomContent, map).getBytes()), true,
                        null);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        IJavaProject jProject = JavaCore.create(project);
        jProject.setOutputLocation(project.getFolder(new Path("target").append("classes")).getFullPath(), null);

        List<IClasspathEntry> entries = new ArrayList<>();

        {
            IClasspathAttribute[] attributes = new IClasspathAttribute[2];
            attributes[0] = JavaCore.newClasspathAttribute("optional", "true");
            attributes[1] = JavaCore.newClasspathAttribute("maven.pomderived", "true");
            IPath path = new Path("src").append("main").append("java");
            IPath output = new Path("target").append("classes");
            IClasspathEntry sourceEntry = JavaCore.newSourceEntry(
                    project.getProject().getFullPath().append(path), null, null,
                    project.getProject().getFullPath().append(output), attributes);
            entries.add(sourceEntry);
        }

        {
            IClasspathAttribute[] attributes = new IClasspathAttribute[1];
            attributes[0] = JavaCore.newClasspathAttribute("maven.pomderived", "true");
            IPath path = new Path("src").append("main").append("resources");
            IPath output = new Path("target").append("classes");
            IPath[] exclusions = new IPath[] { new Path("**") };
            entries.add(JavaCore.newSourceEntry(project.getProject().getFullPath().append(path), null,
                    exclusions, project.getProject().getFullPath().append(output), attributes));
        }

        {
            IClasspathAttribute[] attributes = new IClasspathAttribute[2];
            attributes[0] = JavaCore.newClasspathAttribute("optional", "true");
            attributes[1] = JavaCore.newClasspathAttribute("maven.pomderived", "true");
            IPath path = new Path("src").append("test").append("java");
            IPath output = new Path("target").append("test-classes");
            IClasspathEntry sourceEntry = JavaCore.newSourceEntry(
                    project.getProject().getFullPath().append(path), null, null,
                    project.getProject().getFullPath().append(output), attributes);
            entries.add(sourceEntry);
        }

        {
            IClasspathAttribute[] attributes = new IClasspathAttribute[1];
            attributes[0] = JavaCore.newClasspathAttribute("maven.pomderived", "true");
            IPath path = new Path("src").append("test").append("resources");
            IPath output = new Path("target").append("test-classes");
            IPath[] exclusions = new IPath[] { new Path("**") };
            entries.add(JavaCore.newSourceEntry(project.getProject().getFullPath().append(path), null,
                    exclusions, project.getProject().getFullPath().append(output), attributes));
        }

        {
            IClasspathAttribute[] attributes = new IClasspathAttribute[1];
            attributes[0] = JavaCore.newClasspathAttribute("maven.pomderived", "true");

            IPath path = JavaRuntime.newDefaultJREContainerPath();
            entries.add(JavaCore.newContainerEntry(path, null, attributes, false));
        }

        {
            IClasspathAttribute[] attributes = new IClasspathAttribute[1];
            attributes[0] = JavaCore.newClasspathAttribute("maven.pomderived", "true");

            IPath path = new Path("org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER");
            entries.add(JavaCore.newContainerEntry(path, null, attributes, false));
        }

        jProject.setRawClasspath(entries.toArray(new IClasspathEntry[0]), null);
        project.getWorkspace().save(true, null);
        return Status.ok();
    } catch (CoreException ex) {
        //TODO
        ex.printStackTrace();
        return Status.status(State.ERROR, -1, "Failed to create project", ex);
    }
}

From source file:at.bestsolution.fxide.jdt.services.JDTModuleTypeService.java

License:Open Source License

@Override
public Status createModule(IProject project, IResource resource) {
    IProjectDescription description = project.getWorkspace().newProjectDescription(project.getName());
    description.setNatureIds(new String[] { JavaCore.NATURE_ID });
    ICommand cmd = description.newCommand();
    cmd.setBuilderName(JavaCore.BUILDER_ID);
    description.setBuildSpec(new ICommand[] { cmd });

    try {/* w ww  .  j  a  v  a  2 s . co  m*/
        project.create(description, null);
        project.open(null);

        project.getFolder(new Path("target")).create(true, true, null);
        project.getFolder(new Path("target").append("classes")).create(true, true, null);

        project.getFolder(new Path("target")).setDerived(true, null);
        project.getFolder(new Path("target").append("classes")).setDerived(true, null);

        project.getFolder(new Path("src")).create(true, true, null);

        project.getFolder(new Path("src").append("main")).create(true, true, null);
        project.getFolder(new Path("src").append("main").append("java")).create(true, true, null);
        project.getFolder(new Path("src").append("main").append("resources")).create(true, true, null);

        project.getFolder(new Path("src").append("test")).create(true, true, null);
        project.getFolder(new Path("src").append("test").append("java")).create(true, true, null);
        project.getFolder(new Path("src").append("test").append("resources")).create(true, true, null);

        //         IExecutionEnvironmentsManager executionEnvironmentsManager = JavaRuntime.getExecutionEnvironmentsManager();
        //         IExecutionEnvironment[] executionEnvironments = executionEnvironmentsManager.getExecutionEnvironments();
        //         System.err.println(JavaRuntime.getDefaultVMInstall().getInstallLocation());

        IJavaProject jProject = JavaCore.create(project);
        jProject.setOutputLocation(project.getFolder(new Path("target").append("classes")).getFullPath(), null);

        List<IClasspathEntry> entries = new ArrayList<>();
        entries.add(JavaCore.newSourceEntry(
                project.getProject().getFullPath().append("src").append("main").append("java")));
        entries.add(JavaCore.newSourceEntry(
                project.getProject().getFullPath().append("src").append("main").append("resources")));
        entries.add(JavaCore.newSourceEntry(
                project.getProject().getFullPath().append("src").append("test").append("java")));
        entries.add(JavaCore.newSourceEntry(
                project.getProject().getFullPath().append("src").append("test").append("resources")));
        entries.add(JavaCore.newContainerEntry(JavaRuntime.newDefaultJREContainerPath()));

        jProject.setRawClasspath(entries.toArray(new IClasspathEntry[0]), null);
        project.getWorkspace().save(true, null);
        return Status.ok();
    } catch (CoreException ex) {
        return Status.status(State.ERROR, -1, "Failed to create project", ex);
    }
}

From source file:at.component.newcomponentwizard.generator.NewProjectCreationOperation.java

License:Open Source License

private void setClasspath(IProject project, IFieldData data) throws JavaModelException, CoreException {
    IJavaProject javaProject = JavaCore.create(project);
    // Set output folder
    if (data.getOutputFolderName() != null) {
        IPath path = project.getFullPath().append(data.getOutputFolderName());
        javaProject.setOutputLocation(path, null);
    }//from ww  w  .j  av  a 2 s .  c  om
    IClasspathEntry[] entries = getClassPathEntries(javaProject, data);
    javaProject.setRawClasspath(entries, null);
}

From source file:ca.ubc.cs.ferret.tests.support.ResourceHelper.java

License:Open Source License

public static IJavaProject createPluginProject(IProject project) throws CoreException, JavaModelException {

    if (project == null)
        return null;

    IJavaProject javaProject = JavaCore.create(project);

    // create bin folder
    IFolder binFolder = project.getFolder("bin");
    if (!binFolder.exists())
        binFolder.create(false, true, null);

    // set java nature
    IProjectDescription description = project.getDescription();
    description.setNatureIds(new String[] { PDE.PLUGIN_NATURE, JavaCore.NATURE_ID });
    project.setDescription(description, null);

    // create output folder
    IPath outputLocation = binFolder.getFullPath();
    javaProject.setOutputLocation(outputLocation, null);

    PluginProject pluginProject = new PluginProject();
    pluginProject.setProject(project);//from  ww  w.j  a  va 2s .  com
    pluginProject.configure();

    return javaProject;
}

From source file:com.android.ide.eclipse.adt.internal.build.builders.ResourceManagerBuilder.java

License:Open Source License

@SuppressWarnings("unchecked")
@Override//ww w.ja va 2s .c  o m
protected IProject[] build(int kind, Map args, IProgressMonitor monitor) throws CoreException {
    // Get the project.
    final IProject project = getProject();
    IJavaProject javaProject = JavaCore.create(project);

    // Clear the project of the generic markers
    removeMarkersFromContainer(project, AdtConstants.MARKER_ADT);

    // check for existing target marker, in which case we abort.
    // (this means: no SDK, no target, or unresolvable target.)
    try {
        abortOnBadSetup(javaProject, null);
    } catch (AbortBuildException e) {
        return null;
    }

    // Check the compiler compliance level, displaying the error message
    // since this is the first builder.
    Pair<Integer, String> result = ProjectHelper.checkCompilerCompliance(project);
    String errorMessage = null;
    switch (result.getFirst().intValue()) {
    case ProjectHelper.COMPILER_COMPLIANCE_LEVEL:
        errorMessage = Messages.Requires_Compiler_Compliance_s;
        break;
    case ProjectHelper.COMPILER_COMPLIANCE_SOURCE:
        errorMessage = Messages.Requires_Source_Compatibility_s;
        break;
    case ProjectHelper.COMPILER_COMPLIANCE_CODEGEN_TARGET:
        errorMessage = Messages.Requires_Class_Compatibility_s;
        break;
    }

    if (errorMessage != null) {
        errorMessage = String.format(errorMessage,
                result.getSecond() == null ? "(no value)" : result.getSecond());

        if (JavaCore.VERSION_1_7.equals(result.getSecond())) {
            // If the user is trying to target 1.7 but compiling with something older,
            // the error message can be a bit misleading; instead point them in the
            // direction of updating the project's build target.
            Sdk currentSdk = Sdk.getCurrent();
            if (currentSdk != null) {
                IAndroidTarget target = currentSdk.getTarget(project.getProject());
                if (target != null && target.getVersion().getApiLevel() < 19) {
                    errorMessage = "Using 1.7 requires compiling with Android 4.4 "
                            + "(KitKat); currently using " + target.getVersion();
                }

                ProjectState projectState = Sdk.getProjectState(project);
                if (projectState != null) {
                    BuildToolInfo buildToolInfo = projectState.getBuildToolInfo();
                    if (buildToolInfo == null) {
                        buildToolInfo = currentSdk.getLatestBuildTool();
                    }
                    if (buildToolInfo != null && buildToolInfo.getRevision().getMajor() < 19) {
                        errorMessage = "Using 1.7 requires using Android Build Tools "
                                + "version 19 or later; currently using " + buildToolInfo.getRevision();
                    }
                }
            }
        }

        markProject(AdtConstants.MARKER_ADT, errorMessage, IMarker.SEVERITY_ERROR);
        AdtPlugin.printErrorToConsole(project, errorMessage);

        return null;
    }

    // Check that the SDK directory has been setup.
    String osSdkFolder = AdtPlugin.getOsSdkFolder();

    if (osSdkFolder == null || osSdkFolder.length() == 0) {
        AdtPlugin.printErrorToConsole(project, Messages.No_SDK_Setup_Error);
        markProject(AdtConstants.MARKER_ADT, Messages.No_SDK_Setup_Error, IMarker.SEVERITY_ERROR);

        return null;
    }

    // check the 'gen' source folder is present
    boolean hasGenSrcFolder = false; // whether the project has a 'gen' source folder setup

    IClasspathEntry[] classpaths = javaProject.readRawClasspath();
    if (classpaths != null) {
        for (IClasspathEntry e : classpaths) {
            if (e.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
                IPath path = e.getPath();
                if (path.segmentCount() == 2 && path.segment(1).equals(SdkConstants.FD_GEN_SOURCES)) {
                    hasGenSrcFolder = true;
                    break;
                }
            }
        }
    }

    boolean genFolderPresent = false; // whether the gen folder actually exists
    IResource resource = project.findMember(SdkConstants.FD_GEN_SOURCES);
    genFolderPresent = resource != null && resource.exists();

    if (hasGenSrcFolder == false && genFolderPresent) {
        // No source folder setup for 'gen' in the project, but there's already a
        // 'gen' resource (file or folder).
        String message;
        if (resource.getType() == IResource.FOLDER) {
            // folder exists already! This is an error. If the folder had been created
            // by the NewProjectWizard, it'd be a source folder.
            message = String.format(
                    "%1$s already exists but is not a source folder. Convert to a source folder or rename it.",
                    resource.getFullPath().toString());
        } else {
            // resource exists but is not a folder.
            message = String.format(
                    "Resource %1$s is in the way. ADT needs a source folder called 'gen' to work. Rename or delete resource.",
                    resource.getFullPath().toString());
        }

        AdtPlugin.printErrorToConsole(project, message);
        markProject(AdtConstants.MARKER_ADT, message, IMarker.SEVERITY_ERROR);

        return null;
    } else if (hasGenSrcFolder == false || genFolderPresent == false) {
        // either there is no 'gen' source folder in the project (older SDK),
        // or the folder does not exist (was deleted, or was a fresh svn checkout maybe.)

        // In case we are migrating from an older SDK, we go through the current source
        // folders and delete the generated Java files.
        List<IPath> sourceFolders = BaseProjectHelper.getSourceClasspaths(javaProject);
        IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
        for (IPath path : sourceFolders) {
            IResource member = root.findMember(path);
            if (member != null) {
                removeDerivedResources(member, monitor);
            }
        }

        // create the new source folder, if needed
        IFolder genFolder = project.getFolder(SdkConstants.FD_GEN_SOURCES);
        if (genFolderPresent == false) {
            AdtPlugin.printBuildToConsole(BuildVerbosity.VERBOSE, project,
                    "Creating 'gen' source folder for generated Java files");
            genFolder.create(true /* force */, true /* local */, new SubProgressMonitor(monitor, 10));
        }

        // add it to the source folder list, if needed only (or it will throw)
        if (hasGenSrcFolder == false) {
            IClasspathEntry[] entries = javaProject.getRawClasspath();
            entries = ProjectHelper.addEntryToClasspath(entries,
                    JavaCore.newSourceEntry(genFolder.getFullPath()));
            javaProject.setRawClasspath(entries, new SubProgressMonitor(monitor, 10));
        }

        // refresh specifically the gen folder first, as it may break the build
        // if it doesn't arrive in time then refresh the whole project as usual.
        genFolder.refreshLocal(IResource.DEPTH_ZERO, new SubProgressMonitor(monitor, 10));
        project.refreshLocal(IResource.DEPTH_INFINITE, new SubProgressMonitor(monitor, 10));

        // it seems like doing this fails to properly rebuild the project. the Java builder
        // running right after this builder will not see the gen folder, and will not be
        // restarted after this build. Therefore in this particular case, we start another
        // build asynchronously so that it's rebuilt after this build.
        launchJob(new Job("rebuild") {
            @Override
            protected IStatus run(IProgressMonitor m) {
                try {
                    project.build(IncrementalProjectBuilder.INCREMENTAL_BUILD, m);
                    return Status.OK_STATUS;
                } catch (CoreException e) {
                    return e.getStatus();
                }
            }
        });

    }

    // convert older projects which use bin as the eclipse output folder into projects
    // using bin/classes
    IFolder androidOutput = BaseProjectHelper.getAndroidOutputFolder(project);
    IFolder javaOutput = BaseProjectHelper.getJavaOutputFolder(project);
    if (androidOutput.exists() == false || javaOutput == null
            || javaOutput.getParent().equals(androidOutput) == false) {
        // get what we want as the new java output.
        IFolder newJavaOutput = androidOutput.getFolder(SdkConstants.FD_CLASSES_OUTPUT);

        if (androidOutput.exists() == false) {
            androidOutput.create(true /*force*/, true /*local*/, monitor);
        }

        if (newJavaOutput.exists() == false) {
            newJavaOutput.create(true /*force*/, true /*local*/, monitor);
        }

        // set the java output to this project.
        javaProject.setOutputLocation(newJavaOutput.getFullPath(), monitor);

        // need to do a full build. Can't build while we're already building, so launch a
        // job to build it right after this build
        launchJob(new Job("rebuild") {
            @Override
            protected IStatus run(IProgressMonitor jobMonitor) {
                try {
                    project.build(IncrementalProjectBuilder.CLEAN_BUILD, jobMonitor);
                    return Status.OK_STATUS;
                } catch (CoreException e) {
                    return e.getStatus();
                }
            }
        });
    }

    // check that we have bin/res/
    IFolder binResFolder = androidOutput.getFolder(SdkConstants.FD_RESOURCES);
    if (binResFolder.exists() == false) {
        binResFolder.create(true /* force */, true /* local */, new SubProgressMonitor(monitor, 10));
        project.refreshLocal(IResource.DEPTH_ONE, new SubProgressMonitor(monitor, 10));
    }

    // Check the preference to be sure we are supposed to refresh
    // the folders.
    if (AdtPrefs.getPrefs().getBuildForceResResfresh()) {
        AdtPlugin.printBuildToConsole(BuildVerbosity.VERBOSE, project, Messages.Refreshing_Res);

        // refresh the res folder.
        IFolder resFolder = project.getFolder(AdtConstants.WS_RESOURCES);
        resFolder.refreshLocal(IResource.DEPTH_INFINITE, monitor);

        // Also refresh the assets folder to make sure the ApkBuilder
        // will now it's changed and will force a new resource packaging.
        IFolder assetsFolder = project.getFolder(AdtConstants.WS_ASSETS);
        assetsFolder.refreshLocal(IResource.DEPTH_INFINITE, monitor);
    }

    return null;
}

From source file:com.android.ide.eclipse.adt.internal.wizards.newproject.NewProjectCreator.java

License:Open Source License

/**
 * Creates the actual project, sets its nature and adds the required folders
 * and files to it. This is run asynchronously in a different thread.
 *
 * @param monitor An existing monitor./*from  w w w.jav a 2s  .co m*/
 * @param project The project to create.
 * @param description A description of the project.
 * @param parameters Template parameters.
 * @param dictionary String definition.
 * @param isAndroidProject true if the project is to be set up as a full Android project; false
 * for a plain Java project.
 * @return The project newly created
 * @throws StreamException
 */
private IProject createEclipseProject(@NonNull IProgressMonitor monitor, @NonNull IProject project,
        @NonNull IProjectDescription description, @NonNull Map<String, Object> parameters,
        @Nullable Map<String, String> dictionary, @Nullable ProjectPopulator projectPopulator,
        boolean isAndroidProject) throws CoreException, IOException, StreamException {

    // get the project target
    IAndroidTarget target = (IAndroidTarget) parameters.get(PARAM_SDK_TARGET);
    boolean legacy = isAndroidProject && target.getVersion().getApiLevel() < 4;

    // Create project and open it
    project.create(description, new SubProgressMonitor(monitor, 10));
    if (monitor.isCanceled())
        throw new OperationCanceledException();

    project.open(IResource.BACKGROUND_REFRESH, new SubProgressMonitor(monitor, 10));

    // Add the Java and android nature to the project
    AndroidNature.setupProjectNatures(project, monitor, isAndroidProject);

    // Create folders in the project if they don't already exist
    addDefaultDirectories(project, AdtConstants.WS_ROOT, DEFAULT_DIRECTORIES, monitor);
    String[] sourceFolders;
    if (isAndroidProject) {
        sourceFolders = new String[] { (String) parameters.get(PARAM_SRC_FOLDER), GEN_SRC_DIRECTORY };
    } else {
        sourceFolders = new String[] { (String) parameters.get(PARAM_SRC_FOLDER) };
    }
    addDefaultDirectories(project, AdtConstants.WS_ROOT, sourceFolders, monitor);

    // Create the resource folders in the project if they don't already exist.
    if (legacy) {
        addDefaultDirectories(project, RES_DIRECTORY, RES_DIRECTORIES, monitor);
    } else {
        addDefaultDirectories(project, RES_DIRECTORY, RES_DENSITY_ENABLED_DIRECTORIES, monitor);
    }

    if (projectPopulator != null) {
        try {
            projectPopulator.populate(project);
        } catch (InvocationTargetException ite) {
            AdtPlugin.log(ite, null);
        }
    }

    // Setup class path: mark folders as source folders
    IJavaProject javaProject = JavaCore.create(project);
    setupSourceFolders(javaProject, sourceFolders, monitor);

    if (((Boolean) parameters.get(PARAM_IS_NEW_PROJECT)).booleanValue()) {
        // Create files in the project if they don't already exist
        addManifest(project, parameters, dictionary, monitor);

        // add the default app icon
        addIcon(project, legacy, monitor);

        // Create the default package components
        addSampleCode(project, sourceFolders[0], parameters, dictionary, monitor);

        // add the string definition file if needed
        if (dictionary != null && dictionary.size() > 0) {
            addStringDictionaryFile(project, dictionary, monitor);
        }

        // add the default proguard config
        File libFolder = new File((String) parameters.get(PARAM_SDK_TOOLS_DIR), SdkConstants.FD_LIB);
        addLocalFile(project, new File(libFolder, SdkConstants.FN_PROJECT_PROGUARD_FILE),
                // Write ProGuard config files with the extension .pro which
                // is what is used in the ProGuard documentation and samples
                SdkConstants.FN_PROJECT_PROGUARD_FILE, monitor);

        // Set output location
        javaProject.setOutputLocation(project.getFolder(BIN_CLASSES_DIRECTORY).getFullPath(), monitor);
    }

    File sampleDir = (File) parameters.get(PARAM_SAMPLE_LOCATION);
    if (sampleDir != null) {
        // Copy project
        copySampleCode(project, sampleDir, parameters, dictionary, monitor);
    }

    // Create the reference to the target project
    if (parameters.containsKey(PARAM_REFERENCE_PROJECT)) {
        IProject refProject = (IProject) parameters.get(PARAM_REFERENCE_PROJECT);
        if (refProject != null) {
            IProjectDescription desc = project.getDescription();

            // Add out reference to the existing project reference.
            // We just created a project with no references so we don't need to expand
            // the currently-empty current list.
            desc.setReferencedProjects(new IProject[] { refProject });

            project.setDescription(desc, IResource.KEEP_HISTORY, new SubProgressMonitor(monitor, 10));

            IClasspathEntry entry = JavaCore.newProjectEntry(refProject.getFullPath(), //path
                    new IAccessRule[0], //accessRules
                    false, //combineAccessRules
                    new IClasspathAttribute[0], //extraAttributes
                    false //isExported

            );
            ProjectHelper.addEntryToClasspath(javaProject, entry);
        }
    }

    if (isAndroidProject) {
        Sdk.getCurrent().initProject(project, target);
    }

    // Fix the project to make sure all properties are as expected.
    // Necessary for existing projects and good for new ones to.
    ProjectHelper.fixProject(project);

    Boolean isLibraryProject = (Boolean) parameters.get(PARAM_IS_LIBRARY);
    if (isLibraryProject != null && isLibraryProject.booleanValue() && Sdk.getCurrent() != null
            && project.isOpen()) {
        ProjectState state = Sdk.getProjectState(project);
        if (state != null) {
            // make a working copy of the properties
            ProjectPropertiesWorkingCopy properties = state.getProperties().makeWorkingCopy();

            properties.setProperty(PROPERTY_LIBRARY, Boolean.TRUE.toString());
            try {
                properties.save();
                IResource projectProp = project.findMember(FN_PROJECT_PROPERTIES);
                if (projectProp != null) {
                    projectProp.refreshLocal(DEPTH_ZERO, new NullProgressMonitor());
                }
            } catch (Exception e) {
                String msg = String.format("Failed to save %1$s for project %2$s",
                        SdkConstants.FN_PROJECT_PROPERTIES, project.getName());
                AdtPlugin.log(e, msg);
            }
        }
    }

    return project;
}

From source file:com.android.ide.eclipse.adt.wizards.newproject.NewProjectWizard.java

License:Open Source License

/**
 * Creates the actual project, sets its nature and adds the required folders
 * and files to it. This is run asynchronously in a different thread.
 *
 * @param project The project to create.
 * @param description A description of the project.
 * @param monitor An existing monitor.//from  ww w.  ja v a 2  s  .  co m
 * @param parameters Template parameters.
 * @param stringDictionary String definition.
 * @throws InvocationTargetException to wrap any unmanaged exception and
 *         return it to the calling thread. The method can fail if it fails
 *         to create or modify the project or if it is canceled by the user.
 */
private void createProjectAsync(IProject project, IProjectDescription description, IProgressMonitor monitor,
        Map<String, Object> parameters, Map<String, String> stringDictionary) throws InvocationTargetException {
    monitor.beginTask("Create Android Project", 100);
    try {
        // Create project and open it
        project.create(description, new SubProgressMonitor(monitor, 10));
        if (monitor.isCanceled())
            throw new OperationCanceledException();
        project.open(IResource.BACKGROUND_REFRESH, new SubProgressMonitor(monitor, 10));

        // Add the Java and android nature to the project
        AndroidNature.setupProjectNatures(project, monitor);

        // Create folders in the project if they don't already exist
        addDefaultDirectories(project, AndroidConstants.WS_ROOT, DEFAULT_DIRECTORIES, monitor);
        String[] sourceFolders = new String[] { (String) parameters.get(PARAM_SRC_FOLDER), GEN_SRC_DIRECTORY };
        addDefaultDirectories(project, AndroidConstants.WS_ROOT, sourceFolders, monitor);

        // Create the resource folders in the project if they don't already exist.
        addDefaultDirectories(project, RES_DIRECTORY, RES_DIRECTORIES, monitor);

        // Setup class path: mark folders as source folders
        IJavaProject javaProject = JavaCore.create(project);
        for (String sourceFolder : sourceFolders) {
            setupSourceFolder(javaProject, sourceFolder, monitor);
        }

        // Mark the gen source folder as derived
        IFolder genSrcFolder = project.getFolder(AndroidConstants.WS_ROOT + GEN_SRC_DIRECTORY);
        if (genSrcFolder.exists()) {
            genSrcFolder.setDerived(true);
        }

        if (((Boolean) parameters.get(PARAM_IS_NEW_PROJECT)).booleanValue()) {
            // Create files in the project if they don't already exist
            addManifest(project, parameters, stringDictionary, monitor);

            // add the default app icon
            addIcon(project, monitor);

            // Create the default package components
            addSampleCode(project, sourceFolders[0], parameters, stringDictionary, monitor);

            // add the string definition file if needed
            if (stringDictionary.size() > 0) {
                addStringDictionaryFile(project, stringDictionary, monitor);
            }

            // Set output location
            javaProject.setOutputLocation(project.getFolder(BIN_DIRECTORY).getFullPath(), monitor);
        }

        Sdk.getCurrent().setProject(project, (IAndroidTarget) parameters.get(PARAM_SDK_TARGET),
                null /* apkConfigMap*/);

        // Fix the project to make sure all properties are as expected.
        // Necessary for existing projects and good for new ones to.
        ProjectHelper.fixProject(project);

    } catch (CoreException e) {
        throw new InvocationTargetException(e);
    } catch (IOException e) {
        throw new InvocationTargetException(e);
    } finally {
        monitor.done();
    }
}

From source file:com.android.ide.eclipse.auidt.internal.build.builders.ResourceManagerBuilder.java

License:Open Source License

@SuppressWarnings("unchecked")
@Override//from  w  w w .  ja v  a  2s . c o  m
protected IProject[] build(int kind, Map args, IProgressMonitor monitor) throws CoreException {
    // Get the project.
    final IProject project = getProject();
    IJavaProject javaProject = JavaCore.create(project);

    // Clear the project of the generic markers
    removeMarkersFromContainer(project, AdtConstants.MARKER_ADT);

    // check for existing target marker, in which case we abort.
    // (this means: no SDK, no target, or unresolvable target.)
    try {
        abortOnBadSetup(javaProject);
    } catch (AbortBuildException e) {
        return null;
    }

    // Check the compiler compliance level, displaying the error message
    // since this is the first builder.
    Pair<Integer, String> result = ProjectHelper.checkCompilerCompliance(project);
    String errorMessage = null;
    switch (result.getFirst().intValue()) {
    case ProjectHelper.COMPILER_COMPLIANCE_LEVEL:
        errorMessage = Messages.Requires_Compiler_Compliance_s;
        break;
    case ProjectHelper.COMPILER_COMPLIANCE_SOURCE:
        errorMessage = Messages.Requires_Source_Compatibility_s;
        break;
    case ProjectHelper.COMPILER_COMPLIANCE_CODEGEN_TARGET:
        errorMessage = Messages.Requires_Class_Compatibility_s;
        break;
    }

    if (errorMessage != null) {
        errorMessage = String.format(errorMessage,
                result.getSecond() == null ? "(no value)" : result.getSecond());

        markProject(AdtConstants.MARKER_ADT, errorMessage, IMarker.SEVERITY_ERROR);
        AdtPlugin.printErrorToConsole(project, errorMessage);

        return null;
    }

    // Check that the SDK directory has been setup.
    String osSdkFolder = AdtPlugin.getOsSdkFolder();

    if (osSdkFolder == null || osSdkFolder.length() == 0) {
        AdtPlugin.printErrorToConsole(project, Messages.No_SDK_Setup_Error);
        markProject(AdtConstants.MARKER_ADT, Messages.No_SDK_Setup_Error, IMarker.SEVERITY_ERROR);

        return null;
    }

    // check the project has a target
    IAndroidTarget projectTarget = Sdk.getCurrent().getTarget(project);
    if (projectTarget == null) {
        // no target. marker has been set by the container initializer: exit silently.
        return null;
    }

    // check the 'gen' source folder is present
    boolean hasGenSrcFolder = false; // whether the project has a 'gen' source folder setup

    IClasspathEntry[] classpaths = javaProject.readRawClasspath();
    if (classpaths != null) {
        for (IClasspathEntry e : classpaths) {
            if (e.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
                IPath path = e.getPath();
                if (path.segmentCount() == 2 && path.segment(1).equals(SdkConstants.FD_GEN_SOURCES)) {
                    hasGenSrcFolder = true;
                    break;
                }
            }
        }
    }

    boolean genFolderPresent = false; // whether the gen folder actually exists
    IResource resource = project.findMember(SdkConstants.FD_GEN_SOURCES);
    genFolderPresent = resource != null && resource.exists();

    if (hasGenSrcFolder == false && genFolderPresent) {
        // No source folder setup for 'gen' in the project, but there's already a
        // 'gen' resource (file or folder).
        String message;
        if (resource.getType() == IResource.FOLDER) {
            // folder exists already! This is an error. If the folder had been created
            // by the NewProjectWizard, it'd be a source folder.
            message = String.format(
                    "%1$s already exists but is not a source folder. Convert to a source folder or rename it.",
                    resource.getFullPath().toString());
        } else {
            // resource exists but is not a folder.
            message = String.format(
                    "Resource %1$s is in the way. ADT needs a source folder called 'gen' to work. Rename or delete resource.",
                    resource.getFullPath().toString());
        }

        AdtPlugin.printErrorToConsole(project, message);
        markProject(AdtConstants.MARKER_ADT, message, IMarker.SEVERITY_ERROR);

        return null;
    } else if (hasGenSrcFolder == false || genFolderPresent == false) {
        // either there is no 'gen' source folder in the project (older SDK),
        // or the folder does not exist (was deleted, or was a fresh svn checkout maybe.)

        // In case we are migrating from an older SDK, we go through the current source
        // folders and delete the generated Java files.
        List<IPath> sourceFolders = BaseProjectHelper.getSourceClasspaths(javaProject);
        IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
        for (IPath path : sourceFolders) {
            IResource member = root.findMember(path);
            if (member != null) {
                removeDerivedResources(member, monitor);
            }
        }

        // create the new source folder, if needed
        IFolder genFolder = project.getFolder(SdkConstants.FD_GEN_SOURCES);
        if (genFolderPresent == false) {
            AdtPlugin.printBuildToConsole(BuildVerbosity.VERBOSE, project,
                    "Creating 'gen' source folder for generated Java files");
            genFolder.create(true /* force */, true /* local */, new SubProgressMonitor(monitor, 10));
        }

        // add it to the source folder list, if needed only (or it will throw)
        if (hasGenSrcFolder == false) {
            IClasspathEntry[] entries = javaProject.getRawClasspath();
            entries = ProjectHelper.addEntryToClasspath(entries,
                    JavaCore.newSourceEntry(genFolder.getFullPath()));
            javaProject.setRawClasspath(entries, new SubProgressMonitor(monitor, 10));
        }

        // refresh specifically the gen folder first, as it may break the build
        // if it doesn't arrive in time then refresh the whole project as usual.
        genFolder.refreshLocal(IResource.DEPTH_ZERO, new SubProgressMonitor(monitor, 10));
        project.refreshLocal(IResource.DEPTH_INFINITE, new SubProgressMonitor(monitor, 10));

        // it seems like doing this fails to properly rebuild the project. the Java builder
        // running right after this builder will not see the gen folder, and will not be
        // restarted after this build. Therefore in this particular case, we start another
        // build asynchronously so that it's rebuilt after this build.
        launchJob(new Job("rebuild") {
            @Override
            protected IStatus run(IProgressMonitor m) {
                try {
                    project.build(IncrementalProjectBuilder.INCREMENTAL_BUILD, m);
                    return Status.OK_STATUS;
                } catch (CoreException e) {
                    return e.getStatus();
                }
            }
        });

    }

    // convert older projects which use bin as the eclipse output folder into projects
    // using bin/classes
    IFolder androidOutput = BaseProjectHelper.getAndroidOutputFolder(project);
    IFolder javaOutput = BaseProjectHelper.getJavaOutputFolder(project);
    if (androidOutput.exists() == false || javaOutput == null
            || javaOutput.getParent().equals(androidOutput) == false) {
        // get what we want as the new java output.
        IFolder newJavaOutput = androidOutput.getFolder(SdkConstants.FD_CLASSES_OUTPUT);

        if (androidOutput.exists() == false) {
            androidOutput.create(true /*force*/, true /*local*/, monitor);
        }

        if (newJavaOutput.exists() == false) {
            newJavaOutput.create(true /*force*/, true /*local*/, monitor);
        }

        // set the java output to this project.
        javaProject.setOutputLocation(newJavaOutput.getFullPath(), monitor);

        // need to do a full build. Can't build while we're already building, so launch a
        // job to build it right after this build
        launchJob(new Job("rebuild") {
            @Override
            protected IStatus run(IProgressMonitor jobMonitor) {
                try {
                    project.build(IncrementalProjectBuilder.CLEAN_BUILD, jobMonitor);
                    return Status.OK_STATUS;
                } catch (CoreException e) {
                    return e.getStatus();
                }
            }
        });
    }

    // check that we have bin/res/
    IFolder binResFolder = androidOutput.getFolder(SdkConstants.FD_RESOURCES);
    if (binResFolder.exists() == false) {
        binResFolder.create(true /* force */, true /* local */, new SubProgressMonitor(monitor, 10));
        project.refreshLocal(IResource.DEPTH_ONE, new SubProgressMonitor(monitor, 10));
    }

    // Check the preference to be sure we are supposed to refresh
    // the folders.
    if (AdtPrefs.getPrefs().getBuildForceResResfresh()) {
        AdtPlugin.printBuildToConsole(BuildVerbosity.VERBOSE, project, Messages.Refreshing_Res);

        // refresh the res folder.
        IFolder resFolder = project.getFolder(AdtConstants.WS_RESOURCES);
        resFolder.refreshLocal(IResource.DEPTH_INFINITE, monitor);

        // Also refresh the assets folder to make sure the ApkBuilder
        // will now it's changed and will force a new resource packaging.
        IFolder assetsFolder = project.getFolder(AdtConstants.WS_ASSETS);
        assetsFolder.refreshLocal(IResource.DEPTH_INFINITE, monitor);
    }

    return null;
}

From source file:com.android.ide.eclipse.auidt.internal.wizards.newproject.NewProjectCreator.java

License:Open Source License

/**
 * Creates the actual project, sets its nature and adds the required folders
 * and files to it. This is run asynchronously in a different thread.
 *
 * @param monitor An existing monitor.//  w ww  . j  a  va  2 s  . c om
 * @param project The project to create.
 * @param description A description of the project.
 * @param parameters Template parameters.
 * @param dictionary String definition.
 * @return The project newly created
 * @throws StreamException
 */
private IProject createEclipseProject(IProgressMonitor monitor, IProject project,
        IProjectDescription description, Map<String, Object> parameters, Map<String, String> dictionary,
        ProjectPopulator projectPopulator) throws CoreException, IOException, StreamException {

    // get the project target
    IAndroidTarget target = (IAndroidTarget) parameters.get(PARAM_SDK_TARGET);
    boolean legacy = target.getVersion().getApiLevel() < 4;

    // Create project and open it
    project.create(description, new SubProgressMonitor(monitor, 10));
    if (monitor.isCanceled())
        throw new OperationCanceledException();

    project.open(IResource.BACKGROUND_REFRESH, new SubProgressMonitor(monitor, 10));

    // Add the Java and android nature to the project
    AndroidNature.setupProjectNatures(project, monitor);

    // Create folders in the project if they don't already exist
    addDefaultDirectories(project, AdtConstants.WS_ROOT, DEFAULT_DIRECTORIES, monitor);
    String[] sourceFolders = new String[] { (String) parameters.get(PARAM_SRC_FOLDER), GEN_SRC_DIRECTORY };
    addDefaultDirectories(project, AdtConstants.WS_ROOT, sourceFolders, monitor);

    // Create the resource folders in the project if they don't already exist.
    if (legacy) {
        addDefaultDirectories(project, RES_DIRECTORY, RES_DIRECTORIES, monitor);
    } else {
        addDefaultDirectories(project, RES_DIRECTORY, RES_DENSITY_ENABLED_DIRECTORIES, monitor);
    }

    if (projectPopulator != null) {
        try {
            projectPopulator.populate(project);
        } catch (InvocationTargetException ite) {
            AdtPlugin.log(ite, null);
        }
    }

    // Setup class path: mark folders as source folders
    IJavaProject javaProject = JavaCore.create(project);
    setupSourceFolders(javaProject, sourceFolders, monitor);

    if (((Boolean) parameters.get(PARAM_IS_NEW_PROJECT)).booleanValue()) {
        // Create files in the project if they don't already exist
        addManifest(project, parameters, dictionary, monitor);

        // add the default app icon
        addIcon(project, legacy, monitor);

        // Create the default package components
        addSampleCode(project, sourceFolders[0], parameters, dictionary, monitor);

        // add the string definition file if needed
        if (dictionary.size() > 0) {
            addStringDictionaryFile(project, dictionary, monitor);
        }

        // add the default proguard config
        File libFolder = new File((String) parameters.get(PARAM_SDK_TOOLS_DIR), SdkConstants.FD_LIB);
        addLocalFile(project, new File(libFolder, SdkConstants.FN_PROJECT_PROGUARD_FILE),
                // Write ProGuard config files with the extension .pro which
                // is what is used in the ProGuard documentation and samples
                SdkConstants.FN_PROJECT_PROGUARD_FILE, monitor);

        // Set output location
        javaProject.setOutputLocation(project.getFolder(BIN_CLASSES_DIRECTORY).getFullPath(), monitor);
    }

    File sampleDir = (File) parameters.get(PARAM_SAMPLE_LOCATION);
    if (sampleDir != null) {
        // Copy project
        copySampleCode(project, sampleDir, parameters, dictionary, monitor);
    }

    // Create the reference to the target project
    if (parameters.containsKey(PARAM_REFERENCE_PROJECT)) {
        IProject refProject = (IProject) parameters.get(PARAM_REFERENCE_PROJECT);
        if (refProject != null) {
            IProjectDescription desc = project.getDescription();

            // Add out reference to the existing project reference.
            // We just created a project with no references so we don't need to expand
            // the currently-empty current list.
            desc.setReferencedProjects(new IProject[] { refProject });

            project.setDescription(desc, IResource.KEEP_HISTORY, new SubProgressMonitor(monitor, 10));

            IClasspathEntry entry = JavaCore.newProjectEntry(refProject.getFullPath(), //path
                    new IAccessRule[0], //accessRules
                    false, //combineAccessRules
                    new IClasspathAttribute[0], //extraAttributes
                    false //isExported

            );
            ProjectHelper.addEntryToClasspath(javaProject, entry);
        }
    }

    Sdk.getCurrent().initProject(project, target);

    // Fix the project to make sure all properties are as expected.
    // Necessary for existing projects and good for new ones to.
    ProjectHelper.fixProject(project);

    Boolean isLibraryProject = (Boolean) parameters.get(PARAM_IS_LIBRARY);
    if (isLibraryProject != null && isLibraryProject.booleanValue() && Sdk.getCurrent() != null
            && project.isOpen()) {
        ProjectState state = Sdk.getProjectState(project);
        if (state != null) {
            // make a working copy of the properties
            ProjectPropertiesWorkingCopy properties = state.getProperties().makeWorkingCopy();

            properties.setProperty(PROPERTY_LIBRARY, Boolean.TRUE.toString());
            try {
                properties.save();
                IResource projectProp = project.findMember(FN_PROJECT_PROPERTIES);
                if (projectProp != null) {
                    projectProp.refreshLocal(DEPTH_ZERO, new NullProgressMonitor());
                }
            } catch (Exception e) {
                String msg = String.format("Failed to save %1$s for project %2$s",
                        SdkConstants.FN_PROJECT_PROPERTIES, project.getName());
                AdtPlugin.log(e, msg);
            }
        }
    }

    return project;
}