Beispiel #1
0
 /**
  * Wait for a short while before initial files are loaded. On Mac OS X, files opened by double
  * clicking or 'open' command are passed to Eclipse RCP via <code>SWT.OpenDocument</code> event
  * which comes a slight later than workbench startup.
  *
  * @param monitor
  */
 protected void waitForInitialFilesLoaded(IProgressMonitor monitor) {
   try {
     Thread.sleep(800);
   } catch (InterruptedException e) {
     monitor.setCanceled(true);
   }
 }
 /**
  * Displays an error for the case of an invalid node name
  *
  * @param node the node
  */
 private void displayErrorForInvalidName(INodePO node) {
   String fqNodeName = Utils.getFullyQualifiedName(node);
   ErrorMessagePresenter.getPresenter()
       .showErrorMessage(
           new JBException(
               NLS.bind(Messages.InvalidNodeName, new String[] {fqNodeName}),
               MessageIDs.E_INVALID_NODE_NAME),
           new String[] {fqNodeName},
           null);
   progressMonitor.setCanceled(true);
 }
  private void loadResource(final IPath resource, final LinkingContainerFigure figure) {
    if (_runningMonitor != null) {
      _runningMonitor.setCanceled(true);
    }

    _runningMonitor = new NullProgressMonitor();

    ContainerLoadJob job =
        new ContainerLoadJob((LinkingContainerModel) getContainerModel(), resource, figure);

    job.run(_runningMonitor);
  }
 @Override
 public void doSave(IProgressMonitor monitor) {
   new MessageDialog(
           null,
           "Operation not supported",
           null,
           "Save of un-submitted new tasks is not currently supported.\nPlease submit all new tasks.",
           MessageDialog.INFORMATION,
           new String[] {IDialogConstants.OK_LABEL},
           0)
       .open();
   monitor.setCanceled(true);
   return;
 }
  /*
   * @see org.eclipse.ui.texteditor.quickdiff.IQuickDiffReferenceProvider#dispose()
   */
  public void dispose() {
    IProgressMonitor monitor = fProgressMonitor;
    if (monitor != null) {
      monitor.setCanceled(true);
    }

    IDocumentProvider provider = fDocumentProvider;

    synchronized (fLock) {
      if (provider != null) provider.removeElementStateListener(this);
      fEditorInput = null;
      fDocumentProvider = null;
      fReference = null;
      fDocumentRead = false;
      fProgressMonitor = null;
      fEditor = null;
    }
  }
 /**
  * Returns the default toolkit for a project by inspecting its first AUT
  *
  * @param project the project
  * @return the name of the default toolkit
  */
 private String determineDefaultToolkit(IProjectPO project) {
   String toolkit = null;
   IAUTMainPO firstAUT = null;
   try {
     firstAUT = project.getAutCont().getAutMainList().iterator().next();
   } catch (NoSuchElementException e) {
     ErrorMessagePresenter.getPresenter()
         .showErrorMessage(
             new JBException(Messages.NoAutInProject, MessageIDs.E_NO_AUT_IN_PROJECT),
             null,
             null);
     progressMonitor.setCanceled(true);
   }
   if (firstAUT != null) {
     toolkit = firstAUT.getToolkit();
   }
   if (toolkit.equals(CommandConstants.RCP_TOOLKIT)) {
     toolkit = CommandConstants.SWT_TOOLKIT;
   }
   return toolkit;
 }
  public void execute(
      IProject project, IProjectFacetVersion facetVersion, Object config, IProgressMonitor monitor)
      throws CoreException {

    monitor = Util.getNonNullMonitor(monitor);

    try {

      monitor.beginTask("", 3);

      addNature(project, new SubProgressMonitor(monitor, 1));
      addUserLibToClassPath(project, new SubProgressMonitor(monitor, 1));
      addServletLibToWebInf(project, new SubProgressMonitor(monitor, 1));

    } catch (CoreException e) {
      monitor.setCanceled(true);
      Activator.logException(e);
    } finally {
      monitor.done();
    }
  }
    /** {@inheritDoc} */
    public void run(IProgressMonitor monitor) {
      progressMonitor = monitor;
      IProjectPO project = GeneralStorage.getInstance().getProject();
      progressMonitor.setTaskName(Messages.PreparingConvertProjectTaskName);
      String basePath =
          genPath
              + StringConstants.SLASH
              + genPackage.replace(StringConstants.DOT, StringConstants.SLASH);
      uuidToNodeInfoMap = new HashMap<String, NodeInfo>();
      NodeInfo.setUuidToNodeInfoMap(uuidToNodeInfoMap);
      projects = new HashSet<IProjectPO>();
      workUnits = 0;

      if (project != null) {
        defaultToolkit = determineDefaultToolkit(project);
        addProjectsToConvert(project);

        try {
          for (IProjectPO p : projects) {
            determineClassNamesForProject(p, basePath);
          }
          progressMonitor.beginTask(Messages.PreparingConvertProjectTaskName, workUnits);
          for (IProjectPO p : projects) {
            progressMonitor.setTaskName(NLS.bind(Messages.ConvertProjectTaskName, p.getName()));
            handleProject(p, basePath);
          }
        } catch (StopConversionException e) {
          progressMonitor.setCanceled(true);
          if (!e.wasManuallyTriggered()) {
            ErrorHandlingUtil.createMessageDialog(
                new JBException(e.getMessage(), e, MessageIDs.E_CONVERSION_ABORTED_ERROR));
          }
          return;
        }
      }
      progressMonitor.done();
    }
Beispiel #9
0
  /**
   * This API is allowing to run one job in concurrence with background processing. Indeed since
   * other jobs are performed in background, resource sharing might be an issue.Therefore, this
   * functionality allows a given job to be run without colliding with background ones. Note:
   * multiple thread might attempt to perform concurrent jobs at the same time, and should
   * synchronize (it is deliberately left to clients to decide whether concurrent jobs might
   * interfere or not. In general, multiple read jobs are ok).
   *
   * <p>Waiting policy can be: IJobConstants.ForceImmediateSearch
   * IJobConstants.CancelIfNotReadyToSearch IJobConstants.WaitUntilReadyToSearch
   */
  public boolean performConcurrentJob(
      IJob searchJob, int waitingPolicy, IProgressMonitor progress) {

    if (VERBOSE) JobManager.verbose("STARTING  concurrent job - " + searchJob); // $NON-NLS-1$
    if (!searchJob.isReadyToRun()) {
      if (VERBOSE) JobManager.verbose("ABORTED   concurrent job - " + searchJob); // $NON-NLS-1$
      return IJob.FAILED;
    }

    int concurrentJobWork = 100;
    if (progress != null) progress.beginTask("", concurrentJobWork); // $NON-NLS-1$
    boolean status = IJob.FAILED;
    if (awaitingJobsCount() > 0) {
      switch (waitingPolicy) {
        case IJob.ForceImmediate:
          if (VERBOSE)
            JobManager.verbose("-> NOT READY - forcing immediate - " + searchJob); // $NON-NLS-1$
          boolean wasEnabled = isEnabled();
          try {
            disable(); // pause indexing
            status =
                searchJob.execute(
                    progress == null ? null : new SubProgressMonitor(progress, concurrentJobWork));
          } finally {
            if (wasEnabled) enable();
          }
          if (VERBOSE) JobManager.verbose("FINISHED  concurrent job - " + searchJob); // $NON-NLS-1$
          return status;

        case IJob.CancelIfNotReady:
          if (VERBOSE)
            JobManager.verbose("-> NOT READY - cancelling - " + searchJob); // $NON-NLS-1$
          if (progress != null) progress.setCanceled(true);
          if (VERBOSE) JobManager.verbose("CANCELED concurrent job - " + searchJob); // $NON-NLS-1$
          throw new OperationCanceledException();

        case IJob.WaitUntilReady:
          int awaitingWork;
          IJob previousJob = null;
          IJob currentJob;
          IProgressMonitor subProgress = null;
          int totalWork = this.awaitingJobsCount();
          if (progress != null && totalWork > 0) {
            subProgress = new SubProgressMonitor(progress, concurrentJobWork / 2);
            subProgress.beginTask("", totalWork); // $NON-NLS-1$
            concurrentJobWork = concurrentJobWork / 2;
          }
          int originalPriority = this.thread.getPriority();
          try {
            synchronized (this) {

              // use local variable to avoid potential NPE (see Bug 20435 NPE when searching java
              // method)
              Thread t = this.thread;
              if (t != null) {
                t.setPriority(Thread.currentThread().getPriority());
              }
              this.awaitingClients++;
            }
            while ((awaitingWork = awaitingJobsCount()) > 0) {
              if (subProgress != null && subProgress.isCanceled())
                throw new OperationCanceledException();
              currentJob = currentJob();
              // currentJob can be null when jobs have been added to the queue but job manager is
              // not enabled
              if (currentJob != null && currentJob != previousJob) {
                if (VERBOSE)
                  JobManager.verbose(
                      "-> NOT READY - waiting until ready - " + searchJob); // $NON-NLS-1$
                if (subProgress != null) {
                  subProgress.subTask(
                      EGLModelSearchResources.bind(
                          EGLModelSearchResources.ManagerFilesToIndex,
                          Integer.toString(awaitingWork))); // $NON-NLS-1$
                  subProgress.worked(1);
                }
                previousJob = currentJob;
              }
              try {
                Thread.sleep(50);
              } catch (InterruptedException e) {
              }
            }
          } finally {
            synchronized (this) {
              this.awaitingClients--;

              // use local variable to avoid potential NPE (see Bug 20435 NPE when searching java
              // method)
              Thread t = this.thread;
              if (t != null) {
                t.setPriority(originalPriority);
              }
            }
          }
          if (subProgress != null) {
            subProgress.done();
          }
      }
    }
    status =
        searchJob.execute(
            progress == null ? null : new SubProgressMonitor(progress, concurrentJobWork));
    if (progress != null) {
      progress.done();
    }
    if (VERBOSE) JobManager.verbose("FINISHED  concurrent job - " + searchJob); // $NON-NLS-1$
    return status;
  }
 /** @generated */
 protected void performSaveAs(IProgressMonitor progressMonitor) {
   Shell shell = getSite().getShell();
   IEditorInput input = getEditorInput();
   SaveAsDialog dialog = new SaveAsDialog(shell);
   IFile original =
       input instanceof IFileEditorInput ? ((IFileEditorInput) input).getFile() : null;
   if (original != null) {
     dialog.setOriginalFile(original);
   }
   dialog.create();
   IDocumentProvider provider = getDocumentProvider();
   if (provider == null) {
     // editor has been programmatically closed while the dialog was open
     return;
   }
   if (provider.isDeleted(input) && original != null) {
     String message =
         NLS.bind(Messages.SqlmodelDiagramEditor_SavingDeletedFile, original.getName());
     dialog.setErrorMessage(null);
     dialog.setMessage(message, IMessageProvider.WARNING);
   }
   if (dialog.open() == Window.CANCEL) {
     if (progressMonitor != null) {
       progressMonitor.setCanceled(true);
     }
     return;
   }
   IPath filePath = dialog.getResult();
   if (filePath == null) {
     if (progressMonitor != null) {
       progressMonitor.setCanceled(true);
     }
     return;
   }
   IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();
   IFile file = workspaceRoot.getFile(filePath);
   final IEditorInput newInput = new FileEditorInput(file);
   // Check if the editor is already open
   IEditorMatchingStrategy matchingStrategy = getEditorDescriptor().getEditorMatchingStrategy();
   IEditorReference[] editorRefs =
       PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getEditorReferences();
   for (int i = 0; i < editorRefs.length; i++) {
     if (matchingStrategy.matches(editorRefs[i], newInput)) {
       MessageDialog.openWarning(
           shell,
           Messages.SqlmodelDiagramEditor_SaveAsErrorTitle,
           Messages.SqlmodelDiagramEditor_SaveAsErrorMessage);
       return;
     }
   }
   boolean success = false;
   try {
     provider.aboutToChange(newInput);
     getDocumentProvider(newInput)
         .saveDocument(
             progressMonitor, newInput, getDocumentProvider().getDocument(getEditorInput()), true);
     success = true;
   } catch (CoreException x) {
     IStatus status = x.getStatus();
     if (status == null || status.getSeverity() != IStatus.CANCEL) {
       ErrorDialog.openError(
           shell,
           Messages.SqlmodelDiagramEditor_SaveErrorTitle,
           Messages.SqlmodelDiagramEditor_SaveErrorMessage,
           x.getStatus());
     }
   } finally {
     provider.changed(newInput);
     if (success) {
       setInput(newInput);
     }
   }
   if (progressMonitor != null) {
     progressMonitor.setCanceled(!success);
   }
 }
 /**
  * Sets information whether the work was canceled.
  *
  * @param canceled information whether the work was canceled
  * @author Andreas Bröker
  */
 public void setCanceled(boolean canceled) {
   progressMonitor.setCanceled(canceled);
 }
  public void launch(
      ILaunchConfiguration configuration, String mode, ILaunch launch, IProgressMonitor monitor)
      throws CoreException {

    if (monitor.isCanceled()) {
      DebugPlugin.getDefault().getLaunchManager().removeLaunch(launch);
      return;
    }
    PHPexeItem phpExeItem = PHPLaunchUtilities.getPHPExe(configuration);
    if (phpExeItem == null) {
      Logger.log(Logger.ERROR, "Launch configuration could not find PHP exe item"); // $NON-NLS-1$
      monitor.setCanceled(true);
      monitor.done();
      return;
    }
    // get the launch info: php exe, php ini
    final String phpExeString =
        configuration.getAttribute(IPHPDebugConstants.ATTR_EXECUTABLE_LOCATION, (String) null);
    final String phpIniString =
        configuration.getAttribute(IPHPDebugConstants.ATTR_INI_LOCATION, (String) null);
    final String phpScriptString =
        configuration.getAttribute(IPHPDebugConstants.ATTR_FILE, (String) null);
    if (phpScriptString == null || phpScriptString.trim().length() == 0) {
      DebugPlugin.getDefault().getLaunchManager().removeLaunch(launch);
      displayErrorMessage(PHPDebugCoreMessages.XDebug_ExeLaunchConfigurationDelegate_0);
      return;
    }
    if (monitor.isCanceled()) {
      DebugPlugin.getDefault().getLaunchManager().removeLaunch(launch);
      return;
    }

    // locate the project from the php script
    final IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();
    final IPath filePath = new Path(phpScriptString);
    final IResource scriptRes = workspaceRoot.findMember(filePath);
    if (scriptRes == null) {
      DebugPlugin.getDefault().getLaunchManager().removeLaunch(launch);
      displayErrorMessage(PHPDebugCoreMessages.XDebug_ExeLaunchConfigurationDelegate_1);
      return;
    }

    // resolve php exe location
    final IPath phpExe = new Path(phpExeString);

    // resolve project directory
    IProject project = scriptRes.getProject();

    // Set Project Name as this is required by the source lookup computer
    // delegate
    final String projectString = project.getFullPath().toString();
    ILaunchConfigurationWorkingCopy wc = null;
    if (configuration.isWorkingCopy()) {
      wc = (ILaunchConfigurationWorkingCopy) configuration;
    } else {
      wc = configuration.getWorkingCopy();
    }
    wc.setAttribute(IPHPDebugConstants.PHP_Project, projectString);
    wc.setAttribute(
        IDebugParametersKeys.TRANSFER_ENCODING, PHPProjectPreferences.getTransferEncoding(project));
    wc.setAttribute(
        IDebugParametersKeys.OUTPUT_ENCODING, PHPProjectPreferences.getOutputEncoding(project));
    wc.doSave();

    if (monitor.isCanceled()) {
      DebugPlugin.getDefault().getLaunchManager().removeLaunch(launch);
      return;
    }

    IPath projectLocation = project.getRawLocation();
    if (projectLocation == null) {
      projectLocation = project.getLocation();
    }

    // resolve the script location, but not relative to anything
    IPath phpFile = scriptRes.getLocation();

    if (monitor.isCanceled()) {
      DebugPlugin.getDefault().getLaunchManager().removeLaunch(launch);
      return;
    }

    // Resolve the PHP ini location
    // Locate the php ini by using the attribute. If the attribute was null,
    // try to locate an ini that exists next to the executable.
    File phpIni =
        (phpIniString != null && new File(phpIniString).exists())
            ? new File(phpIniString)
            : PHPINIUtil.findPHPIni(phpExeString);
    File tempIni = PHPINIUtil.prepareBeforeLaunch(phpIni, phpExeString, project);
    launch.setAttribute(IDebugParametersKeys.PHP_INI_LOCATION, tempIni.getAbsolutePath());

    // add process type to process attributes, basically the name of the exe
    // that was launched
    final Map<String, String> processAttributes = new HashMap<String, String>();
    String programName = phpExe.lastSegment();
    final String extension = phpExe.getFileExtension();
    if (extension != null) {
      programName = programName.substring(0, programName.length() - (extension.length() + 1));
    }
    programName = programName.toLowerCase();

    // used by the console colorer extension to determine what class to use
    // should allow the console color providers and line trackers to work
    // process.setAttribute(IProcess.ATTR_PROCESS_TYPE,
    // IPHPConstants.PHPProcessType);

    processAttributes.put(IProcess.ATTR_PROCESS_TYPE, programName);
    // used by the Console to give that console a name
    processAttributes.put(IProcess.ATTR_CMDLINE, phpScriptString);

    if (monitor.isCanceled()) {
      DebugPlugin.getDefault().getLaunchManager().removeLaunch(launch);
      return;
    }

    // determine the environment variables
    String[] envVarString = null;
    DBGpTarget target = null;
    if (mode.equals(ILaunchManager.DEBUG_MODE)) {
      // check the launch for stop at first line, if not there go to
      // project specifics
      boolean stopAtFirstLine = PHPProjectPreferences.getStopAtFirstLine(project);
      stopAtFirstLine =
          configuration.getAttribute(IDebugParametersKeys.FIRST_LINE_BREAKPOINT, stopAtFirstLine);
      String sessionID = DBGpSessionHandler.getInstance().generateSessionId();
      String ideKey = null;
      if (phpExeItem != null) {
        DBGpProxyHandler proxyHandler =
            DBGpProxyHandlersManager.INSTANCE.getHandler(phpExeItem.getUniqueId());
        if (proxyHandler != null && proxyHandler.useProxy()) {
          ideKey = proxyHandler.getCurrentIdeKey();
          if (proxyHandler.registerWithProxy() == false) {
            displayErrorMessage(
                PHPDebugCoreMessages.XDebug_ExeLaunchConfigurationDelegate_2
                    + proxyHandler.getErrorMsg());
            DebugPlugin.getDefault().getLaunchManager().removeLaunch(launch);
            return;
          }
        } else {
          ideKey = DBGpSessionHandler.getInstance().getIDEKey();
        }
      }
      target = new DBGpTarget(launch, phpFile.lastSegment(), ideKey, sessionID, stopAtFirstLine);
      target.setPathMapper(PathMapperRegistry.getByLaunchConfiguration(configuration));
      DBGpSessionHandler.getInstance().addSessionListener(target);
      envVarString = createDebugLaunchEnvironment(configuration, sessionID, ideKey, phpExe);

      int requestPort = getDebugPort(phpExeItem);
      // Check that the debug daemon is functional
      // DEBUGGER - Make sure that the active debugger id is indeed Zend's
      // debugger
      if (!PHPLaunchUtilities.isDebugDaemonActive(
          requestPort, XDebugCommunicationDaemon.XDEBUG_DEBUGGER_ID)) {
        PHPLaunchUtilities.showLaunchErrorMessage(
            NLS.bind(
                PHPDebugCoreMessages.ExeLaunchConfigurationDelegate_PortInUse,
                requestPort,
                phpExeItem.getName()));
        monitor.setCanceled(true);
        monitor.done();
        return;
      }

    } else {
      envVarString =
          PHPLaunchUtilities.getEnvironment(configuration, new String[] {getLibraryPath(phpExe)});
    }

    IProgressMonitor subMonitor = new SubProgressMonitor(monitor, 30);
    subMonitor.beginTask(PHPDebugCoreMessages.XDebug_ExeLaunchConfigurationDelegate_3, 10);

    // determine the working directory. default is the location of the
    // script
    IPath workingPath = phpFile.removeLastSegments(1);
    File workingDir = workingPath.makeAbsolute().toFile();

    boolean found = false;
    for (int i = 0; i < envVarString.length && !found; i++) {
      String envEntity = envVarString[i];
      String[] elements = envEntity.split("="); // $NON-NLS-1$
      if (elements.length > 0 && elements[0].equals("XDEBUG_WORKING_DIR")) { // $NON-NLS-1$
        found = true;
        workingPath = new Path(elements[1]);
        File temp = workingPath.makeAbsolute().toFile();
        if (temp.exists()) {
          workingDir = temp;
        }
      }
    }

    // Detect PHP SAPI type and thus where we need arguments
    File phpExeFile = new File(phpExeString);
    String sapiType = null;
    String phpV = null;
    PHPexeItem[] items = PHPexes.getInstance().getAllItems();
    for (PHPexeItem item : items) {
      if (item.getExecutable().equals(phpExeFile)) {
        sapiType = item.getSapiType();
        phpV = item.getVersion();
        break;
      }
    }
    String[] args = null;
    if (PHPexeItem.SAPI_CLI.equals(sapiType)) {
      args = PHPLaunchUtilities.getProgramArguments(launch.getLaunchConfiguration());
    }

    // define the command line for launching
    String[] cmdLine = null;
    cmdLine =
        PHPLaunchUtilities.getCommandLine(
            configuration,
            phpExe.toOSString(),
            tempIni.toString(),
            phpFile.toOSString(),
            args,
            phpV);

    // Launch the process
    final Process phpExeProcess = DebugPlugin.exec(cmdLine, workingDir, envVarString);
    // Attach a crash detector
    new Thread(new ProcessCrashDetector(launch, phpExeProcess)).start();

    IProcess eclipseProcessWrapper = null;
    if (phpExeProcess != null) {
      subMonitor.worked(10);
      eclipseProcessWrapper =
          DebugPlugin.newProcess(launch, phpExeProcess, phpExe.toOSString(), processAttributes);
      if (eclipseProcessWrapper == null) {

        // another error so we stop everything somehow
        phpExeProcess.destroy();
        subMonitor.done();
        DebugPlugin.getDefault().getLaunchManager().removeLaunch(launch);
        throw new CoreException(new Status(IStatus.ERROR, PHPDebugPlugin.ID, 0, null, null));
      }

      // if launching in debug mode, create the debug infrastructure and
      // link it with the launched process
      if (mode.equals(ILaunchManager.DEBUG_MODE) && target != null) {
        target.setProcess(eclipseProcessWrapper);
        launch.addDebugTarget(target);
        subMonitor.subTask(PHPDebugCoreMessages.XDebug_ExeLaunchConfigurationDelegate_4);
        target.waitForInitialSession(
            (DBGpBreakpointFacade) IDELayerFactory.getIDELayer(),
            XDebugPreferenceMgr.createSessionPreferences(),
            monitor);
      }

    } else {
      // we did not launch
      if (mode.equals(ILaunchManager.DEBUG_MODE)) {
        DBGpSessionHandler.getInstance().removeSessionListener(target);
      }
      DebugPlugin.getDefault().getLaunchManager().removeLaunch(launch);
    }
    subMonitor.done();
  }
  /**
   * Runs the given runnable in a modal context, passing it a progress monitor.
   *
   * <p>The modal nesting level is increased by one from the perspective of the given runnable.
   *
   * <p>If the supplied operation implements <code>IThreadListener</code>, it will be notified of
   * any thread changes required to execute the operation. Specifically, the operation will be
   * notified of the thread that will call its <code>run</code> method before it is called, and will
   * be notified of the change of control back to the thread calling this method when the operation
   * completes. These thread change notifications give the operation an opportunity to transfer any
   * thread-local state to the execution thread before control is transferred to the new thread.
   *
   * @param operation the runnable to run
   * @param fork <code>true</code> if the runnable should run in a separate thread, and <code>false
   *     </code> if in the same thread
   * @param monitor the progress monitor to use to display progress and receive requests for
   *     cancelation
   * @param display the display to be used to read and dispatch events
   * @exception InvocationTargetException if the run method must propagate a checked exception, it
   *     should wrap it inside an <code>InvocationTargetException</code>; runtime exceptions and
   *     errors are automatically wrapped in an <code>InvocationTargetException</code> by this
   *     method
   * @exception InterruptedException if the operation detects a request to cancel, using <code>
   *     IProgressMonitor.isCanceled()</code>, it should exit by throwing <code>InterruptedException
   *     </code>; this method propagates the exception
   */
  public static void run(
      IRunnableWithProgress operation, boolean fork, IProgressMonitor monitor, Display display)
      throws InvocationTargetException, InterruptedException {
    Assert.isTrue(operation != null && monitor != null);

    modalLevel++;
    try {
      if (monitor != null) {
        monitor.setCanceled(false);
      }
      // Is the runnable supposed to be execute in the same thread.
      if (!fork || !runInSeparateThread) {
        runInCurrentThread(operation, monitor);
      } else {
        ModalContextThread t = getCurrentModalContextThread();
        if (t != null) {
          Assert.isTrue(canProgressMonitorBeUsed(monitor, t.progressMonitor));
          runInCurrentThread(operation, monitor);
        } else {
          t = new ModalContextThread(operation, monitor, display);
          Throwable listenerException = null;
          if (operation instanceof IThreadListener) {
            listenerException = invokeThreadListener((IThreadListener) operation, t);
          }

          if (listenerException == null) {
            t.start();
            t.block();
          } else {
            if (t.throwable == null) t.throwable = listenerException;
          }
          Throwable throwable = t.throwable;
          if (throwable != null) {
            if (debug
                && !(throwable instanceof InterruptedException)
                && !(throwable instanceof OperationCanceledException)) {
              System.err.println("Exception in modal context operation:"); // $NON-NLS-1$
              throwable.printStackTrace();
              System.err.println("Called from:"); // $NON-NLS-1$
              // Don't create the InvocationTargetException on the
              // throwable,
              // otherwise it will print its stack trace (from the
              // other thread).
              new InvocationTargetException(null).printStackTrace();
            }
            if (throwable instanceof InvocationTargetException) {
              throw (InvocationTargetException) throwable;
            } else if (throwable instanceof InterruptedException) {
              throw (InterruptedException) throwable;
            } else if (throwable instanceof OperationCanceledException) {
              // See 1GAN3L5: ITPUI:WIN2000 - ModalContext
              // converts OperationCancelException into
              // InvocationTargetException
              throw new InterruptedException(throwable.getMessage());
            } else {
              throw new InvocationTargetException(throwable);
            }
          }
        }
      }
    } finally {
      modalLevel--;
    }
  }
 /**
  * Set the cancellation state.
  *
  * @see IProgressMonitor#setCanceled(boolean)
  * @since 2.0
  */
 public void setCanceled(boolean value) {
   monitor.setCanceled(value);
 }
  @Override
  protected void doSaveDocument(
      IProgressMonitor monitor, Object element, IDocument document, boolean overwrite)
      throws CoreException {

    try {
      // Automatic validation with result
      IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
      CustomValidateAction action = new CustomValidateAction(page, (IEditorInput) element);
      monitor.setTaskName("Validation");
      action.run(monitor);
      if (!action.result) {
        // If validation failed, do not save
        ProblemsView problem = (ProblemsView) page.findView("org.eclipse.ui.views.ProblemView");
        page.activate(problem);
        monitor.setCanceled(true);
        return;
      }
    } catch (Exception e) {
      MindDiagramEditorPlugin.getInstance().logError("Problems occured during validation", e);
      return;
    }

    MindProxy mindRoot = MindProxyFactory.INSTANCE.getRootProxy();
    HashMap<String, Rectangle> boundsMemory = new HashMap<String, Rectangle>();
    HashMap<String, Bendpoints> bendpointsMemory = new HashMap<String, Bendpoints>();
    if (mindRoot != null) {
      SaveUtil.saveBounds(mindRoot.getEditPart(), boundsMemory, bendpointsMemory);
    }

    // Prepare the transaction that will prepare the main definition
    // All merged items are deleted because they must not be serialized
    TransactionalEditingDomain domain = getDiagramDocument(element).getEditingDomain();
    TransactionImpl transaction = new TransactionImpl(domain, false);
    EObject root = ((DiagramImpl) document.getContent()).getElement();

    ResourceSetInfo info = getResourceSetInfo(element);
    if (info != null) {
      if (!overwrite && !info.isSynchronized()) {
        throw new CoreException(
            new Status(
                IStatus.ERROR,
                MindDiagramEditorPlugin.ID,
                IResourceStatus.OUT_OF_SYNC_LOCAL,
                Messages.MindDocumentProvider_UnsynchronizedFileSaveError,
                null));
      }
      info.stopResourceListening();
      fireElementStateChanging(element);
      try {
        monitor.beginTask(
            Messages.MindDocumentProvider_SaveDiagramTask,
            info.getResourceSet().getResources().size() + 1); // "Saving diagram"

        LazyLinkingResource xtextResource = null;
        GMFResource gmfResource = null;

        for (Iterator /*<org.eclipse.emf.ecore.resource.Resource>*/<?> it =
                info.getLoadedResourcesIterator();
            it.hasNext(); ) {
          Resource nextResource = (Resource) it.next();
          monitor.setTaskName(
              NLS.bind(Messages.MindDocumentProvider_SaveNextResourceTask, nextResource.getURI()));
          if (nextResource.isLoaded() && !info.getEditingDomain().isReadOnly(nextResource)) {
            if (nextResource instanceof LazyLinkingResource) {
              // Serialize later
              xtextResource = (LazyLinkingResource) nextResource;
            } else {
              // Save GMF
              try {
                if (nextResource instanceof GMFResource) gmfResource = (GMFResource) nextResource;
                nextResource.save(MindDiagramEditorUtil.getSaveOptions());
              } catch (IOException e) {
                fireElementStateChangeFailed(element);
                throw new CoreException(
                    new Status(
                        IStatus.ERROR,
                        MindDiagramEditorPlugin.ID,
                        EditorStatusCodes.RESOURCE_FAILURE,
                        e.getLocalizedMessage(),
                        null));
              }
            }
          }
          monitor.worked(1);
        }

        // Delete merged elements from the model before saving
        if (root instanceof AdlDefinitionCustomImpl) {
          try {
            transaction.start();
            prepareMainDefinitionBeforeSave((AdlDefinitionCustomImpl) root);
            transaction.commit();
          } catch (InterruptedException e) {
            MindDiagramEditorPlugin.getInstance().logError("Clean merge failed", e);
          } catch (RollbackException e) {
            MindDiagramEditorPlugin.getInstance().logError("Clean merge failed", e);
            transaction.rollback();
          } finally {
          }
        }

        // Merged items are deleted, they will not to be serialized
        // We can save xtext resource
        try {
          xtextResource.save(MindDiagramEditorUtil.getSaveOptions());
        } catch (IOException e) {
          fireElementStateChangeFailed(element);
          throw new CoreException(
              new Status(
                  IStatus.ERROR,
                  MindDiagramEditorPlugin.ID,
                  EditorStatusCodes.RESOURCE_FAILURE,
                  e.getLocalizedMessage(),
                  null));
        }

        // Restore merged elements
        if (root instanceof AdlDefinitionCustomImpl) {
          try {
            transaction.start();
            restoreMainDefinitionAfterSave((AdlDefinitionCustomImpl) root);
            transaction.commit();
          } catch (InterruptedException e) {
            MindDiagramEditorPlugin.getInstance().logError("Restore merge failed", e);
          } catch (RollbackException e) {
            e.printStackTrace();
            MindDiagramEditorPlugin.getInstance().logError("Restore merge failed", e);
            transaction.rollback();
          } finally {
          }
        }

        // Update diagram
        try {
          MindDiagramUpdateCommand update = new MindDiagramUpdateAllCommand(false);
          update.execute(new ExecutionEvent());
        } catch (ExecutionException e) {
          MindDiagramEditorPlugin.getInstance().logError("Update failed", e);
        } finally {
        }

        // Now that editParts have been recreated by the update,
        // we are able to restore the saved bounds
        if (mindRoot != null) {
          SaveUtil.restoreBounds(mindRoot.getEditPart(), boundsMemory, bendpointsMemory);
          boundsMemory.clear();
        }

        // DocumentProvider thinks resource is modified because of restoreMainDefinition
        // Set value to false
        gmfResource.setModified(false);

        monitor.done();
        info.setModificationStamp(computeModificationStamp(info));
      } catch (RuntimeException x) {
        fireElementStateChangeFailed(element);
        throw x;
      } finally {
        info.startResourceListening();
      }
    } else {
      URI newResoruceURI;
      List<IFile> affectedFiles = null;
      if (element instanceof FileEditorInput) {
        IFile newFile = ((FileEditorInput) element).getFile();
        affectedFiles = Collections.singletonList(newFile);
        newResoruceURI = URI.createPlatformResourceURI(newFile.getFullPath().toString(), true);
      } else if (element instanceof URIEditorInput) {
        newResoruceURI = ((URIEditorInput) element).getURI();
      } else {
        fireElementStateChangeFailed(element);
        throw new CoreException(
            new Status(
                IStatus.ERROR,
                MindDiagramEditorPlugin.ID,
                0,
                NLS.bind(
                    Messages.MindDocumentProvider_IncorrectInputError,
                    new Object[] {
                      element,
                      "org.eclipse.ui.part.FileEditorInput",
                      "org.eclipse.emf.common.ui.URIEditorInput"
                    }), //$NON-NLS-1$ //$NON-NLS-2$
                null));
      }
      if (false == document instanceof IDiagramDocument) {
        fireElementStateChangeFailed(element);
        throw new CoreException(
            new Status(
                IStatus.ERROR,
                MindDiagramEditorPlugin.ID,
                0,
                "Incorrect document used: "
                    + document
                    + " instead of org.eclipse.gmf.runtime.diagram.ui.resources.editor.document.IDiagramDocument",
                null)); //$NON-NLS-1$ //$NON-NLS-2$
      }
      IDiagramDocument diagramDocument = (IDiagramDocument) document;
      final Resource newResource =
          diagramDocument.getEditingDomain().getResourceSet().createResource(newResoruceURI);
      final Diagram diagramCopy = (Diagram) EcoreUtil.copy(diagramDocument.getDiagram());
      try {
        new AbstractTransactionalCommand(
            diagramDocument.getEditingDomain(),
            NLS.bind(Messages.MindDocumentProvider_SaveAsOperation, diagramCopy.getName()),
            affectedFiles) {
          protected CommandResult doExecuteWithResult(IProgressMonitor monitor, IAdaptable info)
              throws ExecutionException {
            newResource.getContents().add(diagramCopy);
            return CommandResult.newOKCommandResult();
          }
        }.execute(monitor, null);
        newResource.save(MindDiagramEditorUtil.getSaveOptions());
      } catch (ExecutionException e) {
        fireElementStateChangeFailed(element);
        throw new CoreException(
            new Status(
                IStatus.ERROR, MindDiagramEditorPlugin.ID, 0, e.getLocalizedMessage(), null));
      } catch (IOException e) {
        fireElementStateChangeFailed(element);
        throw new CoreException(
            new Status(
                IStatus.ERROR, MindDiagramEditorPlugin.ID, 0, e.getLocalizedMessage(), null));
      }
      newResource.unload();
    }
  }
Beispiel #16
0
  @Override
  public String startQA(
      final QAModel model,
      IProgressMonitor monitor,
      IFile iFile,
      QAXmlHandler xmlHandler,
      Map<String, String> tuMap) {
    if (monitor == null) {
      monitor = new NullProgressMonitor();
    }
    hasError = false;
    isContinue = false;
    // 目标语言
    final String target_lan = tuMap.get("target_lan");

    // 若未配置该目标语言的词典,退出程序的执行
    if (nonSpellTarLangList.indexOf(target_lan) != -1) {
      return "";
    }

    String targetPureText = TextUtil.resetSpecialString(tuMap.get("tarPureText"));

    String lineNumber = tuMap.get("lineNumber");
    String langPair = tuMap.get("langPair");
    String iFileFullPath = tuMap.get("iFileFullPath");
    String rowId = tuMap.get("rowId");

    if (spelling == null) {
      if (isHunspell) {
        spelling = new Hunspell(model.getShell());
        if (ignoreNontrans) {
          nontransOper = new NonTransElementOperate();
          nontransOper.openNonTransDB();
        }
      } else {
        spelling = new AspellChecker();
      }
    }

    // 若拼写检查器错误,或者出错,返回 null
    if (spelling == null || spelling.isError()) {
      return null;
    }

    // 如果该拼写检查实例为空,退出执行,并且下次遇到相同目标语言不再检查
    if (!spelling.checkLangAvailable(target_lan)) {
      nonSpellTarLangList.add(target_lan);
      if (!isHunspell) {
        Display.getDefault()
            .syncExec(
                new Runnable() {
                  public void run() {
                    String message = Messages.getString("qa.SpellQA.addTip1");
                    message = MessageFormat.format(message, new Object[] {target_lan});
                    isContinue =
                        MessageDialog.openConfirm(
                            model.getShell(), Messages.getString("qa.all.dialog.ok"), message);
                  }
                });

        if (!isContinue) {
          monitor.setCanceled(true);
        }
      }
      return "";
    }

    List<SingleWord> errorWords;
    if (isHunspell) {
      LinkedList<SingleWord> wordList = new LinkedList<SingleWord>();
      getSingleWords(targetPureText, wordList);
      errorWords = spelling.getErrorWords(null, wordList, target_lan);
    } else {
      LinkedList<SingleWord> wordList = new LinkedList<SingleWord>();
      getSingleWords(targetPureText, wordList);
      errorWords = spelling.getErrorWords(targetPureText, wordList, target_lan);
    }

    if (spelling.isError()) {
      return null;
    }

    // 开始输入结果
    if (errorWords == null || errorWords.size() == 0) {
      return "";
    }

    String errorTip = Messages.getString("qa.SpellQA.tip1");
    String qaType = Messages.getString("qa.all.qaItem.SpellQA");

    for (int i = 0; i < errorWords.size(); i++) {
      errorTip += "'" + errorWords.get(i).getPureWord() + "' 、";
    }
    errorTip = errorTip.substring(0, errorTip.length() - 1);
    errorTip += Messages.getString("qa.SpellQA.tip2");

    hasError = true;
    super.printQAResult(
        new QAResultBean(
            lineNumber,
            qaType,
            errorTip,
            iFileFullPath,
            langPair,
            rowId,
            tipLevel,
            QAConstant.QA_SPELL));
    String result = "";
    if (hasError && tipLevel == 0) {
      result = QAConstant.QA_SPELL;
    }
    return result;
  }
Beispiel #17
0
 @Override
 public void setCanceled(boolean b) {
   if (progressMonitor != null) {
     progressMonitor.setCanceled(b);
   }
 }
Beispiel #18
0
 /** @see org.eclipse.core.runtime.jobs.Job#run(org.eclipse.core.runtime.IProgressMonitor) */
 @Override
 public IStatus run(IProgressMonitor monitor) {
   StatusInfo result =
       new StatusInfo(
           IStatus.OK,
           "New POM ["
               + pomCreationDescription.getGroupId()
               + ":"
               + pomCreationDescription.getArtifactId()
               + ":"
               + pomCreationDescription.getVersion()
               + ":"
               + pomCreationDescription.getPackaging()
               + "']");
   try {
     RepositoryModelPersistence.addGroupIdAutocompleteProposal(
         pomCreationDescription.getGroupId());
     RepositoryModelPersistence.addArtifactIdAutocompleteProposal(
         pomCreationDescription.getArtifactId());
     // create a sample file
     monitor.beginTask("Creating pom.xml", 2);
     IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
     IProject selectedProject = root.getProject(projectName);
     if (!selectedProject.exists()) {
       throw new Exception(
           "Project \"" + pomCreationDescription.getArtifactId() + "\" does not exist.");
     }
     final IFile file = selectedProject.getFile(new Path("pom.xml"));
     try {
       InputStream stream =
           openContentStream(PomInteractionHelper.getPomContents(pomCreationDescription));
       if (file.exists()) {
         file.setContents(stream, true, true, monitor);
       } else {
         file.create(stream, true, monitor);
       }
       stream.close();
     } catch (IOException e) {
     }
     monitor.worked(1);
     monitor.setTaskName("Opening file for editing...");
     Display.getDefault()
         .asyncExec(
             new Runnable() {
               public void run() {
                 IWorkbenchPage page =
                     PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
                 try {
                   IDE.openEditor(page, file, true);
                 } catch (PartInitException e) {
                 }
               }
             });
     monitor.worked(1);
   } catch (Exception e) {
     logger.error(e.getMessage());
     monitor.setCanceled(true);
     result = new StatusInfo(IStatus.ERROR, "POM file creation error: " + e.getMessage());
   } finally {
     monitor.done();
   }
   return result;
 }
Beispiel #19
0
 /**
  * Set the progress monitor canceled.
  *
  * @param progress The progress monitor or <code>null</code>.
  */
 public static final void cancel(IProgressMonitor progress) {
   if (progress != null && !progress.isCanceled()) {
     progress.setCanceled(true);
   }
 }
  /*
   * (non-Javadoc)
   *
   * @see org.eclipse.ptp.rtsystem.IRuntimeSystem#shutdown()
   */
  public void shutdown() throws CoreException {
    DebugUtil.trace(
        DebugUtil.RTS_TRACING,
        "RTS {0}: shutdown",
        getResourceManager().getConfiguration().getName()); // $NON-NLS-1$

    /*
     * Remove listener to avoid re-entry
     */
    if (connection != null) {
      connection.removeConnectionChangeListener(fConnectionChangeHandler);
    }

    try {
      stopEvents();
    } catch (CoreException e) {
      // Ignore exception and shutdown anyway
      RMCorePlugin.log(e);
    }

    try {
      doShutdown();
    } finally {

      /*
       * Stop jobs that might be in the pending queue. Also stop the
       * thread that dispatches pending jobs.
       */
      if (jobQueueThread != null) {
        jobQueueThread.interrupt();
        for (Job job : pendingJobQueue) {
          job.cancel();
        }
      }

      /*
       * Stop jobs that are running or that already finished.
       */
      Iterator<Job> iterator = jobs.values().iterator();
      while (iterator.hasNext()) {
        Job job = iterator.next();
        job.cancel();
        iterator.remove();
      }

      synchronized (this) {
        if (startupMonitor != null) {
          startupMonitor.setCanceled(true);
        }
      }

      /*
       * Close the the connection.
       */
      if (connection != null) {
        connection.close();
      }

      jobQueueThread = null;
      fireRuntimeShutdownStateEvent(eventFactory.newRuntimeShutdownStateEvent());
    }
  }