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

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

Introduction

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

Prototype

IProject getProject();

Source Link

Document

Returns the IProject on which this IJavaProject was created.

Usage

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

License:Open Source License

/**
 * Parses the Android Manifest for the specified project, and returns an object containing
 * the result of the parsing.// ww  w.ja  va2  s  . c  o m
 * @param javaProject The java project. Required if <var>markErrors</var> is <code>true</code>
 * @param errorListener the {@link XmlErrorListener} object being notified of the presence
 * of errors. Optional.
 * @param gatherData indicates whether the parsing will extract data from the manifest.
 * @param markErrors indicates whether the error found during parsing should put a
 * marker on the file. For class validation errors to put a marker, <code>gatherData</code>
 * must be set to <code>true</code>
 * @return an {@link AndroidManifestParser} or null if the parsing failed.
 * @throws CoreException
 */
public static AndroidManifestParser parse(IJavaProject javaProject, XmlErrorListener errorListener,
        boolean gatherData, boolean markErrors) throws CoreException {

    IFile manifestFile = getManifest(javaProject.getProject());

    try {
        SAXParser parser = sParserFactory.newSAXParser();

        if (manifestFile != null) {
            ManifestHandler manifestHandler = new ManifestHandler(manifestFile, errorListener, gatherData,
                    javaProject, markErrors);

            parser.parse(new InputSource(manifestFile.getContents()), manifestHandler);

            // get the result from the handler
            return new AndroidManifestParser(manifestHandler.getPackage(), manifestHandler.getActivities(),
                    manifestHandler.getLauncherActivity(), manifestHandler.getProcesses(),
                    manifestHandler.getDebuggable(), manifestHandler.getApiLevelRequirement(),
                    manifestHandler.getInstrumentations(), manifestHandler.getUsesLibraries());
        }
    } catch (ParserConfigurationException e) {
        AdtPlugin.logAndPrintError(e, AndroidManifestParser.class.getCanonicalName(),
                "Bad parser configuration for %s", manifestFile.getFullPath());
    } catch (SAXException e) {
        AdtPlugin.logAndPrintError(e, AndroidManifestParser.class.getCanonicalName(), "Parser exception for %s",
                manifestFile.getFullPath());
    } catch (IOException e) {
        AdtPlugin.logAndPrintError(e, AndroidManifestParser.class.getCanonicalName(), "I/O error for %s",
                manifestFile.getFullPath());
    }

    return null;
}

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

License:Open Source License

/**
 * Returns the list of android-flagged projects for the specified java Model.
 * This list contains projects that are opened in the workspace and that are flagged as android
 * project (through the android nature)/*w w  w  . jav a 2 s. c o  m*/
 * @param javaModel the Java Model object corresponding for the current workspace root.
 * @param filter an optional filter to control which android project are returned. Can be null.
 * @return an array of IJavaProject, which can be empty if no projects match.
 */
@NonNull
public static IJavaProject[] getAndroidProjects(@NonNull IJavaModel javaModel,
        @Nullable IProjectFilter filter) {
    // get the java projects
    IJavaProject[] javaProjectList = null;
    try {
        javaProjectList = javaModel.getJavaProjects();
    } catch (JavaModelException jme) {
        return new IJavaProject[0];
    }

    // temp list to build the android project array
    ArrayList<IJavaProject> androidProjectList = new ArrayList<IJavaProject>();

    // loop through the projects and add the android flagged projects to the temp list.
    for (IJavaProject javaProject : javaProjectList) {
        // get the workspace project object
        IProject project = javaProject.getProject();

        // check if it's an android project based on its nature
        if (isAndroidProject(project)) {
            if (filter == null || filter.accept(project)) {
                androidProjectList.add(javaProject);
            }
        }
    }

    // return the android projects list.
    return androidProjectList.toArray(new IJavaProject[androidProjectList.size()]);
}

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

License:Open Source License

@Nullable
private static IProject findSupportProjectV7() {
    for (IJavaProject javaProject : AdtUtils.getOpenAndroidProjects()) {
        IProject project = javaProject.getProject();
        ProjectState state = Sdk.getProjectState(project);
        if (state.isLibrary()) {
            ManifestInfo manifestInfo = ManifestInfo.get(project);
            if (manifestInfo.getPackage().equals("android.support.v7.gridlayout")) { //$NON-NLS-1$
                return project;
            }/*from  ww w .  j a  va  2s  .  c om*/
        }
    }

    return null;
}

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

License:Open Source License

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

    // 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;
    }/*from  w  w w.  j ava2  s.co  m*/

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

    // 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) {
        // process all of the library project's dependencies
        getDependencyListFromClasspath(libProject, refProjects, jarFiles, true);
    }

    // now process this projects' referenced projects only.
    processReferencedProjects(iProject, refProjects, jarFiles);

    // and the content of its libs folder
    getJarListFromLibsFolder(iProject, jarFiles);

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

    entries.addAll(convertJarsToClasspathEntries(iProject, jarFiles));

    return allocateContainer(javaProject, entries, new Path(AdtConstants.CONTAINER_PRIVATE_LIBRARIES),
            "Android Private Libraries");
}

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

License:Open Source License

private static IClasspathContainer allocateDependencyContainer(IJavaProject javaProject) {
    final IProject iProject = javaProject.getProject();
    final List<IClasspathEntry> entries = new ArrayList<IClasspathEntry>();
    final Set<File> jarFiles = new HashSet<File>();
    final IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();

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

    synchronized (Sdk.getLock()) {
        boolean sdkIsLoaded = plugin.getSdkLoadStatus() == LoadStatus.LOADED;

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

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

            jarFiles.add(annotationsJar);
        }

        if (state.getRenderScriptSupportMode()) {
            if (!sdkIsLoaded) {
                return null;
            }
            BuildToolInfo buildToolInfo = state.getBuildToolInfo();
            if (buildToolInfo == null) {
                buildToolInfo = Sdk.getCurrent().getLatestBuildTool();

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

            File renderScriptSupportJar = RenderScriptProcessor
                    .getSupportJar(buildToolInfo.getLocation().getAbsolutePath());

            jarFiles.add(renderScriptSupportJar);
        }

        // 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() + SdkConstants.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);
            }
        }

        entries.addAll(convertJarsToClasspathEntries(iProject, jarFiles));

        return allocateContainer(javaProject, entries, new Path(CONTAINER_DEPENDENCIES),
                "Android Dependencies");
    }
}

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

License:Open Source License

/**
 * Helper method to get the Android project with the given name
 *
 * @param projectName the name of the project to find
 * @return the {@link IProject} for the Android project. <code>null</code> if not found.
 *//*from w ww  .java 2s . co  m*/
public IProject getAndroidProject(String projectName) {
    IProject iproject = null;
    IJavaProject[] javaProjects = getAndroidProjects(null);
    if (javaProjects != null) {
        for (IJavaProject javaProject : javaProjects) {
            if (javaProject.getElementName().equals(projectName)) {
                iproject = javaProject.getProject();
                break;
            }
        }
    }
    return iproject;
}

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 w  w w.  ja  v  a  2s.c  om
 * <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.ProjectHelper.java

License:Open Source License

/**
 * Checks, and fixes if needed, the compiler compliance level, and the source compatibility
 * level//www  . j ava 2 s.  c  o  m
 * @param javaProject The Java project to check and fix.
 */
public static final void checkAndFixCompilerCompliance(IJavaProject javaProject) {
    Pair<Integer, String> result = checkCompilerCompliance(javaProject);
    if (result.getFirst().intValue() != COMPILER_COMPLIANCE_OK) {
        // setup the preferred compiler compliance level.
        javaProject.setOption(JavaCore.COMPILER_COMPLIANCE, AdtConstants.COMPILER_COMPLIANCE_PREFERRED);
        javaProject.setOption(JavaCore.COMPILER_SOURCE, AdtConstants.COMPILER_COMPLIANCE_PREFERRED);
        javaProject.setOption(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM,
                AdtConstants.COMPILER_COMPLIANCE_PREFERRED);

        // clean the project to make sure we recompile
        try {
            javaProject.getProject().build(IncrementalProjectBuilder.CLEAN_BUILD, new NullProgressMonitor());
        } catch (CoreException e) {
            AdtPlugin.printErrorToConsole(javaProject.getProject(),
                    "Project compiler settings changed. Clean your project.");
        }
    }
}

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

License:Open Source License

/**
 * Checks a Java project compiler level option against a list of supported versions.
 * @param optionValue the Compiler level option.
 * @return true if the option value is supported.
 *//*from ww w. j a  va2s  . co  m*/
private static boolean checkCompliance(@NonNull IJavaProject project, String optionValue) {
    for (String s : AdtConstants.COMPILER_COMPLIANCE) {
        if (s != null && s.equals(optionValue)) {
            return true;
        }
    }

    if (JavaCore.VERSION_1_7.equals(optionValue)) {
        // Requires API 19 and buildTools 19
        Sdk currentSdk = Sdk.getCurrent();
        if (currentSdk != null) {
            IProject p = project.getProject();
            IAndroidTarget target = currentSdk.getTarget(p);
            if (target == null || target.getVersion().getApiLevel() < 19) {
                return false;
            }

            ProjectState projectState = Sdk.getProjectState(p);
            if (projectState != null) {
                BuildToolInfo buildToolInfo = projectState.getBuildToolInfo();
                if (buildToolInfo == null) {
                    buildToolInfo = currentSdk.getLatestBuildTool();
                }
                if (buildToolInfo == null || buildToolInfo.getRevision().getMajor() < 19) {
                    return false;
                }
            }

            return true;
        }
    }

    return false;
}

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

License:Open Source License

/**
 * Find the list of projects on which this JavaProject is dependent on at the compilation level.
 *
 * @param javaProject Java project that we are looking for the dependencies.
 * @return A list of Java projects for which javaProject depend on.
 * @throws JavaModelException//from w  w w. j a  va2  s.c o m
 */
public static List<IJavaProject> getAndroidProjectDependencies(IJavaProject javaProject)
        throws JavaModelException {
    String[] requiredProjectNames = javaProject.getRequiredProjectNames();

    // Go from java project name to JavaProject name
    IJavaModel javaModel = javaProject.getJavaModel();

    // loop through all dependent projects and keep only those that are Android projects
    List<IJavaProject> projectList = new ArrayList<IJavaProject>(requiredProjectNames.length);
    for (String javaProjectName : requiredProjectNames) {
        IJavaProject androidJavaProject = javaModel.getJavaProject(javaProjectName);

        //Verify that the project has also the Android Nature
        try {
            if (!androidJavaProject.getProject().hasNature(AdtConstants.NATURE_DEFAULT)) {
                continue;
            }
        } catch (CoreException e) {
            continue;
        }

        projectList.add(androidJavaProject);
    }

    return projectList;
}