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.amazonaws.eclipse.lambda.project.wizard.NewServerlessProjectWizard.java

License:Open Source License

@Override
protected void finishPage(IProgressMonitor monitor) throws InterruptedException, CoreException {

    pageTwo.performFinish(monitor);/*  w w w.j a v a  2 s  . c  o  m*/

    monitor.setTaskName("Creating New Serverless Java project");

    IJavaProject javaProject = pageTwo.getJavaProject();
    final IProject project = javaProject.getProject();

    Display.getDefault().syncExec(new Runnable() {

        public void run() {

            File readmeFile = null;
            LambdaAnalytics.trackServerlessProjectSelection(dataModel);
            try {
                dataModel.buildServerlessModel();
                addSourceToProject(project, dataModel);
                readmeFile = addServerlessReadmeFileToProject(project, dataModel);
                refreshProject(project);

            } catch (Exception e) {
                LambdaAnalytics.trackServerlessProjectCreationFailed();
                LambdaPlugin.getDefault().reportException("Failed to create new Serverless project!", e);
                StatusManager.getManager().handle(new Status(IStatus.ERROR, LambdaPlugin.PLUGIN_ID,
                        "Failed to create new Serverless project", e), StatusManager.SHOW);
                return;
            }

            LambdaAnalytics.trackServerlessProjectCreationSucceeded();

            try {
                IFile handlerClass = findHandlerClassFile(project, dataModel);
                selectAndReveal(handlerClass); // show in explorer
                openHandlerClassEditor(handlerClass); // show in editor
                if (readmeFile != null) {
                    BrowserUtil.openInternalBrowserAsEditor(readmeFile.toURI().toURL());
                }
            } catch (Exception e) {
                LambdaPlugin.getDefault().warn("Failed to open the start up file.", e);
            }
        }
    });
}

From source file:com.amazonaws.eclipse.sdk.ui.AbstractSdkInstall.java

License:Open Source License

/**
 * Writes a metadata file to the SDK Plugin root directory specifying which version
 * of the AWS SDK for Java the specified project is using.
 * @param javaProject The project using this SdkInstall.
 * @throws IOException if the plugin root directory could not be written to.
 *///from w  w  w  . j  a v  a  2 s .c o  m
public void writeMetadataToProject(IJavaProject javaProject) throws IOException {
    SdkProjectMetadata sdkProjectMetadataFile = new SdkProjectMetadata(javaProject.getProject());
    sdkProjectMetadataFile.setSdkInstallRootForProject(this.getRootDirectory());
}

From source file:com.amazonaws.eclipse.sdk.ui.classpath.ClasspathContainerInitializer.java

License:Open Source License

@Override
public void initialize(IPath containerPath, IJavaProject javaProject) throws CoreException {
    try {//  w ww . jav a2s  .  c om
        SdkProjectMetadata sdkProjectMetadataFile = new SdkProjectMetadata(javaProject.getProject());
        File sdkInstallRoot = sdkProjectMetadataFile.getSdkInstallRootForProject();

        if (sdkInstallRoot == null)
            throw new Exception("No SDK install directory specified");

        SdkInstall sdkInstall = new SdkInstall(sdkInstallRoot);
        if (sdkInstall.isValidSdkInstall() == false)
            throw new Exception("Invalid SDK install directory specified: " + sdkInstall.getRootDirectory());

        AwsClasspathContainer classpathContainer = new AwsClasspathContainer(sdkInstall);
        JavaCore.setClasspathContainer(containerPath, new IJavaProject[] { javaProject },
                new IClasspathContainer[] { classpathContainer }, null);
    } catch (Exception e) {
        SdkInstall defaultSdkInstall = SdkManager.getInstance().getDefaultSdkInstall();
        AwsClasspathContainer classpathContainer = new AwsClasspathContainer(defaultSdkInstall);
        JavaCore.setClasspathContainer(containerPath, new IJavaProject[] { javaProject },
                new IClasspathContainer[] { classpathContainer }, null);
        try {
            defaultSdkInstall.writeMetadataToProject(javaProject);
        } catch (IOException ioe) {
            StatusManager.getManager().handle(
                    new Status(Status.WARNING, SdkPlugin.PLUGIN_ID, ioe.getMessage(), ioe), StatusManager.LOG);
        }

        String message = "Unable to initialize previous AWS SDK for Java classpath entries - defaulting to latest version";
        Status status = new Status(Status.WARNING, SdkPlugin.PLUGIN_ID, message, e);
        StatusManager.getManager().handle(status, StatusManager.LOG);
    }
}

From source file:com.amazonaws.eclipse.sdk.ui.wizard.NewAwsJavaProjectWizard.java

License:Open Source License

private void configureNewProject() {
    final IJavaProject javaProject = pageTwo.getJavaProject();
    selectAndReveal(javaProject.getProject());

    IWorkbenchPart activePart = getActivePart();
    if (activePart instanceof IPackagesViewPart) {
        PackageExplorerPart view = PackageExplorerPart.openInActivePerspective();
        view.tryToReveal(javaProject);//from  ww  w.  j  av  a  2s  .c om
    }

    addAwsSdkToProject();

    try {
        addSamplesToProject();
    } catch (CoreException e) {
        e.printStackTrace();
    }

    try {
        addCredentialsToProject();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (CoreException e) {
        e.printStackTrace();
    }

    // Finally, refresh the project so that the new files show up
    try {
        pageTwo.getJavaProject().getProject().refreshLocal(IResource.DEPTH_INFINITE, null);
    } catch (CoreException e) {
        e.printStackTrace();
    }
}

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

License:Open Source License

/**
 * Parses the SDK resources./*from   w ww . j  av a2 s. c om*/
 */
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 (mParseSdkContentIsRunning) {
                    return new Status(IStatus.WARNING, PLUGIN_ID,
                            "An Android SDK is already being loaded. Please try again later.");
                }

                mParseSdkContentIsRunning = 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()) {
                        mSdkLoadedStatus = 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.loadTargetAndBuildTools(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()) {
                        mSdkLoadedStatus = 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 {
                mParseSdkContentIsRunning = false;
                if (monitor != null) {
                    monitor.done();
                }
            }

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

From source file:com.android.ide.eclipse.adt.build.ApkBuilder.java

License:Open Source License

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

    // Top level check to make sure the build can move forward.
    abortOnBadSetup(project);

    // get the list of referenced projects.
    IProject[] referencedProjects = ProjectHelper.getReferencedProjects(project);
    IJavaProject[] referencedJavaProjects = getJavaProjects(referencedProjects);

    // get the output folder, this method returns the path with a trailing
    // separator
    IJavaProject javaProject = JavaCore.create(project);
    IFolder outputFolder = BaseProjectHelper.getOutputFolder(project);

    // now we need to get the classpath list
    ArrayList<IPath> sourceList = BaseProjectHelper.getSourceClasspaths(javaProject);

    // First thing we do is go through the resource delta to not
    // lose it if we have to abort the build for any reason.
    ApkDeltaVisitor dv = null;
    if (kind == FULL_BUILD) {
        AdtPlugin.printBuildToConsole(AdtConstants.BUILD_VERBOSE, project, Messages.Start_Full_Apk_Build);

        mPackageResources = true;
        mConvertToDex = true;
        mBuildFinalPackage = true;
    } else {
        AdtPlugin.printBuildToConsole(AdtConstants.BUILD_VERBOSE, project, Messages.Start_Inc_Apk_Build);

        // go through the resources and see if something changed.
        IResourceDelta delta = getDelta(project);
        if (delta == null) {
            mPackageResources = true;
            mConvertToDex = true;
            mBuildFinalPackage = true;
        } else {
            dv = new ApkDeltaVisitor(this, sourceList, outputFolder);
            delta.accept(dv);

            // save the state
            mPackageResources |= dv.getPackageResources();
            mConvertToDex |= dv.getConvertToDex();
            mBuildFinalPackage |= dv.getMakeFinalPackage();
        }

        // also go through the delta for all the referenced projects, until we are forced to
        // compile anyway
        for (int i = 0; i < referencedJavaProjects.length
                && (mBuildFinalPackage == false || mConvertToDex == false); i++) {
            IJavaProject referencedJavaProject = referencedJavaProjects[i];
            delta = getDelta(referencedJavaProject.getProject());
            if (delta != null) {
                ReferencedProjectDeltaVisitor refProjectDv = new ReferencedProjectDeltaVisitor(
                        referencedJavaProject);
                delta.accept(refProjectDv);

                // save the state
                mConvertToDex |= refProjectDv.needDexConvertion();
                mBuildFinalPackage |= refProjectDv.needMakeFinalPackage();
            }
        }
    }

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

    if (dv != null && dv.mXmlError) {
        AdtPlugin.printBuildToConsole(AdtConstants.BUILD_VERBOSE, project, Messages.Xml_Error);

        // if there was some XML errors, we just return w/o doing
        // anything since we've put some markers in the files anyway
        return referencedProjects;
    }

    if (outputFolder == null) {
        // mark project and exit
        markProject(AdtConstants.MARKER_ADT, Messages.Failed_To_Get_Output, IMarker.SEVERITY_ERROR);
        return referencedProjects;
    }

    // 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 referencedProjects;
    }

    // get the extra configs for the project.
    // The map contains (name, filter) where 'name' is a name to be used in the apk filename,
    // and filter is the resource filter to be used in the aapt -c parameters to restrict
    // which resource configurations to package in the apk.
    Map<String, String> configs = Sdk.getCurrent().getProjectApkConfigs(project);

    // 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 = outputFolder.findMember(AndroidConstants.FN_RESOURCES_AP_);
        if (tmp == null || tmp.exists() == false) {
            mPackageResources = true;
            mBuildFinalPackage = true;
        } else {
            // if the full package is present, we check the filtered resource packages as well
            if (configs != null) {
                Set<Entry<String, String>> entrySet = configs.entrySet();

                for (Entry<String, String> entry : entrySet) {
                    String filename = String.format(AndroidConstants.FN_RESOURCES_S_AP_, entry.getKey());

                    tmp = outputFolder.findMember(filename);
                    if (tmp == null || (tmp instanceof IFile && tmp.exists() == false)) {
                        String msg = String.format(Messages.s_Missing_Repackaging, filename);
                        AdtPlugin.printBuildToConsole(AdtConstants.BUILD_VERBOSE, project, msg);
                        mPackageResources = true;
                        mBuildFinalPackage = true;
                        break;
                    }
                }
            }
        }
    }

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

    // also check the final file(s)!
    String finalPackageName = ProjectHelper.getApkFilename(project, null /*config*/);
    if (mBuildFinalPackage == false) {
        tmp = outputFolder.findMember(finalPackageName);
        if (tmp == null || (tmp instanceof IFile && tmp.exists() == false)) {
            String msg = String.format(Messages.s_Missing_Repackaging, finalPackageName);
            AdtPlugin.printBuildToConsole(AdtConstants.BUILD_VERBOSE, project, msg);
            mBuildFinalPackage = true;
        } else if (configs != null) {
            // if the full apk is present, we check the filtered apk as well
            Set<Entry<String, String>> entrySet = configs.entrySet();

            for (Entry<String, String> entry : entrySet) {
                String filename = ProjectHelper.getApkFilename(project, entry.getKey());

                tmp = outputFolder.findMember(filename);
                if (tmp == null || (tmp instanceof IFile && tmp.exists() == false)) {
                    String msg = String.format(Messages.s_Missing_Repackaging, filename);
                    AdtPlugin.printBuildToConsole(AdtConstants.BUILD_VERBOSE, project, msg);
                    mBuildFinalPackage = true;
                    break;
                }
            }
        }
    }

    // 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 = outputFolder.getParent();
    if (ic != null) {
        ic.refreshLocal(IResource.DEPTH_ONE, monitor);
    }

    // we need to test all three, as we may need to make the final package
    // but not the intermediary ones.
    if (mPackageResources || mConvertToDex || mBuildFinalPackage) {
        IPath binLocation = outputFolder.getLocation();
        if (binLocation == null) {
            markProject(AdtConstants.MARKER_ADT, Messages.Output_Missing, IMarker.SEVERITY_ERROR);
            return referencedProjects;
        }
        String osBinPath = binLocation.toOSString();

        // 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 = osBinPath + 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();

        if (configs != null) {
            Set<Entry<String, String>> entrySet = configs.entrySet();
            for (Entry<String, String> entry : entrySet) {
                String packageFilepath = osBinPath + File.separator
                        + ProjectHelper.getApkFilename(project, entry.getKey());

                finalPackage = new File(packageFilepath);
                finalPackage.delete();
            }
        }

        // first we check if we need to package the resources.
        if (mPackageResources) {
            // remove some aapt_package only markers.
            removeMarkersFromContainer(project, AndroidConstants.MARKER_AAPT_PACKAGE);

            // need to figure out some path before we can execute aapt;

            // resource to the AndroidManifest.xml file
            IResource manifestResource = project
                    .findMember(AndroidConstants.WS_SEP + AndroidConstants.FN_ANDROID_MANIFEST);

            if (manifestResource == null || manifestResource.exists() == false) {
                // mark project and exit
                String msg = String.format(Messages.s_File_Missing, AndroidConstants.FN_ANDROID_MANIFEST);
                markProject(AdtConstants.MARKER_ADT, msg, IMarker.SEVERITY_ERROR);
                return referencedProjects;
            }

            // get the resource folder
            IFolder resFolder = project.getFolder(AndroidConstants.WS_RESOURCES);

            // and the assets folder
            IFolder assetsFolder = project.getFolder(AndroidConstants.WS_ASSETS);

            // we need to make sure this one exists.
            if (assetsFolder.exists() == false) {
                assetsFolder = null;
            }

            IPath resLocation = resFolder.getLocation();
            IPath manifestLocation = manifestResource.getLocation();

            if (resLocation != null && manifestLocation != null) {
                String osResPath = resLocation.toOSString();
                String osManifestPath = manifestLocation.toOSString();

                String osAssetsPath = null;
                if (assetsFolder != null) {
                    osAssetsPath = assetsFolder.getLocation().toOSString();
                }

                // build the default resource package
                if (executeAapt(project, osManifestPath, osResPath, osAssetsPath,
                        osBinPath + File.separator + AndroidConstants.FN_RESOURCES_AP_,
                        null /*configFilter*/) == false) {
                    // aapt failed. Whatever files that needed to be marked
                    // have already been marked. We just return.
                    return referencedProjects;
                }

                // now do the same thing for all the configured resource packages.
                if (configs != null) {
                    Set<Entry<String, String>> entrySet = configs.entrySet();
                    for (Entry<String, String> entry : entrySet) {
                        String outPathFormat = osBinPath + File.separator + AndroidConstants.FN_RESOURCES_S_AP_;
                        String outPath = String.format(outPathFormat, entry.getKey());
                        if (executeAapt(project, osManifestPath, osResPath, osAssetsPath, outPath,
                                entry.getValue()) == false) {
                            // aapt failed. Whatever files that needed to be marked
                            // have already been marked. We just return.
                            return referencedProjects;
                        }
                    }
                }

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

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

        // then we check if we need to package the .class into classes.dex
        if (mConvertToDex) {
            if (executeDx(javaProject, osBinPath, osBinPath + File.separator + AndroidConstants.FN_CLASSES_DEX,
                    referencedJavaProjects) == false) {
                // dx failed, we return
                return referencedProjects;
            }

            // 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.

        String classesDexPath = osBinPath + File.separator + AndroidConstants.FN_CLASSES_DEX;
        if (finalPackage(osBinPath + File.separator + AndroidConstants.FN_RESOURCES_AP_, classesDexPath,
                osFinalPackagePath, javaProject, referencedJavaProjects) == false) {
            return referencedProjects;
        }

        // now do the same thing for all the configured resource packages.
        if (configs != null) {
            String resPathFormat = osBinPath + File.separator + AndroidConstants.FN_RESOURCES_S_AP_;

            Set<Entry<String, String>> entrySet = configs.entrySet();
            for (Entry<String, String> entry : entrySet) {
                // make the filename for the resource package.
                String resPath = String.format(resPathFormat, entry.getKey());

                // make the filename for the apk to generate
                String apkOsFilePath = osBinPath + File.separator
                        + ProjectHelper.getApkFilename(project, entry.getKey());
                if (finalPackage(resPath, classesDexPath, apkOsFilePath, javaProject,
                        referencedJavaProjects) == false) {
                    return referencedProjects;
                }
            }
        }

        // we are done.

        // get the resource to bin
        outputFolder.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(AdtConstants.BUILD_VERBOSE, getProject(), "Build Success!");
    }
    return referencedProjects;
}

From source file:com.android.ide.eclipse.adt.build.ApkBuilder.java

License:Open Source License

/**
 * Execute the Dx tool for dalvik code conversion.
 * @param javaProject The java project//from   w  w  w. ja va2s.  c o  m
 * @param osBinPath the path to the output folder of the project
 * @param osOutFilePath the path of the dex file to create.
 * @param referencedJavaProjects the list of referenced projects for this project.
 *
 * @throws CoreException
 */
private boolean executeDx(IJavaProject javaProject, String osBinPath, String osOutFilePath,
        IJavaProject[] referencedJavaProjects) throws CoreException {
    IAndroidTarget target = Sdk.getCurrent().getTarget(javaProject.getProject());
    AndroidTargetData targetData = Sdk.getCurrent().getTargetData(target);
    if (targetData == null) {
        throw new CoreException(
                new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID, Messages.ApkBuilder_UnableBuild_Dex_Not_loaded));
    }

    // get the dex wrapper
    DexWrapper wrapper = targetData.getDexWrapper();

    if (wrapper == null) {
        throw new CoreException(
                new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID, Messages.ApkBuilder_UnableBuild_Dex_Not_loaded));
    }

    // make sure dx use the proper output streams.
    // first make sure we actually have the streams available.
    if (mOutStream == null) {
        IProject project = getProject();
        mOutStream = AdtPlugin.getOutPrintStream(project, DX_PREFIX);
        mErrStream = AdtPlugin.getErrPrintStream(project, DX_PREFIX);
    }

    try {
        // get the list of libraries to include with the source code
        String[] libraries = getExternalJars();

        // get the list of referenced projects output to add
        String[] projectOutputs = getProjectOutputs(referencedJavaProjects);

        String[] fileNames = new String[1 + projectOutputs.length + libraries.length];

        // first this project output
        fileNames[0] = osBinPath;

        // then other project output
        System.arraycopy(projectOutputs, 0, fileNames, 1, projectOutputs.length);

        // then external jars.
        System.arraycopy(libraries, 0, fileNames, 1 + projectOutputs.length, libraries.length);

        int res = wrapper.run(osOutFilePath, fileNames,
                AdtPlugin.getBuildVerbosity() == AdtConstants.BUILD_VERBOSE, mOutStream, mErrStream);

        if (res != 0) {
            // output error message and marker the project.
            String message = String.format(Messages.Dalvik_Error_d, res);
            AdtPlugin.printErrorToConsole(getProject(), message);
            markProject(AdtConstants.MARKER_ADT, message, IMarker.SEVERITY_ERROR);
            return false;
        }
    } catch (Throwable ex) {
        String message = ex.getMessage();
        if (message == null) {
            message = ex.getClass().getCanonicalName();
        }
        message = String.format(Messages.Dalvik_Error_s, message);
        AdtPlugin.printErrorToConsole(getProject(), message);
        markProject(AdtConstants.MARKER_ADT, message, IMarker.SEVERITY_ERROR);
        if ((ex instanceof NoClassDefFoundError) || (ex instanceof NoSuchMethodError)) {
            AdtPlugin.printErrorToConsole(getProject(), Messages.Incompatible_VM_Warning,
                    Messages.Requires_1_5_Error);
        }
        return false;
    }

    return true;
}

From source file:com.android.ide.eclipse.adt.build.ApkBuilder.java

License:Open Source License

/**
 * Makes the final package. Package the dex files, the temporary resource file into the final
 * package file./*from w w w. j  av a2 s.c  om*/
 * @param intermediateApk The path to the temporary resource file.
 * @param dex The path to the dex file.
 * @param output The path to the final package file to create.
 * @param javaProject
 * @param referencedJavaProjects
 * @return true if success, false otherwise.
 */
private boolean finalPackage(String intermediateApk, String dex, String output, final IJavaProject javaProject,
        IJavaProject[] referencedJavaProjects) {
    FileOutputStream fos = null;
    try {
        IPreferenceStore store = AdtPlugin.getDefault().getPreferenceStore();
        String osKeyPath = store.getString(AdtPlugin.PREFS_CUSTOM_DEBUG_KEYSTORE);
        if (osKeyPath == null || new File(osKeyPath).exists() == false) {
            osKeyPath = DebugKeyProvider.getDefaultKeyStoreOsPath();
            AdtPlugin.printBuildToConsole(AdtConstants.BUILD_VERBOSE, getProject(),
                    Messages.ApkBuilder_Using_Default_Key);
        } else {
            AdtPlugin.printBuildToConsole(AdtConstants.BUILD_VERBOSE, getProject(),
                    String.format(Messages.ApkBuilder_Using_s_To_Sign, osKeyPath));
        }

        // TODO: get the store type from somewhere else.
        DebugKeyProvider provider = new DebugKeyProvider(osKeyPath, null /* storeType */, new IKeyGenOutput() {
            public void err(String message) {
                AdtPlugin.printErrorToConsole(javaProject.getProject(),
                        Messages.ApkBuilder_Signing_Key_Creation_s + message);
            }

            public void out(String message) {
                AdtPlugin.printBuildToConsole(AdtConstants.BUILD_VERBOSE, javaProject.getProject(),
                        Messages.ApkBuilder_Signing_Key_Creation_s + message);
            }
        });
        PrivateKey key = provider.getDebugKey();
        X509Certificate certificate = (X509Certificate) provider.getCertificate();

        if (key == null) {
            String msg = String.format(Messages.Final_Archive_Error_s, Messages.ApkBuilder_Unable_To_Gey_Key);
            AdtPlugin.printErrorToConsole(javaProject.getProject(), msg);
            markProject(AdtConstants.MARKER_ADT, msg, IMarker.SEVERITY_ERROR);
            return false;
        }

        // compare the certificate expiration date
        if (certificate != null && certificate.getNotAfter().compareTo(new Date()) < 0) {
            // TODO, regenerate a new one.
            String msg = String.format(Messages.Final_Archive_Error_s,
                    String.format(Messages.ApkBuilder_Certificate_Expired_on_s,
                            DateFormat.getInstance().format(certificate.getNotAfter())));
            AdtPlugin.printErrorToConsole(javaProject.getProject(), msg);
            markProject(AdtConstants.MARKER_ADT, msg, IMarker.SEVERITY_ERROR);
            return false;
        }

        // create the jar builder.
        fos = new FileOutputStream(output);
        SignedJarBuilder builder = new SignedJarBuilder(fos, key, certificate);

        // add the intermediate file containing the compiled resources.
        AdtPlugin.printBuildToConsole(AdtConstants.BUILD_VERBOSE, getProject(),
                String.format(Messages.ApkBuilder_Packaging_s, intermediateApk));
        FileInputStream fis = new FileInputStream(intermediateApk);
        try {
            builder.writeZip(fis, null /* filter */);
        } finally {
            fis.close();
        }

        // Now we add the new file to the zip archive for the classes.dex file.
        AdtPlugin.printBuildToConsole(AdtConstants.BUILD_VERBOSE, getProject(),
                String.format(Messages.ApkBuilder_Packaging_s, AndroidConstants.FN_CLASSES_DEX));
        File entryFile = new File(dex);
        builder.writeFile(entryFile, AndroidConstants.FN_CLASSES_DEX);

        // Now we write the standard resources from the project and the referenced projects.
        writeStandardResources(builder, javaProject, referencedJavaProjects);

        // Now we write the standard resources from the external libraries
        for (String libraryOsPath : getExternalJars()) {
            AdtPlugin.printBuildToConsole(AdtConstants.BUILD_VERBOSE, getProject(),
                    String.format(Messages.ApkBuilder_Packaging_s, libraryOsPath));
            try {
                fis = new FileInputStream(libraryOsPath);
                builder.writeZip(fis, mJavaResourcesFilter);
            } finally {
                fis.close();
            }
        }

        // now write the native libraries.
        // First look if the lib folder is there.
        IResource libFolder = javaProject.getProject().findMember(SdkConstants.FD_NATIVE_LIBS);
        if (libFolder != null && libFolder.exists() && libFolder.getType() == IResource.FOLDER) {
            // look inside and put .so in lib/* by keeping the relative folder path.
            writeNativeLibraries(libFolder.getFullPath().segmentCount(), builder, libFolder);
        }

        // close the jar file and write the manifest and sign it.
        builder.close();
    } catch (GeneralSecurityException e1) {
        // mark project and return
        String msg = String.format(Messages.Final_Archive_Error_s, e1.getMessage());
        AdtPlugin.printErrorToConsole(javaProject.getProject(), msg);
        markProject(AdtConstants.MARKER_ADT, msg, IMarker.SEVERITY_ERROR);
        return false;
    } catch (IOException e1) {
        // mark project and return
        String msg = String.format(Messages.Final_Archive_Error_s, e1.getMessage());
        AdtPlugin.printErrorToConsole(javaProject.getProject(), msg);
        markProject(AdtConstants.MARKER_ADT, msg, IMarker.SEVERITY_ERROR);
        return false;
    } catch (KeytoolException e) {
        String eMessage = e.getMessage();

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

        // output more info in the console
        AdtPlugin.printErrorToConsole(javaProject.getProject(), msg,
                String.format(Messages.ApkBuilder_JAVA_HOME_is_s, e.getJavaHome()),
                Messages.ApkBuilder_Update_or_Execute_manually_s, e.getCommandLine());
    } catch (AndroidLocationException e) {
        String eMessage = e.getMessage();

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

        // and also output it in the console
        AdtPlugin.printErrorToConsole(javaProject.getProject(), msg);
    } catch (CoreException e) {
        // mark project and return
        String msg = String.format(Messages.Final_Archive_Error_s, e.getMessage());
        AdtPlugin.printErrorToConsole(javaProject.getProject(), msg);
        markProject(AdtConstants.MARKER_ADT, msg, IMarker.SEVERITY_ERROR);
        return false;
    } finally {
        if (fos != null) {
            try {
                fos.close();
            } catch (IOException e) {
                // pass.
            }
        }
    }

    return true;
}

From source file:com.android.ide.eclipse.adt.build.ApkBuilder.java

License:Open Source License

/**
 * Writes the standard resources of a project and its referenced projects
 * into a {@link SignedJarBuilder}.//from   w  ww.  ja v a  2 s.com
 * Standard resources are non java/aidl files placed in the java package folders.
 * @param jarBuilder the {@link SignedJarBuilder}.
 * @param javaProject the javaProject object.
 * @param referencedJavaProjects the java projects that this project references.
 * @throws IOException 
 * @throws CoreException 
 */
private void writeStandardResources(SignedJarBuilder jarBuilder, IJavaProject javaProject,
        IJavaProject[] referencedJavaProjects) throws IOException, CoreException {
    IWorkspace ws = ResourcesPlugin.getWorkspace();
    IWorkspaceRoot wsRoot = ws.getRoot();

    // create a list of path already put into the archive, in order to detect conflict
    ArrayList<String> list = new ArrayList<String>();

    writeStandardProjectResources(jarBuilder, javaProject, wsRoot, list);

    for (IJavaProject referencedJavaProject : referencedJavaProjects) {
        // only include output from non android referenced project
        // (This is to handle the case of reference Android projects in the context of 
        // instrumentation projects that need to reference the projects to be tested).
        if (referencedJavaProject.getProject().hasNature(AndroidConstants.NATURE) == false) {
            writeStandardProjectResources(jarBuilder, referencedJavaProject, wsRoot, list);
        }
    }
}

From source file:com.android.ide.eclipse.adt.build.ApkBuilder.java

License:Open Source License

/**
 * Returns the list of the output folders for the specified {@link IJavaProject} objects, if
 * they are Android projects.//from  w ww. j  a  v a 2  s.  c o  m
 * 
 * @param referencedJavaProjects the java projects.
 * @return an array, always. Can be empty.
 * @throws CoreException
 */
private String[] getProjectOutputs(IJavaProject[] referencedJavaProjects) throws CoreException {
    ArrayList<String> list = new ArrayList<String>();

    IWorkspace ws = ResourcesPlugin.getWorkspace();
    IWorkspaceRoot wsRoot = ws.getRoot();

    for (IJavaProject javaProject : referencedJavaProjects) {
        // only include output from non android referenced project
        // (This is to handle the case of reference Android projects in the context of 
        // instrumentation projects that need to reference the projects to be tested).
        if (javaProject.getProject().hasNature(AndroidConstants.NATURE) == false) {
            // get the output folder
            IPath path = null;
            try {
                path = javaProject.getOutputLocation();
            } catch (JavaModelException e) {
                continue;
            }

            IResource outputResource = wsRoot.findMember(path);
            if (outputResource != null && outputResource.getType() == IResource.FOLDER) {
                String outputOsPath = outputResource.getLocation().toOSString();

                list.add(outputOsPath);
            }
        }
    }

    return list.toArray(new String[list.size()]);
}