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

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

Introduction

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

Prototype

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

Source Link

Document

Runs the given IRunnableWithProgress in this context.

Usage

From source file:bndtools.editor.components.ComponentNameProposalProvider.java

License:Open Source License

@Override
protected List<IContentProposal> doGenerateProposals(String contents, int position) {
    final String prefix = contents.substring(0, position);
    IJavaProject javaProject = searchContext.getJavaProject();
    final List<IContentProposal> result = new ArrayList<IContentProposal>(100);

    // Resource matches
    IProject project = javaProject.getProject();
    try {//from www  . j  a  v  a  2s  .c  o m
        project.accept(new IResourceProxyVisitor() {
            public boolean visit(IResourceProxy proxy) throws CoreException {
                if (proxy.getType() == IResource.FILE) {
                    if (proxy.getName().toLowerCase().startsWith(prefix)
                            && proxy.getName().toLowerCase().endsWith(XML_SUFFIX)) {
                        result.add(new ResourceProposal(proxy.requestResource()));
                    }
                    return false;
                }
                // Recurse into everything else
                return true;
            }
        }, 0);
    } catch (CoreException e) {
        Plugin.log(new Status(IStatus.ERROR, Plugin.PLUGIN_ID, 0, "Error searching for resources.", e));
    }

    // Class matches
    final IJavaSearchScope scope = SearchEngine.createJavaSearchScope(new IJavaElement[] { javaProject });
    final TypeNameRequestor requestor = new TypeNameRequestor() {
        @Override
        public void acceptType(int modifiers, char[] packageName, char[] simpleTypeName,
                char[][] enclosingTypeNames, String path) {
            if (!Flags.isAbstract(modifiers) && (Flags.isPublic(modifiers) || Flags.isProtected(modifiers))) {
                result.add(new JavaContentProposal(new String(packageName), new String(simpleTypeName), false));
            }
        };
    };
    final IRunnableWithProgress runnable = new IRunnableWithProgress() {
        public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
            try {
                new SearchEngine().searchAllTypeNames(null, 0, prefix.toCharArray(),
                        SearchPattern.R_PREFIX_MATCH, IJavaSearchConstants.CLASS, scope, requestor,
                        IJavaSearchConstants.CANCEL_IF_NOT_READY_TO_SEARCH, monitor);
            } catch (JavaModelException e) {
                throw new InvocationTargetException(e);
            }
        }
    };
    IRunnableContext runContext = searchContext.getRunContext();
    try {
        if (runContext != null) {
            runContext.run(false, false, runnable);
        } else {
            runnable.run(new NullProgressMonitor());
        }
    } catch (InvocationTargetException e) {
        Plugin.log(new Status(IStatus.ERROR, Plugin.PLUGIN_ID, 0, "Error searching for classes.",
                e.getTargetException()));
    } catch (InterruptedException e) {
        // Reset the interruption status and continue
        Thread.currentThread().interrupt();
    }
    return result;
}

From source file:bndtools.editor.components.MethodProposalProvider.java

License:Open Source License

@Override
public List<IContentProposal> doGenerateProposals(String contents, int position) {
    final String prefix = contents.substring(0, position);
    final List<IContentProposal> result = new ArrayList<IContentProposal>();

    try {/*from ww w.j  av a2s.  co m*/
        IRunnableWithProgress runnable = new IRunnableWithProgress() {
            public void run(IProgressMonitor monitor) throws InvocationTargetException {
                SubMonitor progress = SubMonitor.convert(monitor, 10);

                try {
                    IJavaProject project = searchContext.getJavaProject();
                    String targetTypeName = searchContext.getTargetTypeName();
                    IType targetType = project.findType(targetTypeName, progress.newChild(1));

                    if (targetType == null)
                        return;

                    ITypeHierarchy hierarchy = targetType.newSupertypeHierarchy(progress.newChild(5));
                    IType[] classes = hierarchy.getAllClasses();
                    progress.setWorkRemaining(classes.length);
                    for (IType clazz : classes) {
                        IMethod[] methods = clazz.getMethods();
                        for (IMethod method : methods) {
                            if (method.getElementName().toLowerCase().startsWith(prefix)) {
                                // String[] parameterTypes = method.getParameterTypes();
                                // TODO check parameter type
                                result.add(new MethodContentProposal(method));
                            }
                        }
                        progress.worked(1);
                    }
                } catch (JavaModelException e) {
                    throw new InvocationTargetException(e);
                }
            }
        };
        IRunnableContext runContext = searchContext.getRunContext();
        if (runContext != null) {
            runContext.run(false, false, runnable);
        } else {
            runnable.run(new NullProgressMonitor());
        }
        return result;
    } catch (InvocationTargetException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return Collections.emptyList();
}

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   www  . j a  v a2s .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.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  w w .ja  v a  2 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:cn.dockerfoundry.ide.eclipse.server.ui.internal.CloudUiUtil.java

License:Open Source License

public static void runForked(final ICoreRunnable coreRunner, IRunnableContext progressService)
        throws OperationCanceledException, CoreException {
    try {/* www  .j av  a  2  s.  c  o m*/
        IRunnableWithProgress runner = new IRunnableWithProgress() {
            public void run(final IProgressMonitor monitor)
                    throws InvocationTargetException, InterruptedException {
                monitor.beginTask("", IProgressMonitor.UNKNOWN); //$NON-NLS-1$
                try {
                    coreRunner.run(monitor);
                } catch (CoreException e) {
                    throw new InvocationTargetException(e);
                } finally {
                    monitor.done();
                }
            }

        };
        progressService.run(true, true, runner);
    } catch (InvocationTargetException e) {
        if (e.getCause() instanceof CoreException) {
            throw (CoreException) e.getCause();
        } else {
            DockerFoundryServerUiPlugin.getDefault().getLog().log(new Status(IStatus.ERROR,
                    DockerFoundryServerUiPlugin.PLUGIN_ID, "Unexpected exception", e)); //$NON-NLS-1$
        }
    } catch (InterruptedException e) {
        throw new OperationCanceledException();
    }
}

From source file:com.aliyun.odps.eclipse.launch.configuration.udf.UDFSearchEngine.java

License:Apache License

/**
 * Searches for all main methods in the given scope. Valid styles are
 * IJavaElementSearchConstants.CONSIDER_BINARIES and
 * IJavaElementSearchConstants.CONSIDER_EXTERNAL_JARS
 * // w w w.  java  2  s.  co  m
 * @param includeSubtypes whether to consider types that inherit a main method
 */
public IType[] searchUDFClass(IRunnableContext context, final IJavaSearchScope scope,
        final boolean includeSubtypes) throws InvocationTargetException, InterruptedException {
    final IType[][] res = new IType[1][];

    IRunnableWithProgress runnable = new IRunnableWithProgress() {
        public void run(IProgressMonitor pm) throws InvocationTargetException {
            res[0] = searchUDFClass(pm, scope, includeSubtypes);
        }
    };
    context.run(true, true, runnable);

    return res[0];
}

From source file:com.arm.cmsis.pack.installer.ui.handlers.ReloadPacksHandler.java

License:Open Source License

@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
    IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindow(event);
    IRunnableContext context = window.getWorkbench().getProgressService();
    try {/*from   ww  w. j av  a  2  s .  com*/
        context.run(true, false, new IRunnableWithProgress() {
            @Override
            public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
                monitor.beginTask(Messages.ReloadPacksHandler_RefreshPacks, 1);
                Display.getDefault().syncExec(new Runnable() {
                    @Override
                    public void run() {
                        CpPlugIn.getPackManager().reload();
                    }
                });
                monitor.worked(1);
                monitor.done();
            }
        });

    } catch (InvocationTargetException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.arm.cmsis.pack.installer.ui.handlers.UpdatePacksHandler.java

License:Open Source License

@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
    IRunnableContext context = HandlerUtil.getActiveWorkbenchWindow(event).getWorkbench().getProgressService();
    try {/*from w  w  w  .  ja  v a  2s. co m*/
        context.run(true, true, new IRunnableWithProgress() {
            @Override
            public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
                CpPlugIn.getPackManager().getPackInstaller().updatePacks(monitor);
            }
        });

    } catch (InvocationTargetException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.asakusafw.shafu.ui.util.ProgressUtils.java

License:Apache License

/**
 * Invokes {@link ICallable#call(IProgressMonitor)} using {@link IRunnableContext the context}.
 * @param context the target context/*w  w  w . j  a  v  a  2 s  .  co m*/
 * @param callable the target operation
 * @return the operation result
 * @param <T> the operation result type
 * @throws CoreException if the operation was failed
 */
public static <T> T call(IRunnableContext context, final ICallable<T> callable) throws CoreException {
    try {
        final AtomicReference<T> result = new AtomicReference<T>();
        context.run(true, true, new IRunnableWithProgress() {
            @Override
            public void run(IProgressMonitor monitor) throws InvocationTargetException {
                try {
                    result.set(callable.call(monitor));
                } catch (CoreException e) {
                    throw new InvocationTargetException(e);
                }
            }
        });
        return result.get();
    } catch (InvocationTargetException e) {
        Throwable cause = e.getCause();
        if (cause instanceof CoreException) {
            throw (CoreException) cause;
        } else if (cause instanceof OperationCanceledException) {
            throw new CoreException(Status.CANCEL_STATUS);
        } else if (cause instanceof Error) {
            throw (Error) cause;
        } else if (cause instanceof RuntimeException) {
            throw (RuntimeException) cause;
        } else {
            throw new AssertionError(cause);
        }
    } catch (InterruptedException e) {
        throw new CoreException(Status.CANCEL_STATUS);
    }
}

From source file:com.centurylink.mdw.plugin.project.assembly.ProjectInflator.java

License:Apache License

public void inflateRemoteProject(final IRunnableContext container) {
    // get a project handle
    final IProject newProjectHandle = ResourcesPlugin.getWorkspace().getRoot()
            .getProject(workflowProject.getName());

    // get a project descriptor
    IWorkspace workspace = ResourcesPlugin.getWorkspace();
    final IProjectDescription description = workspace.newProjectDescription(newProjectHandle.getName());

    // create the new project operation
    IRunnableWithProgress op = new IRunnableWithProgress() {
        public void run(IProgressMonitor monitor) throws InvocationTargetException {
            CreateProjectOperation op = new CreateProjectOperation(description, "MDW Remote Project");
            try {
                PlatformUI.getWorkbench().getOperationSupport().getOperationHistory().execute(op, monitor,
                        WorkspaceUndoUtil.getUIInfoAdapter(shell));
            } catch (ExecutionException ex) {
                throw new InvocationTargetException(ex);
            }//  w w w .  jav  a 2 s  .  c o  m
        }
    };

    // run the new project creation operation
    try {
        container.run(true, true, op);
    } catch (Exception ex) {
        PluginMessages.uiError(shell, ex, "Create Remote Project", workflowProject);
    }
}