Exemplo n.º 1
0
  public void runAsUserJob(String name, final Object jobFamiliy) {
    Job buildJob =
        new Job(name) {
          /* (non-Javadoc)
           * @see org.eclipse.core.runtime.jobs.Job#run(org.eclipse.core.runtime.IProgressMonitor)
           */
          protected IStatus run(IProgressMonitor monitor) {
            try {
              WorkbenchRunnableAdapter.this.run(monitor);
            } catch (InvocationTargetException e) {
              Throwable cause = e.getCause();
              if (cause instanceof CoreException) {
                return ((CoreException) cause).getStatus();
              } else {
                return RubyUIStatus.createError(IStatus.ERROR, cause);
              }
            } catch (InterruptedException e) {
              return Status.CANCEL_STATUS;
            } finally {
              monitor.done();
            }
            return Status.OK_STATUS;
          }

          public boolean belongsTo(Object family) {
            return jobFamiliy == family;
          }
        };
    buildJob.setRule(fRule);
    buildJob.setUser(true);
    buildJob.schedule();

    // TODO: should block until user pressed 'to background'
  }
        @Override
        public void notifyChanged(final Notification msg) {
          switch (msg.getFeatureID(SdrPackage.class)) {
            case SdrPackage.SDR_ROOT__LOAD_STATUS:
              // The value is the changed load status which will go to null during loading
              // once loading is finished the status will change to reflect that of the SDRROOT.
              if (msg.getNewValue() != null) {
                Job refreshExternalSettingProviderJob =
                    new Job("Refresh External Settings Providers") {

                      @Override
                      protected IStatus run(IProgressMonitor monitor) {
                        CoreModel.getDefault()
                            .getProjectDescriptionManager()
                            .updateExternalSettingsProviders(
                                new String[] {ExternalSettingProvider.ID}, monitor);
                        return Status.OK_STATUS;
                      }
                    };
                refreshExternalSettingProviderJob.setSystem(true); // hide from progress monitor
                refreshExternalSettingProviderJob.setUser(false);
                refreshExternalSettingProviderJob.schedule(1000);
              }
              break;
            default:
              break;
          }
        }
Exemplo n.º 3
0
  /** {@inheritDoc} */
  @Override
  protected void runModelAction() throws Exception {
    if (!MessageDialog.openConfirm(shell, Messages.RemoveScan, Messages.RemoveSelectedScan)) return;

    // Job because removal of many scans and data in log can be slow
    final ScanClient client = model.getScanClient();
    final Job job =
        new Job(Messages.RemoveScan) {
          @Override
          protected IStatus run(final IProgressMonitor monitor) {
            try {
              for (ScanInfo info : infos) client.removeScan(info.getId());
            } catch (final Exception ex) {
              shell
                  .getDisplay()
                  .asyncExec(
                      new Runnable() {
                        @Override
                        public void run() {
                          ExceptionDetailsErrorDialog.openError(shell, Messages.Error, ex);
                        }
                      });
            }
            return Status.OK_STATUS;
          }
        };
    job.setUser(true);
    job.schedule();
  }
Exemplo n.º 4
0
  public void runThisJob(final JobWithProgress theJob) {
    final Job swtJob =
        new Job("Prepare multiple scenarios") {
          @Override
          protected IStatus run(final IProgressMonitor monitor) {
            try {
              // provide a wrapped progress monitpr
              final ASSETProgressMonitor pMon = new WrappedProgressMonitor(monitor);

              // and run the job
              theJob.run(pMon);
            } catch (final Exception e) {
              CorePlugin.logError(IStatus.ERROR, "Failed in scenario generation", e);
            }

            return Status.OK_STATUS;
          }
        };

    swtJob.addJobChangeListener(
        new JobChangeAdapter() {
          @Override
          public void done(final IJobChangeEvent event) {
            if (event.getResult().isOK()) System.out.println("Job completed successfully");
            else System.err.println("Job did not complete successfully");
          }
        });
    swtJob.setUser(true);
    swtJob.schedule(); // start as soon as possible
  }
Exemplo n.º 5
0
 public void run() {
   Job job = createJob();
   job.setUser(true);
   job.setProperty(
       IProgressConstants.ICON_PROPERTY, PDEPluginImages.DESC_PSEARCH_OBJ.createImage());
   job.schedule();
 }
  /* (non-Javadoc)
   * @see org.eclipse.ui.dialogs.SelectionStatusDialog#computeResult()
   */
  protected void computeResult() {
    MavenProject targetPOM = getTargetPOM();
    IMavenProjectFacade targetFacade =
        MavenPlugin.getMavenProjectRegistry()
            .getMavenProject(
                targetPOM.getGroupId(), targetPOM.getArtifactId(), targetPOM.getVersion());
    MavenProject currentPOM = projectHierarchy.getFirst();
    IMavenProjectFacade currentFacade =
        MavenPlugin.getMavenProjectRegistry()
            .getMavenProject(
                currentPOM.getGroupId(), currentPOM.getArtifactId(), currentPOM.getVersion());

    if (targetFacade == null || currentFacade == null) {
      return;
    }
    final boolean same = targetPOM.equals(currentPOM);

    final LinkedList<Dependency> modelDeps = getDependenciesList();

    /*
     * 1) Remove version values from the dependencies from the current POM
     * 2) Add dependencies to dependencyManagement of targetPOM
     */

    // First we remove the version from the original dependency
    final IFile current = currentFacade.getPom();
    final IFile target = targetFacade.getPom();
    Job perform =
        new Job("Updating POM file(s)") {
          @Override
          protected IStatus run(IProgressMonitor monitor) {
            try {
              if (same) {
                performOnDOMDocument(
                    new OperationTuple(
                        current,
                        new CompoundOperation(
                            createManageOperation(modelDeps),
                            createRemoveVersionOperation(modelDeps))));
              } else {
                performOnDOMDocument(
                    new OperationTuple(target, createManageOperation(modelDeps)),
                    new OperationTuple(current, createRemoveVersionOperation(modelDeps)));
              }
            } catch (Exception e) {
              LOG.error("Error updating managed dependencies", e);
              return new Status(
                  IStatus.ERROR,
                  MavenEditorPlugin.PLUGIN_ID,
                  "Error updating managed dependencies",
                  e);
            }
            return Status.OK_STATUS;
          }
        };
    perform.setUser(false);
    perform.setSystem(true);
    perform.schedule();
  }
  /** Listens to a topic */
  private void createTopicListener(final URI uri) throws Exception {

    // Use job because connection might timeout.
    final Job topicJob =
        new Job("Create topic listener") {

          @Override
          protected IStatus run(IProgressMonitor monitor) {
            try {
              topicMonitor = service.createSubscriber(uri, getTopicName());
              topicMonitor.addListener(
                  new IBeanListener<StatusBean>() {
                    @Override
                    public void beanChangePerformed(BeanEvent<StatusBean> evt) {
                      final StatusBean bean = evt.getBean();
                      try {
                        mergeBean(bean);
                      } catch (Exception e) {
                        logger.error("Cannot merge changed bean!");
                      }
                    }
                  });

              adminMonitor = service.createSubscriber(uri, IEventService.ADMIN_MESSAGE_TOPIC);
              adminMonitor.addListener(
                  new IBeanListener<AdministratorMessage>() {
                    @Override
                    public void beanChangePerformed(BeanEvent<AdministratorMessage> evt) {
                      final AdministratorMessage bean = evt.getBean();
                      getSite()
                          .getShell()
                          .getDisplay()
                          .syncExec(
                              new Runnable() {
                                public void run() {
                                  MessageDialog.openError(
                                      getViewSite().getShell(), bean.getTitle(), bean.getMessage());

                                  viewer.refresh();
                                }
                              });
                    }
                  });

              return Status.OK_STATUS;

            } catch (Exception ne) {
              logger.error(
                  "Cannot listen to topic changes because command server is not there", ne);
              return Status.CANCEL_STATUS;
            }
          }
        };

    topicJob.setPriority(Job.INTERACTIVE);
    topicJob.setSystem(true);
    topicJob.setUser(false);
    topicJob.schedule();
  }
  public Object execute(ExecutionEvent event) throws ExecutionException {
    List<StashedCommitNode> nodes = getSelectedNodes(event);
    if (nodes.isEmpty()) return null;

    StashedCommitNode node = nodes.get(0);
    final Repository repo = node.getRepository();
    if (repo == null) return null;
    final int index = node.getIndex();
    if (index < 0) return null;
    final RevCommit commit = node.getObject();
    if (commit == null) return null;

    // Confirm deletion of selected tags
    final AtomicBoolean confirmed = new AtomicBoolean();
    final Shell shell = getActiveShell(event);
    shell
        .getDisplay()
        .syncExec(
            new Runnable() {

              public void run() {
                confirmed.set(
                    MessageDialog.openConfirm(
                        shell,
                        UIText.StashDropCommand_confirmTitle,
                        MessageFormat.format(
                            UIText.StashDropCommand_confirmMessage, Integer.toString(index))));
              }
            });
    if (!confirmed.get()) return null;

    final StashDropOperation op = new StashDropOperation(repo, index);
    Job job =
        new Job(MessageFormat.format(UIText.StashDropCommand_jobTitle, commit.name())) {
          @Override
          protected IStatus run(IProgressMonitor monitor) {
            try {
              op.execute(monitor);
            } catch (CoreException e) {
              Activator.logError(
                  MessageFormat.format(UIText.StashDropCommand_dropFailed, commit.name()), e);
            }
            return Status.OK_STATUS;
          }

          @Override
          public boolean belongsTo(Object family) {
            if (JobFamilies.STASH.equals(family)) return true;
            return super.belongsTo(family);
          }
        };
    job.setUser(true);
    job.setRule(op.getSchedulingRule());
    job.schedule();
    return null;
  }
Exemplo n.º 9
0
  public Object execute(ExecutionEvent event) throws ExecutionException {
    final Shell activeShell = HandlerUtil.getActiveShell(event);
    ISelection currentSelection = HandlerUtil.getCurrentSelection(event);

    if (currentSelection instanceof IStructuredSelection) {
      IStructuredSelection selection = (IStructuredSelection) currentSelection;
      if (selection.isEmpty()) {
        return null;
      }

      Iterator<?> selectionIterator = selection.iterator();
      while (selectionIterator.hasNext()) {
        Object selectedElement = selectionIterator.next();
        IFile file = (IFile) Platform.getAdapterManager().getAdapter(selectedElement, IFile.class);
        if (file != null && "psf".equals(file.getLocation().getFileExtension())) { // $NON-NLS-1$
          final String fileName = file.getLocation().toString();

          Job job =
              new Job(String.format("Import %s", file.getName())) {

                @Override
                protected IStatus run(IProgressMonitor monitor) {
                  AbstractOperation operation =
                      new ImportProjectSetOperation(getName(), fileName, activeShell);

                  try {
                    final IStatus result =
                        OperationHistoryFactory.getOperationHistory()
                            .execute(operation, monitor, null);

                    if (monitor.isCanceled() || result.getSeverity() == IStatus.CANCEL) {
                      // TODO: Abort or Undo
                    }

                    return result;
                  } catch (ExecutionException ex) {
                    Activator.log.error(ex);
                    return new Status(
                        IStatus.ERROR,
                        Activator.PLUGIN_ID,
                        String.format("An error occurred when importing the PSF %s", fileName),
                        ex);
                  }
                }
              };

          job.setUser(true);
          job.schedule();

          job.setPriority(Job.LONG);
        }
      }
    }

    return null;
  }
Exemplo n.º 10
0
  public static void generate(ModelContext context, IFolder folder) {
    final ModelContext modelContext = context;
    final File targetFolder = new File(folder.getLocationURI());
    final List<Object> arguments = new ArrayList<Object>(1);

    final Job job =
        new Job("Generating model.") {
          @Override
          protected IStatus run(IProgressMonitor monitor) {
            arguments.add(modelContext.getContext().getGenModel());
            AbstractAcceleoGenerator generator = null;

            try {
              switch (modelContext.getType()) {
                case ModelAdmin:
                  generator =
                      new GenBEAdminModel(modelContext.getGenClass(), targetFolder, arguments);
                  break;
                case ModelForm:
                  generator =
                      new GenBEFormModel(modelContext.getGenClass(), targetFolder, arguments);
                  break;
                case ModelList:
                  generator =
                      new GenBEListModel(modelContext.getGenClass(), targetFolder, arguments);
                  break;
                case ModelItem:
                  generator =
                      new GenBEItemModel(modelContext.getGenClass(), targetFolder, arguments);
                  break;
                case Model:
                default:
                  generator = new GenFEModel(modelContext.getGenClass(), targetFolder, arguments);
                  break;
              }

              generator.doGenerate(BasicMonitor.toMonitor(monitor));
            } catch (IOException e) {
              return new Status(
                  Status.ERROR,
                  Activator.PLUGIN_ID,
                  "An exception occurred during the code generation! Please check the error view. "
                      + e.getMessage(),
                  e);
            }

            monitor.worked(1);
            return new Status(Status.OK, Activator.PLUGIN_ID, "Code successfully generated!");
          }
        };

    // enqueue the job
    job.setRule(ResourcesPlugin.getWorkspace().getRoot());
    job.setUser(true);
    job.schedule();
  }
Exemplo n.º 11
0
  private synchronized void regenerate() {
    generateButton.setEnabled(false);
    Job k =
        new Job(LibHoverMessages.getString(REGENERATE_MSG)) {

          @Override
          protected IStatus run(IProgressMonitor monitor) {
            IPreferenceStore ps = DevHelpPlugin.getDefault().getPreferenceStore();
            ParseDevHelp.DevHelpParser p =
                new ParseDevHelp.DevHelpParser(ps.getString(PreferenceConstants.DEVHELP_DIRECTORY));
            LibHoverInfo hover = p.parse(monitor);
            // Update the devhelp library info if it is on library list
            Collection<LibHoverLibrary> libs = LibHover.getLibraries();
            for (LibHoverLibrary l : libs) {
              if (l.getName().equals("devhelp")) { // $NON-NLS-1$
                l.setHoverinfo(hover);
                break;
              }
            }
            try {
              // Now, output the LibHoverInfo for caching later
              IPath location =
                  LibhoverPlugin.getDefault().getStateLocation().append("C"); // $NON-NLS-1$
              File ldir = new File(location.toOSString());
              ldir.mkdir();
              location = location.append("devhelp.libhover"); // $NON-NLS-1$
              try (FileOutputStream f = new FileOutputStream(location.toOSString());
                  ObjectOutputStream out = new ObjectOutputStream(f)) {
                out.writeObject(hover);
              }
              monitor.done();
            } catch (IOException e) {
              monitor.done();
              return new Status(IStatus.ERROR, DevHelpPlugin.PLUGIN_ID, e.getLocalizedMessage(), e);
            }

            return Status.OK_STATUS;
          }
        };
    k.setUser(true);
    k.addJobChangeListener(
        new JobChangeAdapter() {
          @Override
          public void done(IJobChangeEvent event) {
            Display.getDefault()
                .syncExec(
                    new Runnable() {
                      @Override
                      public void run() {
                        if (generateButton != null) generateButton.setEnabled(true);
                      }
                    });
          }
        });
    k.schedule();
  }
Exemplo n.º 12
0
 /**
  * Check and recover files opened in the last workbench session. This method consumes 2 ticks from
  * the given progress monitor.
  *
  * @param monitor
  */
 protected void checkAndRecoverFiles(IProgressMonitor monitor) {
   Job subJob = new CheckRecoverFilesJob(workbench);
   subJob.setUser(isUser());
   subJob.setSystem(isSystem());
   subJob.setProgressGroup(monitor, 1);
   subJob.schedule();
   try {
     subJob.join();
   } catch (InterruptedException e) {
   }
 }
Exemplo n.º 13
0
  /**
   * Called when decrypting an XML resource inside an opened editor or via a view. The output XML
   * can not be pretty printed since this would break an existing XML signature in the document.
   *
   * @param wizard The Decryption Wizard
   * @throws Exception to indicate any exceptional condition
   */
  private void decryptData(final NewDecryptionWizard wizard) throws Exception {
    final CreateDecryption decryption = new CreateDecryption();

    WizardDialog dialog = new WizardDialog(getActiveWorkbenchWindow().getShell(), wizard);
    dialog.create();
    dialog.open();

    if (dialog.getReturnCode() == Window.OK && wizard.getModel() != null) {
      Job job =
          new Job(Messages.NewDecryptionCommand_0) {
            public IStatus run(final IProgressMonitor monitor) {
              try {
                monitor.beginTask(Messages.NewDecryptionCommand_2, 6);

                Document doc = decryption.decrypt(wizard.getModel(), monitor);

                if (monitor.isCanceled()) {
                  return Status.CANCEL_STATUS;
                }

                if (doc != null) {
                  IEditorInput output =
                      AbstractEditorService.createOutputFile(
                          "decrypted",
                          IConstants.XML_FILE_TYPE_EXTENSION,
                          Utils.docToInputStram(doc));

                  performOpenEditor(output, IOperationsConstants.ID_TEXT_EDITOR);
                }
              } catch (final Exception ex) {
                getActiveWorkbenchWindow()
                    .getShell()
                    .getDisplay()
                    .asyncExec(
                        new Runnable() {
                          public void run() {
                            LogUtil.logError(
                                XSTUIPlugin.getId(), Messages.NewDecryptionCommand_1, ex, true);
                          }
                        });
              } finally {
                monitor.done();
              }

              return Status.OK_STATUS;
            }
          };
      job.setUser(true);
      job.schedule();
    }

    wizard.dispose();
  }
Exemplo n.º 14
0
    public void launchClean() {
      Job cleanJob =
          new Job("Cleaning cache " + getName()) {
            protected IStatus run(IProgressMonitor monitor) {
              clean();
              return Status.OK_STATUS;
            }
          };

      cleanJob.setUser(true);
      cleanJob.schedule();
    }
Exemplo n.º 15
0
 public void run(final IProgressMonitor monitor)
     throws InvocationTargetException, InterruptedException {
   monitor.beginTask("Saving Excel to File", IProgressMonitor.UNKNOWN);
   Job job = new ActivateJob("Saving Excel to File");
   job.addJobChangeListener(new ActivateJobChangeAdapter());
   job.setUser(true);
   job.join();
   job.schedule();
   if (monitor.isCanceled()) {
     throw new InterruptedException("The long running operation was cancelled");
   }
 }
Exemplo n.º 16
0
 public void refresh() {
   Job job =
       new Job("Refreshing Repository View") {
         @Override
         protected IStatus run(IProgressMonitor monitor) {
           doLongThing();
           syncWithUi();
           return Status.OK_STATUS;
         }
       };
   job.setUser(true);
   job.schedule();
 }
  /**
   * Loads a .xem PeakSearch options IFile.
   *
   * @param file
   */
  private void loadFile(IFile iFile) {
    final IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
    if (window != null) {
      try {
        final String fileToLoad = iFile.getLocation().toString();
        final Job j =
            new Job("Load column file job " + fileToLoad) {
              @Override
              protected IStatus run(final IProgressMonitor monitor) {
                // setProperty(IProgressConstants.ICON_PROPERTY,
                // pluginImage);
                monitor.beginTask(
                    "Please wait while loading file " + "in editor " + fileToLoad,
                    IProgressMonitor.UNKNOWN);

                if (monitor.isCanceled()) {
                  return Status.CANCEL_STATUS;
                }
                IEditorInput input = new ColumnFileEditorInput(fileToLoad);
                IWorkbenchPage page = window.getActivePage();

                monitor.done();
                ColumnEditorAction.openEditors(input, page);
                return Status.OK_STATUS;
              }
            };
        j.setUser(true);
        j.schedule();
        j.addJobChangeListener(
            new JobChangeAdapter() {
              public void done(final IJobChangeEvent event) {
                if (event.getResult().isOK()) {
                  if (FableIOConsole.console != null) {
                    FableIOConsole.console.displayOut(
                        event.getJob().getName() + " completed successfully");
                  }

                } else {
                  if (FableIOConsole.console != null) {
                    FableIOConsole.console.displayOut(
                        event.getJob().getName() + " did not complete successfully");
                  }
                }
              }
            });
      } catch (Exception ex) {
        FableUtils.excMsg(this, "Error opening ColFile", ex);
      }
    }
  }
  public void testSingleNonUIThreadUpdatesToEditorDocument() throws Exception {
    IFile file = getOrCreateFile(PROJECT_NAME + "/" + "testBackgroundChanges.xml");
    ITextFileBufferManager textFileBufferManager = FileBuffers.getTextFileBufferManager();
    textFileBufferManager.connect(
        file.getFullPath(), LocationKind.IFILE, new NullProgressMonitor());

    ITextFileBuffer textFileBuffer =
        textFileBufferManager.getTextFileBuffer(file.getFullPath(), LocationKind.IFILE);
    final IDocument document = textFileBuffer.getDocument();
    document.replace(0, 0, "<?xml encoding=\"UTF-8\" version=\"1.0\"?>\n");
    textFileBuffer.commit(new NullProgressMonitor(), true);

    String testText = document.get() + "<c/><b/><a/>";
    final int end = document.getLength();
    IWorkbenchPage activePage =
        PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
    IEditorPart openedEditor = IDE.openEditor(activePage, file);

    final boolean state[] = new boolean[] {false};
    Job changer =
        new Job("text changer") {
          protected IStatus run(IProgressMonitor monitor) {
            try {
              document.replace(end, 0, "<a/>");
              document.replace(end, 0, "<b/>");
              document.replace(end, 0, "<c/>");
            } catch (Exception e) {
              return new Status(IStatus.ERROR, SSEUIPlugin.ID, e.getMessage());
            } finally {
              state[0] = true;
            }
            return Status.OK_STATUS;
          }
        };
    changer.setUser(true);
    changer.setSystem(false);
    changer.schedule();

    while (!state[0]) {
      openedEditor.getSite().getShell().getDisplay().readAndDispatch();
    }

    String finalText = document.get();
    textFileBuffer.commit(new NullProgressMonitor(), true);
    textFileBufferManager.disconnect(
        file.getFullPath(), LocationKind.IFILE, new NullProgressMonitor());
    activePage.closeEditor(openedEditor, false);
    assertEquals("Non-UI changes did not apply", testText, finalText);
  }
  /** {@inheritDoc} */
  @Override
  void commandButtonExecute(MigrationEditorOperation editor) {
    LOGGER.info(MessageUtil.INF_ACTION_SAVE_CSV);

    TreeViewer treeViewer = editor.getTreeViewer();
    List<JbmEditorMigrationRow> list = createEditorViewData(treeViewer);
    try {
      String temporaryCsvFilePath =
          PluginUtil.getPluginDir() + ApplicationPropertyUtil.OUTPUT_TEMPORARY_CSV;
      outputTemporaryCsv(list, temporaryCsvFilePath);

      FileDialog dialog = new FileDialog(treeViewer.getControl().getShell(), SWT.SAVE);
      String[] extensions = {ApplicationPropertyUtil.EXTENSION_CSV};
      dialog.setFilterExtensions(extensions);
      dialog.setFileName(ApplicationPropertyUtil.DEFAULT_CSV_FILENAME);
      outputFilePath = temporaryCsvFilePath.replaceFirst(StringUtil.SLASH, StringUtil.EMPTY);
      final String formPath = outputFilePath;
      final String toPath = dialog.open();
      if (toPath != null) {
        Job job =
            new Job(MessageUtil.INF_SAVE_CSV_START) {
              @Override
              protected IStatus run(IProgressMonitor monitor) {

                monitor.beginTask(MessageUtil.INF_SAVE_CSV_START, IProgressMonitor.UNKNOWN);

                // Cancellation process
                if (monitor.isCanceled()) {
                  return Status.CANCEL_STATUS;
                }
                // CSV output
                CmnFileUtil.copyFile(formPath, toPath);
                monitor.done();
                return Status.OK_STATUS;
              }
            };
        job.setUser(true);
        job.schedule();
      }
    } catch (JbmException e) {
      PluginUtil.viewErrorDialog(ResourceUtil.OUTPUT_CSV, MessageUtil.ERR_OUTPUT_CSV, e);
    } catch (IOException e) {
      PluginUtil.viewErrorDialog(ResourceUtil.OUTPUT_CSV, MessageUtil.ERR_OUTPUT_CSV, e);
    }
  }
Exemplo n.º 20
0
 private void spawnLoadJob(final String newDirectory) {
   final Job updateDirectory =
       new Job("Update directory") {
         @Override
         protected IStatus run(IProgressMonitor monitor) {
           if (!ImageExplorerDirectoryChooseAction.setImageFolder(newDirectory, filter)) {
             return new Status(
                 IStatus.ERROR,
                 "ERROR",
                 "Couldn't load directory it either doesn't exist or has no files");
           }
           return Status.OK_STATUS;
         }
       };
   updateDirectory.setUser(true);
   updateDirectory.setPriority(Job.DECORATE);
   updateDirectory.schedule(100);
 }
  public Object execute(ExecutionEvent event) throws ExecutionException {

    Job progressJob = UpdateStudioJob.getInstance();

    if ((progressJob != null)
        && ((progressJob.getState() == Job.WAITING) || (progressJob.getState() == Job.RUNNING))) {
      EclipseUtils.showInformationDialog(
          InstallerNLS.UpdateStudio_UpdateAlreadyRunningTitle,
          InstallerNLS.UpdateStudio_UpdateAlreadyRunningMsg);
    } else {
      progressJob =
          UpdateStudioJob.createJob(InstallerNLS.UpdateStudio_CheckingForUpdatesJobDescription);
      progressJob.setUser(true);
      progressJob.schedule();
    }

    return null;
  }
  @Override
  public Object execute(ExecutionEvent event) throws ExecutionException {
    Job job =
        new Job(getJobName()) {

          @Override
          protected IStatus run(IProgressMonitor monitor) {
            int i = 0;
            while (i < MAX_ATTEMPTS) {
              refreshAll(monitor);
              cleanAll(monitor);

              List<IMarker> errorMarkers = getErrorMarkers();
              if (errorMarkers.isEmpty()) {
                buildAll(monitor);
                return Status.OK_STATUS;
              }

              boolean hasOtherProblems = wsHasProblemsThatCantBeSolvedByCleanRefresh(errorMarkers);
              if (hasOtherProblems) {
                return new Status(
                    IStatus.ERROR,
                    Activator.PLUGIN_ID,
                    "Workspace has problems that can't be solved by clean-refresh",
                    null);
              }

              monitor.worked(1);
              i++;
            }
            return new Status(
                IStatus.ERROR,
                Activator.PLUGIN_ID,
                "Workspace problems were not resolved within "
                    + MAX_ATTEMPTS
                    + " clean-refresh attempts",
                null);
          }
        };
    job.setUser(true);
    job.setProperty(IProgressConstants2.SHOW_IN_TASKBAR_ICON_PROPERTY, Boolean.TRUE);
    job.schedule();
    return "Done";
  }
Exemplo n.º 23
0
  @Override
  public boolean performFinish() {

    grabDataFromWorkflowPage();

    if (!performValidations()) {
      return false;
    }

    if (!validateWorkflowAndPlaceholders() && !requestConfirmationForValidationErrorsWarnings()) {
      // keeps the execute dialog open
      return false;
    }

    WorkflowExecutionUtils.setNodeIdentifiersToTransientInCaseOfLocalOnes(
        wfDescription, localNodeId);
    saveWorkflow();

    grabDataFromPlaceholdersPage();

    Job job =
        new Job(Messages.workflowExecutionWizardTitle) {

          @Override
          protected IStatus run(IProgressMonitor monitor) {
            try {
              monitor.beginTask(Messages.settingUpWorkflow, 2);
              monitor.worked(1);
              executeWorkflowInBackground();
              monitor.worked(1);
              return Status.OK_STATUS;
            } finally {
              monitor.done();
            }
          };
        };
    job.setUser(true);
    job.schedule();

    return true;
  }
  public Object execute(ExecutionEvent event) {
    ISelection selection = getSelection(event);
    List<IJavaElement> elements = selectionToJavaElements(selection);

    if (!elements.isEmpty()) {
      Job checkerJob;
      String customClasses =
          CheckerPlugin.getDefault()
              .getPreferenceStore()
              .getString(CheckerPreferences.PREF_CHECKER_CUSTOM_CLASSES);

      // Depending on how this runner was created, we will either:
      // * just run one particular checker
      // * use the custom configured checkers
      // * run "selected" checkers using the action or auto build

      final String actualNames;

      if (!usePrefs && !useCustom && !useSingleCustom) {
        actualNames = checkerName;
      } else if (!usePrefs && !useSingleCustom) {
        actualNames = customClasses;
      } else if (useSingleCustom) {
        actualNames = event.getParameter("checker-framework-eclipse-plugin.checker");
      } else {
        List<String> names = getClassNameFromPrefs();
        actualNames = PluginUtil.join(",", names);
      }

      checkerJob = new CheckerWorker(elements, actualNames);

      checkerJob.setUser(true);
      checkerJob.setPriority(Job.BUILD);
      checkerJob.setRule(new MutexSchedulingRule());
      checkerJob.schedule();
    }

    return null;
  }
  /**
   * Only schedule a rebuild when the project really requires it. A project requires a rebuild when
   * it is in debug mode but the required classes are not loaded.
   */
  public Job scheduleExecute(
      final EditorState editor,
      IStrategoTerm node,
      final IFile errorReportFile,
      final boolean isRebuild) {
    // ignore the parameters, we just want to toggle the debug mode and rebuild the project (if
    // necessary)

    boolean isDebuggerEnabled = observer.isDebuggerEnabled();
    observer.setDebuggerEnabled(!isDebuggerEnabled); // toggle
    boolean needsProjectRebuild = false;
    if (observer.isDebuggerEnabled()) {
      try {
        needsProjectRebuild = observer.needsProjectRebuild();
      } catch (CoreException e) {
        this.openError(editor, e.getMessage());
      }
    }
    Job job = null;
    if (needsProjectRebuild) {
      job =
          new Job("Executing " + displayCaption) {
            @Override
            protected IStatus run(IProgressMonitor monitor) {
              MonitorStateWatchDog protector = new MonitorStateWatchDog(this, monitor, observer);
              try {
                execute(editor, monitor);
                return monitor.isCanceled() ? Status.CANCEL_STATUS : Status.OK_STATUS;
              } finally {
                protector.endProtect();
              }
            }
          };
      job.setUser(true);
      job.schedule();
    }
    return job;
  }
Exemplo n.º 26
0
  private void runAsJob(final URIish uri, final CloneOperation op) {
    final Job job =
        new Job(NLS.bind(UIText.GitCloneWizard_jobName, uri.toString())) {
          @Override
          protected IStatus run(final IProgressMonitor monitor) {
            try {
              return executeCloneOperation(op, monitor);
            } catch (InterruptedException e) {
              return Status.CANCEL_STATUS;
            } catch (InvocationTargetException e) {
              Throwable thr = e.getCause();
              return new Status(IStatus.ERROR, Activator.getPluginId(), 0, thr.getMessage(), thr);
            }
          }

          @Override
          public boolean belongsTo(Object family) {
            return CLONE_JOB_FAMILY.equals(family);
          }
        };
    job.setUser(true);
    job.schedule();
  }
  public void runTests(ObjRef documentRef, String[] testUIDs) {
    if (runningTests) return;

    runningTests = true;
    final ObjRef fdocumentRef = documentRef;
    final String[] ftestUIDs = testUIDs;
    if (tools != null) {
      Job job =
          new Job("Running Archlight Tests") {
            protected IStatus run(IProgressMonitor monitor) {
              try {
                progressMonitor = monitor;
                tools.runTests(fdocumentRef, ftestUIDs);
                return Status.OK_STATUS;
              } finally {
                runningTests = false;
              }
            }
          };
      job.setPriority(Job.LONG);
      job.setUser(true);
      job.schedule();
    }
  }
Exemplo n.º 28
0
  private Job createBatchJob() {
    Job job = new Job("") { // $NON-NLS-1$
          @Override
          protected IStatus run(IProgressMonitor monitor) {
            fBatchInProcess.set(false);
            fForceQuickUpdate.set(false);

            /* Update all saved searches */
            SafeRunner.run(
                new LoggingSafeRunnable() {
                  public void run() throws Exception {
                    if (!Controller.getDefault().isShuttingDown()) updateSavedSearches(true);
                  }
                });

            return Status.OK_STATUS;
          }
        };

    job.setSystem(true);
    job.setUser(false);

    return job;
  }
Exemplo n.º 29
0
  private void doActionInsideEditor(Job job, final JiraTaskEditorPage jiraFormPage) {
    if (jiraFormPage.isDirty()) {
      jiraFormPage.getEditor().doSave(new NullProgressMonitor());
    }
    jiraFormPage.showEditorBusy(true);
    job.setUser(false);
    job.addJobChangeListener(
        new JobChangeAdapter() {
          @Override
          public void done(IJobChangeEvent event) {
            PlatformUI.getWorkbench()
                .getDisplay()
                .asyncExec(
                    new Runnable() {
                      public void run() {
                        jiraFormPage.refresh();
                        //						jiraFormPage.showEditorBusy(false);
                      }
                    });
          }
        });

    job.schedule();
  }
Exemplo n.º 30
0
  @Override
  protected void doFinish(IProgressMonitor monitor) {
    // 默认仓库不记录
    if (!JAEAppHelper.getDefaultAppRepository(app).equals(app.getRepositoryURL()))
      JAEAppHelper.regeditAppRepository(app);

    Job job =
        new Job("编辑应用") {

          @Override
          protected IStatus run(IProgressMonitor monitor) {
            boolean refreshFlag = false;
            try {
              monitor.beginTask("更新应用设置", 100);
              monitor.worked(20);

              monitor.setTaskName("更新应用内存设置");
              String appName = app.getName();
              if (application.getMemory() != appInfo.get("memory")) {
                operator.updateApplicationMemory(appName, appInfo.get("memory"));
              }
              monitor.worked(30);

              monitor.setTaskName("更新应用实例数设置");
              monitor.worked(30);
              if (application.getInstances() != appInfo.get("appCount")) {
                operator.updateApplicationInstances(appName, appInfo.get("appCount"));
                app.refresh(); // 实例数发生变化,需要刷新
                refreshFlag = true;
              }

              List<String> oldUris = new ArrayList<String>(application.getUris());
              Map<String, String> oldEnv = new HashMap<String, String>(application.getEnvAsMap());

              List<String> newUris = new ArrayList<String>();
              for (Map<String, String> uriMap : uriList) {
                String uri = uriMap.get("uri");
                if (null != uri) newUris.add(uri);
              }

              Map<String, String> newEnv = new HashMap<String, String>();
              for (Map<String, String> envMap : envList) {
                String name = envMap.get("name");
                String value = envMap.get("value");

                if (null != name && null != value) newEnv.put(name, value);
              }

              if (!newUris.equals(oldUris)) operator.updateApplicationUris(appName, newUris);

              if (!newEnv.equals(oldEnv)) operator.updateApplicationEnv(appName, newEnv);
            } catch (CloudFoundryClientRuntimeException e) {
              e.printStackTrace();
            } finally {
              if (refreshFlag) {
                PlatformUI.getWorkbench()
                    .getDisplay()
                    .asyncExec(
                        new Runnable() {

                          public void run() {
                            JAEView.getInstance().getCommonViewer().refresh();
                          }
                        });
              }
              monitor.done();
            }
            return Status.OK_STATUS;
          }
        };

    job.setUser(true);
    job.schedule();
  }