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.launch.MainLaunchConfigTab.java

License:Open Source License

/**
 * Associates the launch config and the project. This allows Eclipse to delete the launch
 * config when the project is deleted./*from   w  ww .  ja v a  2s  .  c om*/
 *
 * @param config the launch config working copy.
 */
protected void mapResources(ILaunchConfigurationWorkingCopy config) {
    // get the java model
    IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();
    IJavaModel javaModel = JavaCore.create(workspaceRoot);

    // get the IJavaProject described by the text field.
    IJavaProject javaProject = getJavaProject(javaModel);
    IResource[] resources = null;
    if (javaProject != null) {
        resources = AndroidLaunchController.getResourcesToMap(javaProject.getProject());
    }
    config.setMappedResources(resources);
}

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

License:Open Source License

/**
 * Checks the parameters for correctness, and update the error message and buttons.
 * @return the current IProject of this launch config.
 *///from   w w w.  j ava  2  s .c  o  m
private IProject checkParameters() {
    try {
        //test the project name first!
        String text = mProjText.getText();
        if (text.length() == 0) {
            setErrorMessage("Project Name is required!");
        } else if (text.matches("[a-zA-Z0-9_ \\.-]+") == false) {
            setErrorMessage("Project name contains unsupported characters!");
        } else {
            IJavaProject[] projects = mProjectChooserHelper.getAndroidProjects(null);
            IProject found = null;
            for (IJavaProject javaProject : projects) {
                if (javaProject.getProject().getName().equals(text)) {
                    found = javaProject.getProject();
                    break;
                }

            }

            if (found != null) {
                setErrorMessage(null);
            } else {
                setErrorMessage(String.format("There is no android project named '%1$s'", text));
            }

            return found;
        }
    } finally {
        updateLaunchConfigurationDialog();
    }

    return null;
}

From source file:com.android.ide.eclipse.adt.internal.lint.EclipseLintClient.java

License:Open Source License

/**
 * Removes all markers of the given id from the given resource.
 *
 * @param resource the resource to remove markers from (file or project, or
 *            null for all open projects)
 * @param id the id for the issue whose markers should be deleted
 *//*  ww  w  . ja v a 2s  .  c  o  m*/
public static void removeMarkers(IResource resource, String id) {
    if (resource == null) {
        IJavaProject[] androidProjects = BaseProjectHelper.getAndroidProjects(null);
        for (IJavaProject project : androidProjects) {
            IProject p = project.getProject();
            if (p != null) {
                // Recurse, but with a different parameter so it will not continue recursing
                removeMarkers(p, id);
            }
        }
        return;
    }
    IMarker[] markers = getMarkers(resource);
    for (IMarker marker : markers) {
        if (id.equals(getId(marker))) {
            try {
                marker.delete();
            } catch (CoreException e) {
                AdtPlugin.log(e, null);
            }
        }
    }
}

From source file:com.android.ide.eclipse.adt.internal.lint.LintViewPart.java

License:Open Source License

@Override
public void createPartControl(Composite parent) {
    GridLayout gridLayout = new GridLayout(1, false);
    gridLayout.verticalSpacing = 0;//  www  . ja  v  a2s  . c  o  m
    gridLayout.marginWidth = 0;
    gridLayout.marginHeight = 0;
    parent.setLayout(gridLayout);

    mErrorLabel = new Label(parent, SWT.NONE);
    mErrorLabel.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));

    mSashForm = new SashForm(parent, SWT.NONE);
    mSashForm.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
    mLintView = new LintList(getSite(), mSashForm, mMemento, false /*singleFile*/);

    mDetailsText = new Text(mSashForm, SWT.BORDER | SWT.READ_ONLY | SWT.WRAP | SWT.V_SCROLL | SWT.MULTI);
    Display display = parent.getDisplay();
    mDetailsText.setBackground(display.getSystemColor(SWT.COLOR_INFO_BACKGROUND));
    mDetailsText.setForeground(display.getSystemColor(SWT.COLOR_INFO_FOREGROUND));

    mLintView.addSelectionListener(this);
    mSashForm.setWeights(new int[] { 8, 2 });

    createActions();
    initializeToolBar();

    // If there are currently running jobs, listen for them such that we can update the
    // button state
    refreshStopIcon();

    if (sInitialResources != null) {
        mLintView.setResources(sInitialResources);
        sInitialResources = null;
    } else {
        // No supplied context: show lint warnings for all projects
        IJavaProject[] androidProjects = BaseProjectHelper.getAndroidProjects(null);
        if (androidProjects.length > 0) {
            List<IResource> projects = new ArrayList<IResource>();
            for (IJavaProject project : androidProjects) {
                projects.add(project.getProject());
            }
            mLintView.setResources(projects);
        }
    }

    updateIssueCount();
}

From source file:com.android.ide.eclipse.adt.internal.lint.RunLintAction.java

License:Open Source License

@Override
public Menu getMenu(Control parent) {
    mMenu = new Menu(parent);

    IconFactory iconFactory = IconFactory.getInstance();
    ImageDescriptor allIcon = iconFactory.getImageDescriptor("lintrun"); //$NON-NLS-1$
    LintMenuAction allAction = new LintMenuAction("Check All Projects", allIcon, ACTION_RUN, null);

    addAction(allAction);/*from w  ww. jav a 2s.  c om*/
    addSeparator();
    IJavaProject[] projects = AdtUtils.getOpenAndroidProjects();
    ILabelProvider provider = new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_DEFAULT);
    for (IJavaProject project : projects) {
        IProject p = project.getProject();
        ImageDescriptor icon = ImageDescriptor.createFromImage(provider.getImage(p));
        String label = String.format("Check %1$s", p.getName());
        LintMenuAction projectAction = new LintMenuAction(label, icon, ACTION_RUN, p);
        addAction(projectAction);
    }

    ITextEditor textEditor = AdtUtils.getActiveTextEditor();
    if (textEditor != null) {
        IFile file = AdtUtils.getActiveFile();
        // Currently only supported for XML files
        if (file != null && LintUtils.endsWith(file.getName(), DOT_XML)) {
            ImageDescriptor icon = ImageDescriptor.createFromImage(provider.getImage(file));
            IAction fileAction = new LintMenuAction("Check Current File", icon, ACTION_RUN, file);

            addSeparator();
            addAction(fileAction);
        }
    }

    ISharedImages images = PlatformUI.getWorkbench().getSharedImages();
    ImageDescriptor clear = images.getImageDescriptor(ISharedImages.IMG_ELCL_REMOVEALL);
    LintMenuAction clearAction = new LintMenuAction("Clear Lint Warnings", clear, ACTION_CLEAR, null);
    addSeparator();
    addAction(clearAction);

    LintMenuAction excludeAction = new LintMenuAction("Skip Library Project Dependencies", allIcon,
            ACTION_TOGGLE_EXCLUDE, null);
    addSeparator();
    addAction(excludeAction);
    excludeAction.setChecked(AdtPrefs.getPrefs().getSkipLibrariesFromLint());

    return mMenu;
}

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

License:Open Source License

/**
 * Allocates and returns an {@link AndroidClasspathContainer} object with the proper
 * path to the framework jar file./*from  w ww.ja v a 2  s.co  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;
    IAndroidTarget target = null;

    try {
        AdtPlugin plugin = AdtPlugin.getDefault();
        if (plugin == null) { // This is totally weird, but I've seen it happen!
            return null;
        }

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

            // check if the project has a valid target.
            ProjectState state = Sdk.getProjectState(iProject);
            if (state == null) {
                // looks like the project state (project.properties) couldn't be read!
                markerMessage = String.format(
                        "Project has no %1$s file! Edit the project properties to set one.",
                        SdkConstants.FN_PROJECT_PROPERTIES);
            } else {
                // this might be null if the sdk is not yet loaded.
                target = state.getTarget();

                // if we are loaded and the target is non null, we create a valid
                // ClassPathContainer
                if (sdkIsLoaded && target != null) {
                    // check the renderscript support mode. If support mode is enabled,
                    // target API must be 18+
                    if (!state.getRenderScriptSupportMode() || target.getVersion().getApiLevel() >= 18) {
                        // first make sure the target has loaded its data
                        Sdk.getCurrent().checkAndLoadTargetData(target, null /*project*/);

                        String targetName = target.getClasspathName();

                        return new AndroidClasspathContainer(
                                createClasspathEntries(iProject, target, targetName),
                                new Path(AdtConstants.CONTAINER_FRAMEWORK), targetName,
                                IClasspathContainer.K_DEFAULT_SYSTEM);
                    } else {
                        markerMessage = "Renderscript support mode requires compilation target API to be 18+.";
                    }
                } else {
                    // 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 = state.getTargetHashString();

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

                        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() {
                @Override
                public IClasspathEntry[] getClasspathEntries() {
                    return new IClasspathEntry[0];
                }

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

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

                @Override
                public IPath getPath() {
                    return null;
                }
            };
        }
    } finally {
        processError(iProject, markerMessage, AdtConstants.MARKER_TARGET, outputToConsole);
    }
}

From source file:com.android.ide.eclipse.adt.internal.project.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.
 */// w  w w  . j  ava2 s .co m
public static void checkProjectsCache(ArrayList<IJavaProject> projects) {
    Sdk currentSdk = Sdk.getCurrent();
    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;
        }

        // project that have been resolved before the sdk was loaded
        // will have a ProjectState where the IAndroidTarget is null
        // so we load the target now that the SDK is loaded.
        IAndroidTarget target = currentSdk.loadTargetAndBuildTools(Sdk.getProjectState(iProject));
        if (target == null) {
            // this is really not supposed to happen. This would mean there are cached paths,
            // but project.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.internal.project.AndroidClasspathContainerInitializer.java

License:Open Source License

@Override
public void requestClasspathContainerUpdate(IPath containerPath, IJavaProject project,
        IClasspathContainer containerSuggestion) throws CoreException {
    AdtPlugin plugin = AdtPlugin.getDefault();

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

        // check if the project has a valid target.
        IAndroidTarget target = null;/*from w  ww  .ja  va2  s . c  o  m*/
        if (sdkIsLoaded) {
            target = Sdk.getCurrent().getTarget(project.getProject());
        }
        if (sdkIsLoaded && target != null) {
            String[] paths = getTargetPaths(target);
            IPath android_lib = new Path(paths[CACHE_INDEX_JAR]);
            IClasspathEntry[] entries = containerSuggestion.getClasspathEntries();
            for (int i = 0; i < entries.length; i++) {
                IClasspathEntry entry = entries[i];
                if (entry.getEntryKind() == IClasspathEntry.CPE_LIBRARY) {
                    IPath entryPath = entry.getPath();

                    if (entryPath != null) {
                        if (entryPath.equals(android_lib)) {
                            IPath entrySrcPath = entry.getSourceAttachmentPath();
                            IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
                            if (entrySrcPath != null) {
                                ProjectHelper.saveStringProperty(root, getAndroidSourceProperty(target),
                                        entrySrcPath.toString());
                            } else {
                                ProjectHelper.saveStringProperty(root, getAndroidSourceProperty(target), null);
                            }
                            IClasspathAttribute[] extraAttributtes = entry.getExtraAttributes();
                            if (extraAttributtes.length == 0) {
                                ProjectHelper.saveStringProperty(root, PROPERTY_ANDROID_API, NULL_API_URL);
                            }
                            for (int j = 0; j < extraAttributtes.length; j++) {
                                IClasspathAttribute extraAttribute = extraAttributtes[j];
                                String value = extraAttribute.getValue();
                                if ((value == null || value.trim().length() == 0)
                                        && IClasspathAttribute.JAVADOC_LOCATION_ATTRIBUTE_NAME
                                                .equals(extraAttribute.getName())) {
                                    value = NULL_API_URL;
                                }
                                if (IClasspathAttribute.JAVADOC_LOCATION_ATTRIBUTE_NAME
                                        .equals(extraAttribute.getName())) {
                                    ProjectHelper.saveStringProperty(root, PROPERTY_ANDROID_API, value);

                                }
                            }
                        }
                    }
                }
            }
            rebindClasspathEntries(project.getJavaModel(), containerPath);
        }
    }
}

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

License:Open Source License

@Override
public void initialize(final IJavaProject project, final IClasspathEntry[] currentEntries) {
    this.mOwnerProject = (project == null ? null : project.getProject());
}

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

License:Open Source License

/**
 * Parses the Android Manifest for a given project, and returns an object containing
 * the result of the parsing.//  w  ww  .  j  a  v a 2  s . com
 * <p/>
 * This method can also gather XML error during the parsing. This is done by using an
 * {@link XmlErrorHandler} to mark the files in case of error, as well as a given
 * {@link XmlErrorListener}. To use a different error handler, consider using
 * {@link AndroidManifestParser#parse(IAbstractFile, boolean, com.android.sdklib.xml.AndroidManifestParser.ManifestErrorHandler)}
 * directly.
 *
 * @param javaProject the project containing the manifest to parse.
 * @param gatherData indicates whether the parsing will extract data from the manifest. If null,
 * the method will always return null.
 * @param errorListener an optional error listener. If non null, then the parser will also
 * look for XML errors.
 * @return an {@link ManifestData} or null if the parsing failed.
 */
public static ManifestData parse(IJavaProject javaProject, boolean gatherData, XmlErrorListener errorListener) {

    IFile manifestFile = ProjectHelper.getManifest(javaProject.getProject());
    if (manifestFile != null) {
        return parse(new IFileWrapper(manifestFile), gatherData, errorListener);
    }

    return null;
}