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.launch.junit.AndroidJUnitLaunchConfigurationTab.java

License:Open Source License

/**
 * Show a dialog that lets the user select a Android project.  This in turn provides
 * context for the main type, allowing the user to key a main type name, or
 * constraining the search for main types to the specified project.
 *//*from w w  w .  j a v a 2  s . co m*/
private void handleProjectButtonSelected() {
    IJavaProject project = mProjectChooserHelper.chooseJavaProject(getProjectName());
    if (project == null) {
        return;
    }

    String projectName = project.getElementName();
    mProjText.setText(projectName);
    loadInstrumentations(project.getProject());
}

From source file:com.android.ide.eclipse.adt.launch.junit.InstrumentationRunnerValidator.java

License:Open Source License

/**
 * Initializes the InstrumentationRunnerValidator.
 * /*from   ww  w . j a va2s . c  o m*/
 * @param javaProject the {@link IJavaProject} for the Android project to validate
 */
InstrumentationRunnerValidator(IJavaProject javaProject) {
    mJavaProject = javaProject;
    try {
        AndroidManifestParser manifestParser = AndroidManifestParser.parse(javaProject,
                null /* errorListener */, true /* gatherData */, false /* markErrors */);
        init(manifestParser);
    } catch (CoreException e) {
        AdtPlugin.printErrorToConsole(javaProject.getProject(), "ERROR: Failed to parse %1$s",
                AndroidConstants.FN_ANDROID_MANIFEST);
    }
}

From source file:com.android.ide.eclipse.adt.launch.MainLaunchConfigTab.java

License:Open Source License

/**
 * Show a dialog that lets the user select a project. This in turn provides
 * context for the main type, allowing the user to key a main type name, or
 * constraining the search for main types to the specified project.
 *//*from  w ww. j  a va2 s .c om*/
protected void handleProjectButtonSelected() {
    IJavaProject javaProject = mProjectChooserHelper.chooseJavaProject(mProjText.getText().trim());
    if (javaProject == null) {
        return;
    } // end if
    String projectName = javaProject.getElementName();
    mProjText.setText(projectName);

    // get the list of activities and fill the combo
    IProject project = javaProject.getProject();
    loadActivities(project);
}

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

License:Open Source License

public void createControl(Composite parent) {
    mProjectChooserHelper = new ProjectChooserHelper(parent.getShell());
    mDisplay = parent.getDisplay();//from   ww w. jav  a 2 s. c  om

    GridLayout gl = null;
    GridData gd = null;

    mTopComposite = new Composite(parent, SWT.NONE);
    mTopComposite.setLayoutData(new GridData(GridData.FILL_BOTH));
    mTopComposite.setLayout(new GridLayout(1, false));

    // composite for the project selection.
    Composite projectComposite = new Composite(mTopComposite, SWT.NONE);
    projectComposite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
    projectComposite.setLayout(gl = new GridLayout(3, false));
    gl.marginHeight = gl.marginWidth = 0;

    Label label = new Label(projectComposite, SWT.NONE);
    label.setLayoutData(gd = new GridData(GridData.FILL_HORIZONTAL));
    gd.horizontalSpan = 3;
    label.setText("Select the project to export:");

    new Label(projectComposite, SWT.NONE).setText("Project:");
    mProjectText = new Text(projectComposite, SWT.BORDER);
    mProjectText.setLayoutData(gd = new GridData(GridData.FILL_HORIZONTAL));
    mProjectText.addModifyListener(new ModifyListener() {
        public void modifyText(ModifyEvent e) {
            handleProjectNameChange();
        }
    });

    Button browseButton = new Button(projectComposite, SWT.PUSH);
    browseButton.setText("Browse...");
    browseButton.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            IJavaProject javaProject = mProjectChooserHelper.chooseJavaProject(mProjectText.getText().trim());

            if (javaProject != null) {
                IProject project = javaProject.getProject();

                // set the new name in the text field. The modify listener will take
                // care of updating the status and the ExportWizard object.
                mProjectText.setText(project.getName());
            }
        }
    });

    setControl(mTopComposite);
}

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

License:Open Source License

/**
 * Allocates and returns an {@link AndroidClasspathContainer} object with the proper
 * path to the framework jar file./*  ww  w. j  av  a  2s.c  o m*/
 * @param javaProject The java project that will receive the container.
 */
private static IClasspathContainer allocateAndroidContainer(IJavaProject javaProject) {
    final IProject iProject = javaProject.getProject();

    String markerMessage = null;
    boolean outputToConsole = true;

    try {
        AdtPlugin plugin = AdtPlugin.getDefault();

        // get the lock object for project manipulation during SDK load.
        Object lock = plugin.getSdkLockObject();
        synchronized (lock) {
            boolean sdkIsLoaded = plugin.getSdkLoadStatus() == LoadStatus.LOADED;

            // check if the project has a valid target.
            IAndroidTarget target = null;
            if (sdkIsLoaded) {
                target = Sdk.getCurrent().getTarget(iProject);
            }

            // if we are loaded and the target is non null, we create a valid ClassPathContainer
            if (sdkIsLoaded && target != null) {

                String targetName = target.getClasspathName();

                return new AndroidClasspathContainer(createClasspathEntries(iProject, target, targetName),
                        new Path(CONTAINER_ID), targetName);
            }

            // In case of error, we'll try different thing to provide the best error message
            // possible.
            // Get the project's target's hash string (if it exists)
            String hashString = Sdk.getProjectTargetHashString(iProject);

            if (hashString == null || hashString.length() == 0) {
                // if there is no hash string we only show this if the SDK is loaded.
                // For a project opened at start-up with no target, this would be displayed
                // twice, once when the project is opened, and once after the SDK has
                // finished loading.
                // By testing the sdk is loaded, we only show this once in the console.
                if (sdkIsLoaded) {
                    markerMessage = String
                            .format("Project has no target set. Edit the project properties to set one.");
                }
            } else if (sdkIsLoaded) {
                markerMessage = String.format("Unable to resolve target '%s'", hashString);
            } else {
                // this is the case where there is a hashString but the SDK is not yet
                // loaded and therefore we can't get the target yet.
                // We check if there is a cache of the needed information.
                AndroidClasspathContainer container = getContainerFromCache(iProject);

                if (container == null) {
                    // either the cache was wrong (ie folder does not exists anymore), or 
                    // there was no cache. In this case we need to make sure the project
                    // is resolved again after the SDK is loaded.
                    plugin.setProjectToResolve(javaProject);

                    markerMessage = String.format("Unable to resolve target '%s' until the SDK is loaded.",
                            hashString);

                    // let's not log this one to the console as it will happen at every boot,
                    // and it's expected. (we do keep the error marker though).
                    outputToConsole = false;

                } else {
                    // we created a container from the cache, so we register the project
                    // to be checked for cache validity once the SDK is loaded
                    plugin.setProjectToCheck(javaProject);

                    // and return the container
                    return container;
                }

            }

            // return a dummy container to replace the one we may have had before.
            // It'll be replaced by the real when if/when the target is resolved if/when the
            // SDK finishes loading.
            return new IClasspathContainer() {
                public IClasspathEntry[] getClasspathEntries() {
                    return new IClasspathEntry[0];
                }

                public String getDescription() {
                    return "Unable to get system library for the project";
                }

                public int getKind() {
                    return IClasspathContainer.K_DEFAULT_SYSTEM;
                }

                public IPath getPath() {
                    return null;
                }
            };
        }
    } finally {
        if (markerMessage != null) {
            // log the error and put the marker on the project if we can.
            if (outputToConsole) {
                AdtPlugin.printErrorToConsole(iProject, markerMessage);
            }

            try {
                BaseProjectHelper.addMarker(iProject, AdtConstants.MARKER_TARGET, markerMessage, -1,
                        IMarker.SEVERITY_ERROR, IMarker.PRIORITY_HIGH);
            } catch (CoreException e) {
                // In some cases, the workspace may be locked for modification when we
                // pass here.
                // We schedule a new job to put the marker after.
                final String fmessage = markerMessage;
                Job markerJob = new Job("Android SDK: Resolving error markers") {
                    @Override
                    protected IStatus run(IProgressMonitor monitor) {
                        try {
                            BaseProjectHelper.addMarker(iProject, AdtConstants.MARKER_TARGET, fmessage, -1,
                                    IMarker.SEVERITY_ERROR, IMarker.PRIORITY_HIGH);
                        } catch (CoreException e2) {
                            return e2.getStatus();
                        }

                        return Status.OK_STATUS;
                    }
                };

                // build jobs are run after other interactive jobs
                markerJob.setPriority(Job.BUILD);
                markerJob.schedule();
            }
        } else {
            // no error, remove potential MARKER_TARGETs.
            try {
                if (iProject.exists()) {
                    iProject.deleteMarkers(AdtConstants.MARKER_TARGET, true, IResource.DEPTH_INFINITE);
                }
            } catch (CoreException ce) {
                // In some cases, the workspace may be locked for modification when we pass
                // here, so we schedule a new job to put the marker after.
                Job markerJob = new Job("Android SDK: Resolving error markers") {
                    @Override
                    protected IStatus run(IProgressMonitor monitor) {
                        try {
                            iProject.deleteMarkers(AdtConstants.MARKER_TARGET, true, IResource.DEPTH_INFINITE);
                        } catch (CoreException e2) {
                            return e2.getStatus();
                        }

                        return Status.OK_STATUS;
                    }
                };

                // build jobs are run after other interactive jobs
                markerJob.setPriority(Job.BUILD);
                markerJob.schedule();
            }
        }
    }
}

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

License:Open Source License

/**
 * Checks the projects' caches. If the cache was valid, the project is removed from the list.
 * @param projects the list of projects to check.
 *//*from www. j  a  v a2 s  . c o  m*/
public static void checkProjectsCache(ArrayList<IJavaProject> projects) {
    int i = 0;
    projectLoop: while (i < projects.size()) {
        IJavaProject javaProject = projects.get(i);
        IProject iProject = javaProject.getProject();

        // check if the project is opened
        if (iProject.isOpen() == false) {
            // remove from the list
            // we do not increment i in this case.
            projects.remove(i);

            continue;
        }

        // get the target from the project and its paths
        IAndroidTarget target = Sdk.getCurrent().getTarget(javaProject.getProject());
        if (target == null) {
            // this is really not supposed to happen. This would mean there are cached paths,
            // but default.properties was deleted. Keep the project in the list to force
            // a resolve which will display the error.
            i++;
            continue;
        }

        String[] targetPaths = getTargetPaths(target);

        // now get the cached paths
        String cache = ProjectHelper.loadStringProperty(iProject, PROPERTY_CONTAINER_CACHE);
        if (cache == null) {
            // this should not happen. We'll force resolve again anyway.
            i++;
            continue;
        }

        String[] cachedPaths = cache.split(Pattern.quote(PATH_SEPARATOR));
        if (cachedPaths.length < 3 || cachedPaths.length == 4) {
            // paths length is wrong. simply resolve the project again
            i++;
            continue;
        }

        // Now we compare the paths. The first 4 can be compared directly.
        // because of case sensitiveness we need to use File objects

        if (targetPaths.length != cachedPaths.length) {
            // different paths, force resolve again.
            i++;
            continue;
        }

        // compare the main paths (android.jar, main sources, main javadoc)
        if (new File(targetPaths[CACHE_INDEX_JAR]).equals(new File(cachedPaths[CACHE_INDEX_JAR])) == false
                || new File(targetPaths[CACHE_INDEX_SRC])
                        .equals(new File(cachedPaths[CACHE_INDEX_SRC])) == false
                || new File(targetPaths[CACHE_INDEX_DOCS_URI])
                        .equals(new File(cachedPaths[CACHE_INDEX_DOCS_URI])) == false) {
            // different paths, force resolve again.
            i++;
            continue;
        }

        if (cachedPaths.length > CACHE_INDEX_OPT_DOCS_URI) {
            // compare optional libraries javadoc
            if (new File(targetPaths[CACHE_INDEX_OPT_DOCS_URI])
                    .equals(new File(cachedPaths[CACHE_INDEX_OPT_DOCS_URI])) == false) {
                // different paths, force resolve again.
                i++;
                continue;
            }

            // testing the optional jar files is a little bit trickier.
            // The order is not guaranteed to be identical.
            // From a previous test, we do know however that there is the same number.
            // The number of libraries should be low enough that we can simply go through the
            // lists manually.
            targetLoop: for (int tpi = 4; tpi < targetPaths.length; tpi++) {
                String targetPath = targetPaths[tpi];

                // look for a match in the other array
                for (int cpi = 4; cpi < cachedPaths.length; cpi++) {
                    if (new File(targetPath).equals(new File(cachedPaths[cpi]))) {
                        // found a match. Try the next targetPath
                        continue targetLoop;
                    }
                }

                // if we stop here, we haven't found a match, which means there's a
                // discrepancy in the libraries. We force a resolve.
                i++;
                continue projectLoop;
            }
        }

        // at the point the check passes, and we can remove the project from the list.
        // we do not increment i in this case.
        projects.remove(i);
    }
}

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

License:Open Source License

/**
 * Checks, and fixes if needed, the compiler compliance level, and the source compatibility
 * level/*from   w  w  w  .j a v  a 2  s  . c o  m*/
 * @param javaProject The Java project to check and fix.
 */
public static final void checkAndFixCompilerCompliance(IJavaProject javaProject) {
    if (checkCompilerCompliance(javaProject) != COMPILER_COMPLIANCE_OK) {
        // setup the preferred compiler compliance level.
        javaProject.setOption(JavaCore.COMPILER_COMPLIANCE, AndroidConstants.COMPILER_COMPLIANCE_PREFERRED);
        javaProject.setOption(JavaCore.COMPILER_SOURCE, AndroidConstants.COMPILER_COMPLIANCE_PREFERRED);
        javaProject.setOption(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM,
                AndroidConstants.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.project.ProjectHelper.java

License:Open Source License

/**
 * Find the list of projects on which this JavaProject is dependent on at the compilation level.
 * /*  w  w w .  j ava 2  s  .c o  m*/
 * @param javaProject Java project that we are looking for the dependencies.
 * @return A list of Java projects for which javaProject depend on.
 * @throws JavaModelException
 */
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(AndroidConstants.NATURE)) {
                continue;
            }
        } catch (CoreException e) {
            continue;
        }

        projectList.add(androidJavaProject);
    }

    return projectList;
}

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  a2 s.  c om*/
 * @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.adt.wizards.newxmlfile.NewXmlFileCreationPage.java

License:Open Source License

/**
 * Callback called when the user edits the project text field.
 *//* w  w  w.j av a 2s  .c  o m*/
private void onProjectFieldUpdated() {
    String project = mProjectTextField.getText();

    // Is this a valid project?
    IJavaProject[] projects = mProjectChooserHelper.getAndroidProjects(null /*javaModel*/);
    IProject found = null;
    for (IJavaProject p : projects) {
        if (p.getProject().getName().equals(project)) {
            found = p.getProject();
            break;
        }
    }

    if (found != mProject) {
        changeProject(found);
    }
}