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.edt.ide.ui.internal.project.wizards.NewEGLProjectWizard.java

License:Open Source License

public boolean performFinish() {
    try {//  w  ww .ja  v  a 2 s .  co  m
        ISchedulingRule rule = getCurrentSchedulingRule();
        model.setProjectName(mainPage.getModel().getProjectName());
        // If a page of the dynamically embedded template wizard is not
        // currently being displayed, the performFinish() on this wizard will
        // not get displayed. This code ensures this happens.      

        IProjectTemplate template = model.getSelectedProjectTemplate();

        IWizardNode node = mainPage.getSelectedNode();
        ProjectTemplateWizardNode twn = null;
        if (node != null && node instanceof ProjectTemplateWizardNode) {
            twn = (ProjectTemplateWizardNode) node;
            if (twn.getTemplate().hasWizard()) {
                if (!twn.getWizard().performFinish()) {
                    return false;
                }
            }
        }

        final List ops = ProjectFinishUtility.getCreateProjectFinishOperations(
                (IProjectTemplateClass) template.getProjectTemplateClass(), model, 0, rule);

        //         ops.addAll(opsImport);
        getContainer().run(true, true, new WorkspaceModifyOperation() {
            @Override
            protected void execute(IProgressMonitor monitor)
                    throws CoreException, InvocationTargetException, InterruptedException {

                for (Iterator it = ops.iterator(); it.hasNext();) {
                    Object obj = it.next();
                    if (obj instanceof WorkspaceModifyOperation) {
                        IRunnableWithProgress runnable = (IRunnableWithProgress) obj;
                        try {
                            runnable.run(monitor);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                        if (monitor.isCanceled()) {
                            break;
                        }
                    }
                }
            }
        });

        List opsImport = ProjectFinishUtility.getImportProjectOperations(
                (IProjectTemplateClass) template.getProjectTemplateClass(), model, 0, rule);
        for (Iterator it = opsImport.iterator(); it.hasNext();) {
            Object obj = it.next();
            if (obj instanceof WorkspaceModifyOperation) {
                WorkspaceModifyOperation op = (WorkspaceModifyOperation) obj;
                getContainer().run(false, true, op);
            }
        }

        if (twn != null && twn.getTemplate().hasWizard()) {
            if (twn.getWizard() instanceof BasicProjectTemplateWizard) {
                if (!((BasicProjectTemplateWizard) twn.getWizard()).proecssGenerationDirectorySetting()) {
                    return false;
                }
            }
        }

        // Remember base package name
        IPreferenceStore store = EDTUIPlugin.getDefault().getPreferenceStore();
        if (template.getProjectTemplateClass().needPreserveBasePackage()) {
            store.putValue(EDTUIPreferenceConstants.NEWPROJECTWIZARD_BASEPACKAGE, model.getBasePackageName());
        }
        store.putValue(EDTUIPreferenceConstants.NEWPROJECTWIZARD_SELECTEDTEMPLATE, template.getId());
    } catch (InterruptedException e) {
        e.printStackTrace();
        return false;
    } catch (InvocationTargetException e) {
        if (e.getTargetException() instanceof CoreException) {
            ErrorDialog.openError(getContainer().getShell(), null, null,
                    ((CoreException) e.getTargetException()).getStatus());
        } else {
            e.printStackTrace();
            EDTUIPlugin.log(e);
        }
        return false;
    } finally {
        postPerformFinish();
    }
    return true;
}

From source file:org.eclipse.egit.ui.internal.branch.LaunchFinder.java

License:Open Source License

/**
 * If there is a running launch covering at least one project from the given
 * repositories, return the first such launch configuration.
 *
 * @param repositories/* w ww .  jav a  2  s. com*/
 *            to determine projects to be checked whether they are used in
 *            running launches
 * @param monitor
 *            for progress reporting and cancellation
 * @return the {@link ILaunchConfiguration}, or {@code null} if none found.
 */
@Nullable
public static ILaunchConfiguration getRunningLaunchConfiguration(final Collection<Repository> repositories,
        IProgressMonitor monitor) {
    SubMonitor progress = SubMonitor.convert(monitor, 1);
    final ILaunchConfiguration[] result = { null };
    IRunnableWithProgress operation = new IRunnableWithProgress() {

        @Override
        public void run(IProgressMonitor m) throws InvocationTargetException, InterruptedException {
            Set<IProject> projects = new HashSet<>();
            for (Repository repository : repositories) {
                projects.addAll(Arrays.asList(ProjectUtil.getProjects(repository)));
            }
            result[0] = findLaunch(projects, m);
        }
    };
    try {
        if (ModalContext.isModalContextThread(Thread.currentThread())) {
            operation.run(progress);
        } else {
            ModalContext.run(operation, true, progress, PlatformUI.getWorkbench().getDisplay());
        }
    } catch (InvocationTargetException e) {
        // ignore
    } catch (InterruptedException e) {
        // ignore
    }
    return result[0];
}

From source file:org.eclipse.emf.cdo.dawn.codegen.util.ProjectCreationHelper.java

License:Open Source License

public static void refreshProject(IResource resource, IProgressMonitor monitor)
        throws InvocationTargetException, InterruptedException {
    IRunnableWithProgress op = new WorkspaceModifyOperation(null) {
        @Override/*from   w w  w.ja v  a2 s. co m*/
        protected void execute(IProgressMonitor monitor) throws CoreException, InterruptedException {
            try {
                IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
                root.refreshLocal(IResource.DEPTH_INFINITE, monitor);

            } catch (CoreException e) {

                e.printStackTrace();
            }
        }
    };
    op.run(monitor);
}

From source file:org.eclipse.epf.library.ui.actions.LibraryLockingOperationRunner.java

License:Open Source License

private void doRun(final IRunnableWithProgress runnable, final boolean workUnknown)
        throws InvocationTargetException, InterruptedException {
    final InvocationTargetException[] iteHolder = new InvocationTargetException[1];
    try {/*  w w w .  j  a  v  a  2s . com*/
        IWorkspaceRunnable workspaceRunnable = new IWorkspaceRunnable() {
            public void run(IProgressMonitor pm) throws CoreException {
                try {
                    if (workUnknown) {
                        pm.beginTask("", 2); //$NON-NLS-1$
                        pm.worked(1);
                        try {
                            runnable.run(pm);
                            pm.worked(2);
                        } finally {
                            pm.done();
                        }
                    } else {
                        runnable.run(pm);
                    }
                } catch (InvocationTargetException e) {
                    // Pass it outside the workspace runnable
                    iteHolder[0] = e;
                } catch (InterruptedException e) {
                    // Re-throw as OperationCanceledException, which will be
                    // caught and re-thrown as InterruptedException below.
                    throw new OperationCanceledException(e.getMessage());
                }
                // CoreException and OperationCanceledException are propagated
            }
        };
        ResourcesPlugin.getWorkspace().run(workspaceRunnable,
                new LibrarySchedulingRule(LibraryService.getInstance().getCurrentMethodLibrary()),
                IWorkspace.AVOID_UPDATE, getProgressMonitor());
    } catch (CoreException e) {
        throw new InvocationTargetException(e);
    } catch (OperationCanceledException e) {
        throw new InterruptedException(e.getMessage());
    }
    // Re-throw the InvocationTargetException, if any occurred
    if (iteHolder[0] != null) {
        throw iteHolder[0];
    }
}

From source file:org.eclipse.gmf.examples.runtime.diagram.logic.internal.util.LogicEditorUtil.java

License:Open Source License

/**
 * Creates a new diagram file resource in the selected container and with
 * the selected name. Creates any missing resource containers along the
 * path; does nothing if the container resources already exist.
 * <p>//from w  ww.ja va 2 s . c  om
 * In normal usage, this method is invoked after the user has pressed Finish
 * on the wizard; the enablement of the Finish button implies that all
 * controls on on this page currently contain valid values.
 * </p>
 * <p>
 * Note that this page caches the new file once it has been successfully
 * created; subsequent invocations of this method will answer the same file
 * resource without attempting to create it again.
 * </p>
 * <p>
 * This method should be called within a workspace modify operation since it
 * creates resources.
 * </p>
 *
 * @return the created file resource, or <code>null</code> if the file was
 *         not created
 */
public static final IFile createNewDiagramFile(DiagramFileCreator diagramFileCreator, IPath containerFullPath,
        String fileName, InputStream initialContents, final String kind, Shell shell,
        final IProgressMonitor progressMonitor, final String semanticResourcePath) {

    /** cache of newly-created file */
    final IFile newDiagramFile = diagramFileCreator.createNewFile(containerFullPath, fileName, initialContents,
            shell, new IRunnableContext() {
                public void run(boolean fork, boolean cancelable, IRunnableWithProgress runnable)
                        throws InvocationTargetException, InterruptedException {
                    runnable.run(progressMonitor);
                }
            });

    TransactionalEditingDomain domain = GMFEditingDomainFactory.getInstance().createEditingDomain();
    final ResourceSet resourceSet = domain.getResourceSet();

    AbstractEMFOperation op = new AbstractEMFOperation(domain,
            ExampleDiagramLogicMessages.LogicWizardPage_Title) {

        protected IStatus doExecute(IProgressMonitor monitor, IAdaptable info) throws ExecutionException {

            IFile semanticFile = null;
            boolean semanticFileIsNew = false;
            if (semanticResourcePath != null && semanticResourcePath.length() > 0) {
                try {
                    semanticFile = ResourcesPlugin.getWorkspace().getRoot()
                            .getFile(new Path(semanticResourcePath));
                } catch (Exception e) {

                }
                if (!semanticFile.exists()) {
                    semanticFileIsNew = true;
                    try {
                        semanticFile.create(new ByteArrayInputStream(new byte[0]), false, progressMonitor);
                    } catch (CoreException e) {
                        Log.error(LogicDiagramPlugin.getInstance(), IStatus.ERROR, e.getMessage(), e);
                        return null;
                    }
                }
            }

            try {
                newDiagramFile.refreshLocal(IResource.DEPTH_ZERO, null);
                if (semanticFile != null) {
                    semanticFile.refreshLocal(IResource.DEPTH_ZERO, null);
                }
            } catch (CoreException e) {
                Trace.catching(LogicDiagramPlugin.getInstance(), LogicDiagramDebugOptions.EXCEPTIONS_CATCHING,
                        LogicEditorUtil.class, "createNewDiagramFile", //$NON-NLS-1$
                        e);
            }

            Model semanticModel = null;
            if (semanticFileIsNew) {
                // create blank semantic model
                semanticModel = SemanticFactory.eINSTANCE.createModel();
                Resource semanticResource = resourceSet
                        .createResource(URI.createPlatformResourceURI(semanticResourcePath, true));
                semanticResource.getContents().add(semanticModel);
            } else if (semanticFile != null) {
                // load provided semantic model
                semanticModel = (Model) resourceSet
                        .getResource(URI.createPlatformResourceURI(semanticResourcePath, true), true)
                        .getContents().get(0);
            }

            // create blank notation model file
            final String completeFileName = newDiagramFile.getLocation().toOSString();
            Resource notationModel = resourceSet.createResource(URI.createFileURI(completeFileName));

            if (semanticModel == null) {
                semanticModel = SemanticFactory.eINSTANCE.createModel();
                notationModel.getContents().add(semanticModel);
            }

            Diagram view = ViewService.createDiagram(semanticModel, kind,
                    new PreferencesHint(LogicDiagramPlugin.EDITOR_ID));

            if (view != null) {
                notationModel.getContents().add(0, view);
                view.getDiagram().setName(newDiagramFile.getName());
            }

            try {
                notationModel.save(Collections.EMPTY_MAP);
                semanticModel.eResource().save(Collections.EMPTY_MAP);
            } catch (IOException e) {
                Trace.catching(LogicDiagramPlugin.getInstance(), LogicDiagramDebugOptions.EXCEPTIONS_CATCHING,
                        LogicEditorUtil.class, "createNewDiagramFile", e); //$NON-NLS-1$
                Log.error(LogicDiagramPlugin.getInstance(), LogicDiagramStatusCodes.IGNORED_EXCEPTION_WARNING,
                        e.getLocalizedMessage());
            }

            return Status.OK_STATUS;
        }
    };

    try {
        op.execute(new NullProgressMonitor(), null);

    } catch (ExecutionException e) {
        Trace.catching(LogicDiagramPlugin.getInstance(), LogicDiagramDebugOptions.EXCEPTIONS_CATCHING,
                LogicEditorUtil.class, "createNewDiagramFile", e); //$NON-NLS-1$
        Log.error(LogicDiagramPlugin.getInstance(), LogicDiagramStatusCodes.IGNORED_EXCEPTION_WARNING,
                e.getLocalizedMessage());
    }

    return newDiagramFile;
}

From source file:org.eclipse.gmf.runtime.diagram.ui.resources.editor.util.EditorUtil.java

License:Open Source License

/**
 * Creates a new diagram file resource in the selected container and with
 * the selected name. Creates any missing resource containers along the
 * path; does nothing if the container resources already exist. Creates a
 * new editing domain for this diagram./*w  w w.  j  a v a2s  .  c  o  m*/
 * <p>
 * In normal usage, this method is invoked after the user has pressed Finish
 * on the wizard; the enablement of the Finish button implies that all
 * controls on on this page currently contain valid values.
 * </p>
 * <p>
 * Note that this page caches the new file once it has been successfully
 * created; subsequent invocations of this method will answer the same file
 * resource without attempting to create it again.
 * </p>
 * <p>
 * This method should be called within a workspace modify operation since it
 * creates resources.
 * </p>
 * 
 * @param preferencesHint
 *            The preference hint that is to be used to find the appropriate
 *            preference store from which to retrieve diagram preference
 *            values. The preference hint is mapped to a preference store in
 *            the preference registry <@link DiagramPreferencesRegistry>.
 * 
 * @return the created file resource, or <code>null</code> if the file was
 *         not created
 */
public static IFile createNewDiagramFile(DiagramFileCreator diagramFileCreator, IPath containerFullPath,
        String fileName, InputStream initialContents, final String kind, Shell shell,
        final IProgressMonitor progressMonitor, final PreferencesHint preferencesHint) {
    /** cache of newly-created file */
    final IFile newDiagramFile = diagramFileCreator.createNewFile(containerFullPath, fileName, initialContents,
            shell, new IRunnableContext() {

                public void run(boolean fork, boolean cancelable, IRunnableWithProgress runnable)
                        throws InvocationTargetException, InterruptedException {
                    runnable.run(progressMonitor);
                }
            });

    // Fill the contents of the file dynamically
    Resource notationModel = null;

    try {
        newDiagramFile.refreshLocal(IResource.DEPTH_ZERO, null); //RATLC00514368
        InputStream stream = newDiagramFile.getContents();
        String completeFileName = newDiagramFile.getFullPath().toString();

        try {
            // Empty file....
            ResourceSet resourceSet = new ResourceSetImpl();
            notationModel = resourceSet.createResource(URI.createPlatformResourceURI(completeFileName, true));
        } finally {
            stream.close();
        }

    } catch (Exception e) {
        Trace.catching(EditorPlugin.getInstance(), EditorDebugOptions.EXCEPTIONS_CATCHING, EditorUtil.class,
                "createNewDiagramFile", //$NON-NLS-1$
                e);
    }

    if (notationModel != null) {
        View view = ViewService.createDiagram(kind, preferencesHint);

        if (view != null) {
            notationModel.getContents().add(view.getDiagram());
            view.getDiagram().setName(newDiagramFile.getName());
        }
    }
    try {
        notationModel.save(Collections.EMPTY_MAP);
    } catch (IOException e) {
        Trace.catching(EditorPlugin.getInstance(), EditorDebugOptions.EXCEPTIONS_CATCHING, EditorUtil.class,
                "createNewDiagramFile", e); //$NON-NLS-1$
        Log.error(EditorPlugin.getInstance(), EditorStatusCodes.RESOURCE_FAILURE, e.getLocalizedMessage());
    }
    return newDiagramFile;
}

From source file:org.eclipse.gmt.modisco.jm2t.internal.ui.wizard.TaskWizard.java

License:Open Source License

/**
 * Cancel the client selection.//from   w w w.ja  va  2s. c o  m
 *
 * @return boolean
 */
public boolean performCancel() {
    final List list = getAllWizardFragments();
    IRunnableWithProgress runnable = new IRunnableWithProgress() {
        public void run(IProgressMonitor monitor) throws InvocationTargetException {
            try {
                Iterator iterator = list.iterator();
                while (iterator.hasNext())
                    executeTask((WizardFragment) iterator.next(), CANCEL, monitor);
            } catch (CoreException ce) {
                throw new InvocationTargetException(ce);
            }
        }
    };

    Throwable t = null;
    try {
        if (getContainer() != null)
            getContainer().run(true, true, runnable);
        else
            runnable.run(new NullProgressMonitor());
        return true;
    } catch (InvocationTargetException te) {
        t = te.getCause();
    } catch (Exception e) {
        t = e;
    }
    Trace.trace(Trace.SEVERE, "Error cancelling task wizard", t);

    if (t instanceof CoreException) {
        EclipseUtil.openError(t.getLocalizedMessage(), ((CoreException) t).getStatus());
    } else
        EclipseUtil.openError(t.getLocalizedMessage());

    return false;

}

From source file:org.eclipse.jdt.internal.ui.examples.jspeditor.JspReconcilingStrategy.java

License:Open Source License

private void process(final IReconcileResult[] results) {

    if (results == null)
        return;/*from   w ww.j  a va 2  s  .  c  om*/

    IRunnableWithProgress runnable = new WorkspaceModifyOperation(null) {
        /*
         * @see org.eclipse.ui.actions.WorkspaceModifyOperation#execute(org.eclipse.core.runtime.IProgressMonitor)
         */
        protected void execute(IProgressMonitor monitor)
                throws CoreException, InvocationTargetException, InterruptedException {
            for (int i = 0; i < results.length; i++) {

                if (fProgressMonitor != null && fProgressMonitor.isCanceled())
                    return;

                if (!(results[i] instanceof AnnotationAdapter))
                    continue;

                AnnotationAdapter result = (AnnotationAdapter) results[i];
                Position pos = result.getPosition();

                Annotation annotation = result.createAnnotation();
                getAnnotationModel().addAnnotation(annotation, pos);
            }
        }
    };
    try {
        runnable.run(null);
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

From source file:org.eclipse.jdt.ui.tests.wizardapi.NewJavaProjectWizardTest.java

License:Open Source License

public void testBasicCreate() throws Exception {
    IProject project = fWizardPage.getProjectHandle();

    IRunnableWithProgress op = new WorkspaceModifyDelegatingOperation(fWizardPage.getRunnable());
    op.run(null);

    IJavaProject jproj = fWizardPage.getNewJavaProject();

    assertEquals("a", jproj.getProject(), project);

    IPath outputLocation = jproj.getOutputLocation();
    IClasspathEntry[] classpath = jproj.getRawClasspath();
    assertBasicBuildPath(jproj.getProject(), outputLocation, classpath);
}

From source file:org.eclipse.jdt.ui.tests.wizardapi.NewJavaProjectWizardTest.java

License:Open Source License

public void testProjectChange() throws Exception {
    fWizardPage.initBuildPath();//from w ww .  ja  v a  2 s  . c  om
    IProject project = fWizardPage.getProjectHandle();

    IPath outputLocation = fWizardPage.getOutputLocation();
    IClasspathEntry[] classpath = fWizardPage.getRawClassPath();
    assertBasicBuildPath(project, outputLocation, classpath);

    IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
    IProject otherProject = root.getProject(OTHER_PROJECT_NAME);

    // change the project before create
    fWizardPage.setProjectHandle(otherProject);

    IRunnableWithProgress op = new WorkspaceModifyDelegatingOperation(fWizardPage.getRunnable());
    op.run(null);

    IJavaProject jproj = fWizardPage.getNewJavaProject();

    assertEquals("a", jproj.getProject(), otherProject);

    IPath outputLocation1 = fWizardPage.getOutputLocation();
    IClasspathEntry[] classpath1 = fWizardPage.getRawClassPath();
    assertBasicBuildPath(otherProject, outputLocation1, classpath1);
}