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

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

Introduction

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

Prototype

public void setOpenOnRun(boolean openOnRun) 

Source Link

Document

Sets whether the dialog should be opened before the operation is run.

Usage

From source file:ca.mcgill.cs.swevo.qualyzer.wizards.NewProjectWizard.java

License:Open Source License

@Override
public boolean performFinish() {
    fOne.save();/*from ww  w  .  ja v  a2s . c  o  m*/

    ProgressMonitorDialog dialog = new ProgressMonitorDialog(getShell());
    dialog.setOpenOnRun(true);
    dialog.create();
    dialog.getShell().setText(Messages.getString("wizards.NewProjectWizard.projectCreationStatus")); //$NON-NLS-1$
    try {
        dialog.run(true, false, new IRunnableWithProgress() {

            @Override
            public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
                QualyzerActivator.getDefault().setCreatingProject(true);
                monitor.beginTask(Messages.getString("wizards.NewProjectWizard.creatingNewProject"), //$NON-NLS-1$
                        WORK);
                monitor.worked(1);
                monitor.worked(1);
                Project project = Facade.getInstance().createProject(fOne.getProjectName(),
                        fOne.getInvestigatorNickname(), fOne.getInvestigatorFullname(), fOne.getInstitution());
                monitor.worked(2);

                fProject = ResourcesPlugin.getWorkspace().getRoot().getProject(project.getFolderName());
                monitor.worked(1);
                monitor.done();
                QualyzerActivator.getDefault().setCreatingProject(false);
            }
        });
    } catch (InvocationTargetException e) {

    } catch (InterruptedException e) {

    } catch (QualyzerException e) {
        MessageDialog.openError(getShell(), Messages.getString("wizard.NewProjectWizard.projectError"), //$NON-NLS-1$
                e.getMessage());
        return false;
    }

    return fProject != null && fProject.exists();
}

From source file:com.ebmwebsourcing.petals.components.drivers.ZipUrlInputDialog.java

License:Open Source License

@Override
protected void okPressed() {

    // Parse the jbi.xml of the URL
    ProgressMonitorDialog dlg = new ProgressMonitorDialog(getShell());
    dlg.setOpenOnRun(true);
    try {//from www .j a v a 2 s  .co  m
        dlg.run(true, true, new IRunnableWithProgress() {

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

                // To report progression and support cancellation, the parsing is made in another thread
                final AtomicBoolean isParsed = new AtomicBoolean(false);
                Thread parsingThread = new Thread() {
                    @Override
                    public void run() {

                        try {
                            URI uri = UriAndUrlHelper.urlToUri(getValue());
                            ZipUrlInputDialog.this.slProperties = ArtifactArchiveUtils
                                    .getSharedLibraryVersion(uri);

                        } catch (InvalidJbiXmlException e) {
                            PetalsComponentsPlugin.log(e, IStatus.ERROR);

                        } finally {
                            isParsed.set(true);
                        }
                    }
                };

                try {
                    monitor.beginTask("", IProgressMonitor.UNKNOWN);
                    parsingThread.start();
                    while (!isParsed.get()) {
                        Thread.sleep(500);
                        monitor.worked(2);

                        // Cancelled operation? Let the thread finish its job...
                        if (monitor.isCanceled()) {
                            ZipUrlInputDialog.this.cancelled = true;
                            break;
                        }
                    }

                } finally {
                    monitor.done();
                }
            }
        });

    } catch (InvocationTargetException e) {
        PetalsComponentsPlugin.log(e, IStatus.ERROR);

    } catch (InterruptedException e) {
        // nothing
    }

    // Close the dialog
    super.okPressed();
}

From source file:com.maccasoft.composer.Main.java

License:Open Source License

void handlePlayerUpload() {
    File file = new File("Player/Player.binary");
    if (!file.exists()) {
        file = new File("lib/Player.binary");
    }/*  w  ww. j  a  v a  2s . co  m*/
    if (!file.exists()) {
        file = new File("Player.binary");
    }
    if (!file.exists()) {
        MessageDialog.openError(shell, APP_TITLE, "Player binary file not found!");
        return;
    }

    final File binaryFile = file;

    ProgressMonitorDialog dlg = new ProgressMonitorDialog(shell);
    try {
        dlg.setOpenOnRun(true);
        dlg.run(true, false, new IRunnableWithProgress() {

            @Override
            public void run(final IProgressMonitor monitor)
                    throws InvocationTargetException, InterruptedException {
                PropellerLoader loader = new PropellerLoader(editor.getSerialPort(), true) {

                    SubProgressMonitor subProgressMonitor = new SubProgressMonitor(monitor, 1);

                    @Override
                    protected void bufferUpload(int type, byte[] binaryImage)
                            throws SerialPortException, IOException {
                        StringBuilder sb = new StringBuilder("Loading binary image to ");
                        switch (type) {
                        case DOWNLOAD_EEPROM:
                        case DOWNLOAD_RUN_EEPROM:
                            sb.append("EEPROM via ");
                            // fall through
                        case DOWNLOAD_RUN_BINARY:
                            sb.append("hub memory");
                            break;
                        }
                        monitor.beginTask(sb.toString(), IProgressMonitor.UNKNOWN);
                        super.bufferUpload(type, binaryImage);
                    }

                    @Override
                    protected void notifyProgress(int sent, int total) {
                        subProgressMonitor
                                .subTask(String.format("%d bytes remaining             \r", total - sent));
                    }

                    @Override
                    protected void verifyRam() throws SerialPortException, IOException {
                        subProgressMonitor.subTask("Verifying RAM ... ");
                        super.verifyRam();
                    }

                    @Override
                    protected void eepromWrite() throws SerialPortException, IOException {
                        subProgressMonitor.subTask("Programming EEPROM ... ");
                        super.eepromWrite();
                    }

                    @Override
                    protected void eepromVerify() throws SerialPortException, IOException {
                        subProgressMonitor.subTask("Verifying EEPROM ... ");
                        super.eepromVerify();
                    }
                };

                try {
                    loader.upload(binaryFile, PropellerLoader.DOWNLOAD_RUN_EEPROM);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    } catch (Exception e1) {
        e1.printStackTrace();
    }
}

From source file:net.refractions.udig.project.internal.impl.MapImpl.java

License:Open Source License

public void executeSyncWithoutUndo(final MapCommand command) {
    command.setMap(this);
    if (Display.getCurrent() != null) {
        ProgressMonitorDialog dialog = new ProgressMonitorDialog(
                PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell());
        dialog.setOpenOnRun(true);
        try {//w  w w.ja va2  s.co  m
            dialog.run(false, false, new IRunnableWithProgress() {

                public void run(IProgressMonitor monitor)
                        throws InvocationTargetException, InterruptedException {
                    try {
                        command.run(monitor);
                    } catch (Exception e) {
                        ProjectPlugin.log("Error executing command: " + command.getName(), e); //$NON-NLS-1$
                    }
                }

            });
        } catch (InvocationTargetException e) {
            ProjectPlugin.log("Error executing command: " + command.getName(), e); //$NON-NLS-1$
        } catch (InterruptedException e) {
            ProjectPlugin.log("Error executing command: " + command.getName(), e); //$NON-NLS-1$
        }
    } else {
        try {
            command.run(new NullProgressMonitor());
        } catch (Exception e) {
            ProjectPlugin.log("Error executing command: " + command.getName(), e); //$NON-NLS-1$
        }
    }
}

From source file:nexcore.tool.uml.ui.core.registry.ResourceManager.java

License:Open Source License

/**
 * initializeRunnable/* w w  w.  j av a2  s.  c o  m*/
 *  
 * @param projects
 * @return RunnableWithResult<Object>
 */
private RunnableWithResult<Object> initializeRunnable(final IProject[] projects) {
    return /**
           * <ul>
           * <li>  : nexcore.tool.uml.ui.core</li>
           * <li>  : nexcore.tool.uml.ui.core.registry</li>
           * <li>   : 1</li>
           * <li>? : 2012. 7. 10.</li>
           * <li>? : nspark</li>
           * </ul>
           */
    new RunnableWithResult<Object>() {

        IStatus status = null;

        public Object getResult() {
            return status;
        }

        public IStatus getStatus() {
            return status;
        }

        public void setStatus(IStatus status) {

        }

        IProject[] projectArray;

        public IProject[] getProjects() {
            return projectArray;
        }

        public void setProjects(IProject[] projects) {
            this.projectArray = projects;
        }

        int count = 0;

        ModelUpdater modelUpdate = null;

        public void run() {
            referencedProject.clear();

            setProjects(projects);
            executeProgressDialog();

            // ?  ? ? ? clear
            RESOURCE_MEMENTO.clear();

            status = Status.OK_STATUS;
        }

        private void executeProgressDialog() {
            // prompt ? ?   ?    ? .
            boolean persistableResource = false;

            // RESOURCE_MEMENTO ? ?? ?  ??      .
            if (!RESOURCE_MEMENTO.isEmpty()) {
                persistableResource = promptToPersistableResource();
            }

            //  ?  RESOURCE_MEMENTO? clear     ? ? .
            if (!persistableResource) {
                RESOURCE_MEMENTO.clear();
            }

            ProgressMonitorDialog dialog = null;
            try {
                Shell shell = getShell();
                count = 0;
                modelCount(getProjects());

                dialog = new ProgressMonitorDialog(shell);
                dialog.setOpenOnRun(true);
                dialog.run(true, false, new IRunnableWithProgress() {

                    private List<String> uriList = new ArrayList<String>();

                    private void worked(IProgressMonitor monitor, String uri) {
                        try {
                            if (!uriList.contains(uri)) {
                                monitor.worked(1);
                                uriList.add(uri);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    public void run(final IProgressMonitor monitor)
                            throws InvocationTargetException, InterruptedException {
                        monitor.beginTask(UMLMessage.LABEL_LOAD_RESOURCE, count);

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

                            @Override
                            public void run() {
                                for (IProject project : getProjects()) {
                                    if (!ProjectUtil.isActiveUMLProject(project)) {
                                        continue;
                                    }
                                    try {
                                        IMarker[] findMarkers = project.findMarkers(IMarker.PROBLEM, true,
                                                IResource.DEPTH_ONE);
                                        if (findMarkers != null) {
                                            for (IMarker marker : findMarkers) {
                                                marker.delete();
                                            }
                                        }
                                        //                                            project.deleteMarkers(IMarker.PROBLEM, true, IResource.DEPTH_ONE);
                                    } catch (CoreException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }
                        });
                        resourceManager.addResourceLoadedAdapter();

                        // ? 
                        PrecedingInitializerRegistry.getInstance().executeInitializer();
                        // ///////////////////////////////////////////////////////
                        // ??? 
                        // ///////////////////////////////////////////////////////
                        String UML_MODEL_UPDATE = "UML_MODEL_UPDATE_%s_%s";

                        for (IProject project : getProjects()) {
                            if (!ProjectUtil.isActiveUMLProject(project)) {
                                continue;
                            }

                            monitor.setTaskName(String.format("%s : %s", project.getName(),
                                    UMLMessage.LABEL_MODEL_VERSION_CHECK));

                            String key = String.format(UML_MODEL_UPDATE, project.getName(),
                                    DateUtil.getCurrentDate());

                            //  ??  ???   ?.
                            String model_update = System.getProperty("model.update");

                            if (model_update != null && Boolean.parseBoolean(model_update)) {
                                if (modelUpdate == null) {
                                    modelUpdate = new ModelUpdater();
                                }

                                try {
                                    UiCorePlugin.getDefault().getPreferenceStore().setValue(key, true);
                                    modelUpdate.modelUpdate(project, monitor);
                                    monitor.subTask("");
                                } catch (Exception e) {
                                    e.printStackTrace();
                                } finally {
                                    if (modelUpdate != null) {
                                        modelUpdate.dispose();
                                    }

                                    modelUpdate = null;
                                    UiCorePlugin.getDefault().getPreferenceStore().needsSaving();
                                }
                            }
                        }

                        initUMLPrimitiveTypes();
                        initJavaPrimitiveTypes();
                        initXMLPrimitiveTypes();

                        UMLCacheAdapter crossReferenceAdapter = new UMLCacheAdapter();

                        crossReferenceAdapter.setMonitor(monitor);
                        crossReferenceAdapter.setUriList(uriList);

                        EList<Adapter> cacheAdapter = DomainRegistry.getUMLDomain().getResourceSet()
                                .eAdapters();
                        if (!cacheAdapter.contains(crossReferenceAdapter)) {
                            cacheAdapter.add(crossReferenceAdapter);
                        }

                        long s = System.currentTimeMillis();
                        // ///////////////////////////////////////////////////////
                        for (IProject project : getProjects()) {
                            try {
                                if (!ProjectUtil.isActiveUMLProject(project)) {
                                    continue;
                                }

                                monitor.setTaskName(String.format("%s : %s", project.getName(),
                                        UMLMessage.LABEL_LOAD_RESOURCE));

                                for (IResource resource : project.members()) {
                                    loadUMXResource(resource, monitor, count);
                                }
                                monitor.subTask("");
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }

                        if (UMLDebug.DEBUG) {
                            System.err.println("---------------" + (System.currentTimeMillis() - s));
                        }
                        monitor.subTask("");

                        monitor.done();

                        cacheAdapter.remove(crossReferenceAdapter);
                    }

                    //                        private void loadUMFResource(IResource resource, IProgressMonitor monitor, int total) {
                    //                            try {
                    //                                if (resource instanceof IFolder) {
                    //                                    for (IResource member : ((IFolder) resource).members()) {
                    //                                        loadUMFResource(member, monitor, total);
                    //                                    }
                    //                                } else if (resource instanceof IFile) {
                    //                                    try {
                    //                                        if (ProjectUtil.isFragmentFile((IFile) resource)) {
                    //                                            monitor.worked(1);
                    //                                            String subTask = String.format(" %s", ((IFile) resource).getFullPath()
                    //                                                .toString());
                    //                                            monitor.subTask(subTask);
                    //
                    //                                            URI uri = URI.createURI(((IFile) resource).getFullPath().toString());
                    //                                            Resource res = DomainRegistry.getUMLDomain()
                    //                                                .getResourceSet()
                    //                                                .getResource(uri, true);
                    //                                            res.setTrackingModification(true);
                    //                                            
                    //                                            ((ResourceImpl)res).setIntrinsicIDToEObjectMap(new HashMap<String, EObject>());
                    //                                            //  ? ? ? ? UML ?
                    //                                            //  ?   ?
                    //                                            // ? ?? .
                    //                                            EObject eObject;
                    //                                            if (!res.getContents().isEmpty()) {
                    ////                                                EcoreUtil.UnresolvedProxyCrossReferencer.find(res);
                    //                                            }
                    //                                        }
                    //                                    } catch (Exception e) {
                    //                                        // ignore
                    //                                    }
                    //                                }
                    //                            } catch (CoreException e) {
                    //                                e.printStackTrace();
                    //                            }
                    //                        }

                    /**
                     * 
                     * @param resource
                     * @param monitor
                     * @param total
                     *            void
                     */
                    private synchronized void loadUMXResource(IResource resource, IProgressMonitor monitor,
                            int total) {
                        try {
                            if (resource instanceof IFolder) {
                                for (IResource member : ((IFolder) resource).members()) {
                                    loadUMXResource(member, monitor, total);
                                }
                            } else if (resource instanceof IFile) {
                                try {
                                    if (DomainUtil.isUMXFile((IFile) resource)) {
                                        if (monitor != null) {
                                            String path = ((IFile) resource).getFullPath().toString();
                                            worked(monitor, path);
                                            String subTask = String.format("Loading : %s", path);
                                            monitor.subTask(subTask);
                                        }
                                        URI uri = URI.createURI(((IFile) resource).getFullPath().toString());

                                        boolean active = isActive(uri);
                                        if (!active) {
                                            return;
                                        }

                                        Resource res = DomainRegistry.getUMLDomain().getResource(uri, true);

                                        // ? ?    does not exist. ?  .
                                        // ? ?? ?  ??  ?   ?  ? unload   load .
                                        // ? ?  ?  ??.
                                        if (res != null && (!res.getErrors().isEmpty()
                                                || !res.getWarnings().isEmpty())) {
                                            res.unload();
                                            res = DomainRegistry.getUMLDomain().getResourceSet()
                                                    .getResource(uri, true);
                                        }

                                        if (!res.getContents().isEmpty()) {
                                            if (!res.isTrackingModification()) {
                                                res.setTrackingModification(true);
                                            }
                                            final Resource umlResource = res;

                                            DomainUtil.run(new TransactionalAction() {
                                                /**
                                                 * @see nexcore.tool.uml.manager.transaction.TransactionalAction#doExecute()
                                                 */
                                                @Override
                                                public void doExecute() {
                                                    EcoreUtil.resolveAll(umlResource);
                                                }
                                            });
                                        }
                                    }
                                } catch (Exception e) {
                                    // ignore
                                    e.printStackTrace();
                                }
                            }
                        } catch (CoreException e) {
                            e.printStackTrace();
                        }
                    }

                    /**
                     * 
                     * void
                     */
                    private void initJavaPrimitiveTypes() {
                        URI uri = URI.createURI(UMLResource.JAVA_PRIMITIVE_TYPES_LIBRARY_URI);
                        Resource resource = DomainRegistry.getUMLDomain().getResource(uri, true);
                        if (resource != null) {
                            addElement(resource);
                        }
                    }

                    /**
                     * 
                     * void
                     */
                    private void initUMLPrimitiveTypes() {
                        URI uri = URI.createURI(UMLResource.UML_PRIMITIVE_TYPES_LIBRARY_URI);
                        Resource resource = DomainRegistry.getUMLDomain().getResource(uri, true);
                        if (resource != null) {
                            addElement(resource);
                        }
                    }

                    /**
                     * 
                     * void
                     */
                    private void initXMLPrimitiveTypes() {
                        URI uri = URI.createURI(UMLResource.XML_PRIMITIVE_TYPES_LIBRARY_URI);
                        Resource resource = DomainRegistry.getUMLDomain().getResource(uri, true);
                        if (resource != null) {
                            addElement(resource);
                        }
                    }
                });

            } catch (InvocationTargetException e1) {
                e1.printStackTrace();
            } catch (InterruptedException e1) {
                e1.printStackTrace();
            } finally {
                dialog.close();
                System.gc();

                if (referencedProject.size() > 0) {
                    boolean openQuestion = promptToOpenWithReferences();
                    if (!openQuestion) {
                        referencedProject.clear();
                        return;
                    }

                    setProjects(referencedProject.keySet().toArray(new IProject[] {}));

                    openProject(referencedProject.keySet().toArray(new IProject[] {}));

                    resourceManager.removeResourceLoadedAdapter();
                }
            }
        }

        private int modelCount(IProject[] projects) {
            for (IProject project : projects) {
                if (!ProjectUtil.isActiveUMLProject(project)) {
                    continue;
                }

                try {
                    for (IResource r : project.members()) {
                        count(r);
                    }
                } catch (CoreException e) {
                    e.printStackTrace();
                }
            }

            return count;
        }

        /**
         * promptToOpenWithReferences
         *  
         * @return boolean
         */
        private boolean promptToOpenWithReferences() {
            IPreferenceStore store = UiCorePlugin.getDefault().getPreferenceStore();
            String key = "OPEN_REQUIRED_PROJECTS";
            String value = store.getString(key);
            if (MessageDialogWithToggle.ALWAYS.equals(value)) {
                return true;
            }
            if (MessageDialogWithToggle.NEVER.equals(value)) {
                return false;
            }

            String message = UMLMessage.MESSAGE_REFERENCED_PROJECTS;//"? ? .";

            MessageDialogWithToggle dialog = MessageDialogWithToggle.openInformation(getShell(), "Information",
                    message, null, false, store, key);//MessageDialogWithToggle.openYesNoCancelQuestion(getShell(), "Question", message, null, false, store, key);
            int result = dialog.getReturnCode();
            // the result is equal to SWT.DEFAULT if the user uses the 'esc' key to close the dialog
            return dialog.getReturnCode() == IDialogConstants.OK_ID || result == SWT.DEFAULT;
        }

        /**
         * promptToPersistableResource
         *  
         * @return boolean
         */
        private boolean promptToPersistableResource() {

            return true;
        }

        private void count(IResource resource) {
            if (resource instanceof IFolder) {
                try {
                    for (IResource member : ((IFolder) resource).members()) {
                        count(member);
                    }
                } catch (CoreException e) {

                }
            } else if (resource instanceof IFile) {
                if (ProjectUtil.isModelFile((IFile) resource)) {
                    count++;

                    URI uri = URI.createURI(resource.getFullPath().toString());

                    IProject project = resource.getProject();
                    List<String> list = RESOURCE_MEMENTO.get(project.getName());
                    if (list != null && list.contains(uri.toString())) {
                        ResourceManager.getInstance().setActivation(uri, true);
                    } else {
                        ResourceManager.getInstance().setActivation(uri, false);
                    }
                }
            }
        }
    };
}

From source file:org.eclipse.cmf.occi.docker.design.services.DockerServices.java

License:Open Source License

/**
 * Called by all basic command (not by import command).
 * /*www. j av  a  2s.co m*/
 * @param eo
 * @param command
 * @param occiCommand
 */
private void executeCommand(final EObject eo, final String command, final boolean occiCommand) {
    Shell shell = this.getShell();
    try {
        final int kind = this.eobjectKind(eo);

        String machineName = null;
        final Compute compute;
        final Entity entity;
        if (command == null) {
            MessageDialog.openInformation(shell, "Warning", "This command : " + command + " is not supported.");
            return;
        }

        switch (kind) {
        case 0:
            Machine machine = ((Machine) eo);
            machineName = machine.getName();
            if (machineName == null || machineName.trim().isEmpty()) {
                MessageDialog.openInformation(shell, "Warning", "Machine name is required !");
                return;
            }
            compute = (Compute) eo;
            break;
        case 1:
            Container container = ((Container) eo);
            machineName = container.getName();
            if (machineName == null || machineName.trim().isEmpty()) {
                MessageDialog.openInformation(shell, "Warning", "Container name is required !");
                return;
            }
            compute = (Container) eo;
            break;
        default:
            if (!occiCommand) {
                MessageDialog.openInformation(shell, "Warning", "Unsupported compute !");
                return;
            }
            compute = null;
            break;
        }
        if (eo instanceof Entity) {
            entity = (Entity) eo;
        } else {
            System.err.println("Not an entity !");
            return;
        }

        IRunnableWithProgress runnable = new IRunnableWithProgress() {
            @Override
            public void run(final IProgressMonitor monitor)
                    throws InvocationTargetException, InterruptedException {
                if (!monitor.isCanceled()) {
                    monitor.beginTask("Operation in progress : " + command, Monitor.UNKNOWN);
                    Display display = Display.getCurrent();
                    boolean result = display.readAndDispatch();
                    System.out.println("result display read and dispatch : " + result);
                    SubMonitor subMonitor = SubMonitor.convert(monitor, 100);
                    // consume..
                    subMonitor.worked(10);
                    if (occiCommand) {
                        switch (command) {
                        case "occiCreate":
                            entity.occiCreate();
                            break;
                        case "occiUpdate":
                            entity.occiUpdate();
                            break;
                        case "occiDelete":
                            boolean confirm = showConfirmDialog();
                            if (confirm) {
                                entity.occiDelete();
                            }
                            break;
                        case "occiRetrieve":
                            entity.occiRetrieve();
                            break;
                        }
                    } else {
                        if (compute != null) {

                            switch (command) {

                            case "start":
                                compute.start();
                                break;
                            case "startall":
                                if (compute instanceof Machine) {
                                    Machine machine = (Machine) compute;
                                    machine.startall();
                                }

                                break;
                            case "stop":
                                compute.stop(StopMethod.GRACEFUL);
                                break;
                            case "synchronize":
                                compute.occiRetrieve();
                                break;
                            case "restart":
                                compute.restart(RestartMethod.GRACEFUL);
                                break;
                            default:
                                System.err.println("command : " + command + " is not supported.");
                                break;
                            }
                        }
                    }
                    result = display.readAndDispatch();
                    System.out.println("result display read and dispatch : " + result);
                    subMonitor.worked(100);
                    monitor.done();
                } else {
                    System.out.println("Operation : " + command + " cancelled.");
                }

            }
        };

        ProgressMonitorDialog dialog = new ProgressMonitorDialog(shell);
        dialog.setOpenOnRun(true);

        dialog.run(false, true, runnable);
        //  dialog.run(false, true, runnable);
        // MessageDialog.openInformation(shell, "Operation succeed",
        //      "Command " + command + " has been successfully executed !");
    } catch (Throwable ex) {
        ex.printStackTrace();
        MessageDialog.openError(shell, "Error on command " + command,
                ex.getCause().getClass().getName() + " --> " + ex.getCause().getMessage());
    }

}

From source file:org.eclipse.ptp.rm.ui.wizards.AbstractRemoteProxyResourceManagerConfigurationWizardPage.java

License:Open Source License

/**
 * Check if the proxy path supplied in proxyPathText is a valid file on the
 * remote system.// ww  w . ja  v  a  2 s . com
 * 
 * @return true if valid
 * @since 1.1
 */
protected boolean validateProxyPath() {
    if (!proxyPathEnabled) {
        return true;
    }
    proxyPathIsValid = false;
    final String path = proxyPathText.getText();
    if (path != null && !path.equals("")) { //$NON-NLS-1$
        if (connection != null) {
            checkConnection();
            if (connection.isOpen()) {
                if (remoteServices != null) {
                    final IRemoteFileManager fileMgr = remoteServices.getFileManager(connection);
                    if (fileMgr != null) {
                        IRunnableWithProgress op = new IRunnableWithProgress() {
                            public void run(IProgressMonitor monitor)
                                    throws InvocationTargetException, InterruptedException {
                                try {
                                    IFileStore file = fileMgr.getResource(path);
                                    if (!monitor.isCanceled()) {
                                        proxyPathIsValid = file.fetchInfo(EFS.NONE, monitor).exists();
                                    }
                                } catch (CoreException e) {
                                    throw new InvocationTargetException(e);
                                }
                            }

                        };
                        try {
                            ProgressMonitorDialog dialog = new ProgressMonitorDialog(getShell());
                            dialog.setOpenOnRun(false);
                            dialog.run(true, true, op);
                        } catch (InvocationTargetException e) {
                            // return false
                        } catch (InterruptedException e) {
                            // return false
                        }
                    }
                }
            }
        }
    }
    return proxyPathIsValid;
}

From source file:org.eclipse.tcf.te.tcf.filesystem.ui.internal.operations.UiExecutor.java

License:Open Source License

public static IStatus execute(final IOperation operation) {
    final Display display = Display.getCurrent();
    Assert.isNotNull(display);/* w w w.j a va  2s.c  o  m*/
    final Shell parent = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
    final ProgressMonitorDialog dlg = new ProgressMonitorDialog(parent);
    dlg.setOpenOnRun(false);

    display.timerExec(500, new Runnable() {
        @Override
        public void run() {
            Shell shell = dlg.getShell();
            if (shell != null && !shell.isDisposed()) {
                Shell activeShell = display.getActiveShell();
                if (activeShell == null || activeShell == parent) {
                    dlg.open();
                } else {
                    display.timerExec(500, this);
                }
            }
        }
    });
    final AtomicReference<IStatus> ref = new AtomicReference<IStatus>();
    try {
        dlg.run(true, true, new IRunnableWithProgress() {
            @Override
            public void run(IProgressMonitor monitor) {
                ref.set(operation.run(monitor));
            }
        });
    } catch (InvocationTargetException e) {
        ref.set(StatusHelper.getStatus(e.getTargetException()));
    } catch (InterruptedException e) {
        return Status.CANCEL_STATUS;
    }
    IStatus status = ref.get();
    if (!status.isOK() && status.getMessage().length() > 0) {
        ErrorDialog.openError(parent, operation.getName(), Messages.UiExecutor_errorRunningOperation, status);
        UIPlugin.getDefault().getLog().log(status);
    }
    return status;
}

From source file:org.eclipse.ui.internal.activities.ws.WorkbenchActivitySupport.java

License:Open Source License

/**
 * Create a new instance of this class.//from  www . jav  a 2s.  c  om
 */
public WorkbenchActivitySupport() {
    triggerPointManager = new TriggerPointManager();
    IExtensionTracker tracker = PlatformUI.getWorkbench().getExtensionTracker();
    tracker.registerHandler(this,
            ExtensionTracker.createExtensionPointFilter(getActivitySupportExtensionPoint()));
    mutableActivityManager = new MutableActivityManager(getTriggerPointAdvisor());
    proxyActivityManager = new ProxyActivityManager(mutableActivityManager);
    mutableActivityManager.addActivityManagerListener(new IActivityManagerListener() {

        private Set lastEnabled = new HashSet(mutableActivityManager.getEnabledActivityIds());

        /* (non-Javadoc)
         * @see org.eclipse.ui.activities.IActivityManagerListener#activityManagerChanged(org.eclipse.ui.activities.ActivityManagerEvent)
         */
        public void activityManagerChanged(ActivityManagerEvent activityManagerEvent) {
            Set activityIds = mutableActivityManager.getEnabledActivityIds();
            // only update the windows if we've not processed this new enablement state already.
            if (!activityIds.equals(lastEnabled)) {
                lastEnabled = new HashSet(activityIds);

                // abort if the workbench isn't running
                if (!PlatformUI.isWorkbenchRunning()) {
                    return;
                }

                // refresh the managers on all windows.
                final IWorkbench workbench = PlatformUI.getWorkbench();
                IWorkbenchWindow[] windows = workbench.getWorkbenchWindows();
                for (int i = 0; i < windows.length; i++) {
                    if (windows[i] instanceof WorkbenchWindow) {
                        final WorkbenchWindow window = (WorkbenchWindow) windows[i];

                        final ProgressMonitorDialog dialog = new ProgressMonitorDialog(window.getShell());

                        final IRunnableWithProgress runnable = new IRunnableWithProgress() {

                            /**
                             * When this operation should open a dialog
                             */
                            private long openTime;

                            /**
                             * Whether the dialog has been opened yet.
                             */
                            private boolean dialogOpened = false;

                            /* (non-Javadoc)
                             * @see org.eclipse.jface.operation.IRunnableWithProgress#run(org.eclipse.core.runtime.IProgressMonitor)
                             */
                            public void run(IProgressMonitor monitor) {

                                openTime = System.currentTimeMillis()
                                        + workbench.getProgressService().getLongOperationTime();

                                //two work units - updating the window bars, and updating view bars
                                monitor.beginTask(ActivityMessages.ManagerTask, 2);

                                monitor.subTask(ActivityMessages.ManagerWindowSubTask);

                                //update window managers...
                                updateWindowBars(window);
                                monitor.worked(1);

                                monitor.subTask(ActivityMessages.ManagerViewsSubTask);
                                // update all of the (realized) views in all of the pages
                                IWorkbenchPage[] pages = window.getPages();
                                for (int j = 0; j < pages.length; j++) {
                                    IWorkbenchPage page = pages[j];
                                    IViewReference[] refs = page.getViewReferences();
                                    for (int k = 0; k < refs.length; k++) {
                                        IViewPart part = refs[k].getView(false);
                                        if (part != null) {
                                            updateViewBars(part);
                                        }
                                    }
                                }
                                monitor.worked(1);

                                monitor.done();
                            }

                            /**
                             * Update the managers on the given given view.
                             * 
                             * @param part the view to update
                             */
                            private void updateViewBars(IViewPart part) {
                                IViewSite viewSite = part.getViewSite();
                                // check for badly behaving or badly initialized views
                                if (viewSite == null) {
                                    return;
                                }
                                IActionBars bars = viewSite.getActionBars();
                                IContributionManager manager = bars.getMenuManager();
                                if (manager != null) {
                                    updateManager(manager);
                                }
                                manager = bars.getToolBarManager();
                                if (manager != null) {
                                    updateManager(manager);
                                }
                                manager = bars.getStatusLineManager();
                                if (manager != null) {
                                    updateManager(manager);
                                }
                            }

                            /**
                             * Update the managers on the given window.
                             * 
                             * @param window the window to update
                             */
                            private void updateWindowBars(final WorkbenchWindow window) {
                                IContributionManager manager = window.getMenuBarManager();
                                if (manager != null) {
                                    updateManager(manager);
                                }
                                manager = window.getCoolBarManager2();
                                if (manager != null) {
                                    updateManager(manager);
                                }
                                manager = window.getToolBarManager2();
                                if (manager != null) {
                                    updateManager(manager);
                                }
                                manager = window.getStatusLineManager();
                                if (manager != null) {
                                    updateManager(manager);
                                }
                            }

                            /**
                             * Update the given manager in the UI thread.
                             * This may also open the progress dialog if 
                             * the operation is taking too long.
                             * 
                             * @param manager the manager to update
                             */
                            private void updateManager(final IContributionManager manager) {
                                if (!dialogOpened && System.currentTimeMillis() > openTime) {
                                    dialog.open();
                                    dialogOpened = true;
                                }

                                manager.update(true);
                            }
                        };

                        // don't open the dialog by default - that'll be
                        // handled by the runnable if we take too long
                        dialog.setOpenOnRun(false);
                        // run this in the UI thread
                        workbench.getDisplay().asyncExec(new Runnable() {

                            /* (non-Javadoc)
                             * @see java.lang.Runnable#run()
                             */
                            public void run() {
                                BusyIndicator.showWhile(workbench.getDisplay(), new Runnable() {

                                    /* (non-Javadoc)
                                     * @see java.lang.Runnable#run()
                                     */
                                    public void run() {
                                        try {
                                            dialog.run(false, false, runnable);
                                        } catch (InvocationTargetException e) {
                                            log(e);
                                        } catch (InterruptedException e) {
                                            log(e);
                                        }
                                    }
                                });
                            }
                        });
                    }
                }
            }
        }

        /**
         * Logs an error message to the workbench log.
         * 
         * @param e the exception to log
         */
        private void log(Exception e) {
            StatusUtil.newStatus(IStatus.ERROR, "Could not update contribution managers", e); //$NON-NLS-1$ 
        }
    });
}

From source file:org.fusesource.ide.jvmmonitor.internal.ui.actions.OpenDeclarationAction.java

License:Open Source License

/**
 * Searches the source for the given class name with progress monitor.
 * // w  ww .ja  v  a 2s .  c  om
 * @return The source
 * @throws InterruptedException
 *             if operation is canceled
 */
private IType searchSource() throws InterruptedException {
    final ProgressMonitorDialog dialog = new ProgressMonitorDialog(
            PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell());
    dialog.setOpenOnRun(false);

    // search source corresponding to the class name
    final IType[] source = new IType[1];
    IRunnableWithProgress op = new IRunnableWithProgress() {
        @Override
        public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
            if (!searchEngineInitialized) {
                monitor.subTask(Messages.searchingSoruceMsg);
                searchEngineInitialized = true;
            }

            // open progress monitor dialog when it takes long time
            new Timer().schedule(new TimerTask() {
                @Override
                public void run() {
                    Display.getDefault().syncExec(new Runnable() {
                        @Override
                        public void run() {
                            dialog.open();
                        }
                    });
                }
            }, 400);

            if (className == null) {
                return;
            }

            try {
                source[0] = doSearchSource(className);
            } catch (CoreException e) {
                throw new InvocationTargetException(e);
            }
            if (monitor.isCanceled()) {
                throw new InterruptedException();
            }
        }
    };

    try {
        dialog.run(true, true, op);
    } catch (InvocationTargetException e) {
        Activator.log(IStatus.ERROR, NLS.bind(Messages.searchClassFailedMsg, className), e);
    }

    return source[0];
}