Example usage for org.eclipse.jface.operation IRunnableWithProgress IRunnableWithProgress

List of usage examples for org.eclipse.jface.operation IRunnableWithProgress IRunnableWithProgress

Introduction

In this page you can find the example usage for org.eclipse.jface.operation IRunnableWithProgress IRunnableWithProgress.

Prototype

IRunnableWithProgress

Source Link

Usage

From source file:com.motorola.studio.android.devices.services.console.ADBShellHandler.java

License:Apache License

@Override
public IStatus runService(IInstance theInstance, Map<Object, Object> arguments, IProgressMonitor monitor) {
    IStatus status = Status.OK_STATUS;/*from  w w  w .ja v  a2 s  .  com*/
    List<String> command = new LinkedList<String>();
    final IInstance instance = theInstance;

    File sdkPath = new File(SdkUtils.getSdkPath());
    String adbPath = SdkUtils.getAdbPath();
    File adb = new File(adbPath);

    if ((sdkPath != null) && sdkPath.exists() && sdkPath.isDirectory()) {
        if (adb.exists() && adb.isFile()) {
            if (instance instanceof ISerialNumbered) {
                final String[] serialNumber = new String[1];

                serialNumber[0] = ((ISerialNumbered) instance).getSerialNumber();

                if (serialNumber[0] == null) {
                    PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable() {

                        public void run() {
                            ProgressMonitorDialog dialog = new ProgressMonitorDialog(
                                    new Shell(PlatformUI.getWorkbench().getDisplay()));
                            try {
                                dialog.run(false, false, new IRunnableWithProgress() {

                                    public void run(IProgressMonitor monitor)
                                            throws InvocationTargetException, InterruptedException {
                                        int limit = 20;

                                        SubMonitor theMonitor = SubMonitor.convert(monitor);
                                        theMonitor.beginTask(ServicesNLS.ADBShellHandler_WaitingDeviceToLoad,
                                                limit);

                                        int times = 0;

                                        while ((serialNumber[0] == null) && (times < limit)) {
                                            theMonitor.worked(1);
                                            Thread.sleep(500);
                                            serialNumber[0] = ((ISerialNumbered) instance).getSerialNumber();
                                            times++;
                                        }

                                        theMonitor.setWorkRemaining(0);
                                    }
                                });
                            } catch (Exception e) {
                                //do nothing
                            }
                        }
                    });

                }

                // Fix a condition that Studio holds the UI thread forever 
                if (serialNumber[0] == null) {
                    status = new Status(IStatus.ERROR, DeviceServicesPlugin.PLUGIN_ID,
                            ServicesNLS.ERR_ADBShellHandler_CouldNotExecuteTheAdbShell);
                    return status;
                }

                if (adbPath.contains(" ")) //$NON-NLS-1$
                {
                    if (DeviceServicesPlugin.IS_WIN32) {
                        adbPath = "\"" + adbPath + "\""; //$NON-NLS-1$ //$NON-NLS-2$
                    } else {
                        adbPath = adbPath.replace(" ", "\\ "); //$NON-NLS-1$ //$NON-NLS-2$
                    }
                }

                command.add(adbPath);
                command.add(SERIAL_PARAMETER);
                command.add(serialNumber[0]);
                command.add(SHELL_COMMAND);

                try {
                    Integer i = consolesCache.get(serialNumber[0]);
                    i = (i == null ? 1 : ++i);
                    consolesCache.put(serialNumber[0], i);

                    String[] cmdArray = command.toArray(new String[4]);
                    StringBuffer sb = new StringBuffer();
                    for (String cmd : cmdArray) {
                        sb.append(cmd);
                        sb.append(" "); //$NON-NLS-1$
                    }

                    Process p = Runtime.getRuntime().exec(cmdArray);

                    String consoleName = CONSOLE_NAME + " - " + serialNumber[0]; //$NON-NLS-1$

                    if (i != null) {
                        consoleName += " (" + i + ")"; //$NON-NLS-1$ //$NON-NLS-2$
                    }
                    consolesProcesses.put(consoleName, p);
                    DeviceServicesPlugin.redirectProcessStreamsToConsole(p, consoleName);
                    DeviceServicesPlugin.addConsoleKilledListener(listener);
                } catch (IOException e) {
                    status = new Status(IStatus.ERROR, DeviceServicesPlugin.PLUGIN_ID,
                            ServicesNLS.ERR_ADBShellHandler_CouldNotExecuteTheAdbShell, e);
                }
            }

        } else {
            status = new Status(IStatus.ERROR, DeviceServicesPlugin.PLUGIN_ID,
                    ServicesNLS.ERR_ADBShellHandler_MissingAdbShell);
        }
    } else {
        status = new Status(IStatus.ERROR, DeviceServicesPlugin.PLUGIN_ID,
                ServicesNLS.ERR_ADBShellHandler_AndroidSdkIsNotConfigured);
    }

    return status;
}

From source file:com.motorola.studio.android.devices.services.console.EmulatorConsoleHandler.java

License:Apache License

@Override
public IStatus runService(final IInstance instance, Map<Object, Object> arguments, IProgressMonitor monitor) {
    IStatus status = Status.OK_STATUS;//www  .  j  av  a2  s. c o m
    if (instance instanceof ISerialNumbered) {
        // Retrieve the emulator port from its serial number
        Pattern pattern = Pattern.compile("emulator-([0-9]+)");
        final String[] serialNumber = new String[1];

        serialNumber[0] = ((ISerialNumbered) instance).getSerialNumber();
        if (serialNumber[0] == null) {
            PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable() {

                public void run() {
                    ProgressMonitorDialog dialog = new ProgressMonitorDialog(
                            new Shell(PlatformUI.getWorkbench().getDisplay()));
                    try {
                        dialog.run(false, false, new IRunnableWithProgress() {

                            public void run(IProgressMonitor monitor)
                                    throws InvocationTargetException, InterruptedException {
                                int limit = 20;

                                SubMonitor theMonitor = SubMonitor.convert(monitor);
                                theMonitor.beginTask(ServicesNLS.ADBShellHandler_WaitingDeviceToLoad, limit);

                                int times = 0;

                                while ((serialNumber[0] == null) && (times < limit)) {
                                    theMonitor.worked(1);
                                    Thread.sleep(500);
                                    serialNumber[0] = ((ISerialNumbered) instance).getSerialNumber();
                                    times++;
                                }

                                theMonitor.setWorkRemaining(0);
                            }
                        });
                    } catch (Exception e) {
                        //do nothing
                    }
                }
            });
        }

        // Fix a condition that Studio holds the UI thread forever 
        if (serialNumber[0] == null) {
            status = new Status(IStatus.ERROR, DeviceServicesPlugin.PLUGIN_ID,
                    ServicesNLS.ERR_EmulatorConsoleHandler_CouldNotOpenTheConsoleShell);
            return status;
        }

        Matcher matcher = pattern.matcher(serialNumber[0]);
        if (matcher.matches()) {
            String port = matcher.group(1);
            final TelnetFrameworkAndroid telnet = new TelnetFrameworkAndroid();
            try {
                Integer i = consolesCache.get(serialNumber[0]);
                i = (i == null ? 1 : ++i);
                consolesCache.put(serialNumber[0], i);

                telnet.connect(LOCALHOST, Integer.parseInt(port));
                InputStream in = telnet.getInputStream();
                OutputStream out = telnet.getOutputStream();

                String consoleName = CONSOLE_NAME + " - " + serialNumber[0];

                if (i != null) {
                    consoleName += " (" + i + ")";
                }

                telnetsCache.put(consoleName, telnet);
                DeviceServicesPlugin.addConsoleKilledListener(listener);
                DeviceServicesPlugin.redirectStreamsToConsole(in, out, consoleName);
            } catch (IOException e) {
                status = new Status(IStatus.ERROR, DeviceServicesPlugin.PLUGIN_ID,
                        ServicesNLS.ERR_EmulatorConsoleHandler_CouldNotOpenTheConsoleShell, e);
            }
        }
    } else {
        status = new Status(IStatus.ERROR, DeviceServicesPlugin.PLUGIN_ID,
                ServicesNLS.ERR_EmulatorConsoleHandler_CouldNotRetrieveTheEmulatorPort);
    }

    return status;
}

From source file:com.motorola.studio.android.emulator.ui.view.AbstractAndroidView.java

License:Apache License

/**
 * Stops all emulator instances with the Progress Monitor opened. 
 *//* w  w  w.java  2 s .c  o m*/
private void stopEmulatorInstances() {
    // defines the runnable object for stopping emulator instances.
    final IRunnableWithProgress stopRunnable = new IRunnableWithProgress() {
        public void run(IProgressMonitor monitor) {
            Collection<IAndroidEmulatorInstance> startedInstances = DeviceFrameworkManager.getInstance()
                    .getAllStartedInstances();
            boolean errorsHappened = false;

            for (IAndroidEmulatorInstance instance : startedInstances) {
                try {
                    instance.stop(true);
                } catch (InstanceStopException e) {
                    errorsHappened = true;
                }
            }

            // if closing on shutdown, use a progress bar and stall UI
            if (closingOnShutdown) {
                // start a progress monitor
                monitor.beginTask("", IProgressMonitor.UNKNOWN);

                // make sure the stop instance job finished
                Job[] jobs = Job.getJobManager().find(null); // get all jobs
                for (Job job : jobs) {
                    if (job.getName().equals(EmulatorNLS.UI_AbstractAndroidView_StopInstanceJob)) {
                        // when job result is not null, it has finished
                        while (job.getResult() == null) {
                            try {
                                // sleep a little so the waiting is not too busy
                                Thread.sleep(1000);
                            } catch (InterruptedException e) {
                                // do nothing
                            }
                        }
                    }
                }
            }

            if (errorsHappened) {
                EclipseUtils.showErrorDialog(EmulatorNLS.GEN_Error,
                        EmulatorNLS.EXC_AncroidView_CannotRunMultipleStopServices);
            }

        }
    };

    // executes the runnable defined above.
    PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable() {
        public void run() {
            Shell currentShell = getViewSite().getShell();
            ProgressMonitorDialog dialog = new ProgressMonitorDialog(currentShell);
            try {
                dialog.run(true, false, stopRunnable);
            } catch (Exception e) {
                // Should not have exceptions. 
                // The runnable is not interrupted and it handles exceptions internally
                // Log runtime exceptions
                error("Runtime exception was thrown: " + e.getClass().getSimpleName());
            }
        }
    });
}

From source file:com.motorola.studio.android.generatemenucode.ui.GenerateMenuCodeHandler.java

License:Apache License

/**
 * Open {@link GenerateMenuCodeDialog} and use {@link JavaModifierBasedOnMenu} to insert code into Android source code (Activity/Fragment).
 *//*from w w  w  .  jav  a2 s. c o m*/
public Object execute(ExecutionEvent event) throws ExecutionException {
    SelectionBean selectionBean = resolveSelection(event);

    if (selectionBean.isProject() || selectionBean.isAllowedClassInstance()) {

        final IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindow(event);

        GenerateMenuCodeDialog menuDialog = new GenerateMenuCodeDialog(window.getShell(),
                CodeUtilsNLS.GenerateMenuCodeDialog_DefaultMessage, CodeUtilsNLS.GenerateMenuCodeDialog_Title,
                CodeUtilsNLS.GenerateMenuCodeDialog_ShellTitle,
                CodeUtilsActivator.getImageDescriptor(WIZARD_IMAGE_PATH).createImage());

        final JavaModifierBasedOnMenu modifier = new JavaModifierBasedOnMenu();
        menuDialog.init(modifier, selectionBean.getJavaProject(), selectionBean.getJavaFile());

        int status = menuDialog.open();
        if (status == Window.OK) {
            ICompilationUnit compilationUnit = menuDialog.getJavaFile();
            IEditorPart editor = null;
            try {
                editor = JavaUI.openInEditor(compilationUnit);
            } catch (Exception e) {
                StudioLogger.warn(GenerateMenuCodeHandler.class,
                        "Unable to open editor or bring it to front for Java file while trying to generate menu code based on xml file", //$NON-NLS-1$
                        e);
            }
            final ProgressMonitorDialog dialog = new ProgressMonitorDialog(menuDialog.getShell());
            final IEditorPart editorPart = editor;

            PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {

                public void run() {
                    try {

                        dialog.run(true, false, new IRunnableWithProgress() {

                            public void run(IProgressMonitor monitor)
                                    throws InvocationTargetException, InterruptedException {
                                try {
                                    // collect usage data - UDC
                                    StudioLogger.collectUsageData(UsageDataConstants.WHAT_VIEW_BY_MENU_EXEC,
                                            UsageDataConstants.KIND_VIEW_BY_MENU_EXEC,
                                            "View by menu feature executed.", //$NON-NLS-1$
                                            CodeUtilsActivator.PLUGIN_ID, CodeUtilsActivator.getDefault()
                                                    .getBundle().getVersion().toString());
                                    modifier.insertCode(monitor, editorPart);
                                } catch (final JavaModelException e) {
                                    final MultiStatus errorStatus = new MultiStatus(
                                            CodeUtilsActivator.PLUGIN_ID, IStatus.ERROR,
                                            "Error inserting code on activity/fragment based on menu", //$NON-NLS-1$
                                            null);
                                    errorStatus.merge(e.getStatus());

                                    PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {

                                        public void run() {
                                            IStatus mostSevere = EclipseUtils.findMostSevereError(errorStatus);
                                            ErrorDialog.openError(
                                                    PlatformUI.getWorkbench().getDisplay().getActiveShell(),
                                                    "Error inserting code on activity/fragment based on menu", //$NON-NLS-1$
                                                    e.getMessage(), mostSevere);
                                        }
                                    });
                                    StudioLogger.error(this.getClass(),
                                            "Error inserting code on activity/fragment based on menu" //$NON-NLS-1$
                                                    + ": " + e.getMessage()); //$NON-NLS-1$
                                }
                            }
                        });
                    } catch (Exception e) {
                        StudioLogger.error(this.getClass(),
                                "Error inserting code on activity/fragment based on menu" //$NON-NLS-1$
                                        + ": " + e.getMessage()); //$NON-NLS-1$
                    }
                }
            });
        }
    } else {
        EclipseUtils.showErrorDialog(CodeUtilsNLS.GenerateMenuCodeDialog_Title,
                CodeUtilsNLS.GenerateMenuCodeHandler_SelectedClassNeitherActivityFragment);//GenerateMenuCodeHandler_SelectedClassNeitherActivityFragment
    }

    return null;
}

From source file:com.motorola.studio.android.generateviewbylayout.ui.AbstractCodeGeneratorHandler.java

License:Apache License

protected static void executeCodeGenerationWizard(ExecutionEvent event, IFile javaFile,
        final IProject javaProject, final AbstractLayoutItemsDialog layoutDialog) {
    final JavaModifierBasedOnLayout modifier = new JavaModifierBasedOnLayout();

    layoutDialog.init(modifier, javaProject, javaFile);

    int status = layoutDialog.open();
    if (status == Window.OK) {
        ICompilationUnit compilationUnit = layoutDialog.getJavaFile();
        IEditorPart editor = null;/*w ww  .  ja v a2  s  .  c om*/
        try {
            editor = JavaUI.openInEditor(compilationUnit);
        } catch (Exception e) {
            StudioLogger.warn(AbstractCodeGeneratorHandler.class,
                    "Unable to open editor or bring it to front for Java file while trying to generate code from layout xml file", //$NON-NLS-1$
                    e);
        }
        final ProgressMonitorDialog dialog = new ProgressMonitorDialog(layoutDialog.getShell());
        final IEditorPart editorPart = editor;

        PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {

            public void run() {
                try {

                    dialog.run(true, false, new IRunnableWithProgress() {

                        public void run(IProgressMonitor monitor)
                                throws InvocationTargetException, InterruptedException {
                            try {

                                // collect usage data - UDC
                                StudioLogger.collectUsageData(UsageDataConstants.WHAT_VIEW_BY_LAYOUT_EXEC,
                                        UsageDataConstants.KIND_VIEW_BY_LAYOUT_EXEC,
                                        "View by layout feature executed.", //$NON-NLS-1$
                                        CodeUtilsActivator.PLUGIN_ID,
                                        CodeUtilsActivator.getDefault().getBundle().getVersion().toString());
                                modifier.insertCode(monitor, editorPart);
                            }

                            catch (final JavaModelException e) {
                                final MultiStatus errorStatus = new MultiStatus(CodeUtilsActivator.PLUGIN_ID,
                                        IStatus.ERROR,
                                        "Error inserting code on activity/fragment based on layout", null);
                                errorStatus.merge(e.getStatus());

                                PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {

                                    public void run() {
                                        IStatus mostSevere = EclipseUtils.findMostSevereError(errorStatus);
                                        ErrorDialog.openError(
                                                PlatformUI.getWorkbench().getDisplay().getActiveShell(),
                                                "Error inserting code on activity/fragment based on layout",
                                                e.getMessage(), mostSevere);
                                    }
                                });
                                StudioLogger.error(this.getClass(),
                                        "Error inserting code on activity/fragment based on layout" + ": " //$NON-NLS-2$
                                                + e.getMessage());
                            }
                        }
                    });
                } catch (Exception e) {
                    StudioLogger.error(this.getClass(),
                            "Error inserting code on activity/fragment based on layout" + ": " //$NON-NLS-2$
                                    + e.getMessage());
                }
            }
        });
    }
}

From source file:com.motorola.studio.android.packaging.ui.export.PackageExportWizardArea.java

License:Apache License

/**
 * do the finish: Create the package for each selected descriptor
 *//*from  w w  w  .j  a v a  2  s .  c o  m*/
public boolean performFinish() {
    final boolean[] finished = { false };
    boolean destOK = false;
    final MultiStatus status = new MultiStatus(PackagingUIPlugin.PLUGIN_ID, IStatus.OK, "", null); //$NON-NLS-1$
    ProgressMonitorDialog monitorDialog = null;
    String DESCRIPTION_TO_LOG = StudioLogger.DESCRIPTION_DEFAULT;

    try {
        destOK = checkDestination();
    } catch (CoreException e) {
        status.add(e.getStatus());
    }

    if (destOK) {
        monitorDialog = new ProgressMonitorDialog(parentComposite.getShell());
        try {
            monitorDialog.run(false, false, new IRunnableWithProgress() {

                @Override
                public void run(IProgressMonitor aMonitor)
                        throws InvocationTargetException, InterruptedException {
                    int finishSize = getSelectedItems().size() * PackagingUIPlugin.PROGRESS_MONITOR_MULTIPLIER;
                    SubMonitor monitor = SubMonitor.convert(aMonitor);
                    monitor.beginTask(Messages.PACKAGE_EXPORT_WIZARD_AREA_FINISH_ACTION_LABEL, finishSize);
                    IPath exportDestinationFolder = new Path(destinationText.getText());
                    IPath exportDestinationFile = null;

                    for (TreeItem item : getSelectedItems()) {
                        // get the eclipse project as a java project to get
                        // the project
                        // destination
                        IProject eclipseProject = (IProject) item.getData();
                        try {
                            monitor.worked(PackagingUIPlugin.PROGRESS_MONITOR_MULTIPLIER / 4);

                            JavaProject javaProject = new JavaProject();
                            javaProject.setProject(eclipseProject);

                            // find all packages built by Android builder
                            Map<String, String> apkConfigurations = SdkUtils
                                    .getAPKConfigurationsForProject(eclipseProject);

                            Set<String> apkConfNames = new HashSet<String>();
                            if (apkConfigurations != null) {
                                apkConfNames.addAll(apkConfigurations.keySet());
                            }
                            apkConfNames.add(""); // the default package //$NON-NLS-1$

                            SubMonitor submonitor = monitor
                                    .newChild(PackagingUIPlugin.PROGRESS_MONITOR_MULTIPLIER / 4);

                            submonitor.beginTask(Messages.PACKAGE_EXPORT_WIZARD_AREA_EXPORTING_ACTION_LABEL,
                                    3 * PackagingUIPlugin.PROGRESS_MONITOR_MULTIPLIER * apkConfNames.size());

                            for (String apkConfName : apkConfNames) {

                                String apkName = eclipseProject.getName() + (apkConfName.isEmpty() ? apkConfName
                                        : "-" //$NON-NLS-1$ //$NON-NLS-2$
                                                + apkConfName);
                                if (defaultDestination.getSelection()) {
                                    exportDestinationFolder = eclipseProject.getLocation()
                                            .append(CertificateManagerActivator.PACKAGE_PROJECT_DESTINATION);
                                }
                                exportDestinationFile = exportDestinationFolder.append(apkName)
                                        .addFileExtension(CertificateManagerActivator.PACKAGE_EXTENSION);
                                File file = exportDestinationFile.toFile();
                                submonitor.worked(PackagingUIPlugin.PROGRESS_MONITOR_MULTIPLIER);

                                //always export unsigned package
                                AdtUtils.exportUnsignedReleaseApk(javaProject.getProject(), file, submonitor);

                                submonitor.worked(PackagingUIPlugin.PROGRESS_MONITOR_MULTIPLIER);

                                if (signCheckBox.getSelection()) {
                                    //sign the package if required
                                    IStatus signStatus = signPackage(eclipseProject, file);
                                    status.add(signStatus);
                                }

                                //zipalign the file and we are done exporting the package
                                PackageFile.zipAlign(file);

                                submonitor.worked(PackagingUIPlugin.PROGRESS_MONITOR_MULTIPLIER);
                            }
                            submonitor.done();
                        } catch (CoreException e) {
                            StudioLogger.error(PackageExportWizardArea.class,
                                    "Error while building project or getting project output folder" //$NON-NLS-1$
                                            + eclipseProject.getName(),
                                    e);
                            status.add(new Status(IStatus.ERROR, PackagingUIPlugin.PLUGIN_ID,
                                    Messages.PACKAGE_EXPORT_WIZARD_AREA_ERROR_PROJECT_BUILD + " " //$NON-NLS-1$
                                            + eclipseProject.getName()));
                        } finally {
                            try {
                                eclipseProject.refreshLocal(IResource.DEPTH_INFINITE,
                                        monitor.newChild(PackagingUIPlugin.PROGRESS_MONITOR_MULTIPLIER / 4));
                            } catch (CoreException e) {
                                // do nothing
                            }
                        }
                        monitor.worked(PackagingUIPlugin.PROGRESS_MONITOR_MULTIPLIER / 4);
                    }
                    finished[0] = true;

                }
            });
        } catch (Exception e) {
            StudioLogger.warn("Error finishing package export.");
        }
    }

    if (!status.isOK()) {
        status.getMessage();
        DESCRIPTION_TO_LOG = Messages.PACKAGE_EXPORT_WIZARD_AREA_READONLY_TITLE;
        ErrorDialog.openError(parentComposite.getShell(), Messages.PACKAGE_EXPORT_WIZARD_AREA_READONLY_TITLE,
                Messages.PACKAGE_EXPORT_WIZARD_AREA_READONLY_MESSAGE, status);
    }

    // Saving usage data
    try {
        StudioLogger.collectUsageData(StudioLogger.WHAT_APP_MANAGEMENT_PACKAGE,
                StudioLogger.KIND_APP_MANAGEMENT, DESCRIPTION_TO_LOG, PackagingUIPlugin.PLUGIN_ID,
                PackagingUIPlugin.getDefault().getBundle().getVersion().toString());
    } catch (Throwable e) {
        // Do nothing, but error on the log should never prevent app from
        // working
    }

    return finished[0];
}

From source file:com.motorolamobility.studio.android.certmanager.ui.wizards.RemoveExternalPackageSignatureWizard.java

License:Apache License

/**
 * Finishes this wizard removing packages signatures
 *//*from  w  w w.  j  a  va  2  s.  co  m*/
@Override
public boolean performFinish() {
    final List<String> defectivePackages = new ArrayList<String>();
    IRunnableWithProgress finishAction = new IRunnableWithProgress() {

        @Override
        public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
            List<String> selectedFiles = RemoveExternalPackageSignatureWizard.this.page.getSelectedPackages();
            monitor.beginTask(CertificateManagerNLS.UNSIGN_EXTERNAL_PKG_WIZARD_WINDOW_TITLE,
                    selectedFiles.size());
            for (String selected : selectedFiles) {
                File file = new File(selected);
                monitor.setTaskName(
                        CertificateManagerNLS.UNSIGN_EXTERNAL_PKG_WIZARD_OPERATION + " " + file.getName());
                if ((file != null) && file.exists() && file.isFile() && file.canWrite()) {
                    OutputStream fileToWrite = null;
                    JarFile jar = null;
                    PackageFile pack = null;
                    try {
                        // Open package and remove signature
                        jar = new JarFile(file);
                        pack = new PackageFile(jar);
                        try {
                            pack.removeMetaEntryFiles();
                        } catch (IOException e) {
                            StudioLogger.error(RemoveExternalPackageSignatureWizard.class.toString(),
                                    "Impossible to delete temporary files");
                            throw e;
                        }

                        // Write the new package file
                        fileToWrite = new FileOutputStream(file);
                        pack.write(fileToWrite);
                        PackageFile.zipAlign(file);
                    } catch (IOException e) {
                        defectivePackages.add(selected);
                        StudioLogger.error(RemoveExternalPackageSignatureWizard.class.toString(),
                                "Impossible write to package: " + selected + " " + e.getMessage());
                    } catch (SecurityException e) {
                        defectivePackages.add(selected);
                        StudioLogger.error(RemoveExternalPackageSignatureWizard.class.toString(),
                                "Impossible write to package: " + selected + " " + e.getMessage());
                    } finally {

                        System.gc(); // Force garbage collector to avoid
                        // errors when deleting temp files

                        try {
                            if (jar != null) {
                                jar.close();
                            }

                            if (pack != null) {
                                pack.removeTemporaryEntryFiles();
                            }

                            if (fileToWrite != null) {
                                fileToWrite.close();
                            }
                        } catch (IOException e) {
                            // Silent exception. Only log the deletion
                            // exception.
                            StudioLogger.error(CertificateManagerActivator.PLUGIN_ID,
                                    "Deleting temporary files");
                        }
                    }
                } else {
                    defectivePackages.add(selected);
                }
                monitor.worked(1);
            }
            monitor.done();
        }

    };

    try {
        PlatformUI.getWorkbench().getProgressService().runInUI(new ProgressMonitorDialog(getShell()),
                finishAction, null);
    } catch (InvocationTargetException e1) {
        StudioLogger.error(RemoveExternalPackageSignatureWizard.class.toString(),
                "Error running finish actions");
    } catch (InterruptedException e1) {
        StudioLogger.error(RemoveExternalPackageSignatureWizard.class.toString(),
                "Error running finish actions");
    }

    if (ResourcesPlugin.getWorkspace().getRoot().getLocation().isPrefixOf(this.page.getSourcePath())) {
        org.eclipse.ui.actions.WorkspaceModifyOperation op = new org.eclipse.ui.actions.WorkspaceModifyOperation() {

            @Override
            protected void execute(IProgressMonitor monitor)
                    throws CoreException, InvocationTargetException, InterruptedException {
                for (IContainer container : ResourcesPlugin.getWorkspace().getRoot().findContainersForLocation(
                        RemoveExternalPackageSignatureWizard.this.page.getSourcePath())) {

                    container.refreshLocal(IResource.DEPTH_INFINITE, monitor);
                }

            }

        };
        try {
            PlatformUI.getWorkbench().getProgressService().run(false, false, op);
        } catch (InvocationTargetException e) {
            StudioLogger.error(RemoveExternalPackageSignatureWizard.class.toString(),
                    "Error refreshing workspace");
        } catch (InterruptedException e) {
            StudioLogger.error(RemoveExternalPackageSignatureWizard.class.toString(),
                    "Error refreshing workspace");
        }
    }

    if (!defectivePackages.isEmpty()) {
        MultiStatus errors = new MultiStatus(CertificateManagerActivator.PLUGIN_ID, IStatus.ERROR,
                CertificateManagerNLS.UNSIGN_EXTERNAL_PKG_WIZARD_ERROR_REASON, null);
        for (String defect : defectivePackages) {
            errors.add(new Status(IStatus.ERROR, CertificateManagerActivator.PLUGIN_ID, defect));
        }

        ErrorDialog errorBox = new ErrorDialog(getShell(),
                CertificateManagerNLS.UNSIGN_EXTERNAL_PKG_WIZARD_WINDOW_TITLE,
                CertificateManagerNLS.UNSIGN_EXTERNAL_PKG_WIZARD_ERROR, errors, IStatus.ERROR);
        errorBox.open();
    }

    return true;
}

From source file:com.motorolamobility.studio.android.certmanager.ui.wizards.SignExternalPackageWizard.java

License:Apache License

/**
 * Finishes this wizard, signing the selected packages
 *//*from   w  w w.  j  a v a2 s  .  co m*/
@Override
public boolean performFinish() {
    final List<String> defectivePackages = new ArrayList<String>();
    IRunnableWithProgress finishAction = new IRunnableWithProgress() {

        @Override
        public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
            List<String> selectedFiles = SignExternalPackageWizard.this.page.getSelectedPackages();
            monitor.beginTask(CertificateManagerNLS.SIGN_EXTERNAL_PKG_WIZARD_WINDOW_TITLE,
                    selectedFiles.size() * 2);
            for (String selected : selectedFiles) {
                File file = new File(selected);
                monitor.setTaskName(
                        CertificateManagerNLS.SIGN_EXTERNAL_PKG_WIZARD_OPERATION + " " + file.getName());
                if ((file != null) && file.exists() && file.isFile() && file.canWrite()) {
                    OutputStream fileToWrite = null;
                    PackageFile pack = null;
                    JarFile jar = null;
                    try {

                        // Update monitor
                        monitor.worked(1);
                        monitor.setTaskName(CertificateManagerNLS.SIGN_EXTERNAL_PKG_WIZARD_OPERATION + " "
                                + file.getName());

                        String keyStorePassword = SignExternalPackageWizard.this.page.getKeystorePassword();
                        if (SignExternalPackageWizard.this.page.getSavePasswordSelection()) {
                            SignExternalPackageWizard.this.page.getPasswordProvider()
                                    .saveKeyStorePassword(keyStorePassword);
                        }
                        String keyEntryPassword = SignExternalPackageWizard.this.page.getKeyEntryPassword();
                        boolean keepTrying;
                        if (keyEntryPassword != null) {
                            keepTrying = true;
                        } else {
                            keepTrying = false;
                            throw new Exception();
                        }
                        while (keepTrying) {
                            try {
                                // Open package and remove signature
                                jar = new JarFile(file);
                                pack = new PackageFile(jar);
                                pack.removeMetaEntryFiles();

                                // Sign the new package
                                PackageFileSigner.signPackage(pack,
                                        SignExternalPackageWizard.this.page.getSelectedKeyEntry(),
                                        keyEntryPassword, PackageFileSigner.MOTODEV_STUDIO);
                                keepTrying = false;
                            } catch (UnrecoverableKeyException sE) {
                                keyEntryPassword = SignExternalPackageWizard.this.page.getPasswordProvider()
                                        .getPassword(SignExternalPackageWizard.this.page.getSelectedKeyEntry()
                                                .getAlias(), true, false);
                                if (keyEntryPassword == null) {
                                    keepTrying = false;
                                } else {
                                    keepTrying = true;
                                }
                            }
                        }

                        // Write the new package file
                        fileToWrite = new FileOutputStream(file);
                        pack.write(fileToWrite);
                        PackageFile.zipAlign(file);
                    } catch (IOException e) {
                        defectivePackages.add(selected);
                        StudioLogger.error(SignExternalPackageWizard.class.toString(),
                                "Impossible write to package: " + selected + " " + e.getMessage());
                    } catch (SignException e) {
                        defectivePackages.add(selected);
                        StudioLogger.error(SignExternalPackageWizard.class.toString(),
                                "Impossible sign the package: " + selected + " " + e.getMessage());
                    } catch (SecurityException e) {
                        defectivePackages.add(selected);
                        StudioLogger.error(SignExternalPackageWizard.class.toString(),
                                "Impossible sign the package: " + selected + " " + e.getMessage());
                    } catch (Exception e) {
                        defectivePackages.add(selected);
                        StudioLogger.error(SignExternalPackageWizard.class.toString(),
                                "Impossible sign the package: " + selected + " " + e.getMessage());
                    } finally {
                        System.gc(); // Force garbage collector to avoid
                        // errors when deleting temp files

                        try {
                            if (pack != null) {
                                pack.removeTemporaryEntryFiles();
                            }

                            if (fileToWrite != null) {
                                fileToWrite.close();
                            }

                            if (jar != null) {
                                jar.close();
                            }
                        } catch (IOException e) {
                            // Silent exception. Only log the deletion
                            // exception.
                            StudioLogger.error(CertificateManagerActivator.PLUGIN_ID,
                                    "Deleting temporary files");
                        }
                    }
                } else {
                    defectivePackages.add(selected);
                }
                monitor.worked(1);
            }
            monitor.done();
        }

    };

    try {
        PlatformUI.getWorkbench().getProgressService().runInUI(new ProgressMonitorDialog(getShell()),
                finishAction, null);
    } catch (InvocationTargetException e1) {
        StudioLogger.error(SignExternalPackageWizard.class.toString(), "Error running finish actions");
    } catch (InterruptedException e1) {
        StudioLogger.error(SignExternalPackageWizard.class.toString(), "Error running finish actions");
    }

    if (ResourcesPlugin.getWorkspace().getRoot().getLocation().isPrefixOf(this.page.getSourcePath())) {
        WorkspaceModifyOperation op = new WorkspaceModifyOperation() {

            @Override
            protected void execute(IProgressMonitor monitor)
                    throws CoreException, InvocationTargetException, InterruptedException {
                for (IContainer container : ResourcesPlugin.getWorkspace().getRoot()
                        .findContainersForLocation(SignExternalPackageWizard.this.page.getSourcePath())) {

                    container.refreshLocal(IResource.DEPTH_INFINITE, monitor);
                }

            }

        };
        try {
            PlatformUI.getWorkbench().getProgressService().run(false, false, op);
        } catch (InvocationTargetException e) {
            StudioLogger.error(SignExternalPackageWizard.class.toString(), "Error refreshing workspace");
        } catch (InterruptedException e) {
            StudioLogger.error(SignExternalPackageWizard.class.toString(), "Error refreshing workspace");
        }
    }
    if (!defectivePackages.isEmpty()) {
        MultiStatus errors = new MultiStatus(CertificateManagerActivator.PLUGIN_ID, IStatus.ERROR,
                CertificateManagerNLS.UNSIGN_EXTERNAL_PKG_WIZARD_ERROR_REASON, null);
        for (String defect : defectivePackages) {
            errors.add(new Status(IStatus.ERROR, CertificateManagerActivator.PLUGIN_ID, defect));
        }

        ErrorDialog errorBox = new ErrorDialog(getShell(),
                CertificateManagerNLS.SIGN_EXTERNAL_PKG_WIZARD_WINDOW_TITLE,
                CertificateManagerNLS.SIGN_EXTERNAL_PKG_WIZARD_ERROR, errors, IStatus.ERROR);
        errorBox.open();
    }
    return true;

}

From source file:com.mountainminds.eclemma.internal.ui.wizards.SessionExportWizard.java

License:Open Source License

private boolean createReport() {
    final ICoverageSession session = page1.getSelectedSession();
    final ISessionExporter exporter = CoverageTools.getExporter(session);
    exporter.setFormat(page1.getExportFormat());
    exporter.setDestination(page1.getDestination());
    final IRunnableWithProgress op = new IRunnableWithProgress() {
        public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
            try {
                exporter.export(monitor);
            } catch (Exception e) {
                throw new InvocationTargetException(e);
            }//  www . j a  va2s.c  om
        }
    };
    try {
        getContainer().run(true, true, op);
    } catch (InterruptedException e) {
        return false;
    } catch (InvocationTargetException ite) {
        final Throwable ex = ite.getTargetException();
        EclEmmaUIPlugin.log(ex);
        final String title = UIMessages.ExportReportErrorDialog_title;
        String msg = UIMessages.ExportReportErrorDialog_message;
        msg = NLS.bind(msg, session.getDescription());
        final IStatus status;
        if (ex instanceof CoreException) {
            status = ((CoreException) ex).getStatus();
        } else {
            status = EclEmmaUIPlugin.errorStatus(String.valueOf(ex.getMessage()), ex);
        }
        ErrorDialog.openError(getShell(), title, msg, status);
        return false;
    }
    return true;
}

From source file:com.mountainminds.eclemma.internal.ui.wizards.SessionImportWizard.java

License:Open Source License

private boolean importSession() {
    final ISessionImporter importer = CoverageTools.getImporter();
    importer.setDescription(page2.getSessionDescription());
    importer.setExecutionDataSource(page1.getExecutionDataSource());
    importer.setScope(page2.getScope());
    importer.setCopy(page1.getCreateCopy());
    IRunnableWithProgress op = new IRunnableWithProgress() {
        public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
            try {
                importer.importSession(monitor);
            } catch (Exception e) {
                throw new InvocationTargetException(e);
            }//from  ww w.  j av  a  2 s  . c o m
        }
    };
    try {
        getContainer().run(true, true, op);
    } catch (InterruptedException e) {
        return false;
    } catch (InvocationTargetException ite) {
        Throwable ex = ite.getTargetException();
        EclEmmaUIPlugin.log(ex);
        final String title = UIMessages.ImportReportErrorDialog_title;
        final String msg = UIMessages.ImportReportErrorDialog_message;
        final IStatus status;
        if (ex instanceof CoreException) {
            status = ((CoreException) ex).getStatus();
        } else {
            status = EclEmmaUIPlugin.errorStatus(String.valueOf(ex.getMessage()), ex);
        }
        ErrorDialog.openError(getShell(), title, msg, status);
        return false;
    }
    return true;
}