Java 类org.eclipse.core.runtime.IStatus 实例源码

项目:EclipseMinifyBuilder    文件:PrefsAccess.java   
/**
 * Associate one resource's properties with another resource.
 * 
 * @param fromPrefs the preferences to take the properties from
 * @param fromResource the resource to take the properties from
 * @param toPrefs the preferences to move the properties to
 * @param toResource the resource to associated with the properties
 * @throws BackingStoreException
 */
public static void moveResource(Preferences fromPrefs, IResource fromResource,
        Preferences toPrefs, IResource toResource) 
        throws CoreException {
    try {
        String[] keys = fromPrefs.keys();
        for (String key: keys) {
            if (key.endsWith("//" + fromResource.getProjectRelativePath().toPortableString())) {
                String resourcePreference = key.substring(0, key.indexOf('/'));
                toPrefs.put(preferenceKey(toResource, resourcePreference), fromPrefs.get(key, ""));
                fromPrefs.remove(key);
            }
        }
        fromPrefs.flush();
        toPrefs.flush();
    } catch (BackingStoreException e) {
        throw new CoreException(new Status(
                IStatus.ERROR, MinifyBuilder.BUILDER_ID, e.getMessage(), e));
    }
}
项目:n4js    文件:EclipseGracefulUIShutdownEnabler.java   
/**
 * Called to eagerly configure the logging-mechanism.
 */
public static void enableOnce() {
    if (logged)
        return;
    // workaround for shutdown-stack-traces due to non-initialized loggers.
    // @see https://bugs.eclipse.org/bugs/show_bug.cgi?id=460863
    ResourcesPlugin.getPlugin().getLog()
            .log(new Status(IStatus.OK, ResourcesPlugin.PI_RESOURCES,
                    "Place holder to init log-system. Loaded by " + EclipseGracefulUIShutdownEnabler.class.getName()
                            + " @see https://bugs.eclipse.org/bugs/show_bug.cgi?id=460863 "));

    // without actual logging the following line is enough (but restricted):
    // StatusHandlerRegistry.getDefault().getDefaultHandlerDescriptor();

    logged = true;
}
项目:n4js    文件:AbstractBuilderParticipantTest.java   
/** Tears down the external libraries. */
protected void tearDownExternalLibraries(boolean tearDownShippedCode) throws Exception {
    ((TypeDefinitionGitLocationProviderImpl) gitLocationProvider).setGitLocation(PUBLIC_DEFINITION_LOCATION);

    final URI nodeModulesLocation = locationProvider.getTargetPlatformNodeModulesLocation();
    externalLibraryPreferenceStore.remove(nodeModulesLocation);
    final IStatus result = externalLibraryPreferenceStore.save(new NullProgressMonitor());
    assertTrue("Error while saving external library preference changes.", result.isOK());

    if (tearDownShippedCode) {
        shippedCodeInitializeTestHelper.teardowneBuiltIns();
    }

    // cleanup leftovers in the file system
    File nodeModuleLocationFile = new File(nodeModulesLocation);
    assertTrue("Provided npm location does not exist.", nodeModuleLocationFile.exists());
    assertTrue("Provided npm location is not a folder.", nodeModuleLocationFile.isDirectory());
    FileDeleter.delete(nodeModuleLocationFile);
    assertFalse("Provided npm location should be deleted.", nodeModuleLocationFile.exists());

    waitForAutoBuild();

    super.tearDown();
}
项目:n4js    文件:N4jscBase.java   
private void validateBinaries() throws ExitCodeException {
    IStatus status = nodeJsBinaryProvider.get().validate();
    if (!status.isOK()) {
        System.out.println(status.getMessage());
        if (null != status.getException()) {
            dumpThrowable(status.getException());
        }
        throw new ExitCodeException(EXITCODE_CONFIGURATION_ERROR, status.getMessage(), status.getException());
    }
    if (null != targetPlatformFile) {
        status = npmBinaryProvider.get().validate();
        if (!status.isOK()) {
            System.out.println(status.getMessage());
            if (null != status.getException()) {
                dumpThrowable(status.getException());
            }
            throw new ExitCodeException(EXITCODE_CONFIGURATION_ERROR, status.getMessage(), status.getException());
        }
    }
}
项目:n4js    文件:AbstractN4JSPreferencePage.java   
/** copied from PropertyAndPreferencePage */
private static void applyToStatusLine(DialogPage page, IStatus status) {
    String message = status.getMessage();
    if (message != null && message.length() == 0) {
        message = null;
    }
    switch (status.getSeverity()) {
    case IStatus.OK:
        page.setMessage(message, IMessageProvider.NONE);
        page.setErrorMessage(null);
        break;
    case IStatus.WARNING:
        page.setMessage(message, IMessageProvider.WARNING);
        page.setErrorMessage(null);
        break;
    case IStatus.INFO:
        page.setMessage(message, IMessageProvider.INFORMATION);
        page.setErrorMessage(null);
        break;
    default:
        page.setMessage(null);
        page.setErrorMessage(message);
        break;
    }
}
项目:n4js    文件:ExternalLibraryPreferencePage.java   
@Override
public boolean performOk() {
    final MultiStatus multistatus = statusHelper
            .createMultiStatus("Status of importing target platform.");
    try {
        new ProgressMonitorDialog(getShell()).run(true, false, monitor -> {
            final IStatus status = store.save(monitor);
            if (!status.isOK()) {
                setMessage(status.getMessage(), ERROR);
                multistatus.merge(status);
            } else {
                updateInput(viewer, store.getLocations());
            }
        });
    } catch (final InvocationTargetException | InterruptedException exc) {
        multistatus.merge(statusHelper.createError("Error while building external libraries.", exc));
    }

    if (multistatus.isOK())
        return super.performOk();
    else
        return false;
}
项目:neoscada    文件:PortValidator.java   
@Override
public IStatus validate ( final Object value )
{
    if ( ! ( value instanceof Number ) )
    {
        return new Status ( IStatus.ERROR, Activator.PLUGIN_ID, "Value must be a number" );
    }

    final int port = ( (Number)value ).intValue ();

    if ( port < MIN || port > MAX )
    {
        return new Status ( IStatus.ERROR, Activator.PLUGIN_ID, String.format ( "Port number must be between %s and %s (inclusive)", MIN, MAX ) );
    }

    if ( port < 1024 && isUnix () )
    {
        return new Status ( IStatus.WARNING, Activator.PLUGIN_ID, String.format ( "Port numbers below 1024 are reserved for privileged users (root) and may not be available for use." ) );
    }

    return Status.OK_STATUS;
}
项目:pgcodekeeper    文件:ApplicationStandalone.java   
@Override
public Object start(IApplicationContext context) {
    try {
        return Main.main(Platform.getApplicationArgs()) ? EXIT_OK : EXIT_ERROR;
    }   catch (Exception e) {
        e.printStackTrace(System.err);
        Status error = new Status(IStatus.ERROR, ApgdiffConsts.APGDIFF_PLUGIN_ID,
                "pgCodeKeeper error", e);
        Platform.getLog(Activator.getContext().getBundle()).log(error);
        return EXIT_ERROR;
    } finally {
        // only needed when org.apache.felix.gogo.shell bundle is present
        /*try {
            // see bug #514338
            Thread.sleep(110);
        } catch (InterruptedException ex) {
            // no action
        }*/
    }
}
项目:gw4e.project    文件:GraphWalkerContextManager.java   
public static void generateOffline(final IResource resource, IPackageFragment pkg, String classfile , BuildPolicy[]  generators, int timeout, IWorkbenchWindow aww) {
    Job job = new Job("GW4E Offline Generation Source Job") {
        @Override
        public IStatus run(IProgressMonitor monitor) {
            try {
                if (resource instanceof IFile) {
                    SubMonitor subMonitor = SubMonitor.convert(monitor, 120);
                    IFile file = (IFile) resource;
                    if (PreferenceManager.isGraphModelFile(file)) {
                        AbstractPostConversion converter = getOfflineConversion(file,pkg,classfile,generators,timeout);
                        ConversionRunnable runnable = converter.createConversionRunnable(aww);
                        subMonitor.subTask("Processing converter ");
                        SubMonitor child = subMonitor.split(1);
                        runnable.run(child);
                    }                       
                }
            } catch (Exception e) {
                e.printStackTrace();
                ResourceManager.logException(e);
            }
            return Status.OK_STATUS;
        }
    };
    job.setUser(true);
    job.schedule();
}
项目:neoscada    文件:PreviewPage.java   
@Override
public void setVisible ( final boolean visible )
{
    super.setVisible ( visible );
    if ( visible )
    {
        try
        {
            getContainer ().run ( false, false, new IRunnableWithProgress () {

                @Override
                public void run ( final IProgressMonitor monitor ) throws InvocationTargetException, InterruptedException
                {
                    setMergeResult ( PreviewPage.this.mergeController.merge ( wrap ( monitor ) ) );
                }
            } );
        }
        catch ( final Exception e )
        {
            final Status status = new Status ( IStatus.ERROR, Activator.PLUGIN_ID, Messages.PreviewPage_StatusErrorFailedToMerge, e );
            StatusManager.getManager ().handle ( status );
            ErrorDialog.openError ( getShell (), Messages.PreviewPage_TitleErrorFailedToMerge, Messages.PreviewPage_MessageErrorFailedToMerge, status );
        }
    }
}
项目:neoscada    文件:ConnectionManager.java   
private void showError ( final IStatus status )
{
    if ( !status.matches ( IStatus.ERROR ) )
    {
        return;
    }

    final Display display = PlatformUI.getWorkbench ().getDisplay ();
    if ( !display.isDisposed () )
    {
        display.asyncExec ( new Runnable () {

            @Override
            public void run ()
            {
                if ( !display.isDisposed () )
                {
                    ErrorDialog.openError ( PlatformUI.getWorkbench ().getActiveWorkbenchWindow ().getShell (), "Connection error", "Connection failed", status, IStatus.ERROR );
                }
            }
        } );
    }
}
项目:n4js    文件:WorkingSetManagerImpl.java   
@Override
public IStatus saveState(final IProgressMonitor monitor) {

    final Preferences node = getPreferences();

    // Save ordered labels.
    node.put(ORDERED_IDS_KEY, Joiner.on(SEPARATOR).join(orderedWorkingSetIds));

    // Save visible labels.
    node.put(VISIBLE_IDS_KEY, Joiner.on(SEPARATOR).join(visibleWorkingSetIds));

    try {
        node.flush();
    } catch (final BackingStoreException e) {
        final String message = "Error occurred while saving state to preference store.";
        LOGGER.error(message, e);
        return statusHelper.createError(message, e);
    }

    return statusHelper.OK();
}
项目:neoscada    文件:Activator.java   
private void fillFactories ( final Collection<LoginFactory> factories, final IConfigurationElement ele )
{
    for ( final IConfigurationElement child : ele.getChildren ( "factory" ) ) //$NON-NLS-1$
    {
        try
        {
            final LoginFactory factory = (LoginFactory)child.createExecutableExtension ( "class" );//$NON-NLS-1$
            if ( factory != null )
            {
                factories.add ( factory );
            }
        }
        catch ( final Exception e )
        {
            getLog ().log ( new Status ( IStatus.WARNING, PLUGIN_ID, Messages.Activator_ErrorParse, e ) );
        }
    }
}
项目:n4js    文件:WorkingSetManagerBrokerImpl.java   
private IStatus restoreState() {

        final Preferences node = getPreferences();
        // Top level element.
        workingSetTopLevel.set(node.getBoolean(IS_WORKINGSET_TOP_LEVEL_KEY, false));

        // Active working set manager.
        final String value = node.get(ACTIVE_MANAGER_KEY, "");
        WorkingSetManager workingSetManager = contributions.get().get(value);
        if (workingSetManager == null) {
            if (!contributions.get().isEmpty()) {
                workingSetManager = contributions.get().values().iterator().next();
            }
        }
        if (workingSetManager != null) {
            setActiveManager(workingSetManager);
        }

        return Status.OK_STATUS;
    }
项目:Equella    文件:JPFProjectNature.java   
@Override
public void configure() throws CoreException
{
    IProjectDescription description = project.getDescription();
    JPFManifestBuilder.addBuilderToProject(description);
    project.setDescription(description, null);
    JPFClasspathContainer.addToProject(JavaCore.create(project));
    new Job("Check JPF Manifest")
    {
        @Override
        protected IStatus run(IProgressMonitor monitor)
        {
            try
            {
                project.build(IncrementalProjectBuilder.FULL_BUILD, JPFManifestBuilder.BUILDER_ID, null, monitor);
            }
            catch( CoreException e )
            {
                JPFClasspathLog.logError(e);
            }
            return Status.OK_STATUS;
        }
    }.schedule();
}
项目:neoscada    文件:ExportEventsWizard.java   
@Override
public boolean performFinish ()
{
    try
    {
        getContainer ().run ( true, true, new IRunnableWithProgress () {

            public void run ( final IProgressMonitor monitor ) throws InvocationTargetException, InterruptedException
            {
                doExport ( monitor );
            }
        } );
        return true;
    }
    catch ( final Exception e )
    {
        StatusManager.getManager ().handle ( new Status ( IStatus.ERROR, Activator.PLUGIN_ID, Messages.ExportWizard_ErrorMessage, e ) );
        return false;
    }
}
项目:Equella    文件:WorkspaceModelManager.java   
@Override
protected IStatus run(IProgressMonitor monitor)
{
    boolean more = false;
    do
    {
        IModel[] changedModels = null;
        synchronized( models )
        {
            changedModels = models.toArray(new IModel[models.size()]);
            models.clear();
        }
        fireModelProviderEvent(new ModelProviderEvent(this, IModelProviderEvent.MODELS_CHANGED, new IModel[0],
            new IModel[0], changedModels));
        synchronized( models )
        {
            more = !models.isEmpty();
        }
    }
    while( more );
    return Status.OK_STATUS;
}
项目:scanning    文件:StatusQueueView.java   
protected void togglePausedConsumer(IAction pauseConsumer) {

        // The button can get out of sync if two clients are used.
        final boolean currentState = queueConnection.isQueuePaused(getSubmissionQueueName());
        try {
            pauseConsumer.setChecked(!currentState); // We are toggling it.

            IPublisher<PauseBean> pauser = service.createPublisher(getUri(), IEventService.CMD_TOPIC);
            pauser.setStatusSetName(IEventService.CMD_SET); // The set that other clients may check
            pauser.setStatusSetAddRequired(true);

            PauseBean pbean = new PauseBean();
            pbean.setQueueName(getSubmissionQueueName()); // The queue we are pausing
            pbean.setPause(pauseConsumer.isChecked());
            pauser.broadcast(pbean);

        } catch (Exception e) {
            ErrorDialog.openError(getViewSite().getShell(), "Cannot pause queue "+getSubmissionQueueName(), "Cannot pause queue "+getSubmissionQueueName()+"\n\nPlease contact your support representative.",
                    new Status(IStatus.ERROR, Activator.PLUGIN_ID, e.getMessage()));
        }
        pauseConsumer.setChecked(queueConnection.isQueuePaused(getSubmissionQueueName()));
    }
项目:gemoc-studio-modeldebugging    文件:AbstractGemocAnimatorServices.java   
/**Refreshes given {@link DRepresentation} in the given {@link TransactionalEditingDomain}.
 * @param transactionalEditingDomain the {@link TransactionalEditingDomain}
 * @param representations the {@link List} of {@link DRepresentation} to refresh
 */
public void refreshRepresentations(
        final TransactionalEditingDomain transactionalEditingDomain,
        final List<DRepresentation> representations) {
    // TODO prevent the editors from getting dirty
    if (representations.size() != 0) {
        final RefreshRepresentationsCommand refresh = new RefreshRepresentationsCommand(
                transactionalEditingDomain,
                new NullProgressMonitor(),
                representations);
        try {
            CommandExecution.execute(transactionalEditingDomain, refresh);
        } catch (Exception e){
            String repString = representations.stream().map(r -> r.getName()).collect(Collectors.joining(", "));
            Activator.getDefault().getLog().log(new Status(IStatus.WARNING, Activator.PLUGIN_ID, "Failed to refresh Sirius representation(s)["+repString+"], we hope to be able to do it later", e));
        }

    }
}
项目:n4js    文件:NpmManager.java   
private IStatus cleanCacheInternal(final IProgressMonitor monitor) {
    checkNotNull(monitor, "monitor");

    final SubMonitor subMonitor = SubMonitor.convert(monitor, 1);
    try {

        subMonitor.setTaskName("Cleaning npm cache");

        performGitPull(subMonitor.newChild(1, SubMonitor.SUPPRESS_ALL_LABELS));
        final File targetInstallLocation = new File(locationProvider.getTargetPlatformInstallLocation());
        return clean(targetInstallLocation);

    } finally {
        subMonitor.done();
    }
}
项目:VerveineC-Cpp    文件:PluginApplication.java   
@Override
public Object start(IApplicationContext ctxt) throws Exception {
    Activator.log(IStatus.INFO, "Starting VerveineC");

    String[] appArgs = (String[])ctxt.getArguments().get(IApplicationContext.APPLICATION_ARGS);

    VerveineCParser verveine = new VerveineCParser();

    verveine.setOptions(appArgs);
    if (verveine.parse()) {
        verveine.emitMSE();
    }
    else {
        Activator.log(IStatus.ERROR, "Error in model creation, aborting");
    }
    return null;
}
项目:AgentWorkbench    文件:P2OperationsHandler.java   
/**
 * Installs an {@link IInstallableUnit} from a p2 repository.
 * 
 * @param installableUnitID the ID of the IU to be installed
 * @param repositoryURI the repository ID
 * @return true if successful
 */
public boolean installIU(String installableUnitID, URI repositoryURI) {

    // --- Make sure the repository is known and enabled ---------
    this.addRepository(repositoryURI);

    // --- Query the repository for the IU of interest -----------
    IQueryResult<IInstallableUnit> queryResult = this.queryRepositoryForInstallableUnit(repositoryURI, installableUnitID);

    if (queryResult.isEmpty() == false) {

        // --- If found, trigger an InstallOperation ---------------
        InstallOperation installOperation = new InstallOperation(this.getProvisioningSession(), queryResult.toSet());
        IStatus result = this.performOperation(installOperation);
        return result.isOK();

    } else {

        // --- If not, print an error message -----------------------
        String errorMessage = "Installable unit " + installableUnitID + " could not be found in the repositoty " + repositoryURI;
        System.err.println(errorMessage);
        return false;

    }

}
项目:neoscada    文件:AbstractStepGeneratorPage.java   
private void tick ()
{
    if ( !this.running )
    {
        return;
    }

    final long now = System.currentTimeMillis ();
    try
    {
        if ( now - this.lastTimestamp > this.period )
        {
            this.lastTimestamp = now;
            step ();
        }
    }
    catch ( final Throwable e )
    {
        Activator.getDefault ().getLog ().log ( new Status ( IStatus.ERROR, Activator.PLUGIN_ID, "Failed to step", e ) ); //$NON-NLS-1$
    }
    finally
    {
        setTimer ();
    }

}
项目:Hydrograph    文件:DebugDataViewer.java   
public void submitRecordCountJob() {
    Job job = new Job(Messages.FETCHING_TOTAL_NUMBER_OF_RECORDS) {
        @Override
        protected IStatus run(IProgressMonitor monitor) {

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

                @Override
                public void run() {
                    statusManager.getStatusLineManager().getProgressMonitor().beginTask(Messages.FETCHING_TOTAL_NUMBER_OF_RECORDS, IProgressMonitor.UNKNOWN);
                }
            });

            final StatusMessage status = dataViewerAdapter.fetchRowCount();

            Display.getDefault().asyncExec(new Runnable() {
                @Override
                public void run() {
                    statusManager.getStatusLineManager().getProgressMonitor().done();
                    statusManager.setStatus(status);
                    statusManager.enableJumpPagePanel(true);
                    actionFactory.getAction(ResetSortAction.class.getName()).setEnabled(false);
                    actionFactory.getAction(ClearFilterAction.class.getName()).setEnabled(false);
                }
            });
            return Status.OK_STATUS;
        }
    };

    job.schedule();
}
项目:incubator-netbeans    文件:TestUtil.java   
public static void handleException(Exception exception) throws Throwable {
        if (exception instanceof CoreException) {
            CoreException e = (CoreException) exception;
            IStatus status = e.getStatus();
            if (status instanceof RepositoryStatus) {
                RepositoryStatus rs = (RepositoryStatus) status;
                String html = rs.getHtmlMessage();
                if(html != null && !html.trim().equals("")) {
//                    HtmlBrowser.URLDisplayer displayer = HtmlBrowser.URLDisplayer.getDefault ();
//                    if (displayer != null) {
//                        displayer.showURL (url);
//                    } else {
//                        //LOG.info("No URLDisplayer found.");
//                    }

                    final HtmlPanel p = new HtmlPanel();
                    p.setHtml(html);
                    BugzillaUtil.show(p, "html", "ok");
                }
                throw new Exception(rs.getHtmlMessage());
            }
            if (e.getStatus().getException() != null) {
                throw e.getStatus().getException();
            }
            if (e.getCause() != null) {
                throw e.getCause();
            }
            throw e;
        }
        exception.printStackTrace();
        throw exception;
    }
项目:n4js    文件:N4SchemeURIBasedStorage.java   
@Override
public InputStream getContents() throws CoreException {
    URIHandler handler = schemeHelper.createURIHandler(URIConverter.INSTANCE);
    try {
        return handler.createInputStream(getURI(), Collections.emptyMap());
    } catch (IOException e) {
        throw new CoreException(new Status(IStatus.ERROR, "org.eclipse.n4js.ts.ui", "Cannot load "
                + getFullPath(), e));
    }
}
项目:neoscada    文件:FactoryInformationBean.java   
protected void setError ( final Exception e )
{
    Activator.getDefault ().getLog ().log ( new Status ( IStatus.ERROR, Activator.PLUGIN_ID, "Failed to load factory", e ) );

    setFactoryInformation ( null );
    setState ( State.ERROR );
}
项目:CharmMylynConnector    文件:CharmTaskAttachmentHandler.java   
@Override
public void postContent(@NonNull TaskRepository repository, @NonNull ITask task,
        @NonNull AbstractTaskAttachmentSource source, @Nullable String comment,
        @Nullable TaskAttribute attachmentAttribute, @Nullable IProgressMonitor monitor) throws CoreException {

    monitor.beginTask("Uploading attachment", 1);

    CharmClient client = connector.getClient(repository);

    try {
        byte attachment[] = readData(source, monitor);

        String filename = source.getName();
        String description = source.getDescription();

        if (CONTEXT_DESCRIPTION.equals(source.getDescription()))
            filename = CONTEXT_DESCRIPTION + "-" + dateFormat.format(new Date()) + ".zip";

        else if (attachmentAttribute != null) {
            TaskAttachmentMapper mapper = TaskAttachmentMapper.createFrom(attachmentAttribute);
            if (mapper.getFileName() != null)
                filename = mapper.getFileName();
            if (mapper.getDescription() != null)
                description = mapper.getDescription();
        }

        client.putAttachmentData(task, filename, source.getContentType(), description, attachment, monitor);
        Policy.advance(monitor, 1);

    } catch (IOException | CharmHttpException e) {
        throw new CoreException(new Status(IStatus.ERROR, CharmCorePlugin.PLUGIN_ID,
                NLS.bind("Uploading attachment failed: {0}", e.getMessage(), e)));
    } finally {
        monitor.done();
    }

}
项目:gemoc-studio    文件:EclipseMessagingSystem.java   
/**
 * This method dispatches the messages between the console and error log view
 * DevError and DevWarning go in both
 * UserError and UserWarning go only in the colsole
 */
@Override
public void log(Kind msgKind, String message, String messageGroup, Throwable throwable) {

    // some error message should go to the eclipse error view
    switch (msgKind) {
    case DevWARNING:
        if(messageGroup ==  null || !messageGroup.isEmpty())
            Activator.getDefault().getLog().log(new Status(IStatus.WARNING, messageGroup, IStatus.WARNING, message != null ? message : "<null>",throwable));
        break;
    case DevERROR:
        if(messageGroup ==  null || !messageGroup.isEmpty())
            Activator.getDefault().getLog().log(new Status(IStatus.ERROR, messageGroup, IStatus.ERROR, message != null ? message : "<null>",throwable));
        break;
    default:
        break;
    }

    if(ConsoleLogLevel.isLevelEnoughToLog(ConsoleLogLevel.kind2Level(msgKind), getConsoleLogLevel())){
        String stackTrace = "";
        if(throwable != null){
            StringWriter sw = new StringWriter();
            throwable.printStackTrace(new PrintWriter(sw));
            stackTrace = "\n"+sw.toString();
        }
        getConsoleIO().print(getConsoleMessageFor(msgKind,message+stackTrace));
    }
}
项目:pgcodekeeper    文件:UsageReporter.java   
@Override
protected IStatus run(IProgressMonitor monitor) {
    if (monitor.isCanceled()) {
        return Status.CANCEL_STATUS;
    }
    monitor.beginTask(Messages.UsageReport_Querying_Enablement, 2);

    if (monitor.isCanceled()) {
        return Status.CANCEL_STATUS;
    }
    monitor.worked(1);
    try {
        lockToAskUser.lock();

        if (mainPrefs.getBoolean(USAGE_REPORT_PREF.ASK_USER_USAGEREPORT_ID)) {
            if (monitor.isCanceled()) {
                return Status.CANCEL_STATUS;
            }
            askUser();
        }
    } finally {
        lockToAskUser.unlock();
    }
    report();
    monitor.worked(2);
    monitor.done();

    return Status.OK_STATUS;
}
项目:incubator-netbeans    文件:SubmitTaskCommand.java   
@Override
public void execute() throws CoreException, IOException, MalformedURLException {

    LogUtils.logBugtrackingUsage(repositoryConnector.getConnectorKind(), "ISSUE_EDIT");

    MylynSubmitTaskJob job = new MylynSubmitTaskJob(taskDataManager, repositoryConnector, taskRepository,
            task, taskData, changedOldAttributes);
    if (submitJobListener != null) {
        job.addSubmitJobListener(submitJobListener);
    }

    Logger log = Logger.getLogger(this.getClass().getName());
    if(log.isLoggable(Level.FINE)) {
        log.log(
            Level.FINE, 
            "executing SubmitJobCommand for task with id {0}:{1} ", //NOI18N
            new Object[] { task.getTaskId(), taskRepository.getUrl() });
    }

    job.startJob(monitor);
    IStatus status = job.getStatus();
    rr = job.getResponse();
    submittedTask = Accessor.getInstance().toNbTask(job.getTask());
    if (status != null && status != Status.OK_STATUS) {
        log.log(Level.INFO, "Command failed with status: {0}", status); //NOI18N
        if (status.getException() instanceof CoreException) {
            throw (CoreException) status.getException();
        } else {
            throw new CoreException(status);
        }
    }
}
项目:Hydrograph    文件:DataViewerListeners.java   
/**
 * 
 * Attach next page listener
 * 
 * @param button
 */
public void attachNextPageButtonListener(Button button) {
    button.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(final SelectionEvent e) {
            statusManager.setStatus(new StatusMessage(StatusConstants.PROGRESS, Messages.FETCHING_NEXT_PAGE));
            statusManager.setAllWindowControlsEnabled(false);

            Job job = new Job(Messages.FETCHING_NEXT_PAGE) {
                @Override
                protected IStatus run(IProgressMonitor monitor) {
                    final StatusMessage status = dataViewerAdapter.next();
                    dataViewLoader.updateDataViewLists();
                    Display.getDefault().asyncExec(new Runnable() {
                        @Override
                        public void run() {
                            refreshDataViewerWindow(status);
                            statusManager.clearJumpToPageText();
                            DataViewerUtility.INSTANCE.resetSort(debugDataViewer);
                            debugDataViewer.redrawTableCursor();
                        }
                    });
                    return Status.OK_STATUS;
                }
            };

            job.schedule();
        }
    });
}
项目:incubator-netbeans    文件:SimpleQueryCommand.java   
@Override
public void execute () throws CoreException {
    final Logger log = Logger.getLogger(this.getClass().getName());
    if (log.isLoggable(Level.FINE)) {
        Map<String, String> attrs = query.getAttributes();
        log.log(
                Level.FINE,
                "executing SimpleQueryCommand for query {0} on repository {1} with url \n\t{2} and parameters \n\t{3}", // NOI18N
                new Object[]{query.getSummary(), taskRepository.getUrl(), query.getUrl(), attrs != null ? attrs : null});
    }
    TaskDataCollector collector = new TaskDataCollector() {
        @Override
        public void accept (TaskData taskData) {
            try {
                Accessor acc = Accessor.getInstance();
                NbTask task = acc.getOrCreateTask(taskRepository, taskData.getTaskId(), true);
                taskDataManager.putUpdatedTaskData(acc.getDelegate(task), taskData, true);
                tasks.add(task);
            } catch (CoreException ex) {
                log.log(Level.INFO, "Cannot save task data " + taskData.getTaskId(), ex);
            }
        }
    };
    status = repositoryConnector.performQuery(taskRepository, query, collector, new SynchronizationSession(), monitor);
    if (status != null && status.getSeverity() == IStatus.ERROR) {
        if (status.getException() instanceof CoreException) {
            throw (CoreException) status.getException();
        } else {
            throw new CoreException(status);
        }
    }
}
项目:gemoc-studio-modeldebugging    文件:Activator.java   
public void start(BundleContext context) throws Exception {
    try {
        Class.forName("javafx.embed.swt.FXCanvas");
        super.start(context);
        plugin = this;
    } catch (ClassNotFoundException e) {
        ErrorDialog.openError(null,"State Graph Unavailable", "Please install JavaFX or use the Oracle JRE",
                new Status(IStatus.ERROR,PLUGIN_ID,"JavaFX is needed for the timeline to work"));
    }
}
项目:Hydrograph    文件:ExternalSchemaFileSelectionDialog.java   
public IStatus validate(Object[] selection) {
    if(selection.length == 1 && selection[0] instanceof IFile)
    {
        ((Text)eltDefaultText.getSWTWidgetControl()).setText(((IFile) selection[0]).getName());
    }
    if(extensions.length!=0 && (Extensions.SCHEMA.toString().equalsIgnoreCase(extensions[0])  || Extensions.XML.toString().equalsIgnoreCase(extensions[0]))) {
     if(selection.length == 1 && selection[0] instanceof IFolder)
     {
         return OK;
     }
    }

    return selection.length == 1 && selection[0] instanceof IFile
            && checkExtension(((IFile) selection[0]).getFileExtension()) ? OK : ERROR;
}
项目:visuflow-plugin    文件:JimpleBreakpointManager.java   
private void loadBreakpoints(IResource project) {
    try {
        IMarker[] markers = project.findMarkers(IBreakpoint.BREAKPOINT_MARKER, true, IResource.DEPTH_INFINITE);
        List<IMarker> methodBreakpoints = filterJavaMethodBreakpoints(markers);
        List<IMarker> jimpleChildBreakpoints = filterJimpleChildBreakpoints(methodBreakpoints);
        for (IMarker marker : jimpleChildBreakpoints) {
            String unitFqn = (String) marker.getAttribute("Jimple.unit.fqn");
            WorkspaceJob createBreakpoint = new WorkspaceJob("Create Jimple breakpoint") {
                @Override
                public IStatus runInWorkspace(IProgressMonitor monitor) throws CoreException {
                    JimpleBreakpoint jimpleBreakpoint = getJimpleBreakpoint(unitFqn);
                    if(jimpleBreakpoint == null) {
                        IMarker jimpleMarker = createJimpleMarker(marker);
                        jimpleBreakpoint = createBreakpointWithoutJavaBreakpoints(jimpleMarker);
                        addBreakpoint(jimpleBreakpoint);
                    }

                    IBreakpoint javaBreakpoint = DebugPlugin.getDefault().getBreakpointManager().getBreakpoint(marker);
                    jimpleBreakpoint.addJavaBreakpoint(javaBreakpoint);
                    return Status.OK_STATUS;
                }
            };
            createBreakpoint.schedule();
        }
    } catch (CoreException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
项目:n4js    文件:AbstractExportOperation.java   
/**
 * Returns the status of the operation. If there were any errors, the result is a status object containing
 * individual status objects for each error. If there were no errors, the result is a status object with error code
 * <code>OK</code>.
 *
 * @return the status
 */
public IStatus getStatus() {
    IStatus[] errors = new IStatus[errorTable.size()];
    errorTable.toArray(errors);
    return new MultiStatus(
            "org.eclipse.n4js.ui",
            IStatus.OK,
            errors,
            N4ExportMessages.FileSystemExportOperation_problemsExporting,
            null);
}
项目:gw4e.project    文件:BuildPoliciesCache.java   
/**
 * @param graphFile
 * @throws CoreException
 * @throws IOException
 * @throws InterruptedException
 */
public void update(List<BuildPolicy> policies) throws CoreException, IOException, InterruptedException {
    Job job = new WorkspaceJob("Updating cache") {
        public IStatus runInWorkspace(IProgressMonitor monitor) throws CoreException {
            try {
                IFile fileCache = getCache();
                Properties p = ResourceManager.loadIFileAsProperties(fileCache,
                        getFileCacheName(resource.getProject().getName()));
                String serialized = serialize(policies);
                if (serialized == null) {
                    log("BuildPoliciesCache.update " + fileCache + " failed to updated for resource " + resource
                            + " " + policies.toString());
                    return Status.OK_STATUS;
                }
                p.put(resource.getName(), System.currentTimeMillis() + ":" + serialized);
                log("BuildPoliciesCache.update " + fileCache + " updated for resource " + resource + " "
                        + p.toString());
                save(p, monitor);
                return Status.OK_STATUS;
            } catch (Exception e) {
                ResourceManager.logException(e);
                return Status.CANCEL_STATUS;
            }
        }
    };
    job.setRule(resource.getProject());
    job.setUser(true);
    job.schedule();
}
项目:CharmMylynConnector    文件:CharmRepositoryConnector.java   
@Override
public @NonNull IStatus performQuery(@NonNull TaskRepository repository, @NonNull IRepositoryQuery query,
        @NonNull TaskDataCollector collector, @Nullable ISynchronizationSession session,
        @NonNull IProgressMonitor monitor) {

    try {

        List<CharmQueryResult> charmTasks = getClient(repository).queryTasks(monitor, query).getQueryResults();
        SubMonitor subMonitor = SubMonitor.convert(monitor, charmTasks.size());

        for (CharmQueryResult charmTask : charmTasks) {
            TaskData taskData = this.taskDataHandler.parseQueryResults(repository, charmTask, monitor);
            taskData.setPartial(true);
            collector.accept(taskData);
            subMonitor.split(1);
        }

    } catch (CharmException | CoreException e) {
        return new Status(IStatus.ERROR, CharmCorePlugin.PLUGIN_ID, NLS.bind("Query failed: ''{0}''", e.getMessage()),
                e);
    } finally {
        monitor.done();
    }

    return Status.OK_STATUS;

}
项目:n4js    文件:ProcessExecutionCommandStatus.java   
/**
 * Executes command given by the supplier and returns {@link IStatus} of the execution Provided message will be used
 * to create error status if command execution fails.
 */
public IStatus execute(Supplier<ProcessExecutionCommand> commandSupplier, final String msg) {

    final ProcessResult per = commandSupplier.get().execute();

    if (per.isOK())
        return OK_STATUS;

    final Throwable cause = per.toThrowable(msg);
    if (null != cause)
        return statusHelper.createError(cause.getMessage(), cause);

    return statusHelper.createError(per.toString(), cause);
}