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.wizards.newxmlfile.NewXmlFileCreationPage.java

License:Open Source License

/**
 * Callback called when the user uses the "Browse Projects" button.
 *//*from   w w  w  .jav  a2 s.co  m*/
private void onProjectBrowse() {
    IJavaProject p = mProjectChooserHelper.chooseJavaProject(mProjectTextField.getText());
    if (p != null) {
        changeProject(p.getProject());
        mProjectTextField.setText(mProject.getName());
    }
}

From source file:com.android.ide.eclipse.auidt.AdtPlugin.java

License:Open Source License

/**
 * Parses the SDK resources./*  ww  w.  j a va  2  s.  com*/
 */
private void parseSdkContent(long delay) {
    // Perform the update in a thread (here an Eclipse runtime job)
    // since this should never block the caller (especially the start method)
    Job job = new Job(Messages.AdtPlugin_Android_SDK_Content_Loader) {
        @SuppressWarnings("unchecked")
        @Override
        protected IStatus run(IProgressMonitor monitor) {
            try {

                if (mSdkIsLoading) {
                    return new Status(IStatus.WARNING, PLUGIN_ID,
                            "An Android SDK is already being loaded. Please try again later.");
                }

                mSdkIsLoading = true;

                SubMonitor progress = SubMonitor.convert(monitor, "Initialize SDK Manager", 100);

                Sdk sdk = Sdk.loadSdk(AdtPrefs.getPrefs().getOsSdkFolder());

                if (sdk != null) {

                    ArrayList<IJavaProject> list = new ArrayList<IJavaProject>();
                    synchronized (Sdk.getLock()) {
                        mSdkIsLoaded = LoadStatus.LOADED;

                        progress.setTaskName("Check Projects");

                        for (IJavaProject javaProject : mPostLoadProjectsToResolve) {
                            IProject iProject = javaProject.getProject();
                            if (iProject.isOpen()) {
                                // 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.
                                sdk.loadTarget(Sdk.getProjectState(iProject));
                                list.add(javaProject);
                            }
                        }

                        // done with this list.
                        mPostLoadProjectsToResolve.clear();
                    }

                    // check the projects that need checking.
                    // The method modifies the list (it removes the project that
                    // do not need to be resolved again).
                    AndroidClasspathContainerInitializer.checkProjectsCache(mPostLoadProjectsToCheck);

                    list.addAll(mPostLoadProjectsToCheck);

                    // update the project that needs recompiling.
                    if (list.size() > 0) {
                        IJavaProject[] array = list.toArray(new IJavaProject[list.size()]);
                        ProjectHelper.updateProjects(array);
                    }

                    progress.worked(10);
                } else {
                    // SDK failed to Load!
                    // Sdk#loadSdk() has already displayed an error.
                    synchronized (Sdk.getLock()) {
                        mSdkIsLoaded = LoadStatus.FAILED;
                    }
                }

                // Notify resource changed listeners
                progress.setTaskName("Refresh UI");
                progress.setWorkRemaining(mTargetChangeListeners.size());

                // Clone the list before iterating, to avoid ConcurrentModification
                // exceptions
                final List<ITargetChangeListener> listeners = (List<ITargetChangeListener>) mTargetChangeListeners
                        .clone();
                final SubMonitor progress2 = progress;
                AdtPlugin.getDisplay().asyncExec(new Runnable() {
                    @Override
                    public void run() {
                        for (ITargetChangeListener listener : listeners) {
                            try {
                                listener.onSdkLoaded();
                            } catch (Exception e) {
                                AdtPlugin.log(e, "Failed to update a TargetChangeListener."); //$NON-NLS-1$
                            } finally {
                                progress2.worked(1);
                            }
                        }
                    }
                });
            } catch (Throwable t) {
                log(t, "Unknown exception in parseSdkContent."); //$NON-NLS-1$
                return new Status(IStatus.ERROR, PLUGIN_ID, "parseSdkContent failed", t); //$NON-NLS-1$

            } finally {
                mSdkIsLoading = false;
                if (monitor != null) {
                    monitor.done();
                }
            }

            return Status.OK_STATUS;
        }
    };
    job.setPriority(Job.BUILD); // build jobs are run after other interactive jobs
    if (delay > 0) {
        job.schedule(delay);
    } else {
        job.schedule();
    }
}

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

License:Open Source License

/**
 * Aborts the build if the SDK/project setups are broken. This does not
 * display any errors.//from   w ww  . ja va 2 s.c o  m
 *
 * @param javaProject The {@link IJavaProject} being compiled.
 * @throws CoreException
 */
protected void abortOnBadSetup(IJavaProject javaProject) throws AbortBuildException {
    IProject iProject = javaProject.getProject();
    // check if we have finished loading the project target.
    Sdk sdk = Sdk.getCurrent();
    if (sdk == null) {
        throw new AbortBuildException();
    }

    // get the target for the project
    IAndroidTarget target = sdk.getTarget(javaProject.getProject());

    if (target == null) {
        throw new AbortBuildException();
    }

    // check on the target data.
    if (sdk.checkAndLoadTargetData(target, javaProject) != LoadStatus.LOADED) {
        throw new AbortBuildException();
    }

    // abort if there are TARGET or ADT type markers
    stopOnMarker(iProject, AdtConstants.MARKER_TARGET, IResource.DEPTH_ZERO, false /*checkSeverity*/);
    stopOnMarker(iProject, AdtConstants.MARKER_ADT, IResource.DEPTH_ZERO, false /*checkSeverity*/);
}

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

License:Open Source License

@Override
protected IProject[] build(int kind, @SuppressWarnings("rawtypes") Map args, IProgressMonitor monitor)
        throws CoreException {
    // get a project object
    IProject project = getProject();//www. j  a v  a 2s .  c o m

    if (DEBUG_LOG) {
        AdtPlugin.log(IStatus.INFO, "%s BUILD(POST)", project.getName());
    }

    // Benchmarking start
    long startBuildTime = 0;
    if (BuildHelper.BENCHMARK_FLAG) {
        // End JavaC Timer
        String msg = "BENCHMARK ADT: Ending Compilation \n BENCHMARK ADT: Time Elapsed: " + //$NON-NLS-1$
                (System.nanoTime() - BuildHelper.sStartJavaCTime) / Math.pow(10, 6) + "ms"; //$NON-NLS-1$
        AdtPlugin.printBuildToConsole(BuildVerbosity.ALWAYS, project, msg);
        msg = "BENCHMARK ADT: Starting PostCompilation"; //$NON-NLS-1$
        AdtPlugin.printBuildToConsole(BuildVerbosity.ALWAYS, project, msg);
        startBuildTime = System.nanoTime();
    }

    // list of referenced projects. This is a mix of java projects and library projects
    // and is computed below.
    IProject[] allRefProjects = null;

    try {
        // get the project info
        ProjectState projectState = Sdk.getProjectState(project);

        // this can happen if the project has no project.properties.
        if (projectState == null) {
            return null;
        }

        boolean isLibrary = projectState.isLibrary();

        // get the libraries
        List<IProject> libProjects = projectState.getFullLibraryProjects();

        IJavaProject javaProject = JavaCore.create(project);

        // get the list of referenced projects.
        List<IProject> javaProjects = ProjectHelper.getReferencedProjects(project);
        List<IJavaProject> referencedJavaProjects = BuildHelper.getJavaProjects(javaProjects);

        // mix the java project and the library projects
        final int size = libProjects.size() + javaProjects.size();
        ArrayList<IProject> refList = new ArrayList<IProject>(size);
        refList.addAll(libProjects);
        refList.addAll(javaProjects);
        allRefProjects = refList.toArray(new IProject[size]);

        // get the android output folder
        IFolder androidOutputFolder = BaseProjectHelper.getAndroidOutputFolder(project);
        IFolder resOutputFolder = androidOutputFolder.getFolder(SdkConstants.FD_RES);

        // First thing we do is go through the resource delta to not
        // lose it if we have to abort the build for any reason.
        if (args.containsKey(POST_C_REQUESTED) && AdtPrefs.getPrefs().getBuildSkipPostCompileOnFileSave()) {
            // Skip over flag setting
        } else if (kind == FULL_BUILD) {
            AdtPlugin.printBuildToConsole(BuildVerbosity.VERBOSE, project, Messages.Start_Full_Apk_Build);

            if (DEBUG_LOG) {
                AdtPlugin.log(IStatus.INFO, "%s full build!", project.getName());
            }

            // Full build: we do all the steps.
            mPackageResources = true;
            mConvertToDex = true;
            mBuildFinalPackage = true;
        } else {
            AdtPlugin.printBuildToConsole(BuildVerbosity.VERBOSE, project, Messages.Start_Inc_Apk_Build);

            // go through the resources and see if something changed.
            IResourceDelta delta = getDelta(project);
            if (delta == null) {
                // no delta? Same as full build: we do all the steps.
                mPackageResources = true;
                mConvertToDex = true;
                mBuildFinalPackage = true;
            } else {
                PatternBasedDeltaVisitor dv = new PatternBasedDeltaVisitor(project, project, "POST:Main");

                ChangedFileSet manifestCfs = ChangedFileSetHelper.getMergedManifestCfs(project);
                dv.addSet(manifestCfs);

                ChangedFileSet resCfs = ChangedFileSetHelper.getResCfs(project);
                dv.addSet(resCfs);

                ChangedFileSet androidCodeCfs = ChangedFileSetHelper.getCodeCfs(project);
                dv.addSet(androidCodeCfs);

                ChangedFileSet javaResCfs = ChangedFileSetHelper.getJavaResCfs(project);
                dv.addSet(javaResCfs);
                dv.addSet(ChangedFileSetHelper.NATIVE_LIBS);

                delta.accept(dv);

                // save the state
                mPackageResources |= dv.checkSet(manifestCfs) || dv.checkSet(resCfs);

                mConvertToDex |= dv.checkSet(androidCodeCfs);

                mBuildFinalPackage |= dv.checkSet(javaResCfs) || dv.checkSet(ChangedFileSetHelper.NATIVE_LIBS);
            }

            // check the libraries
            if (libProjects.size() > 0) {
                for (IProject libProject : libProjects) {
                    delta = getDelta(libProject);
                    if (delta != null) {
                        PatternBasedDeltaVisitor visitor = new PatternBasedDeltaVisitor(project, libProject,
                                "POST:Lib");

                        ChangedFileSet libResCfs = ChangedFileSetHelper.getFullResCfs(libProject);
                        visitor.addSet(libResCfs);
                        visitor.addSet(ChangedFileSetHelper.NATIVE_LIBS);
                        // FIXME: add check on the library.jar?

                        delta.accept(visitor);

                        mPackageResources |= visitor.checkSet(libResCfs);
                        mBuildFinalPackage |= visitor.checkSet(ChangedFileSetHelper.NATIVE_LIBS);
                    }
                }
            }

            // also go through the delta for all the referenced projects
            final int referencedCount = referencedJavaProjects.size();
            for (int i = 0; i < referencedCount; i++) {
                IJavaProject referencedJavaProject = referencedJavaProjects.get(i);
                delta = getDelta(referencedJavaProject.getProject());
                if (delta != null) {
                    PatternBasedDeltaVisitor visitor = new PatternBasedDeltaVisitor(project,
                            referencedJavaProject.getProject(), "POST:RefedProject");

                    ChangedFileSet javaResCfs = ChangedFileSetHelper.getJavaResCfs(project);
                    visitor.addSet(javaResCfs);

                    ChangedFileSet bytecodeCfs = ChangedFileSetHelper.getByteCodeCfs(project);
                    visitor.addSet(bytecodeCfs);

                    delta.accept(visitor);

                    // save the state
                    mConvertToDex |= visitor.checkSet(bytecodeCfs);
                    mBuildFinalPackage |= visitor.checkSet(javaResCfs);
                }
            }
        }

        // store the build status in the persistent storage
        saveProjectBooleanProperty(PROPERTY_CONVERT_TO_DEX, mConvertToDex);
        saveProjectBooleanProperty(PROPERTY_PACKAGE_RESOURCES, mPackageResources);
        saveProjectBooleanProperty(PROPERTY_BUILD_APK, mBuildFinalPackage);

        // Top level check to make sure the build can move forward. Only do this after recording
        // delta changes.
        abortOnBadSetup(javaProject);

        // remove older packaging markers.
        removeMarkersFromContainer(javaProject.getProject(), AdtConstants.MARKER_PACKAGING);

        if (androidOutputFolder == null) {
            // mark project and exit
            markProject(AdtConstants.MARKER_PACKAGING, Messages.Failed_To_Get_Output, IMarker.SEVERITY_ERROR);
            return allRefProjects;
        }

        // finished with the common init and tests. Special case of the library.
        if (isLibrary) {
            // check the jar output file is present, if not create it.
            IFile jarIFile = androidOutputFolder
                    .getFile(project.getName().toLowerCase() + AdtConstants.DOT_JAR);
            if (mConvertToDex == false && jarIFile.exists() == false) {
                mConvertToDex = true;
            }

            // also update the crunch cache always since aapt does it smartly only
            // on the files that need it.
            if (DEBUG_LOG) {
                AdtPlugin.log(IStatus.INFO, "%s running crunch!", project.getName());
            }
            BuildHelper helper = new BuildHelper(project, mOutStream, mErrStream, true /*debugMode*/,
                    AdtPrefs.getPrefs().getBuildVerbosity() == BuildVerbosity.VERBOSE, mResourceMarker);
            updateCrunchCache(project, helper);

            // refresh recursively bin/res folder
            resOutputFolder.refreshLocal(IResource.DEPTH_INFINITE, monitor);

            if (mConvertToDex) { // in this case this means some class files changed and
                                 // we need to update the jar file.
                if (DEBUG_LOG) {
                    AdtPlugin.log(IStatus.INFO, "%s updating jar!", project.getName());
                }

                // resource to the AndroidManifest.xml file
                IFile manifestFile = project.getFile(SdkConstants.FN_ANDROID_MANIFEST_XML);
                String appPackage = AndroidManifest.getPackage(new IFileWrapper(manifestFile));

                IFolder javaOutputFolder = BaseProjectHelper.getJavaOutputFolder(project);

                writeLibraryPackage(jarIFile, project, appPackage, javaOutputFolder);
                saveProjectBooleanProperty(PROPERTY_CONVERT_TO_DEX, mConvertToDex = false);

                // refresh the bin folder content with no recursion to update the library
                // jar file.
                androidOutputFolder.refreshLocal(IResource.DEPTH_ONE, monitor);

                // Also update the projects. The only way to force recompile them is to
                // reset the library container.
                List<ProjectState> parentProjects = projectState.getParentProjects();
                LibraryClasspathContainerInitializer.updateProject(parentProjects);
            }

            return allRefProjects;
        }

        // Check to see if we're going to launch or export. If not, we can skip
        // the packaging and dexing process.
        if (!args.containsKey(POST_C_REQUESTED) && AdtPrefs.getPrefs().getBuildSkipPostCompileOnFileSave()) {
            AdtPlugin.printBuildToConsole(BuildVerbosity.VERBOSE, project, Messages.Skip_Post_Compiler);
            return allRefProjects;
        } else {
            AdtPlugin.printBuildToConsole(BuildVerbosity.VERBOSE, project, Messages.Start_Full_Post_Compiler);
        }

        // first thing we do is check that the SDK directory has been setup.
        String osSdkFolder = AdtPlugin.getOsSdkFolder();

        if (osSdkFolder.length() == 0) {
            // this has already been checked in the precompiler. Therefore,
            // while we do have to cancel the build, we don't have to return
            // any error or throw anything.
            return allRefProjects;
        }

        // do some extra check, in case the output files are not present. This
        // will force to recreate them.
        IResource tmp = null;

        if (mPackageResources == false) {
            // check the full resource package
            tmp = androidOutputFolder.findMember(AdtConstants.FN_RESOURCES_AP_);
            if (tmp == null || tmp.exists() == false) {
                mPackageResources = true;
            }
        }

        // check classes.dex is present. If not we force to recreate it.
        if (mConvertToDex == false) {
            tmp = androidOutputFolder.findMember(SdkConstants.FN_APK_CLASSES_DEX);
            if (tmp == null || tmp.exists() == false) {
                mConvertToDex = true;
            }
        }

        // also check the final file(s)!
        String finalPackageName = ProjectHelper.getApkFilename(project, null /*config*/);
        if (mBuildFinalPackage == false) {
            tmp = androidOutputFolder.findMember(finalPackageName);
            if (tmp == null || (tmp instanceof IFile && tmp.exists() == false)) {
                String msg = String.format(Messages.s_Missing_Repackaging, finalPackageName);
                AdtPlugin.printBuildToConsole(BuildVerbosity.VERBOSE, project, msg);
                mBuildFinalPackage = true;
            }
        }

        // at this point we know if we need to recreate the temporary apk
        // or the dex file, but we don't know if we simply need to recreate them
        // because they are missing

        // refresh the output directory first
        IContainer ic = androidOutputFolder.getParent();
        if (ic != null) {
            ic.refreshLocal(IResource.DEPTH_ONE, monitor);
        }

        // Get the DX output stream. Since the builder is created for the life of the
        // project, they can be kept around.
        if (mOutStream == null) {
            mOutStream = new AndroidPrintStream(project, null /*prefix*/, AdtPlugin.getOutStream());
            mErrStream = new AndroidPrintStream(project, null /*prefix*/, AdtPlugin.getOutStream());
        }

        // we need to test all three, as we may need to make the final package
        // but not the intermediary ones.
        if (mPackageResources || mConvertToDex || mBuildFinalPackage) {
            BuildHelper helper = new BuildHelper(project, mOutStream, mErrStream, true /*debugMode*/,
                    AdtPrefs.getPrefs().getBuildVerbosity() == BuildVerbosity.VERBOSE, mResourceMarker);

            IPath androidBinLocation = androidOutputFolder.getLocation();
            if (androidBinLocation == null) {
                markProject(AdtConstants.MARKER_PACKAGING, Messages.Output_Missing, IMarker.SEVERITY_ERROR);
                return allRefProjects;
            }
            String osAndroidBinPath = androidBinLocation.toOSString();

            // resource to the AndroidManifest.xml file
            IFile manifestFile = androidOutputFolder.getFile(SdkConstants.FN_ANDROID_MANIFEST_XML);

            if (manifestFile == null || manifestFile.exists() == false) {
                // mark project and exit
                String msg = String.format(Messages.s_File_Missing, SdkConstants.FN_ANDROID_MANIFEST_XML);
                markProject(AdtConstants.MARKER_PACKAGING, msg, IMarker.SEVERITY_ERROR);
                return allRefProjects;
            }

            // Remove the old .apk.
            // This make sure that if the apk is corrupted, then dx (which would attempt
            // to open it), will not fail.
            String osFinalPackagePath = osAndroidBinPath + File.separator + finalPackageName;
            File finalPackage = new File(osFinalPackagePath);

            // if delete failed, this is not really a problem, as the final package generation
            // handle already present .apk, and if that one failed as well, the user will be
            // notified.
            finalPackage.delete();

            // Check if we need to package the resources.
            if (mPackageResources) {
                // also update the crunch cache always since aapt does it smartly only
                // on the files that need it.
                if (DEBUG_LOG) {
                    AdtPlugin.log(IStatus.INFO, "%s running crunch!", project.getName());
                }
                if (updateCrunchCache(project, helper) == false) {
                    return allRefProjects;
                }

                // refresh recursively bin/res folder
                resOutputFolder.refreshLocal(IResource.DEPTH_INFINITE, monitor);

                if (DEBUG_LOG) {
                    AdtPlugin.log(IStatus.INFO, "%s packaging resources!", project.getName());
                }
                // remove some aapt_package only markers.
                removeMarkersFromContainer(project, AdtConstants.MARKER_AAPT_PACKAGE);

                try {
                    helper.packageResources(manifestFile, libProjects, null /*resfilter*/, 0 /*versionCode */,
                            osAndroidBinPath, AdtConstants.FN_RESOURCES_AP_);
                } catch (AaptExecException e) {
                    BaseProjectHelper.markResource(project, AdtConstants.MARKER_PACKAGING, e.getMessage(),
                            IMarker.SEVERITY_ERROR);
                    return allRefProjects;
                } catch (AaptResultException e) {
                    // attempt to parse the error output
                    String[] aaptOutput = e.getOutput();
                    boolean parsingError = AaptParser.parseOutput(aaptOutput, project);

                    // if we couldn't parse the output we display it in the console.
                    if (parsingError) {
                        AdtPlugin.printErrorToConsole(project, (Object[]) aaptOutput);

                        // if the exec failed, and we couldn't parse the error output (and
                        // therefore not all files that should have been marked, were marked),
                        // we put a generic marker on the project and abort.
                        BaseProjectHelper.markResource(project, AdtConstants.MARKER_PACKAGING,
                                Messages.Unparsed_AAPT_Errors, IMarker.SEVERITY_ERROR);
                    }
                }

                // build has been done. reset the state of the builder
                mPackageResources = false;

                // and store it
                saveProjectBooleanProperty(PROPERTY_PACKAGE_RESOURCES, mPackageResources);
            }

            String classesDexPath = osAndroidBinPath + File.separator + SdkConstants.FN_APK_CLASSES_DEX;

            // then we check if we need to package the .class into classes.dex
            if (mConvertToDex) {
                if (DEBUG_LOG) {
                    AdtPlugin.log(IStatus.INFO, "%s running dex!", project.getName());
                }
                try {
                    Collection<String> dxInputPaths = helper.getCompiledCodePaths();

                    helper.executeDx(javaProject, dxInputPaths, classesDexPath);
                } catch (DexException e) {
                    String message = e.getMessage();

                    AdtPlugin.printErrorToConsole(project, message);
                    BaseProjectHelper.markResource(project, AdtConstants.MARKER_PACKAGING, message,
                            IMarker.SEVERITY_ERROR);

                    Throwable cause = e.getCause();

                    if (cause instanceof NoClassDefFoundError || cause instanceof NoSuchMethodError) {
                        AdtPlugin.printErrorToConsole(project, Messages.Incompatible_VM_Warning,
                                Messages.Requires_1_5_Error);
                    }

                    // dx failed, we return
                    return allRefProjects;
                }

                // build has been done. reset the state of the builder
                mConvertToDex = false;

                // and store it
                saveProjectBooleanProperty(PROPERTY_CONVERT_TO_DEX, mConvertToDex);
            }

            // now we need to make the final package from the intermediary apk
            // and classes.dex.
            // This is the default package with all the resources.

            try {
                if (DEBUG_LOG) {
                    AdtPlugin.log(IStatus.INFO, "%s making final package!", project.getName());
                }
                helper.finalDebugPackage(osAndroidBinPath + File.separator + AdtConstants.FN_RESOURCES_AP_,
                        classesDexPath, osFinalPackagePath, libProjects, mResourceMarker);
            } catch (KeytoolException e) {
                String eMessage = e.getMessage();

                // mark the project with the standard message
                String msg = String.format(Messages.Final_Archive_Error_s, eMessage);
                BaseProjectHelper.markResource(project, AdtConstants.MARKER_PACKAGING, msg,
                        IMarker.SEVERITY_ERROR);

                // output more info in the console
                AdtPlugin.printErrorToConsole(project, msg,
                        String.format(Messages.ApkBuilder_JAVA_HOME_is_s, e.getJavaHome()),
                        Messages.ApkBuilder_Update_or_Execute_manually_s, e.getCommandLine());

                return allRefProjects;
            } catch (ApkCreationException e) {
                String eMessage = e.getMessage();

                // mark the project with the standard message
                String msg = String.format(Messages.Final_Archive_Error_s, eMessage);
                BaseProjectHelper.markResource(project, AdtConstants.MARKER_PACKAGING, msg,
                        IMarker.SEVERITY_ERROR);
            } catch (AndroidLocationException e) {
                String eMessage = e.getMessage();

                // mark the project with the standard message
                String msg = String.format(Messages.Final_Archive_Error_s, eMessage);
                BaseProjectHelper.markResource(project, AdtConstants.MARKER_PACKAGING, msg,
                        IMarker.SEVERITY_ERROR);
            } catch (NativeLibInJarException e) {
                String msg = e.getMessage();

                BaseProjectHelper.markResource(project, AdtConstants.MARKER_PACKAGING, msg,
                        IMarker.SEVERITY_ERROR);

                AdtPlugin.printErrorToConsole(project, (Object[]) e.getAdditionalInfo());
            } catch (CoreException e) {
                // mark project and return
                String msg = String.format(Messages.Final_Archive_Error_s, e.getMessage());
                AdtPlugin.printErrorToConsole(project, msg);
                BaseProjectHelper.markResource(project, AdtConstants.MARKER_PACKAGING, msg,
                        IMarker.SEVERITY_ERROR);
            } catch (DuplicateFileException e) {
                String msg1 = String.format(
                        "Found duplicate file for APK: %1$s\nOrigin 1: %2$s\nOrigin 2: %3$s",
                        e.getArchivePath(), e.getFile1(), e.getFile2());
                String msg2 = String.format(Messages.Final_Archive_Error_s, msg1);
                AdtPlugin.printErrorToConsole(project, msg2);
                BaseProjectHelper.markResource(project, AdtConstants.MARKER_PACKAGING, msg2,
                        IMarker.SEVERITY_ERROR);
            }

            // we are done.

            // refresh the bin folder content with no recursion.
            androidOutputFolder.refreshLocal(IResource.DEPTH_ONE, monitor);

            // build has been done. reset the state of the builder
            mBuildFinalPackage = false;

            // and store it
            saveProjectBooleanProperty(PROPERTY_BUILD_APK, mBuildFinalPackage);

            // reset the installation manager to force new installs of this project
            ApkInstallManager.getInstance().resetInstallationFor(project);

            AdtPlugin.printBuildToConsole(BuildVerbosity.VERBOSE, getProject(), "Build Success!");
        }
    } catch (AbortBuildException e) {
        return allRefProjects;
    } catch (Exception exception) {
        // try to catch other exception to actually display an error. This will be useful
        // if we get an NPE or something so that we can at least notify the user that something
        // went wrong.

        // first check if this is a CoreException we threw to cancel the build.
        if (exception instanceof CoreException) {
            if (((CoreException) exception).getStatus().getSeverity() == IStatus.CANCEL) {
                // Project is already marked with an error. Nothing to do
                return allRefProjects;
            }
        }

        String msg = exception.getMessage();
        if (msg == null) {
            msg = exception.getClass().getCanonicalName();
        }

        msg = String.format("Unknown error: %1$s", msg);
        AdtPlugin.logAndPrintError(exception, project.getName(), msg);
        markProject(AdtConstants.MARKER_PACKAGING, msg, IMarker.SEVERITY_ERROR);
    }

    // Benchmarking end
    if (BuildHelper.BENCHMARK_FLAG) {
        String msg = "BENCHMARK ADT: Ending PostCompilation. \n BENCHMARK ADT: Time Elapsed: " + //$NON-NLS-1$
                ((System.nanoTime() - startBuildTime) / Math.pow(10, 6)) + "ms"; //$NON-NLS-1$
        AdtPlugin.printBuildToConsole(BuildVerbosity.ALWAYS, project, msg);
        // End Overall Timer
        msg = "BENCHMARK ADT: Done with everything! \n BENCHMARK ADT: Time Elapsed: " + //$NON-NLS-1$
                (System.nanoTime() - BuildHelper.sStartOverallTime) / Math.pow(10, 6) + "ms"; //$NON-NLS-1$
        AdtPlugin.printBuildToConsole(BuildVerbosity.ALWAYS, project, msg);
    }

    return allRefProjects;
}

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

License:Open Source License

protected SourceProcessor(IJavaProject javaProject, IFolder genFolder, SourceChangeHandler deltaVisitor) {
    mJavaProject = javaProject;/*from w w  w  . j  a  v  a  2  s.c om*/
    mGenFolder = genFolder;
    mDeltaVisitor = deltaVisitor;

    mDeltaVisitor.init(this);

    IProject project = javaProject.getProject();

    // get all the source files
    buildSourceFileList();

    // load the known dependencies
    loadOutputAndDependencies();

    boolean mustCompile = loadState(project);

    // if we stored that we have to compile some files, we build the list that will compile them
    // all. For now we have to reuse the full list since we don't know which files needed
    // compilation.
    if (mustCompile) {
        mToCompile.addAll(mFiles.keySet());
    }
}

From source file:com.android.ide.eclipse.auidt.internal.launch.EmulatorConfigTab.java

License:Open Source License

@Override
public void initializeFrom(ILaunchConfiguration configuration) {
    AvdManager avdManager = Sdk.getCurrent().getAvdManager();

    TargetMode mode = AndroidLaunchConfiguration.parseTargetMode(configuration,
            LaunchConfigDelegate.DEFAULT_TARGET_MODE);

    boolean multipleDevices = mode.isMultiDevice();
    if (multipleDevices && !mSupportMultiDeviceLaunch) {
        // The launch config says to run on multiple devices, but this launch type does not
        // suppport multiple devices. In such a case, switch back to default mode.
        // This could happen if a launch config used for Run is then used for Debug.
        multipleDevices = false;//ww w .j a v  a 2  s  . c  o  m
        mode = LaunchConfigDelegate.DEFAULT_TARGET_MODE;
    }

    mAutoTargetButton.setSelection(mode == TargetMode.AUTO);
    mManualTargetButton.setSelection(mode == TargetMode.MANUAL);
    mAllDevicesTargetButton.setSelection(multipleDevices);

    mDeviceTypeCombo.setEnabled(multipleDevices);
    if (multipleDevices) {
        int index = 0;
        if (mode == TargetMode.ALL_EMULATORS) {
            index = 1;
        } else if (mode == TargetMode.ALL_DEVICES) {
            index = 2;
        }
        mDeviceTypeCombo.select(index);
    }

    // look for the project name to get its target.
    String stringValue = "";
    try {
        stringValue = configuration.getAttribute(IJavaLaunchConfigurationConstants.ATTR_PROJECT_NAME,
                stringValue);
    } catch (CoreException ce) {
        // let's not do anything here, we'll use the default value
    }

    IProject project = null;

    // get the list of existing Android projects from the workspace.
    IJavaProject[] projects = BaseProjectHelper.getAndroidProjects(null /*filter*/);
    if (projects != null) {
        // look for the project whose name we read from the configuration.
        for (IJavaProject p : projects) {
            if (p.getElementName().equals(stringValue)) {
                project = p.getProject();
                break;
            }
        }
    }

    // update the AVD list
    if (project != null) {
        mProjectTarget = Sdk.getCurrent().getTarget(project);
    }

    updateAvdList(avdManager);

    stringValue = "";
    try {
        stringValue = configuration.getAttribute(LaunchConfigDelegate.ATTR_AVD_NAME, stringValue);
    } catch (CoreException e) {
        // let's not do anything here, we'll use the default value
    }

    if (stringValue != null && stringValue.length() > 0 && avdManager != null) {
        AvdInfo targetAvd = avdManager.getAvd(stringValue, true /*validAvdOnly*/);
        mPreferredAvdSelector.setSelection(targetAvd);
    } else {
        mPreferredAvdSelector.setSelection(null);
    }

    boolean value = LaunchConfigDelegate.DEFAULT_WIPE_DATA;
    try {
        value = configuration.getAttribute(LaunchConfigDelegate.ATTR_WIPE_DATA, value);
    } catch (CoreException e) {
        // let's not do anything here, we'll use the default value
    }
    mWipeDataButton.setSelection(value);

    value = LaunchConfigDelegate.DEFAULT_NO_BOOT_ANIM;
    try {
        value = configuration.getAttribute(LaunchConfigDelegate.ATTR_NO_BOOT_ANIM, value);
    } catch (CoreException e) {
        // let's not do anything here, we'll use the default value
    }
    mNoBootAnimButton.setSelection(value);

    int index = -1;

    index = LaunchConfigDelegate.DEFAULT_SPEED;
    try {
        index = configuration.getAttribute(LaunchConfigDelegate.ATTR_SPEED, index);
    } catch (CoreException e) {
        // let's not do anything here, we'll use the default value
    }
    if (index == -1) {
        mSpeedCombo.clearSelection();
    } else {
        mSpeedCombo.select(index);
    }

    index = LaunchConfigDelegate.DEFAULT_DELAY;
    try {
        index = configuration.getAttribute(LaunchConfigDelegate.ATTR_DELAY, index);
    } catch (CoreException e) {
        // let's not do anything here, we'll put a proper value in
        // performApply anyway
    }
    if (index == -1) {
        mDelayCombo.clearSelection();
    } else {
        mDelayCombo.select(index);
    }

    String commandLine = null;
    try {
        commandLine = configuration.getAttribute(LaunchConfigDelegate.ATTR_COMMANDLINE, ""); //$NON-NLS-1$
    } catch (CoreException e) {
        // let's not do anything here, we'll use the default value
    }
    if (commandLine != null) {
        mEmulatorCLOptions.setText(commandLine);
    }
}

From source file:com.android.ide.eclipse.auidt.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, false, null);

    addAction(allAction);/*  w  w  w  . ja  v  a2 s  .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, false, 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, false, 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, true, null);
    addSeparator();
    addAction(clearAction);

    return mMenu;
}

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

License:Open Source License

/**
 * Allocates and returns an {@link AndroidClasspathContainer} object with the proper
 * path to the framework jar file./*  w ww  .ja va2s  .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) {
                    // 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);
                }

                // 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.auidt.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.
 *///from www  .  java  2s  .c o 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.loadTarget(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.auidt.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 w  w  .  ja v  a2 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);
        }
    }
}