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

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

Introduction

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

Prototype

IClasspathEntry[] getRawClasspath() throws JavaModelException;

Source Link

Document

Returns the raw classpath for the project, as a list of classpath entries.

Usage

From source file:com.amazonaws.eclipse.sdk.ui.classpath.AwsSdkClasspathUtils.java

License:Open Source License

/**
 * Modifies the classpath of the specified Java project to remove the classpath container
 * for the AWS SDK for Java.//from   w w  w .j  a  v a2  s . c o m
 * 
 * If the specified SDK installation is not already present on the project's classpath,
 * nothing is done, and no error is returned.
 * 
 * @param javaProject The Java project to modify.
 * @param sdkInstall The AWS SDK for Java installation to remove.
 */
public static void removeAwsSdkFromProjectClasspath(IJavaProject javaProject, SdkInstall sdkInstall) {
    try {
        AwsClasspathContainer classpathContainer = new AwsClasspathContainer(sdkInstall);

        IClasspathEntry[] rawClasspath = javaProject.getRawClasspath();
        List<IClasspathEntry> newList = new ArrayList<IClasspathEntry>();
        for (IClasspathEntry entry : rawClasspath) {
            if (entry.getPath().equals(classpathContainer.getPath()) == false) {
                newList.add(entry);
            }
        }

        javaProject.setRawClasspath(newList.toArray(new IClasspathEntry[newList.size()]), null);
    } catch (JavaModelException e) {
        e.printStackTrace();
    }
}

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

License:Open Source License

@SuppressWarnings("unchecked")
@Override/* ww w.j  a v a2  s  . c  o  m*/
protected IProject[] build(int kind, Map args, IProgressMonitor monitor) throws CoreException {
    // Get the project.
    IProject project = getProject();

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

    // check for existing target marker, in which case we abort.
    // (this means: no SDK, no target, or unresolvable target.)
    abortOnBadSetup(project);

    // Check the compiler compliance level, displaying the error message
    // since this is the first builder.
    int res = ProjectHelper.checkCompilerCompliance(project);
    String errorMessage = null;
    switch (res) {
    case ProjectHelper.COMPILER_COMPLIANCE_LEVEL:
        errorMessage = Messages.Requires_Compiler_Compliance_5;
    case ProjectHelper.COMPILER_COMPLIANCE_SOURCE:
        errorMessage = Messages.Requires_Source_Compatibility_5;
    case ProjectHelper.COMPILER_COMPLIANCE_CODEGEN_TARGET:
        errorMessage = Messages.Requires_Class_Compatibility_5;
    }

    if (errorMessage != null) {
        BaseProjectHelper.addMarker(project, AdtConstants.MARKER_ADT, errorMessage, IMarker.SEVERITY_ERROR);
        AdtPlugin.printErrorToConsole(project, errorMessage);

        // interrupt the build. The next builders will not run.
        stopBuild(errorMessage);
    }

    // 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);

        // This interrupts the build. The next builders will not run.
        stopBuild(Messages.No_SDK_Setup_Error);
    }

    // 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.
        // This interrupts the build. The next builders will not run.
        stopBuild("Project has no target");
    }

    // check the 'gen' source folder is present
    boolean hasGenSrcFolder = false; // whether the project has a 'gen' source folder setup
    IJavaProject javaProject = JavaCore.create(project);

    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);

        // This interrupts the build. The next builders will not run.
        stopBuild(message);
    } 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.
        ArrayList<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(AdtConstants.BUILD_VERBOSE, project,
                    "Creating 'gen' source folder for generated Java files");
            genFolder.create(true /* force */, true /* local */, new SubProgressMonitor(monitor, 10));
            genFolder.setDerived(true);
        }

        // 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 the whole project
        project.refreshLocal(IResource.DEPTH_INFINITE, new SubProgressMonitor(monitor, 10));
    }

    // Check the preference to be sure we are supposed to refresh
    // the folders.
    if (AdtPlugin.getAutoResRefresh()) {
        AdtPlugin.printBuildToConsole(AdtConstants.BUILD_VERBOSE, project, Messages.Refreshing_Res);

        // refresh the res folder.
        IFolder resFolder = project.getFolder(AndroidConstants.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(AndroidConstants.WS_ASSETS);
        assetsFolder.refreshLocal(IResource.DEPTH_INFINITE, monitor);
    }

    return null;
}

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

License:Open Source License

@SuppressWarnings("unchecked")
@Override/* ww  w .  j  av a  2s .  c  om*/
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.lint.EclipseLintClient.java

License:Open Source License

@Override
@NonNull/*  ww  w.  j ava  2s . c  om*/
protected ClassPathInfo getClassPath(@NonNull Project project) {
    ClassPathInfo info;
    if (mProjectInfo == null) {
        mProjectInfo = Maps.newHashMap();
        info = null;
    } else {
        info = mProjectInfo.get(project);
    }

    if (info == null) {
        List<File> sources = null;
        List<File> classes = null;
        List<File> libraries = null;

        IProject p = getProject(project);
        if (p != null) {
            try {
                IJavaProject javaProject = BaseProjectHelper.getJavaProject(p);

                // Output path
                File file = workspacePathToFile(javaProject.getOutputLocation());
                classes = Collections.singletonList(file);

                // Source path
                IClasspathEntry[] entries = javaProject.getRawClasspath();
                sources = new ArrayList<File>(entries.length);
                libraries = new ArrayList<File>(entries.length);
                for (int i = 0; i < entries.length; i++) {
                    IClasspathEntry entry = entries[i];
                    int kind = entry.getEntryKind();

                    if (kind == IClasspathEntry.CPE_VARIABLE) {
                        entry = JavaCore.getResolvedClasspathEntry(entry);
                        if (entry == null) {
                            // It's possible that the variable is no longer valid; ignore
                            continue;
                        }
                        kind = entry.getEntryKind();
                    }

                    if (kind == IClasspathEntry.CPE_SOURCE) {
                        sources.add(workspacePathToFile(entry.getPath()));
                    } else if (kind == IClasspathEntry.CPE_LIBRARY) {
                        libraries.add(entry.getPath().toFile());
                    }
                    // Note that we ignore IClasspathEntry.CPE_CONTAINER:
                    // Normal Android Eclipse projects supply both
                    //   AdtConstants.CONTAINER_FRAMEWORK
                    // and
                    //   AdtConstants.CONTAINER_LIBRARIES
                    // here. We ignore the framework classes for obvious reasons,
                    // but we also ignore the library container because lint will
                    // process the libraries differently. When Eclipse builds a
                    // project, it gets the .jar output of the library projects
                    // from this container, which means it doesn't have to process
                    // the library sources. Lint on the other hand wants to process
                    // the source code, so instead it actually looks at the
                    // project.properties file to find the libraries, and then it
                    // iterates over all the library projects in turn and analyzes
                    // those separately (but passing the main project for context,
                    // such that the including project's manifest declarations
                    // are used for data like minSdkVersion level).
                    //
                    // Note that this container will also contain *other*
                    // libraries (Java libraries, not library projects) that we
                    // *should* include. However, we can't distinguish these
                    // class path entries from the library project jars,
                    // so instead of looking at these, we simply listFiles() in
                    // the libs/ folder after processing the classpath info
                }

                // Add in libraries
                File libs = new File(project.getDir(), FD_NATIVE_LIBS);
                if (libs.isDirectory()) {
                    File[] jars = libs.listFiles();
                    if (jars != null) {
                        for (File jar : jars) {
                            if (SdkUtils.endsWith(jar.getPath(), DOT_JAR)) {
                                libraries.add(jar);
                            }
                        }
                    }
                }
            } catch (CoreException e) {
                AdtPlugin.log(e, null);
            }
        }

        if (sources == null) {
            sources = super.getClassPath(project).getSourceFolders();
        }
        if (classes == null) {
            classes = super.getClassPath(project).getClassFolders();
        }
        if (libraries == null) {
            libraries = super.getClassPath(project).getLibraries();
        }

        // No test folders in Eclipse:
        // https://bugs.eclipse.org/bugs/show_bug.cgi?id=224708
        List<File> tests = Collections.emptyList();

        info = new ClassPathInfo(sources, classes, libraries, tests);
        mProjectInfo.put(project, info);
    }

    return info;
}

From source file:com.android.ide.eclipse.adt.internal.project.AndroidClasspathContainerInitializer.java

License:Open Source License

private static void rebindClasspathEntries(IJavaModel model, IPath containerPath) throws JavaModelException {
    ArrayList<IJavaProject> affectedProjects = new ArrayList<IJavaProject>();

    IJavaProject[] projects = model.getJavaProjects();
    for (int i = 0; i < projects.length; i++) {
        IJavaProject project = projects[i];
        IClasspathEntry[] entries = project.getRawClasspath();
        for (int k = 0; k < entries.length; k++) {
            IClasspathEntry curr = entries[k];
            if (curr.getEntryKind() == IClasspathEntry.CPE_CONTAINER && containerPath.equals(curr.getPath())) {
                affectedProjects.add(project);
            }// ww w  . java 2s .c om
        }
    }
    if (!affectedProjects.isEmpty()) {
        IJavaProject[] affected = affectedProjects.toArray(new IJavaProject[affectedProjects.size()]);
        updateProjects(affected);
    }
}

From source file:com.android.ide.eclipse.adt.internal.project.LibraryClasspathContainerInitializer.java

License:Open Source License

private static IClasspathContainer allocateContainer(IJavaProject javaProject, List<IClasspathEntry> entries,
        IPath id, String description) {

    if (AdtPlugin.getDefault() == null) { // This is totally weird, but I've seen it happen!
        return null;
    }//from w ww  . j  av  a2 s .  c om

    // First check that the project has a library-type container.
    try {
        IClasspathEntry[] rawClasspath = javaProject.getRawClasspath();
        final IClasspathEntry[] oldRawClasspath = rawClasspath;

        boolean foundContainer = false;
        for (IClasspathEntry entry : rawClasspath) {
            // get the entry and kind
            final int kind = entry.getEntryKind();

            if (kind == IClasspathEntry.CPE_CONTAINER) {
                String path = entry.getPath().toString();
                String idString = id.toString();
                if (idString.equals(path)) {
                    foundContainer = true;
                    break;
                }
            }
        }

        // if there isn't any, add it.
        if (foundContainer == false) {
            // add the android container to the array
            rawClasspath = ProjectHelper.addEntryToClasspath(rawClasspath,
                    JavaCore.newContainerEntry(id, true /*isExported*/));
        }

        // set the new list of entries to the project
        if (rawClasspath != oldRawClasspath) {
            javaProject.setRawClasspath(rawClasspath, new NullProgressMonitor());
        }
    } catch (JavaModelException e) {
        // This really shouldn't happen, but if it does, simply return null (the calling
        // method will fails as well)
        return null;
    }

    return new AndroidClasspathContainer(entries.toArray(new IClasspathEntry[entries.size()]), id, description,
            IClasspathContainer.K_APPLICATION);
}

From source file:com.android.ide.eclipse.adt.internal.project.ProjectHelper.java

License:Open Source License

/**
 * Adds the corresponding source folder to the project's class path entries.
 * This method does not check whether the entry is already defined in the project.
 *
 * @param javaProject The java project of which path entries to update.
 * @param newEntry The new class path entry to add.
 * @throws JavaModelException/*from  w  w  w.j  a v  a2s  .c o m*/
 */
public static void addEntryToClasspath(IJavaProject javaProject, IClasspathEntry newEntry)
        throws JavaModelException {

    IClasspathEntry[] entries = javaProject.getRawClasspath();
    entries = addEntryToClasspath(entries, newEntry);
    javaProject.setRawClasspath(entries, new NullProgressMonitor());
}

From source file:com.android.ide.eclipse.adt.internal.project.ProjectHelper.java

License:Open Source License

/**
 * Checks whether the given class path entry is already defined in the project.
 *
 * @param javaProject The java project of which path entries to check.
 * @param newEntry The parent source folder to remove.
 * @return True if the class path entry is already defined.
 * @throws JavaModelException/*w w w.  j ava  2 s  .c  om*/
 */
public static boolean isEntryInClasspath(IJavaProject javaProject, IClasspathEntry newEntry)
        throws JavaModelException {

    IClasspathEntry[] entries = javaProject.getRawClasspath();
    for (IClasspathEntry entry : entries) {
        if (entry.equals(newEntry)) {
            return true;
        }
    }
    return false;
}

From source file:com.android.ide.eclipse.adt.internal.project.ProjectHelper.java

License:Open Source License

/**
 * Fix the project classpath entries. The method ensures that:
 * <ul>/*from ww  w. j a  va2  s.c o  m*/
 * <li>The project does not reference any old android.zip/android.jar archive.</li>
 * <li>The project does not use its output folder as a sourc folder.</li>
 * <li>The project does not reference a desktop JRE</li>
 * <li>The project references the AndroidClasspathContainer.
 * </ul>
 * @param javaProject The project to fix.
 * @throws JavaModelException
 */
public static void fixProjectClasspathEntries(IJavaProject javaProject) throws JavaModelException {

    // get the project classpath
    IClasspathEntry[] entries = javaProject.getRawClasspath();
    IClasspathEntry[] oldEntries = entries;
    boolean forceRewriteOfCPE = false;

    // check if the JRE is set as library
    int jreIndex = ProjectHelper.findClasspathEntryByPath(entries, JavaRuntime.JRE_CONTAINER,
            IClasspathEntry.CPE_CONTAINER);
    if (jreIndex != -1) {
        // the project has a JRE included, we remove it
        entries = ProjectHelper.removeEntryFromClasspath(entries, jreIndex);
    }

    // get the output folder
    IPath outputFolder = javaProject.getOutputLocation();

    boolean foundFrameworkContainer = false;
    IClasspathEntry foundLibrariesContainer = null;
    IClasspathEntry foundDependenciesContainer = null;

    for (int i = 0; i < entries.length;) {
        // get the entry and kind
        IClasspathEntry entry = entries[i];
        int kind = entry.getEntryKind();

        if (kind == IClasspathEntry.CPE_SOURCE) {
            IPath path = entry.getPath();

            if (path.equals(outputFolder)) {
                entries = ProjectHelper.removeEntryFromClasspath(entries, i);

                // continue, to skip the i++;
                continue;
            }
        } else if (kind == IClasspathEntry.CPE_CONTAINER) {
            String path = entry.getPath().toString();
            if (AdtConstants.CONTAINER_FRAMEWORK.equals(path)) {
                foundFrameworkContainer = true;
            } else if (AdtConstants.CONTAINER_PRIVATE_LIBRARIES.equals(path)) {
                foundLibrariesContainer = entry;
            } else if (AdtConstants.CONTAINER_DEPENDENCIES.equals(path)) {
                foundDependenciesContainer = entry;
            }
        }

        i++;
    }

    // look to see if we have the m2eclipse nature
    boolean m2eNature = false;
    try {
        m2eNature = javaProject.getProject().hasNature("org.eclipse.m2e.core.maven2Nature");
    } catch (CoreException e) {
        AdtPlugin.log(e, "Failed to query project %s for m2e nature", javaProject.getProject().getName());
    }

    // if the framework container is not there, we add it
    if (!foundFrameworkContainer) {
        // add the android container to the array
        entries = ProjectHelper.addEntryToClasspath(entries,
                JavaCore.newContainerEntry(new Path(AdtConstants.CONTAINER_FRAMEWORK)));
    }

    // same thing for the library container
    if (foundLibrariesContainer == null) {
        // add the exported libraries android container to the array
        entries = ProjectHelper.addEntryToClasspath(entries,
                JavaCore.newContainerEntry(new Path(AdtConstants.CONTAINER_PRIVATE_LIBRARIES), true));
    } else if (!m2eNature && !foundLibrariesContainer.isExported()) {
        // the container is present but it's not exported and since there's no m2e nature
        // we do want it to be exported.
        // keep all the other parameters the same.
        entries = ProjectHelper.replaceEntryInClasspath(entries,
                JavaCore.newContainerEntry(new Path(AdtConstants.CONTAINER_PRIVATE_LIBRARIES),
                        foundLibrariesContainer.getAccessRules(), foundLibrariesContainer.getExtraAttributes(),
                        true));
        forceRewriteOfCPE = true;
    }

    // same thing for the dependencies container
    if (foundDependenciesContainer == null) {
        // add the android dependencies container to the array
        entries = ProjectHelper.addEntryToClasspath(entries,
                JavaCore.newContainerEntry(new Path(AdtConstants.CONTAINER_DEPENDENCIES), true));
    } else if (!m2eNature && !foundDependenciesContainer.isExported()) {
        // the container is present but it's not exported and since there's no m2e nature
        // we do want it to be exported.
        // keep all the other parameters the same.
        entries = ProjectHelper.replaceEntryInClasspath(entries,
                JavaCore.newContainerEntry(new Path(AdtConstants.CONTAINER_DEPENDENCIES),
                        foundDependenciesContainer.getAccessRules(),
                        foundDependenciesContainer.getExtraAttributes(), true));
        forceRewriteOfCPE = true;
    }

    // set the new list of entries to the project
    if (entries != oldEntries || forceRewriteOfCPE) {
        javaProject.setRawClasspath(entries, new NullProgressMonitor());
    }

    // If needed, check and fix compiler compliance and source compatibility
    ProjectHelper.checkAndFixCompilerCompliance(javaProject);
}

From source file:com.android.ide.eclipse.adt.internal.project.ProjectHelperTest.java

License:Open Source License

public final void testFixProjectClasspathEntriesFromOldContainer() throws Exception {
    // create a project with a path to an android .zip
    IJavaProject javaProject = Mocks.createProject(
            new IClasspathEntry[] { Mocks.createClasspathEntry(new Path("Project/src"), //$NON-NLS-1$
                    IClasspathEntry.CPE_SOURCE),
                    Mocks.createClasspathEntry(new Path(OLD_CONTAINER_ID), IClasspathEntry.CPE_CONTAINER), },
            new Path("Project/bin"));

    ProjectHelper.fixProjectClasspathEntries(javaProject);

    IClasspathEntry[] fixedEntries = javaProject.getRawClasspath();
    assertEquals(3, fixedEntries.length);
    assertEquals("Project/src", fixedEntries[0].getPath().toString());
    assertEquals(OLD_CONTAINER_ID, fixedEntries[1].getPath().toString());
    assertEquals(CONTAINER_ID, fixedEntries[2].getPath().toString());
}