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

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

Introduction

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

Prototype

IRunnableWithProgress

Source Link

Usage

From source file:bndtools.editor.contents.ExportPatternsListPart.java

License:Open Source License

private void generatePackageInfos(final Collection<? extends File> pkgDirs) throws CoreException {
    final IWorkspaceRunnable wsOperation = new IWorkspaceRunnable() {
        public void run(IProgressMonitor monitor) throws CoreException {
            SubMonitor progress = SubMonitor.convert(monitor, pkgDirs.size());
            MultiStatus status = new MultiStatus(Plugin.PLUGIN_ID, 0,
                    "Errors occurred while creating packageinfo files.", null);
            for (File pkgDir : pkgDirs) {
                IContainer[] locations = ResourcesPlugin.getWorkspace().getRoot()
                        .findContainersForLocationURI(pkgDir.toURI());
                if (locations != null && locations.length > 0) {
                    IFile pkgInfoFile = locations[0].getFile(new Path(PACKAGEINFO));

                    ByteArrayInputStream input = new ByteArrayInputStream("version 1.0".getBytes());
                    try {
                        pkgInfoFile.create(input, false, progress.newChild(1, 0));
                    } catch (CoreException e) {
                        status.add(new Status(IStatus.ERROR, Plugin.PLUGIN_ID, 0,
                                "Error creating file " + pkgInfoFile.getFullPath(), e));
                    }/*ww w  .  j  a  v  a2  s.c o  m*/
                }
            }

            if (!status.isOK())
                throw new CoreException(status);
        }
    };
    IRunnableWithProgress uiOperation = new IRunnableWithProgress() {
        public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
            try {
                ResourcesPlugin.getWorkspace().run(wsOperation, monitor);
            } catch (CoreException e) {
                throw new InvocationTargetException(e);
            }
        }
    };
    try {
        PlatformUI.getWorkbench().getActiveWorkbenchWindow().run(true, true, uiOperation);
    } catch (InvocationTargetException e) {
        throw (CoreException) e.getTargetException();
    } catch (InterruptedException e) {
        // ignore
    }
}

From source file:bndtools.editor.exports.ExportPatternsListPart.java

License:Open Source License

private static void generatePackageInfos(final Collection<? extends FileVersionTuple> pkgs)
        throws CoreException {
    final IWorkspaceRunnable wsOperation = new IWorkspaceRunnable() {
        @Override//www. j  a va2 s .  co m
        public void run(IProgressMonitor monitor) throws CoreException {
            SubMonitor progress = SubMonitor.convert(monitor, pkgs.size());
            MultiStatus status = new MultiStatus(Plugin.PLUGIN_ID, 0,
                    "Errors occurred while creating packageinfo files.", null);
            for (FileVersionTuple pkg : pkgs) {
                IContainer[] locations = ResourcesPlugin.getWorkspace().getRoot()
                        .findContainersForLocationURI(pkg.getFile().toURI());
                if (locations != null && locations.length > 0) {
                    IContainer container = locations[0];

                    PackageInfoStyle packageInfoStyle = PackageInfoStyle
                            .calculatePackageInfoStyle(container.getProject());
                    IFile pkgInfoFile = container.getFile(new Path(packageInfoStyle.getFileName()));

                    try {
                        String formattedPackageInfo = packageInfoStyle.format(pkg.getVersion(), pkg.getName());
                        ByteArrayInputStream input = new ByteArrayInputStream(
                                formattedPackageInfo.getBytes("UTF-8"));
                        if (pkgInfoFile.exists())
                            pkgInfoFile.setContents(input, false, true, progress.newChild(1, 0));
                        else
                            pkgInfoFile.create(input, false, progress.newChild(1, 0));
                    } catch (CoreException e) {
                        status.add(new Status(IStatus.ERROR, Plugin.PLUGIN_ID, 0,
                                "Error creating file " + pkgInfoFile.getFullPath(), e));
                    } catch (UnsupportedEncodingException e) {
                        /* just ignore, should never happen */
                    }
                }
            }

            if (!status.isOK())
                throw new CoreException(status);
        }
    };
    IRunnableWithProgress uiOperation = new IRunnableWithProgress() {
        @Override
        public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
            try {
                ResourcesPlugin.getWorkspace().run(wsOperation, monitor);
            } catch (CoreException e) {
                throw new InvocationTargetException(e);
            }
        }
    };
    try {
        PlatformUI.getWorkbench().getActiveWorkbenchWindow().run(true, true, uiOperation);
    } catch (InvocationTargetException e) {
        throw (CoreException) e.getTargetException();
    } catch (InterruptedException e) {
        // ignore
    }
}

From source file:bndtools.editor.pkgpatterns.PkgPatternsProposalProvider.java

License:Open Source License

@Override
protected Collection<? extends IContentProposal> doGenerateProposals(String contents, int position) {
    String prefix = contents.substring(0, position);

    final int replaceFromPos;
    if (prefix.startsWith("!")) { //$NON-NLS-1$
        prefix = prefix.substring(1);/*from   w  w w.  j  a va2  s.co m*/
        replaceFromPos = 1;
    } else {
        replaceFromPos = 0;
    }

    Comparator<PkgPatternProposal> comparator = new Comparator<PkgPatternProposal>() {
        @Override
        public int compare(PkgPatternProposal o1, PkgPatternProposal o2) {
            int result = o1.getPackageFragment().getElementName()
                    .compareTo(o2.getPackageFragment().getElementName());
            if (result == 0) {
                result = Boolean.valueOf(o1.isWildcard()).compareTo(Boolean.valueOf(o2.isWildcard()));
            }
            return result;
        }
    };
    final TreeSet<PkgPatternProposal> result = new TreeSet<PkgPatternProposal>(comparator);

    final IJavaSearchScope scope = SearchEngine
            .createJavaSearchScope(new IJavaElement[] { searchContext.getJavaProject() });
    final SearchPattern pattern = SearchPattern.createPattern("*" + prefix + "*", IJavaSearchConstants.PACKAGE,
            IJavaSearchConstants.DECLARATIONS, SearchPattern.R_PATTERN_MATCH);
    final SearchRequestor requestor = new SearchRequestor() {
        @Override
        public void acceptSearchMatch(SearchMatch match) throws CoreException {
            IPackageFragment pkg = (IPackageFragment) match.getElement();
            // Reject the default package and any package starting with
            // "java." since these cannot be imported
            if (pkg.isDefaultPackage() || pkg.getElementName().startsWith("java."))
                return;

            result.add(new PkgPatternProposal(pkg, false, replaceFromPos));
            result.add(new PkgPatternProposal(pkg, true, replaceFromPos));
        }
    };
    IRunnableWithProgress runnable = new IRunnableWithProgress() {
        @Override
        public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
            try {
                new SearchEngine().search(pattern,
                        new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() }, scope,
                        requestor, monitor);
            } catch (CoreException e) {
                throw new InvocationTargetException(e);
            }
        }
    };

    try {
        IRunnableContext runContext = searchContext.getRunContext();
        if (runContext != null) {
            runContext.run(false, false, runnable);
        } else {
            runnable.run(new NullProgressMonitor());
        }
        return result;
    } catch (InvocationTargetException e) {
        logger.logError("Error searching for packages.", e);
        return Collections.emptyList();
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        return Collections.emptyList();
    }
}

From source file:bndtools.internal.pkgselection.JavaSearchScopePackageLister.java

License:Open Source License

@Override
public String[] getPackages(boolean includeNonSource, IPackageFilter filter) throws PackageListException {
    final List<IJavaElement> packageList = new LinkedList<IJavaElement>();
    final SearchRequestor requestor = new SearchRequestor() {
        @Override/*  w w  w  .  j a v  a  2s  . c o  m*/
        public void acceptSearchMatch(SearchMatch match) throws CoreException {
            IJavaElement enclosingElement = (IJavaElement) match.getElement();
            String name = enclosingElement.getElementName();
            if (name.length() > 0) { // Do not include default pkg
                packageList.add(enclosingElement);
            }
        }
    };
    final SearchPattern pattern = SearchPattern.createPattern("*", IJavaSearchConstants.PACKAGE,
            IJavaSearchConstants.DECLARATIONS, SearchPattern.R_PATTERN_MATCH | SearchPattern.R_CASE_SENSITIVE);

    IRunnableWithProgress operation = new IRunnableWithProgress() {
        @Override
        public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
            try {
                new SearchEngine().search(pattern, SearchUtils.getDefaultSearchParticipants(), scope, requestor,
                        monitor);
            } catch (CoreException e) {
                throw new InvocationTargetException(e);
            }
        }
    };

    try {
        runContext.run(true, true, operation);
    } catch (InvocationTargetException e) {
        throw new PackageListException(e.getCause());
    } catch (InterruptedException e) {
        throw new PackageListException("Operation interrupted");
    }

    // Remove non-source and excludes
    Set<String> packageNames = new LinkedHashSet<String>();
    for (Iterator<IJavaElement> iter = packageList.iterator(); iter.hasNext();) {
        boolean omit = false;
        IJavaElement element = iter.next();
        if (!includeNonSource) {
            IPackageFragment pkgFragment = (IPackageFragment) element;
            try {
                if (pkgFragment.getCompilationUnits().length == 0) {
                    omit = true;
                }
            } catch (JavaModelException e) {
                throw new PackageListException(e);
            }
        }

        if (filter != null && !filter.select(element.getElementName())) {
            omit = true;
        }
        if (!omit) {
            packageNames.add(element.getElementName());
        }
    }

    return packageNames.toArray(new String[0]);
}

From source file:bndtools.MakeBundleWithRefreshAction.java

License:Open Source License

@Override
public void run(IAction action) {
    // What should we refresh??
    IStructuredSelection selection = StructuredSelection.EMPTY;
    if (targetPart instanceof IEditorPart) {
        IEditorInput input = ((IEditorPart) targetPart).getEditorInput();
        if (input instanceof IFileEditorInput) {
            IFile file = ((IFileEditorInput) input).getFile();
            selection = new StructuredSelection(file);
        }/*from w  ww  . j  a va2  s  . c o m*/
    } else {
        ISelection sel = targetPart.getSite().getSelectionProvider().getSelection();
        if (sel instanceof IStructuredSelection) {
            selection = (IStructuredSelection) sel;
        }
    }
    selectionChanged(action, selection);
    super.run(action);

    final List<IResource> resources = new ArrayList<IResource>(selection.size());
    for (Iterator<?> iter = selection.iterator(); iter.hasNext();) {
        Object next = iter.next();
        if (next instanceof IResource)
            resources.add((IResource) next);
    }
    if (!resources.isEmpty()) {
        final IWorkspace workspace = resources.get(0).getWorkspace();
        final IWorkspaceRunnable operation = new IWorkspaceRunnable() {
            public void run(IProgressMonitor monitor) throws CoreException {
                SubMonitor progress = SubMonitor.convert(monitor, resources.size());
                MultiStatus status = new MultiStatus(Plugin.PLUGIN_ID, 0,
                        "One or more errors occurred while refreshing resources", null);
                for (IResource resource : resources) {
                    try {
                        resource.getParent().refreshLocal(1, progress.newChild(1));
                    } catch (CoreException e) {
                        status.add(new Status(IStatus.ERROR, Plugin.PLUGIN_ID, 0, e.getMessage(), e));
                    }
                }
                if (!status.isOK()) {
                    ErrorDialog.openError(targetPart.getSite().getShell(), "Error", null, status);
                }
            }
        };
        IRunnableWithProgress task = new IRunnableWithProgress() {
            public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
                try {
                    workspace.run(operation, monitor);
                } catch (CoreException e) {
                    throw new InvocationTargetException(e);
                }
            }
        };
        try {
            targetPart.getSite().getWorkbenchWindow().run(false, false, task);
        } catch (InvocationTargetException e) {
            CoreException ce = (CoreException) e.getCause();
            ErrorDialog.openError(targetPart.getSite().getShell(), "Error", null,
                    new Status(IStatus.ERROR, Plugin.PLUGIN_ID, 0, "Error refreshing resources", ce));
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }

    // Process it
    IRunnableContext context = targetPart.getSite().getWorkbenchWindow();
    try {
        context.run(false, false, new IRunnableWithProgress() {
            public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
            }
        });
    } catch (InvocationTargetException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:bndtools.utils.EditorUtils.java

License:Open Source License

public static boolean saveEditorIfDirty(final IEditorPart editor, String dialogTitle, String message) {
    if (editor.isDirty()) {
        if (MessageDialog.openConfirm(editor.getEditorSite().getShell(), dialogTitle, message)) {
            IRunnableWithProgress saveRunnable = new IRunnableWithProgress() {
                @Override//from  ww w.j  a va  2  s . c om
                public void run(IProgressMonitor monitor)
                        throws InvocationTargetException, InterruptedException {
                    editor.doSave(monitor);
                }
            };
            IWorkbenchWindow window = editor.getSite().getWorkbenchWindow();
            try {
                window.run(false, false, saveRunnable);
            } catch (InvocationTargetException e1) {
            } catch (InterruptedException e1) {
                Thread.currentThread().interrupt();
            }
        }
    }
    return !editor.isDirty();
}

From source file:bndtools.wizards.bndfile.EmptyBndFileWizard.java

License:Open Source License

@Override
public boolean performFinish() {
    final EnableSubBundlesOperation operation = new EnableSubBundlesOperation(getShell(),
            ResourcesPlugin.getWorkspace(), mainPage.getContainerFullPath());

    try {//  ww w. j  a  va  2  s.c  om
        getContainer().run(false, false, new IRunnableWithProgress() {
            @Override
            public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
                try {
                    IWorkspace ws = ResourcesPlugin.getWorkspace();
                    ws.run(operation, monitor);

                    if (monitor.isCanceled())
                        throw new InterruptedException();
                } catch (CoreException e) {
                    throw new InvocationTargetException(e);
                }
            }
        });
    } catch (InvocationTargetException e) {
        ErrorDialog.openError(getShell(), "Error", null, new Status(IStatus.ERROR, Plugin.PLUGIN_ID, 0,
                "An error occurred while enabling sub-bundles", e.getCause()));
        return false;
    } catch (InterruptedException e) {
        return false;
    }

    // Open editor on new file.
    InputStream newBundleFileContent = operation.getNewBundleInputStream();
    mainPage.setInitialContents(newBundleFileContent);
    IFile file = mainPage.createNewFile();
    if (file == null)
        return false;

    IWorkbenchWindow dw = workbench.getActiveWorkbenchWindow();
    try {
        if (dw != null) {
            IWorkbenchPage page = dw.getActivePage();
            if (page != null) {
                IDE.openEditor(page, file, true);
            }
        }
    } catch (PartInitException e) {
        ErrorDialog.openError(getShell(), Messages.EmptyBndFileWizard_errorTitleNewBndFile, null, new Status(
                IStatus.ERROR, Plugin.PLUGIN_ID, 0, Messages.EmptyBndFileWizard_errorOpeningBndEditor, e));
    }

    return true;
}

From source file:bndtools.wizards.project.AbstractNewBndProjectWizard.java

License:Open Source License

@Override
public boolean performFinish() {
    boolean result = super.performFinish();
    if (result) {
        final IJavaProject javaProj = (IJavaProject) getCreatedElement();
        final IProject project = javaProj.getProject();
        final Map<String, String> templateParams = getProjectTemplateParams();

        try {//from  w  w  w .jav  a 2s .  com
            // Run using the progress bar from the wizard dialog
            getContainer().run(false, false, new IRunnableWithProgress() {
                @Override
                public void run(IProgressMonitor monitor)
                        throws InvocationTargetException, InterruptedException {
                    try {
                        // Make changes to the project
                        final IWorkspaceRunnable op = new IWorkspaceRunnable() {
                            @Override
                            public void run(IProgressMonitor monitor) throws CoreException {
                                try {
                                    generateProjectContent(project, monitor, templateParams);
                                } catch (Exception e) {
                                    throw new CoreException(new Status(IStatus.ERROR, Plugin.PLUGIN_ID, 0,
                                            "Error generating project content from template", e));
                                }
                            }
                        };
                        javaProj.getProject().getWorkspace().run(op, monitor);
                    } catch (CoreException e) {
                        throw new InvocationTargetException(e);
                    }
                }
            });
            result = true;
        } catch (InvocationTargetException e) {
            Throwable targetException = e.getTargetException();
            final IStatus status;
            if (targetException instanceof CoreException) {
                status = ((CoreException) targetException).getStatus();
            } else {
                status = new Status(IStatus.ERROR, Plugin.PLUGIN_ID, 0, "Error creating bnd project contents",
                        targetException);
            }
            logger.logStatus(status);
            ErrorDialog.openError(getShell(), "Error", "Error creating bnd project", status);
            result = false;
        } catch (InterruptedException e) {
            // Shouldn't happen
        }

        // get bnd.bnd file
        IFile bndFile = javaProj.getProject().getFile(Project.BNDFILE);

        // check to see if we need to add marker about missing workspace
        try {
            if (!Central.hasWorkspaceDirectory()) {
                IResource markerTarget = bndFile;
                if (markerTarget == null || markerTarget.getType() != IResource.FILE || !markerTarget.exists())
                    markerTarget = project;
                IMarker marker = markerTarget.createMarker(BndtoolsConstants.MARKER_BND_MISSING_WORKSPACE);
                marker.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_ERROR);
                marker.setAttribute(IMarker.MESSAGE,
                        "Missing Bnd Workspace. Create a new workspace with the 'New Bnd OSGi Workspace' wizard.");
                marker.setAttribute(BuildErrorDetailsHandler.PROP_HAS_RESOLUTIONS, true);
                marker.setAttribute("$bndType", BndtoolsConstants.MARKER_BND_MISSING_WORKSPACE);
            }
        } catch (Exception e1) {
            // ignore exceptions, this is best effort to help new users
        }

        // Open the bnd.bnd file in the editor
        try {
            if (bndFile.exists())
                IDE.openEditor(getWorkbench().getActiveWorkbenchWindow().getActivePage(), bndFile);
        } catch (PartInitException e) {
            ErrorDialog.openError(getShell(), "Error", null,
                    new Status(IStatus.ERROR, Plugin.PLUGIN_ID, 0,
                            MessageFormat.format("Failed to open project descriptor file {0} in the editor.",
                                    bndFile.getFullPath().toString()),
                            e));
        }
    }
    return result;
}

From source file:bndtools.wizards.project.NewBndProjectWizardPageTwo.java

License:Open Source License

void doSetProjectDesc(final IProject project, final IProjectDescription desc) throws CoreException {
    final IWorkspaceRunnable workspaceOp = new IWorkspaceRunnable() {
        @Override/*w ww. jav  a2  s.  c  om*/
        public void run(IProgressMonitor monitor) throws CoreException {
            project.setDescription(desc, monitor);
        }
    };
    try {
        getContainer().run(true, true, new IRunnableWithProgress() {
            @Override
            public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
                try {
                    project.getWorkspace().run(workspaceOp, monitor);
                } catch (CoreException e) {
                    throw new InvocationTargetException(e);
                }
            }
        });
    } catch (InvocationTargetException e) {
        throw (CoreException) e.getTargetException();
    } catch (InterruptedException e) {
        throw new CoreException(new Status(IStatus.ERROR, Plugin.PLUGIN_ID, 0,
                "Interrupted while adding Bnd OSGi Project nature to project.", e));
    }
}

From source file:br.ufes.inf.uml2ctx.ui.popupMenus.AcceleoGenerateUml2ctxAction.java

License:Open Source License

/**{@inheritDoc}
 *
 * @see org.eclipse.ui.actions.ActionDelegate#run(org.eclipse.jface.action.IAction)
 * @generated/*from w  w w  .  j a v a  2 s.  c o m*/
 */
public void run(IAction action) {
    if (files != null) {
        IRunnableWithProgress operation = new IRunnableWithProgress() {
            public void run(IProgressMonitor monitor) {
                try {
                    Iterator<IFile> filesIt = files.iterator();
                    while (filesIt.hasNext()) {
                        IFile model = (IFile) filesIt.next();
                        URI modelURI = URI.createPlatformResourceURI(model.getFullPath().toString(), true);
                        try {
                            IContainer target = model.getProject().getFolder("model");
                            GenerateAll generator = new GenerateAll(modelURI, target, getArguments());
                            generator.doGenerate(monitor);
                        } catch (IOException e) {
                            IStatus status = new Status(IStatus.ERROR, Activator.PLUGIN_ID, e.getMessage(), e);
                            Activator.getDefault().getLog().log(status);
                        } finally {
                            model.getProject().refreshLocal(IResource.DEPTH_INFINITE, monitor);
                        }
                    }
                } catch (CoreException e) {
                    IStatus status = new Status(IStatus.ERROR, Activator.PLUGIN_ID, e.getMessage(), e);
                    Activator.getDefault().getLog().log(status);
                }
            }
        };
        try {
            PlatformUI.getWorkbench().getProgressService().run(true, true, operation);
        } catch (InvocationTargetException e) {
            IStatus status = new Status(IStatus.ERROR, Activator.PLUGIN_ID, e.getMessage(), e);
            Activator.getDefault().getLog().log(status);
        } catch (InterruptedException e) {
            IStatus status = new Status(IStatus.ERROR, Activator.PLUGIN_ID, e.getMessage(), e);
            Activator.getDefault().getLog().log(status);
        }
    }
}