Example usage for org.eclipse.jface.dialogs ProgressMonitorDialog run

List of usage examples for org.eclipse.jface.dialogs ProgressMonitorDialog run

Introduction

In this page you can find the example usage for org.eclipse.jface.dialogs ProgressMonitorDialog run.

Prototype

@Override
public void run(boolean fork, boolean cancelable, IRunnableWithProgress runnable)
        throws InvocationTargetException, InterruptedException 

Source Link

Document

This implementation of IRunnableContext#run(boolean, boolean, IRunnableWithProgress) runs the given IRunnableWithProgress using the progress monitor for this progress dialog and blocks until the runnable has been run, regardless of the value of fork.

Usage

From source file:com.mentor.nucleus.bp.core.common.Transaction.java

License:Open Source License

/**
 * Wrapper method to create a progress dialog if necessary, that is if the
 * amount of deltas is over a certain size
 *
 * @param transactionType//ww  w . ja  va2  s  . c o m
 */
void revert(final boolean inMemoryOnly) {
    int deltaCount = getDeltaCount();
    if (deltaCount > 200) {
        ProgressMonitorDialog pmDialog = new ProgressMonitorDialog(
                PlatformUI.getWorkbench().getDisplay().getActiveShell());
        try {
            pmDialog.run(false, false, new IRunnableWithProgress() {

                public void run(IProgressMonitor monitor)
                        throws InvocationTargetException, InterruptedException {
                    revert(monitor, inMemoryOnly);
                }

            });
        } catch (InvocationTargetException e) {
            CorePlugin.logError("Unable to invoke undo of the last transaction.", e);
        } catch (InterruptedException e) {
            CorePlugin.logError("The undo of the last transaction was interrupted.", e);
        }
    } else {
        revert(new NullProgressMonitor(), inMemoryOnly);
    }
}

From source file:com.mentor.nucleus.bp.core.ui.NewDomainWizard.java

License:Open Source License

public boolean createDomain(IWizardContainer container, ProgressMonitorDialog dialog) {
    IProject project = (IProject) m_sys.getAdapter(IProject.class);
    String domainName = PersistenceManager.getDefaultInstance()
            .getUniqueNameOfParent(m_sys.getPersistableComponent(), m_domainName, null);
    final String id = Ooaofooa.createModelRootId(project, domainName, true);
    final Ooaofooa modelRoot = Ooaofooa.getInstance(id, false);
    String message = "";//$NON-NLS-1$
    if (container != null && dialog == null)
        dialog = new ProgressMonitorDialog(getShell());

    if (!m_useTemplate) {
        final CorePlugin plugin = CorePlugin.getDefault();
        URL installURL = plugin.getBundle().getEntry("/");//$NON-NLS-1$
        try {//from   w  ww  .  j a  v a 2 s  . c om
            URL url = new URL(installURL, Ooaofooa.MODELS_DIRNAME + "/default." + Ooaofooa.MODELS_EXT); //$NON-NLS-1$
            final InputStream inStream = url.openStream();
            ImportStreamStatus iss = new ImportStreamStatus(id, inStream);
            if (container == null) {
                iss.run(new NullProgressMonitor());
            } else {
                dialog.run(true, false, iss);
            }
            message = iss.getMessage();
            try {
                inStream.close();
            } catch (IOException e2) {
                /* do nothing */ }
        } catch (IOException e1) {
            CorePlugin.logError("Internal error: failed to open default." + Ooaofooa.MODELS_EXT, e1);//$NON-NLS-1$
            return false;
        } catch (InterruptedException e) {
            CorePlugin.logError("Internal error: import was interrupted", e); //$NON-NLS-1$
            return false;
        } catch (InvocationTargetException e) {
            CorePlugin.logError("Internal error: plugin.doLoad not found", e); //$NON-NLS-1$
            return false;
        }
    } else {
        String templateFileName = m_templateFile;
        final IPath templatePath = new Path(templateFileName);
        // import the domain file into the model root with the id of the full path of the domain file
        if (templatePath.getFileExtension().equals(Ooaofooa.MODELS_EXT)) {
            final InputStream inStream;
            try {
                inStream = new FileInputStream(templatePath.toFile());
            } catch (FileNotFoundException e) {
                CorePlugin.logError("Internal error: failed to open " + templateFileName, e);
                return false;
            }
            try {
                ImportStreamStatus iss = new ImportStreamStatus(id, inStream);
                if (container == null) {
                    // for unit tests to prevent displaying progress dialogs
                    iss.run(new NullProgressMonitor());
                } else {
                    dialog.run(true, false, iss);
                }
                message = iss.getMessage();
                inStream.close();
            } catch (InterruptedException e) {
                CorePlugin.logError("Internal error: import was interrupted", e); //$NON-NLS-1$
                return false;
            } catch (InvocationTargetException e) {
                CorePlugin.logError("Internal error: plugin.doLoad not found", e); //$NON-NLS-1$
                return false;
            } catch (IOException e) {
                CorePlugin.logError("Unable to close stream to import file.", e); //$NON-NLS-1$
                /* do nothing */
            }
        } else {
            try {
                ImportFileStatus ifs = new ImportFileStatus(id, templatePath.toFile());
                if (container == null) {
                    // For unit tests.
                    ifs.run(new NullProgressMonitor());
                } else {
                    dialog.run(true, false, ifs);
                }
                message = ifs.getMessage();
            } catch (InterruptedException e) {
                CorePlugin.logError("Internal error: import was interrupted", e); //$NON-NLS-1$
                return false;
            } catch (InvocationTargetException e) {
                CorePlugin.logError("Internal error: plugin.doLoad not found", e); //$NON-NLS-1$
                return false;
            }
        }
        if (!message.equals("")) {
            CorePlugin.showImportErrorMessage(true, message);
            return true;
        }
    }
    // set the just loaded Domain instance name to the name specified by the user
    final Domain_c dom = Domain_c.DomainInstance(modelRoot, null, false);
    if (dom == null) {
        // There was a load error, already logged
        return false;
    }
    dom.setName(Ooaofooa.Getuniqueinitialname(modelRoot, m_domainName, dom.Converttoinstance()));
    IDConvertor.getInstance().recreateUUID(dom);

    // Create a PMC for the new domain
    try {
        if (dom.getPersistableComponent() == null) {
            PersistenceManager.getDefaultInstance().registerModel(dom, project);
        }
        IRunnableWithProgress persistenceRunnable = new IRunnableWithProgress() {

            public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
                try {
                    monitor.beginTask("Persisting newly created model...", getComponentCount(dom));
                    persistSelfAndChildren(dom, monitor);
                    displayDuplicateDialog();
                    monitor.done();
                } catch (CoreException e) {
                    CorePlugin.logError("Unable to persist newly created model.", e);
                } finally {
                    duplicateNames.clear();
                }
            }

        };
        if (m_parseOnImport) {
            try {
                if (container == null) {
                    // For unit tests.
                    CorePlugin.parseAll(dom, new NullProgressMonitor());
                } else {
                    dialog.run(false, false, new IRunnableWithProgress() {

                        public void run(IProgressMonitor monitor)
                                throws InvocationTargetException, InterruptedException {
                            CorePlugin.parseAll(dom, monitor);
                        }

                    });
                }
            } catch (InvocationTargetException e) {
                CorePlugin.logError("Unable to parse model", e);
            } catch (InterruptedException e) {
                CorePlugin.logError("Unable to parse model", e);
            }
        }

        OALPersistenceUtil.persistOAL(modelRoot);

        if (container == null) {
            persistenceRunnable.run(new NullProgressMonitor());
        } else {
            dialog.run(false, false, persistenceRunnable);
        }
    } catch (CoreException e) {
        CorePlugin.logError("Unable to register model", e);
    } catch (InvocationTargetException e) {
        CorePlugin.logError("Unable to persist newly created model.", e);
    } catch (InterruptedException e) {
        CorePlugin.logError("Unable to persist newly created model.", e);
    }
    return true;
}

From source file:com.mentor.nucleus.bp.core.ui.PasteAction.java

License:Open Source License

public void run() {
    // clear the processor map
    processorMap.clear();//w w w.  j av a  2s  . com
    IRunnableWithProgress runnable = new IRunnableWithProgress() {

        public void run(final IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
            TransactionManager manager = getTransactionManager();
            Transaction transaction = null;
            List<NonRootModelElement> destinations = getDestinations();
            try {
                transaction = manager.startTransaction("Paste", //$NON-NLS-1$
                        new ModelRoot[] { Ooaofooa.getDefaultInstance(),
                                (ModelRoot) OoaofgraphicsUtil.getGraphicsRoot(
                                        Ooaofooa.DEFAULT_WORKING_MODELSPACE,
                                        OoaofgraphicsUtil.getGraphicsClass()) });
                for (NonRootModelElement destination : destinations) {
                    ModelStreamProcessor processor = new ModelStreamProcessor();
                    processorMap.put(destination, processor);
                    processor.setDestinationElement(destination);
                    Object contents = CorePlugin.getSystemClipboard().getContents(TextTransfer.getInstance());
                    if (contents instanceof String) {
                        String clipboardContents = (String) contents;
                        processor.setContents(clipboardContents);
                        String modelContents = clipboardContents.substring(clipboardContents.indexOf("\n") + 1);
                        ByteArrayInputStream in = new ByteArrayInputStream(modelContents.getBytes());
                        IModelImport importer = CorePlugin.getStreamImportFactory().create(in,
                                Ooaofooa.getInstance(Ooaofooa.CLIPBOARD_MODEL_ROOT_NAME), true,
                                destination.getPersistableComponent().getFile().getFullPath());
                        processor.runImporter(importer, monitor);
                        processor.processFirstStep(monitor);
                        runSubtypeProcessing(destination);
                        processor.processSecondStep(monitor);
                    }
                }
            } catch (Exception e) {
                CorePlugin.logError("Unable to start Paste transaction.", e); //$NON-NLS-1$
                if (transaction != null && manager != null && manager.getActiveTransaction() == transaction) {
                    manager.cancelTransaction(transaction, e);
                    transaction = null;
                }
            } finally {
                if (transaction != null)
                    manager.endTransaction(transaction);
            }
            if (transaction != null) {
                // only perform finishing work if the transaction
                // was successful
                boolean result = displayProblemDialog(manager, transaction, monitor);
                if (!result) {
                    // return as the user has cancelled the paste
                    return;
                }
                transaction = null;
                for (NonRootModelElement destination : destinations) {
                    ModelStreamProcessor processor = processorMap.get(destination);
                    processor.runParseOnImportedElements(manager, monitor);
                }
                // gather all of the loaded instances, including graphical
                for (NonRootModelElement destination : destinations) {
                    ModelStreamProcessor processor = processorMap.get(destination);
                    NonRootModelElement[] loadedInstances = processor.getImporter().getLoadedInstances();
                    NonRootModelElement[] loadedGraphicalInstances = processor.getImporter()
                            .getLoadedGraphicalInstances();
                    List<NonRootModelElement> instances = new ArrayList<NonRootModelElement>();
                    instances.addAll(Arrays.asList(loadedInstances));
                    instances.addAll(Arrays.asList(loadedGraphicalInstances));
                    for (IPasteListener listener : CorePlugin.getPasteListeners()) {
                        listener.pasteCompleted(destination, instances);
                    }
                }
            }
        }

    };
    ProgressMonitorDialog dialog = new ProgressMonitorDialog(
            PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell());
    try {
        dialog.run(false, false, runnable);
    } catch (InvocationTargetException e) {
        CorePlugin.logError("Unable to import contents from clipboard.", e); //$NON-NLS-1$
    } catch (InterruptedException e) {
        CorePlugin.logError("Unable to import contents from clipboard.", e); //$NON-NLS-1$
    }
}

From source file:com.mentor.nucleus.bp.io.mdl.wizards.ModelImportWizard.java

License:Open Source License

public boolean importModel(SystemModel_c system) {
    fSystem = system;/*from   w ww . ja  v  a  2  s.  com*/
    ProgressMonitorDialog dialog = new ProgressMonitorDialog(getShell());
    String templateFileName = fImportPage.getSourceFilePath();
    final IPath templatePath = new Path(templateFileName);
    // import the domain file into the model root with the id of the full
    // path of the domain file
    if (templatePath.getFileExtension().equals(Ooaofooa.MODELS_EXT)) {
        final InputStream inStream;
        try {
            inStream = new FileInputStream(templatePath.toFile());
        } catch (FileNotFoundException e) {
            CorePlugin.logError("Internal error: failed to open " + templateFileName, e);
            return false;
        }
        try {
            // turn off model change listeners
            ModelRoot.disableChangeNotification();
            // below we create an importer simply to
            // discover if we are importing an old BP
            // domain file, if so we call NewDomainWizard
            // to handle the import. Otherwise we need
            // to create an import stream.
            String domainName = new Path(fImportPage.getSourceFilePath()).removeFileExtension().lastSegment();
            String rootId = Ooaofooa.createModelRootId((IProject) fSystem.getAdapter(IProject.class),
                    domainName, true);
            Ooaofooa domainRoot = Ooaofooa.getInstance(rootId);
            fImporter = CorePlugin.getModelImportFactory().create(inStream, domainRoot, fSystem, false, true,
                    true, false);
            if (fImporter.getHeader().getModelComponentType().equalsIgnoreCase("Domain")) { //$NON-NLS-1$
                // close the above input stream as it was only used
                // to determine if we are importing an old domain
                inStream.close();
                DomainCreationRunnable runnable = new DomainCreationRunnable(domainName, dialog);
                if (getContainer() != null) {
                    dialog.run(false, false, runnable);
                } else {
                    runnable.run(new NullProgressMonitor());
                }
                return runnable.result;
            }
            ImportStreamStatus iss = new ImportStreamStatus(inStream);
            if (getContainer() == null) {
                // for unit tests to prevent displaying progress dialogs
                iss.run(new NullProgressMonitor());
            } else {
                dialog.run(true, false, iss);
            }
        } catch (InterruptedException e) {
            com.mentor.nucleus.bp.io.core.CorePlugin.logError("Internal error: import was interrupted", e); //$NON-NLS-1$
            return false;
        } catch (InvocationTargetException e) {
            com.mentor.nucleus.bp.io.core.CorePlugin.logError("Internal error: plugin.doLoad not found", e); //$NON-NLS-1$
            return false;
        } catch (IOException e) {
            com.mentor.nucleus.bp.io.core.CorePlugin.logError("Unable to import chosen model file.", e); //$NON-NLS-1$
        } finally {
            ModelRoot.enableChangeNotification();
        }
    }
    return true;
}

From source file:com.microsoft.azuretools.docker.utils.AzureDockerUIResources.java

License:Open Source License

public static void updateAzureResourcesWithProgressDialog(Shell shell, IProject project) {
    ProgressMonitorDialog dialog = new ProgressMonitorDialog(shell);
    try {/*  ww  w. ja  v a  2 s.  c om*/
        dialog.run(true, true, new IRunnableWithProgress() {
            public void run(IProgressMonitor monitor) {
                monitor.beginTask("Loading Azure Resources", 100);
                try {
                    monitor.subTask("Creating an Azure instance...");
                    AzureManager azureAuthManager = AuthMethodManager.getInstance().getAzureManager();
                    if (monitor.isCanceled()) {
                        monitor.done();
                        return;
                    }
                    // not signed in
                    if (azureAuthManager == null) {
                        monitor.done();
                        return;
                    }
                    AzureDockerHostsManager dockerManager = AzureDockerHostsManager
                            .getAzureDockerHostsManagerEmpty(azureAuthManager);
                    monitor.worked(10);

                    monitor.subTask("Retrieving the subscription details...");
                    dockerManager.refreshDockerSubscriptions();
                    if (monitor.isCanceled()) {
                        monitor.done();
                        return;
                    }

                    monitor.worked(10);
                    monitor.subTask("Retrieving the key vault...");
                    dockerManager.refreshDockerVaults();
                    monitor.worked(10);
                    if (monitor.isCanceled()) {
                        monitor.done();
                        return;
                    }

                    monitor.worked(10);
                    monitor.subTask("Retrieving the key vault details...");
                    dockerManager.refreshDockerVaultDetails();
                    if (monitor.isCanceled()) {
                        CANCELED = true;
                        monitor.done();
                        return;
                    }

                    monitor.worked(10);
                    monitor.subTask("Retrieving the network details...");
                    dockerManager.refreshDockerVnetDetails();
                    if (monitor.isCanceled()) {
                        monitor.done();
                        return;
                    }

                    monitor.worked(10);
                    monitor.subTask("Retrieving the storage account details...");
                    dockerManager.refreshDockerStorageAccountDetails();
                    if (monitor.isCanceled()) {
                        monitor.done();
                        return;
                    }

                    monitor.subTask("Retrieving the Docker virtual machines details...");
                    dockerManager.refreshDockerHostDetails();
                    CANCELED = false;
                } catch (Exception e) {
                    CANCELED = true;
                    log.log(Level.SEVERE, "updateAzureResourcesWithProgressDialog: " + e.getMessage(), e);
                    e.printStackTrace();
                }

                monitor.done();
            }
        });
    } catch (Exception e) {
        CANCELED = true;
        log.log(Level.SEVERE, "updateAzureResourcesWithProgressDialog: " + e.getMessage(), e);
        e.printStackTrace();
    }
}

From source file:com.microsoft.azuretools.docker.utils.AzureDockerUIResources.java

License:Open Source License

public static void createArtifact(Shell shell, IProject project) {
    if (project == null) {
        return;//from   w  w  w.ja v a  2 s .c  o m
    }

    String projectName = project.getName();
    String destinationPath = project.getLocation() + "/" + projectName + ".war";
    ProgressMonitorDialog dialog = new ProgressMonitorDialog(shell);
    try {
        dialog.run(true, true, new IRunnableWithProgress() {
            public void run(IProgressMonitor progressMonitor) {
                progressMonitor.beginTask("Creating WAR artifact", 100);
                try {
                    progressMonitor
                            .subTask(String.format("Building selected project: %s ...", project.getName()));
                    progressMonitor.worked(35);
                    project.build(IncrementalProjectBuilder.FULL_BUILD, null);

                    progressMonitor.subTask("Exporting to WAR ...");
                    progressMonitor.worked(75);
                    IDataModel dataModel = DataModelFactory
                            .createDataModel(new WebComponentExportDataModelProvider());
                    dataModel.setProperty(IJ2EEComponentExportDataModelProperties.PROJECT_NAME, projectName);
                    dataModel.setProperty(IJ2EEComponentExportDataModelProperties.ARCHIVE_DESTINATION,
                            destinationPath);

                    if (dataModel.getDefaultOperation() != null)
                        try {
                            dataModel.getDefaultOperation().execute(null, null);
                        } catch (Exception ignored) {
                        }

                    //                  progressMonitor.subTask("");
                    //                  progressMonitor.worked(1);
                    //                  if (progressMonitor.isCanceled()) {
                    //                     if (displayWarningOnCreateKeyVaultCancelAction() == 0) {
                    //                        progressMonitor.done();
                    //                        return Status.CANCEL_STATUS;
                    //                     }
                    //                  }
                    progressMonitor.done();
                } catch (Exception e) {
                    String msg = "An error occurred while attempting to create WAR artifact" + "\n"
                            + e.getMessage();
                    log.log(Level.SEVERE, "createArtifact: " + msg, e);
                    e.printStackTrace();
                }

                progressMonitor.done();
            }
        });
    } catch (Exception e) {
        CANCELED = true;
        log.log(Level.SEVERE, "updateAzureResourcesWithProgressDialog: " + e.getMessage(), e);
        e.printStackTrace();
    }
}

From source file:com.mmyumu.magictome.handlers.OpenHandler.java

License:Open Source License

@Execute
public void execute(IEclipseContext context, @Named(IServiceConstants.ACTIVE_SHELL) final Shell shell)
        throws InvocationTargetException, InterruptedException {
    FileDialog dialog = new FileDialog(shell);
    dialog.setFilterExtensions(new String[] { "*.xml" });
    dialog.setFilterNames(new String[] { "MTG Database XML File" });
    dialog.setText("Open MTG Database");
    final String filePath = dialog.open();

    if (filePath != null) {
        ProgressMonitorDialog monitorDialog = new ProgressMonitorDialog(shell);
        monitorDialog.run(true, true, new IRunnableWithProgress() {
            public void run(IProgressMonitor monitor) {
                monitor.beginTask("Importing card database", 100);
                try {
                    JAXBContext jc = JAXBContext.newInstance(MtgCarddatabase.class);
                    Unmarshaller unmarshaller = jc.createUnmarshaller();

                    unmarshaller.setProperty("com.sun.xml.internal.bind.ObjectFactory", new ObjectFactoryEx());
                    monitor.worked(30);//from  ww w .j a v a2 s  .c  o m
                    final MtgCarddatabase mtgCarddatabase = (MtgCarddatabase) unmarshaller
                            .unmarshal(new File(filePath));
                    monitor.worked(80);
                    shell.getDisplay().syncExec(new Runnable() {
                        public void run() {
                            // Add sets to Model
                            List<IModelCheckElement> sets = new ArrayList<>();
                            for (Set set : mtgCarddatabase.getSets().getSet()) {
                                SetEx setEx = (SetEx) set;
                                sets.add(setEx);
                            }
                            MtgDatabaseModel mtgModel = ModelProvider.getModel(AppParams.ID,
                                    MtgDatabaseModel.class);
                            SetsModel setsModel = mtgModel.getSetsModel();
                            setsModel.addElements(sets);

                            // Add cards to Model
                            List<IModelElement> cards = new ArrayList<>();
                            for (Card card : mtgCarddatabase.getCards().getCard()) {
                                CardEx cardEx = (CardEx) card;
                                cards.add(cardEx);
                            }
                            CardsModel cardsModel = mtgModel.getCardsModel();
                            cardsModel.addElements(cards);

                            AppLifecycle.save();
                        }
                    });

                    // Add cards to the set
                    // for (Card card :
                    // mtgCarddatabase.getCards().getCard()) {
                    // CardEx cardEx = (CardEx) card;
                    // ((SetExFull) cardEx.getSet()).addCard(cardEx);
                    // }
                    monitor.worked(100);
                } catch (JAXBException e) {
                    logger.error(e, "Error while parsing XML file");
                }
                monitor.done();
            }
        });
    }

}

From source file:com.mmyumu.magictome.handlers.SaveHandler.java

License:Open Source License

@Execute
public void execute(IEclipseContext context, @Named(IServiceConstants.ACTIVE_SHELL) Shell shell,
        @Named(IServiceConstants.ACTIVE_PART) final MContribution contribution)
        throws InvocationTargetException, InterruptedException {
    final IEclipseContext pmContext = context.createChild();

    ProgressMonitorDialog dialog = new ProgressMonitorDialog(shell);
    dialog.open();/*from   w  w  w . j ava 2 s  .c  om*/
    dialog.run(true, true, new IRunnableWithProgress() {
        public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
            pmContext.set(IProgressMonitor.class.getName(), monitor);
            if (contribution != null) {
                // Object clientObject = contribution.getObject();
                //               ContextInjectionFactory.invoke(clientObject, Persist.class, //$NON-NLS-1$
                // pmContext, null);
            }
        }
    });

    pmContext.dispose();
}

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  .j a v a  2 s  .co  m*/
    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;//from  w w w . jav  a2s. 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;
}