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.android.ide.eclipse.adt.internal.wizards.exportgradle.ProjectSetupBuilder.java

License:Open Source License

@NonNull
private static List<IJavaProject> getReferencedProjects(IJavaProject javaProject)
        throws JavaModelException, InternalException {

    List<IJavaProject> projects = Lists.newArrayList();

    IClasspathEntry entries[] = javaProject.getRawClasspath();
    for (IClasspathEntry classpathEntry : entries) {
        if (classpathEntry.getContentKind() == IPackageFragmentRoot.K_SOURCE
                && classpathEntry.getEntryKind() == IClasspathEntry.CPE_PROJECT) {
            // found required project on build path
            String subProjectRoot = classpathEntry.getPath().toString();
            IJavaProject subProject = getJavaProject(subProjectRoot);
            // is project available in workspace?
            if (subProject != null) {
                projects.add(subProject);
            } else {
                throw new InternalException(String.format(
                        "Project '%s' is missing project dependency '%s' in Eclipse workspace.\n"
                                + "Make sure all dependencies are opened.",
                        javaProject.getProject().getName(), classpathEntry.getPath().toString()));
            }//ww  w . j a va2  s  .co m
        }
    }

    return projects;
}

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

License:Open Source License

/**
 * Adds the given folder to the project's class path.
 *
 * @param javaProject The Java Project to update.
 * @param sourceFolders Template Parameters.
 * @param monitor An existing monitor.// w ww  .j  av  a  2s. c  o m
 * @throws JavaModelException if the classpath could not be set.
 */
private void setupSourceFolders(IJavaProject javaProject, String[] sourceFolders, IProgressMonitor monitor)
        throws JavaModelException {
    IProject project = javaProject.getProject();

    // get the list of entries.
    IClasspathEntry[] entries = javaProject.getRawClasspath();

    // remove the project as a source folder (This is the default)
    entries = removeSourceClasspath(entries, project);

    // add the source folders.
    for (String sourceFolder : sourceFolders) {
        IFolder srcFolder = project.getFolder(sourceFolder);

        // remove it first in case.
        entries = removeSourceClasspath(entries, srcFolder);
        entries = ProjectHelper.addEntryToClasspath(entries, JavaCore.newSourceEntry(srcFolder.getFullPath()));
    }

    javaProject.setRawClasspath(entries, new SubProgressMonitor(monitor, 10));
}

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

License:Open Source License

/**
 * Fix the project classpath entries. The method ensures that:
 * <ul>//from   ww  w  .  j a v a 2 s.  co  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;

    // 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 foundContainer = false;

    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) {
            if (AndroidClasspathContainerInitializer.checkPath(entry.getPath())) {
                foundContainer = true;
            }
        }

        i++;
    }

    // if the framework container is not there, we add it
    if (foundContainer == false) {
        // add the android container to the array
        entries = ProjectHelper.addEntryToClasspath(entries,
                AndroidClasspathContainerInitializer.getContainerEntry());
    }

    // set the new list of entries to the project
    if (entries != oldEntries) {
        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.wizards.newproject.NewProjectWizard.java

License:Open Source License

/**
 * Adds the given folder to the project's class path.
 *
 * @param javaProject The Java Project to update.
 * @param sourceFolder Template Parameters.
 * @param monitor An existing monitor.//from   w w w. j a  v  a2s  .com
 * @throws JavaModelException if the classpath could not be set.
 */
private void setupSourceFolder(IJavaProject javaProject, String sourceFolder, IProgressMonitor monitor)
        throws JavaModelException {
    IProject project = javaProject.getProject();

    // Add "src" to class path
    IFolder srcFolder = project.getFolder(sourceFolder);

    IClasspathEntry[] entries = javaProject.getRawClasspath();
    entries = removeSourceClasspath(entries, srcFolder);
    entries = removeSourceClasspath(entries, srcFolder.getParent());

    entries = ProjectHelper.addEntryToClasspath(entries, JavaCore.newSourceEntry(srcFolder.getFullPath()));

    javaProject.setRawClasspath(entries, new SubProgressMonitor(monitor, 10));
}

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

License:Open Source License

@SuppressWarnings("unchecked")
@Override/*from  w  w  w. jav  a 2s .  com*/
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.lint.EclipseLintClient.java

License:Open Source License

@Override
@NonNull/*from w w w. j  a v  a2 s  .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);
                        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 (AdtUtils.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();
        }

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

    return info;
}

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

License:Open Source License

private static IClasspathContainer allocateLibraryContainer(IJavaProject javaProject) {
    final IProject iProject = javaProject.getProject();

    AdtPlugin plugin = AdtPlugin.getDefault();
    if (plugin == null) { // This is totally weird, but I've seen it happen!
        return null;
    }// ww  w  .jav a  2 s. co m

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

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

            if (kind == IClasspathEntry.CPE_CONTAINER) {
                String path = entry.getPath().toString();
                if (AdtConstants.CONTAINER_LIBRARIES.equals(path)) {
                    foundLibrariesContainer = true;
                    break;
                }
            }
        }

        // if there isn't any, add it.
        if (foundLibrariesContainer == false) {
            // add the android container to the array
            rawClasspath = ProjectHelper.addEntryToClasspath(rawClasspath, JavaCore
                    .newContainerEntry(new Path(AdtConstants.CONTAINER_LIBRARIES), 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;
    }

    // check if the project has a valid target.
    ProjectState state = Sdk.getProjectState(iProject);
    if (state == null) {
        // getProjectState should already have logged an error. Just bail out.
        return null;
    }

    /*
     * At this point we're going to gather a list of all that need to go in the
     * dependency container.
     * - Library project outputs (direct and indirect)
     * - Java project output (those can be indirectly referenced through library projects
     *   or other other Java projects)
     * - Jar files:
     *    + inside this project's libs/
     *    + inside the library projects' libs/
     *    + inside the referenced Java projects' classpath
     */

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

    IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();

    // list of java project dependencies and jar files that will be built while
    // going through the library projects.
    Set<File> jarFiles = new HashSet<File>();
    Set<IProject> refProjects = new HashSet<IProject>();

    // process all the libraries

    List<IProject> libProjects = state.getFullLibraryProjects();
    for (IProject libProject : libProjects) {
        // get the project output
        IFolder outputFolder = BaseProjectHelper.getAndroidOutputFolder(libProject);

        if (outputFolder != null) { // can happen when closing/deleting a library)
            IFile jarIFile = outputFolder.getFile(libProject.getName().toLowerCase() + AdtConstants.DOT_JAR);

            // get the source folder for the library project
            List<IPath> srcs = BaseProjectHelper.getSourceClasspaths(libProject);
            // find the first non-derived source folder.
            IPath sourceFolder = null;
            for (IPath src : srcs) {
                IFolder srcFolder = workspaceRoot.getFolder(src);
                if (srcFolder.isDerived() == false) {
                    sourceFolder = src;
                    break;
                }
            }

            // we can directly add a CPE for this jar as there's no risk of a duplicate.
            IClasspathEntry entry = JavaCore.newLibraryEntry(jarIFile.getLocation(), sourceFolder, // source attachment path
                    null, // default source attachment root path.
                    true /*isExported*/);

            entries.add(entry);

            // process all of the library project's dependencies
            getDependencyListFromClasspath(libProject, refProjects, jarFiles, true);
            // and the content of its libs folder.
            getJarListFromLibsFolder(libProject, jarFiles);
        }
    }

    // now process this projects' referenced projects only.
    processReferencedProjects(iProject, refProjects, jarFiles);
    // and the content of its libs folder
    getJarListFromLibsFolder(iProject, jarFiles);

    // annotations support for older version of android
    if (state.getTarget() != null && state.getTarget().getVersion().getApiLevel() <= 15) {
        File annotationsJar = new File(Sdk.getCurrent().getSdkLocation(), SdkConstants.FD_TOOLS + File.separator
                + SdkConstants.FD_SUPPORT + File.separator + SdkConstants.FN_ANNOTATIONS_JAR);

        jarFiles.add(annotationsJar);
    }

    // now add a classpath entry for each Java project (this is a set so dups are already
    // removed)
    for (IProject p : refProjects) {
        entries.add(JavaCore.newProjectEntry(p.getFullPath(), true /*isExported*/));
    }

    // and process the jar files list, but first sanitize it to remove dups.
    JarListSanitizer sanitizer = new JarListSanitizer(
            iProject.getFolder(SdkConstants.FD_OUTPUT).getLocation().toFile(),
            new AndroidPrintStream(iProject, null /*prefix*/, AdtPlugin.getOutStream()));

    String errorMessage = null;

    try {
        List<File> sanitizedList = sanitizer.sanitize(jarFiles);

        for (File jarFile : sanitizedList) {
            if (jarFile instanceof CPEFile) {
                CPEFile cpeFile = (CPEFile) jarFile;
                IClasspathEntry e = cpeFile.getClasspathEntry();

                entries.add(JavaCore.newLibraryEntry(e.getPath(), e.getSourceAttachmentPath(),
                        e.getSourceAttachmentRootPath(), e.getAccessRules(), e.getExtraAttributes(),
                        true /*isExported*/));
            } else {
                String jarPath = jarFile.getAbsolutePath();

                IPath sourceAttachmentPath = null;
                IClasspathAttribute javaDocAttribute = null;

                File jarProperties = new File(jarPath + DOT_PROPERTIES);
                if (jarProperties.isFile()) {
                    Properties p = new Properties();
                    InputStream is = null;
                    try {
                        p.load(is = new FileInputStream(jarProperties));

                        String value = p.getProperty(ATTR_SRC);
                        if (value != null) {
                            File srcPath = getFile(jarFile, value);

                            if (srcPath.exists()) {
                                sourceAttachmentPath = new Path(srcPath.getAbsolutePath());
                            }
                        }

                        value = p.getProperty(ATTR_DOC);
                        if (value != null) {
                            File docPath = getFile(jarFile, value);
                            if (docPath.exists()) {
                                try {
                                    javaDocAttribute = JavaCore.newClasspathAttribute(
                                            IClasspathAttribute.JAVADOC_LOCATION_ATTRIBUTE_NAME,
                                            docPath.toURI().toURL().toString());
                                } catch (MalformedURLException e) {
                                    AdtPlugin.log(e, "Failed to process 'doc' attribute for %s",
                                            jarProperties.getAbsolutePath());
                                }
                            }
                        }

                    } catch (FileNotFoundException e) {
                        // shouldn't happen since we check upfront
                    } catch (IOException e) {
                        AdtPlugin.log(e, "Failed to read %s", jarProperties.getAbsolutePath());
                    } finally {
                        if (is != null) {
                            try {
                                is.close();
                            } catch (IOException e) {
                                // ignore
                            }
                        }
                    }
                }

                if (javaDocAttribute != null) {
                    entries.add(JavaCore.newLibraryEntry(new Path(jarPath), sourceAttachmentPath,
                            null /*sourceAttachmentRootPath*/, new IAccessRule[0],
                            new IClasspathAttribute[] { javaDocAttribute }, true /*isExported*/));
                } else {
                    entries.add(JavaCore.newLibraryEntry(new Path(jarPath), sourceAttachmentPath,
                            null /*sourceAttachmentRootPath*/, true /*isExported*/));
                }
            }
        }
    } catch (DifferentLibException e) {
        errorMessage = e.getMessage();
        AdtPlugin.printErrorToConsole(iProject, (Object[]) e.getDetails());
    } catch (Sha1Exception e) {
        errorMessage = e.getMessage();
    }

    processError(iProject, errorMessage, AdtConstants.MARKER_DEPENDENCY, true /*outputToConsole*/);

    return new AndroidClasspathContainer(entries.toArray(new IClasspathEntry[entries.size()]),
            new Path(AdtConstants.CONTAINER_LIBRARIES), "Android Dependencies",
            IClasspathContainer.K_APPLICATION);
}

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

License:Open Source License

/**
 * Fix the project classpath entries. The method ensures that:
 * <ul>/* ww w. ja v a2s  . co 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;

    // 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;
    boolean foundLibrariesContainer = false;

    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;
            }
            if (AdtConstants.CONTAINER_LIBRARIES.equals(path)) {
                foundLibrariesContainer = true;
            }
        }

        i++;
    }

    // same thing for the library container
    if (foundLibrariesContainer == false) {
        // add the android container to the array
        entries = ProjectHelper.addEntryToClasspath(entries,
                JavaCore.newContainerEntry(new Path(AdtConstants.CONTAINER_LIBRARIES)));
    }

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

    // set the new list of entries to the project
    if (entries != oldEntries) {
        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.mock.Mocks.java

License:Open Source License

public static IJavaProject createProject(IClasspathEntry[] entries, IPath outputLocation) throws Exception {
    IJavaProject javaProject = createMock(IJavaProject.class);
    final Capture<IClasspathEntry[]> capturedEntries = new Capture<IClasspathEntry[]>();
    Capture<IPath> capturedOutput = new Capture<IPath>();
    capturedEntries.setValue(entries);/*from   w  w  w. ja v a 2s.co  m*/
    capturedOutput.setValue(outputLocation);

    IProject project = createProject();
    expect(javaProject.getProject()).andReturn(project).anyTimes();
    expect(javaProject.getOutputLocation()).andReturn(capturedOutput.getValue()).anyTimes();

    expect(javaProject.getRawClasspath()).andAnswer(new IAnswer<IClasspathEntry[]>() {
        @Override
        public IClasspathEntry[] answer() throws Throwable {
            return capturedEntries.getValue();
        }
    }).anyTimes();

    javaProject.setRawClasspath(capture(capturedEntries), isA(IProgressMonitor.class));
    expectLastCall().anyTimes();

    javaProject.setRawClasspath(capture(capturedEntries), capture(capturedOutput), isA(IProgressMonitor.class));
    expectLastCall().anyTimes();

    final Capture<String> capturedCompliance = new Capture<String>();
    capturedCompliance.setValue("1.4");
    final Capture<String> capturedSource = new Capture<String>();
    capturedSource.setValue("1.4");
    final Capture<String> capturedTarget = new Capture<String>();
    capturedTarget.setValue("1.4");

    expect(javaProject.getOption(JavaCore.COMPILER_COMPLIANCE, true)).andAnswer(new IAnswer<String>() {
        @Override
        public String answer() throws Throwable {
            return capturedCompliance.getValue();
        }
    });
    expect(javaProject.getOption(JavaCore.COMPILER_SOURCE, true)).andAnswer(new IAnswer<String>() {
        @Override
        public String answer() throws Throwable {
            return capturedSource.getValue();
        }
    });
    expect(javaProject.getOption(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, true))
            .andAnswer(new IAnswer<String>() {
                @Override
                public String answer() throws Throwable {
                    return capturedTarget.getValue();
                }
            });

    javaProject.setOption(eq(JavaCore.COMPILER_COMPLIANCE), capture(capturedCompliance));
    expectLastCall().anyTimes();
    javaProject.setOption(eq(JavaCore.COMPILER_SOURCE), capture(capturedSource));
    expectLastCall().anyTimes();
    javaProject.setOption(eq(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM), capture(capturedTarget));
    expectLastCall().anyTimes();

    replay(javaProject);

    return javaProject;
}

From source file:com.buglabs.dragonfly.ui.actions.ConvertProjectActionDelegate.java

License:Open Source License

public void run(IAction action) {
    Job job = new Job("Convert Project") {

        @Override//from w w  w.  jav  a2  s .  c  o  m
        protected IStatus run(IProgressMonitor monitor) {
            try {
                IJavaProject jproj = JavaCore.create(project);

                jproj.setOption(JavaCore.COMPILER_PB_ASSERT_IDENTIFIER, JavaCore.WARNING);
                jproj.setOption(JavaCore.COMPILER_PB_ENUM_IDENTIFIER, JavaCore.WARNING);

                IClasspathEntry[] importCP = jproj.getRawClasspath();
                List cpl = new ArrayList();
                IClasspathEntry jre = JavaCore.newContainerEntry(JavaRuntime.newDefaultJREContainerPath());
                IClasspathEntry pde = JavaCore
                        .newContainerEntry(new Path("org.eclipse.pde.core.requiredPlugins"));

                for (int i = 0; i < importCP.length; ++i) {
                    String cpName = importCP[i].getPath().toString();

                    if (cpName.equals("com.buglabs.osgi.concierge.jdt.ConciergeClasspathContainerInitializer")
                            || cpName.equals("com.buglabs.phoneme.personal.PhoneMEClasspathContainer")
                            || cpName.equals(
                                    "com.buglabs.osgi.concierge.jdt.OSGiBundleClassPathContainerInitializer")
                            || cpName.equals("org.eclipse.jdt.launching.JRE_CONTAINER")) {

                        if (!cpl.contains(jre)) {
                            cpl.add(jre);
                        }

                        if (!cpl.contains(pde)) {
                            cpl.add(pde);
                        }
                    } else {
                        System.out.println(cpName);
                        cpl.add(importCP[i]);
                    }
                }

                jproj.setRawClasspath((IClasspathEntry[]) cpl.toArray(new IClasspathEntry[cpl.size()]),
                        monitor);
                ConciergeUtils.addNatureToProject(project, "org.eclipse.pde.PluginNature", monitor);
                ConciergeUtils.removeNatureFromProject(project,
                        "com.buglabs.osgi.concierge.natures.ConciergeProjectNature", monitor);

                project.build(IncrementalProjectBuilder.CLEAN_BUILD, monitor);

                return Status.OK_STATUS;
            } catch (Exception e) {
                return new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Unable to convert BUG project.", e);
            }
        }

    };

    job.schedule();
}