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.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;
    }//from   ww w. j ava 2s. c  o 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.common.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  ww  .j a  v a 2 s .  c o m*/
 * @param javaModel the Java Model object corresponding for the current workspace root.
 * @return an array of IJavaProject, which can be empty if no projects match.
 */
public static IJavaProject[] getAndroidProjects(IJavaModel javaModel) {
    // 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
        try {
            if (project.hasNature(AndroidConstants.NATURE)) {
                androidProjectList.add(javaProject);
            }
        } catch (CoreException e) {
            // this exception, thrown by IProject.hasNature(), means the project either doesn't
            // exist or isn't opened. So, in any case we just skip it (the exception will
            // bypass the ArrayList.add()
        }
    }

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

From source file:com.android.ide.eclipse.editors.resources.explorer.ResourceExplorerView.java

License:Open Source License

/**
 * Processes a new selection.//from w  w w .  jav a2 s  .c  o  m
 */
public void selectionChanged(IWorkbenchPart part, ISelection selection) {
    // first we test if the part is an editor.
    if (part instanceof IEditorPart) {
        // if it is, we check if it's a file editor.
        IEditorInput input = ((IEditorPart) part).getEditorInput();

        if (input instanceof IFileEditorInput) {
            // from the file editor we can get the IFile object, and from it, the IProject.
            IFile file = ((IFileEditorInput) input).getFile();

            // get the file project
            IProject project = file.getProject();

            handleProjectSelection(project);
        }
    } else if (selection instanceof IStructuredSelection) {
        // if it's not an editor, we look for structured selection.
        for (Iterator<?> it = ((IStructuredSelection) selection).iterator(); it.hasNext();) {
            Object element = it.next();
            IProject project = null;

            // if we are in the navigator or package explorer, the selection could contain a
            // IResource object.
            if (element instanceof IResource) {
                project = ((IResource) element).getProject();
            } else if (element instanceof IJavaElement) {
                // if we are in the package explorer on a java element, we handle that too.
                IJavaElement javaElement = (IJavaElement) element;
                IJavaProject javaProject = javaElement.getJavaProject();
                if (javaProject != null) {
                    project = javaProject.getProject();
                }
            } else if (element instanceof IAdaptable) {
                // finally we try to get a project object from IAdaptable.
                project = (IProject) ((IAdaptable) element).getAdapter(IProject.class);
            }

            // if we found a project, handle it, and return.
            if (project != null) {
                if (handleProjectSelection(project)) {
                    return;
                }
            }
        }
    }
}

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 ww. j a v a2  s .c  o 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.basistech.m2e.code.quality.findbugs.EclipseFindbugsProjectConfigurator.java

License:Open Source License

@Override
protected void handleProjectConfigurationChange(final IMavenProjectFacade mavenProjectFacade,
        final IProject project, final IProgressMonitor monitor, final MavenPluginWrapper mavenPluginWrapper,
        MavenSession session) throws CoreException {
    log.debug("entering handleProjectConfigurationChange");
    IJavaProject javaProject = JavaCore.create(project);
    if (javaProject == null || !javaProject.exists() || !javaProject.getProject().isOpen()) {
        return;/*ww  w. j ava2 s . c  o m*/
    }
    final MavenPluginConfigurationTranslator mavenFindbugsConfig = MavenPluginConfigurationTranslator
            .newInstance(this, mavenPluginWrapper, project, mavenProjectFacade.getMavenProject(monitor),
                    monitor, session);
    UserPreferences prefs;
    try {
        final List<MojoExecution> mojoExecutions = mavenPluginWrapper.getMojoExecutions();
        if (mojoExecutions.size() != 1) {
            log.error("Wrong number of executions. Expected 1. Found " + mojoExecutions.size());
            return;
        }
        prefs = this.buildFindbugsPreferences(mavenFindbugsConfig);
        final EclipseFindbugsConfigManager fbPluginNature = EclipseFindbugsConfigManager.newInstance(project);
        // Add the builder and nature
        fbPluginNature.configure(monitor);
        FindbugsPlugin.saveUserPreferences(project, prefs);
        FindbugsPlugin.setProjectSettingsEnabled(project, null, true);
    } catch (final CoreException ex) {
        log.error(ex.getLocalizedMessage());
    }
}

From source file:com.blackducksoftware.integration.eclipseplugin.internal.listeners.ProjectDependenciesChangedListener.java

License:Apache License

public String getProjectNameFromElement(final IJavaElement el) throws CoreException {
    final IJavaProject javaProj = el.getJavaProject();
    if (javaProj != null) {
        final IProject proj = javaProj.getProject();
        if (proj != null) {
            final IProjectDescription description = proj.getDescription();
            if (description != null) {
                return description.getName();
            }/*ww  w .  j  a  v a2 s.  c  om*/
        }
    }
    return null;
}

From source file:com.carrotgarden.eclipse.fileinstall.Manager.java

License:BSD License

/**
 * Handle worker build start.// ww  w. j av  a  2 s  .com
 * 
 * @see Builder
 */
public void builderAboutToBuild(final IJavaProject java) {
    final String name = java.getProject().getName();
    final Project.Worker worker = workerMap.get(name);
    if (worker == null) {
        return;
    }
    doBuildInitiate(worker);
}

From source file:com.carrotgarden.eclipse.fileinstall.Manager.java

License:BSD License

/**
 * Handle worker build finish./*  w w  w  .  j  a v a  2s . c  om*/
 * 
 * @see Builder
 */
public void builderBuildFinished(final IJavaProject java) {
    final String name = java.getProject().getName();
    final Project.Worker worker = workerMap.get(name);
    if (worker == null) {
        return;
    }
    doBuildTerminate(worker);
}

From source file:com.carrotgarden.eclipse.fileinstall.Manager.java

License:BSD License

/**
 * Handle worker clean start./*from  w  ww.  j  a  v  a2s. c  o  m*/
 * 
 * @see Builder
 */
public void builderCleanStarting(final IJavaProject java) {
    final String name = java.getProject().getName();
    final Project.Worker worker = workerMap.get(name);
    if (worker == null) {
        return;
    }
}

From source file:com.carrotgarden.eclipse.fileinstall.Manager.java

License:BSD License

public boolean hasWorker(final IJavaProject java) {
    return workerMap.containsKey(java.getProject().getName());
}