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

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

Introduction

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

Prototype

public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException;

Source Link

Document

Runs this operation.

Usage

From source file:org.eclipse.stp.bpmn.diagram.generation.impl.BPMNProcessGenerator.java

License:Open Source License

/**
 * Creates a transactional editing domain and creates resources,
 * placed as to fit the path./*from  w w  w. ja va 2s  . co  m*/
 * The constructor supposes the creation of the handle 
 * and its semantic file match,
 * which should have the same name and the .bpmn file extension.
 * 
 * The constructor finally creates a diagram and a BpmnDiagram object.
 * @param the path to a file supposed to hold the graphical 
 * elements, ie the bpmn_diagram file.
 * 
 * Note that this method is inspired from 
 * BpmnDiagramEditorUtil#createNewDiagramFile
 * 
 * Appends to the diagram generated.
 */
public BPMNProcessGenerator(final IPath path, final boolean virtual) {

    _editingDomain = GMFEditingDomainFactory.INSTANCE.createEditingDomain();
    final ResourceSet resourceSet = _editingDomain.getResourceSet();
    InternalRecordingCommand command = new InternalRecordingCommand() {

        @SuppressWarnings("unchecked") //$NON-NLS-1$
        @Override
        protected void doExecute() {

            /*
             * the graphical resource is created first as it will depend
             * on the semantic resource, the semantic resource is
             * deducted from the graphical resource path so that it is
             * relative to it.
             * In the bpmn_diagram file, the path to semantic elements 
             * should be modeler.bpmn#ID, not
             * test.bpm/modeler.bpmn#ID.
             *  
             */
            //create the graphical resource.
            IFile diagramFile = null;
            if (!virtual) {
                diagramFile = BpmnDiagramFileCreator.getInstance().createNewFile(path.removeLastSegments(1),
                        path.lastSegment(), null, null, new IRunnableContext() {
                            public void run(boolean fork, boolean cancelable, IRunnableWithProgress runnable)
                                    throws InvocationTargetException, InterruptedException {
                                runnable.run(new NullProgressMonitor());
                            }
                        });
            }
            Resource graphicalResource = resourceSet.createResource(URI.createPlatformResourceURI(
                    virtual ? path.toString() : diagramFile.getFullPath().toString()));

            // create the path to the semantic resource so that it is 
            // relative to the graphical resource.
            IPath modelFileRelativePath = path.removeFileExtension().addFileExtension("bpmn"); //$NON-NLS-1$
            IFile modelFile = null;
            if (!virtual) {
                modelFile = diagramFile.getParent().getFile(new Path(modelFileRelativePath.lastSegment()));
            }
            // create the semantic resource.
            Resource semanticResource = resourceSet.createResource(URI.createPlatformResourceURI(
                    virtual ? modelFileRelativePath.toString() : modelFile.getFullPath().toString()));

            // now create the semantic models and 
            // add them to their respective resources.
            _semanticModel = BpmnFactory.eINSTANCE.createBpmnDiagram();
            semanticResource.getContents().add(_semanticModel);

            _graphicalModel = ViewService.getInstance().createDiagram(new EObjectAdapter(_semanticModel),
                    BpmnDiagramEditPart.MODEL_ID, BpmnDiagramEditorPlugin.DIAGRAM_PREFERENCES_HINT);

            graphicalResource.getContents().add(_graphicalModel);
        }
    };
    _editingDomain.getCommandStack().execute(command);
}

From source file:org.eclipse.stp.bpmn.diagram.part.BpmnDiagramEditorUtil.java

License:Open Source License

/**
 * <p>//from   w w w  .j a va 2s .  c  o m
 * This method should be called within a workspace modify operation since it
 * creates resources.
 * </p>
 * 
 * @notgenerated
 * @return the created file resource, or <code>null</code> if the file was
 *         not created
 */
@SuppressWarnings("unchecked") //$NON-NLS-1$
public static IFile createNewDiagramFile(DiagramFileCreator diagramFileCreator, IPath containerFullPath,
        String fileName, InputStream initialContents, String kind, Shell shell,
        IProgressMonitor progressMonitor) {
    TransactionalEditingDomain editingDomain = GMFEditingDomainFactory.INSTANCE.createEditingDomain();
    ResourceSet resourceSet = editingDomain.getResourceSet();
    progressMonitor.beginTask("Creating diagram and model files", 4); //$NON-NLS-1$
    final IProgressMonitor subProgressMonitor = new SubProgressMonitor(progressMonitor, 1);
    final IFile diagramFile = diagramFileCreator.createNewFile(containerFullPath, fileName, initialContents,
            shell, new IRunnableContext() {
                public void run(boolean fork, boolean cancelable, IRunnableWithProgress runnable)
                        throws InvocationTargetException, InterruptedException {
                    runnable.run(subProgressMonitor);
                }
            });
    final Resource diagramResource = resourceSet
            .createResource(URI.createPlatformResourceURI(diagramFile.getFullPath().toString()));
    List affectedFiles = new ArrayList();
    affectedFiles.add(diagramFile);

    IPath modelFileRelativePath = diagramFile.getFullPath().removeFileExtension().addFileExtension("bpmn"); //$NON-NLS-1$
    IFile modelFile = diagramFile.getParent().getFile(new Path(modelFileRelativePath.lastSegment()));
    final Resource modelResource = new GMFResource(
            URI.createPlatformResourceURI(modelFile.getFullPath().toString()));
    affectedFiles.add(modelFile);

    final String kindParam = kind;
    AbstractTransactionalCommand command = new AbstractTransactionalCommand(editingDomain,
            "Creating diagram and model", affectedFiles) { //$NON-NLS-1$
        protected CommandResult doExecuteWithResult(IProgressMonitor monitor, IAdaptable info)
                throws ExecutionException {

            BpmnDiagram model = createInitialModelGen();
            modelResource.getContents().add(model);
            Diagram diagram = ViewService.createDiagram(model, kindParam,
                    BpmnDiagramEditorPlugin.DIAGRAM_PREFERENCES_HINT);
            diagramResource.getContents().add(diagram);
            diagram.setName(diagramFile.getName());
            diagram.setElement(model);
            BPMNVisual2ProcessGenerator generator = new BPMNVisual2ProcessGenerator(diagram);
            Pool p = generator.addPool(BpmnDiagramMessages.BpmnDiagramEditorUtil_pool_default_name,
                    BpmnDiagramXYLayoutEditPolicy.DEFAULT_POOL_X_COORD,
                    BpmnDiagramXYLayoutEditPolicy.DEFAULT_POOL_X_COORD, PoolEditPart.POOL_WIDTH,
                    PoolEditPart.POOL_HEIGHT);
            generator.addActivity(p, BpmnDiagramMessages.BpmnDiagramEditorUtil_task_default_name,
                    ActivityType.TASK, ActivityEditPart.ACTIVITY_FIGURE_SIZE.width / 2,
                    PoolEditPart.POOL_HEIGHT / 2 - ActivityEditPart.ACTIVITY_FIGURE_SIZE.height / 2,
                    ActivityEditPart.ACTIVITY_FIGURE_SIZE.width, ActivityEditPart.ACTIVITY_FIGURE_SIZE.height);
            generator.generateViews();

            try {
                Map options = new HashMap();
                options.put(XMIResource.OPTION_ENCODING, "UTF-8"); //$NON-NLS-1$
                modelResource.save(options);
                diagramResource.save(Collections.EMPTY_MAP);
            } catch (IOException e) {

                BpmnDiagramEditorPlugin.getInstance().logError("Unable to store model and diagram resources", //$NON-NLS-1$
                        e);
            }
            return CommandResult.newOKCommandResult();
        }
    };

    try {
        OperationHistoryFactory.getOperationHistory().execute(command,
                new SubProgressMonitor(progressMonitor, 1), null);
    } catch (ExecutionException e) {
        BpmnDiagramEditorPlugin.getInstance().logError("Unable to create model and diagram", e); //$NON-NLS-1$
    }

    try {
        modelFile.setCharset("UTF-8", new SubProgressMonitor(progressMonitor, 1)); //$NON-NLS-1$
    } catch (CoreException e) {
        BpmnDiagramEditorPlugin.getInstance().logError("Unable to set charset for model file", e); //$NON-NLS-1$
    }
    try {
        diagramFile.setCharset("UTF-8", new SubProgressMonitor(progressMonitor, 1)); //$NON-NLS-1$
    } catch (CoreException e) {
        BpmnDiagramEditorPlugin.getInstance().logError("Unable to set charset for diagram file", e); //$NON-NLS-1$
    }

    return diagramFile;
}

From source file:org.eclipse.team.internal.ccvs.ui.actions.CVSAction.java

License:Open Source License

/**
 * Convenience method for running an operation with the appropriate progress.
 * Any exceptions are propagated so they can be handled by the
 * <code>CVSAction#run(IAction)</code> error handling code.
 * //from  w  w  w .ja v a 2  s  .com
 * @param runnable  the runnable which executes the operation
 * @param cancelable  indicate if a progress monitor should be cancelable
 * @param progressKind  one of PROGRESS_BUSYCURSOR or PROGRESS_DIALOG
 */
final protected void run(final IRunnableWithProgress runnable, boolean cancelable, int progressKind)
        throws InvocationTargetException, InterruptedException {
    final Exception[] exceptions = new Exception[] { null };

    // Ensure that no repository view refresh happens until after the action
    final IRunnableWithProgress innerRunnable = new IRunnableWithProgress() {
        public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
            getRepositoryManager().run(runnable, monitor);
        }
    };

    switch (progressKind) {
    case PROGRESS_BUSYCURSOR:
        BusyIndicator.showWhile(Display.getCurrent(), new Runnable() {
            public void run() {
                try {
                    innerRunnable.run(new NullProgressMonitor());
                } catch (InvocationTargetException e) {
                    exceptions[0] = e;
                } catch (InterruptedException e) {
                    exceptions[0] = e;
                }
            }
        });
        break;
    case PROGRESS_DIALOG:
    default:
        new ProgressMonitorDialog(getShell()).run(cancelable, cancelable, innerRunnable);
        break;
    }
    if (exceptions[0] != null) {
        if (exceptions[0] instanceof InvocationTargetException)
            throw (InvocationTargetException) exceptions[0];
        else
            throw (InterruptedException) exceptions[0];
    }
}

From source file:org.eclipse.team.internal.ccvs.ui.CVSUIPlugin.java

License:Open Source License

/**
 * Run an operation involving the given resource. If an exception is thrown
 * and the code on the status is IResourceStatus.OUT_OF_SYNC_LOCAL then
 * the user will be prompted to refresh and try again. If they agree, then the
 * supplied operation will be run again.
 *//* w ww  .  j  av  a 2s  . co  m*/
public static void runWithRefresh(Shell parent, IResource[] resources, IRunnableWithProgress runnable,
        IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
    boolean firstTime = true;
    while (true) {
        try {
            runnable.run(monitor);
            return;
        } catch (InvocationTargetException e) {
            if (!firstTime)
                throw e;
            IStatus status = null;
            if (e.getTargetException() instanceof CoreException) {
                status = ((CoreException) e.getTargetException()).getStatus();
            } else if (e.getTargetException() instanceof TeamException) {
                status = ((TeamException) e.getTargetException()).getStatus();
            } else {
                throw e;
            }
            if (status.getCode() == IResourceStatus.OUT_OF_SYNC_LOCAL) {
                if (promptToRefresh(parent, resources, status)) {
                    try {
                        for (int i = 0; i < resources.length; i++) {
                            resources[i].refreshLocal(IResource.DEPTH_INFINITE, null);
                        }
                    } catch (CoreException coreEx) {
                        // Throw the original exception to the caller
                        log(coreEx);
                        throw e;
                    }
                    firstTime = false;
                    // Fall through and the operation will be tried again
                } else {
                    // User chose not to continue. Treat it as a cancel.
                    throw new InterruptedException();
                }
            } else {
                throw e;
            }
        }
    }
}

From source file:org.eclipse.team.internal.ccvs.ui.FileModificationValidator.java

License:Open Source License

private IStatus edit(final IFile[] files, final Shell shell) {
    if (isPerformEdit()) {
        try {/* w  ww  .  j  av a2s  .com*/
            if (shell != null && !promptToEditFiles(files, shell)) {
                // The user didn't want to edit.
                // OK is returned but the file remains read-only
                throw new InterruptedException();
            }

            // see if the file is up to date
            if (shell != null && promptToUpdateFiles(files, shell)) {
                // The user wants to update the file
                // Run the update in a runnable in order to get a busy cursor.
                // This runnable is syncExeced in order to get a busy cursor
                IRunnableWithProgress updateRunnable = new IRunnableWithProgress() {
                    public void run(IProgressMonitor monitor)
                            throws InvocationTargetException, InterruptedException {
                        performUpdate(files, monitor);
                    }
                };
                if (isRunningInUIThread()) {
                    // Only show a busy cursor if validate edit is blocking the UI
                    CVSUIPlugin.runWithProgress(shell, false, updateRunnable);
                } else {
                    // We can't show a busy cursor (i.e., run in the UI thread)
                    // since this thread may hold locks and
                    // running an edit in the UI thread could try to obtain the
                    // same locks, resulting in a deadlock.
                    updateRunnable.run(new NullProgressMonitor());
                }
            }

            // Run the edit in a runnable in order to get a busy cursor.
            // This runnable is syncExeced in order to get a busy cursor
            IRunnableWithProgress editRunnable = new IRunnableWithProgress() {
                public void run(IProgressMonitor monitor)
                        throws InvocationTargetException, InterruptedException {
                    try {
                        performEdit(files, monitor);
                    } catch (CVSException e) {
                        throw new InvocationTargetException(e);
                    }
                }
            };
            if (isRunningInUIThread()) {
                // Only show a busy cursor if validate edit is blocking the UI
                CVSUIPlugin.runWithProgress(shell, false, editRunnable);
            } else {
                // We can't show a busy cursor (i.e., run in the UI thread)
                // since this thread may hold locks and
                // running an edit in the UI thread could try to obtain the
                // same locks, resulting in a deadlock.
                editRunnable.run(new NullProgressMonitor());
            }
        } catch (InvocationTargetException e) {
            return getStatus(e);
        } catch (InterruptedException e) {
            // Must return an error to indicate that it is not OK to edit the files
            return new Status(IStatus.CANCEL, CVSUIPlugin.ID, 0,
                    CVSUIMessages.FileModificationValidator_vetoMessage, null); //;
        }
    } else if (isPerformEditInBackground()) {
        IStatus status = setWritable(files);
        if (status.isOK())
            performEdit(files);
        return status;
    } else {
        // Allow the files to be edited without notifying the server
        return setWritable(files);
    }

    return Status.OK_STATUS;

}

From source file:org.eclipse.team.internal.ccvs.ui.FileModificationValidator.java

License:Open Source License

private EditorsAction fetchEditors(IFile[] files, Shell shell)
        throws InvocationTargetException, InterruptedException {
    final EditorsAction editors = new EditorsAction(getProvider(files), files);
    IRunnableWithProgress runnable = new IRunnableWithProgress() {
        public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
            editors.run(monitor);/*  www  .ja v  a2s .c om*/
        }
    };
    if (isRunningInUIThread()) {
        // Show a busy cursor if we are running in the UI thread
        CVSUIPlugin.runWithProgress(shell, false, runnable);
    } else {
        // We can't show a busy cursor (i.e., run in the UI thread)
        // since this thread may hold locks and
        // running a CVS operation in the UI thread could try to obtain the
        // same locks, resulting in a deadlock.
        runnable.run(new NullProgressMonitor());
    }
    return editors;
}

From source file:org.eclipse.team.internal.ccvs.ui.repo.RepositoryManager.java

License:Open Source License

/**
 * Run the given runnable, waiting until the end to perform a refresh
 * /*from   w w w .j a v  a 2 s  .  c om*/
 * @param runnable
 * @param monitor
 */
public void run(IRunnableWithProgress runnable, IProgressMonitor monitor)
        throws InvocationTargetException, InterruptedException {
    try {
        notificationLevel++;
        runnable.run(monitor);
    } finally {
        notificationLevel = Math.max(0, notificationLevel - 1);
        if (notificationLevel == 0) {
            try {
                Collection roots = changedRepositories.values();
                broadcastRepositoriesChanged(
                        (ICVSRepositoryLocation[]) roots.toArray(new ICVSRepositoryLocation[roots.size()]));
            } finally {
                changedRepositories.clear();
            }
        }
    }
}

From source file:org.eclipse.team.internal.ccvs.ui.tags.TagSelectionDialog.java

License:Open Source License

/**
 * Creates a runnable context that allows refreshing the tags in the background. 
 * //from   w ww.j a  v a  2 s . c  om
 * @since 3.1
 */
private IRunnableContext getRunnableContext() {
    return new IRunnableContext() {
        public void run(boolean fork, boolean cancelable, final IRunnableWithProgress runnable)
                throws InvocationTargetException, InterruptedException {
            final Job refreshJob = new Job(CVSUIMessages.TagSelectionDialog_7) {
                protected IStatus run(IProgressMonitor monitor) {
                    if (monitor.isCanceled())
                        return Status.CANCEL_STATUS;
                    try {
                        setBusy(true);
                        runnable.run(monitor);
                    } catch (InvocationTargetException e) {
                        return new CVSStatus(IStatus.ERROR, CVSUIMessages.TagSelectionDialog_8, e);
                    } catch (InterruptedException e) {
                        return new CVSStatus(IStatus.ERROR, CVSUIMessages.TagSelectionDialog_8, e);
                    } finally {
                        setBusy(false);
                    }
                    if (monitor.isCanceled())
                        return Status.CANCEL_STATUS;
                    else
                        return Status.OK_STATUS;
                }
            };
            refreshJob.setUser(false);
            refreshJob.setPriority(Job.DECORATE);
            getShell().addDisposeListener(new DisposeListener() {
                public void widgetDisposed(DisposeEvent e) {
                    refreshJob.cancel();
                }
            });
            refreshJob.schedule();
        }
    };
}

From source file:org.eclipse.team.internal.ui.actions.JobRunnableContext.java

License:Open Source License

IStatus run(IRunnableWithProgress runnable, IProgressMonitor monitor) {
    try {//  www  .j  av  a 2s .c  om
        runnable.run(monitor);
    } catch (InvocationTargetException e) {
        return TeamException.asTeamException(e).getStatus();
    } catch (InterruptedException e) {
        return Status.CANCEL_STATUS;
    }
    return getCompletionStatus();
}

From source file:org.eclipse.team.internal.ui.actions.ProgressDialogRunnableContext.java

License:Open Source License

private IRunnableWithProgress wrapRunnable(final IRunnableWithProgress runnable) {
    return new IRunnableWithProgress() {
        public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
            try {
                if (schedulingRule == null && !postponeBuild) {
                    runnable.run(monitor);
                } else {
                    final Exception[] exception = new Exception[] { null };
                    ResourcesPlugin.getWorkspace().run(new IWorkspaceRunnable() {
                        public void run(IProgressMonitor pm) throws CoreException {
                            try {
                                runnable.run(pm);
                            } catch (InvocationTargetException e) {
                                exception[0] = e;
                            } catch (InterruptedException e) {
                                exception[0] = e;
                            }/*from  www .  j a  v a  2s. com*/
                        }
                    }, schedulingRule, 0 /* allow updates */, monitor);
                    if (exception[0] != null) {
                        if (exception[0] instanceof InvocationTargetException) {
                            throw (InvocationTargetException) exception[0];
                        } else if (exception[0] instanceof InterruptedException) {
                            throw (InterruptedException) exception[0];
                        }
                    }
                }
            } catch (CoreException e) {
                throw new InvocationTargetException(e);
            }
        }
    };
}