예제 #1
0
 /** @return a tuple with the process created and a string representation of the cmdarray. */
 public Tuple<Process, String> run(
     String[] cmdarray, File workingDir, IPythonNature nature, IProgressMonitor monitor) {
   if (monitor == null) {
     monitor = new NullProgressMonitor();
   }
   String executionString = getArgumentsAsStr(cmdarray);
   monitor.setTaskName("Executing: " + executionString);
   monitor.worked(5);
   Process process = null;
   try {
     monitor.setTaskName("Making pythonpath environment..." + executionString);
     String[] envp = null;
     if (nature != null) {
       envp =
           getEnvironment(
               nature,
               nature.getProjectInterpreter(),
               nature.getRelatedInterpreterManager()); // Don't remove as it *should* be updated
       // based on the nature)
     }
     // Otherwise, use default (used when configuring the interpreter for instance).
     monitor.setTaskName("Making exec..." + executionString);
     if (workingDir != null) {
       if (!workingDir.isDirectory()) {
         throw new RuntimeException(
             org.python.pydev.shared_core.string.StringUtils.format(
                 "Working dir must be an existing directory (received: %s)", workingDir));
       }
     }
     process = createProcess(cmdarray, envp, workingDir);
   } catch (Exception e) {
     throw new RuntimeException(e);
   }
   return new Tuple<Process, String>(process, executionString);
 }
 @Override
 public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
   try {
     result = CommandResult.SUCCESS;
     if (m_scope == null && m_variables == null) {
       monitor.setTaskName("Clearing all variables and scopes");
       ISharedDataService svc = (ISharedDataService) ServiceManager.get(ISharedDataService.class);
       for (String scope : svc.getSharedScopes()) {
         svc.removeSharedScope(scope);
       }
       svc.getSharedScope(ISharedDataService.GLOBAL_SCOPE).clear();
     } else if (m_variables != null) {
       monitor.beginTask(
           "Clearing variables in scope " + m_scope.getScopeName(), m_variables.size());
       for (SharedVariable var : m_variables) {
         monitor.subTask("Removing variable " + var.name);
         m_scope.clear(var.name);
         monitor.worked(1);
         if (monitor.isCanceled()) return;
       }
     } else {
       monitor.setTaskName("Clearing variables in scope " + m_scope.getScopeName());
       m_scope.clear();
     }
     monitor.done();
   } catch (Exception ex) {
     ex.printStackTrace();
     message = ex.getLocalizedMessage();
     result = CommandResult.FAILED;
   }
 }
예제 #3
0
파일: Transfer.java 프로젝트: ranbirs/esftp
  public void setTask(int template, String task[]) {
    if (m_monitor != null) {
      switch (template) {
        case TASK_CONNECT:
          m_monitor.setTaskName("Connecting to SFTP Site");
          break;

        case TASK_SCANNING:
          m_monitor.setTaskName("Scanning directories");
          break;

        case TASK_TRANSFER:
          if (task.length == 2) {
            m_monitor.setTaskName(task[0] + ":\t" + task[1]);
          }
          break;

        case TASK_COMPLETE:
          m_monitor.setTaskName("Transfer completed");
          break;

        case TASK_ERROR:
          if (task.length >= 1) {
            m_monitor.setTaskName("ERROR: " + task[0]);
            for (int a = 0; a < task.length; a++) {
              m_output.append(task[a] + "\n");
              System.out.println(task[a]);
            }
          }
          break;
      }
    }
  }
예제 #4
0
  /**
   * @param process process from where the output should be gotten
   * @param executionString string to execute (only for errors)
   * @param monitor monitor for giving progress
   * @return a tuple with the output of stdout and stderr
   */
  public static Tuple<String, String> getProcessOutput(
      Process process, String executionString, IProgressMonitor monitor, String encoding) {
    if (monitor == null) {
      monitor = new NullProgressMonitor();
    }
    if (process != null) {

      try {
        process.getOutputStream().close(); // we won't write to it...
      } catch (IOException e2) {
      }

      monitor.setTaskName("Reading output...");
      monitor.worked(5);
      // No need to synchronize as we'll waitFor() the process before getting the contents.
      ThreadStreamReader std = new ThreadStreamReader(process.getInputStream(), false, encoding);
      ThreadStreamReader err = new ThreadStreamReader(process.getErrorStream(), false, encoding);

      std.start();
      err.start();

      boolean interrupted = true;
      while (interrupted) {
        interrupted = false;
        try {
          monitor.setTaskName("Waiting for process to finish.");
          monitor.worked(5);
          process.waitFor(); // wait until the process completion.
        } catch (InterruptedException e1) {
          interrupted = true;
        }
      }

      try {
        // just to see if we get something after the process finishes (and let the other threads
        // run).
        Object sync = new Object();
        synchronized (sync) {
          sync.wait(50);
        }
      } catch (Exception e) {
        // ignore
      }
      return new Tuple<String, String>(std.getContents(), err.getContents());

    } else {
      try {
        throw new CoreException(
            PydevPlugin.makeStatus(
                IStatus.ERROR,
                "Error creating process - got null process(" + executionString + ")",
                new Exception("Error creating process - got null process.")));
      } catch (CoreException e) {
        Log.log(IStatus.ERROR, e.getMessage(), e);
      }
    }
    return new Tuple<String, String>(
        "", "Error creating process - got null process(" + executionString + ")"); // no output
  }
예제 #5
0
  protected RefactoringStatus doCheckFinalConditions(
      IProgressMonitor pm, CheckConditionsContext context) throws CoreException {
    try {
      pm.beginTask("", 18); // $NON-NLS-1$
      pm.setTaskName(RefactoringCoreMessages.RenameFieldRefactoring_checking);
      RefactoringStatus result = new RefactoringStatus();
      result.merge(Checks.checkIfCuBroken(fField));
      if (result.hasFatalError()) return result;
      result.merge(checkNewElementName(getNewElementName()));
      pm.worked(1);
      result.merge(checkEnclosingHierarchy());
      pm.worked(1);
      result.merge(checkNestedHierarchy(fField.getDeclaringType()));
      pm.worked(1);

      if (fUpdateReferences) {
        pm.setTaskName(RefactoringCoreMessages.RenameFieldRefactoring_searching);
        fReferences = getReferences(new SubProgressMonitor(pm, 3), result);
        pm.setTaskName(RefactoringCoreMessages.RenameFieldRefactoring_checking);
      } else {
        fReferences = new SearchResultGroup[0];
        pm.worked(3);
      }

      if (fUpdateReferences) result.merge(analyzeAffectedCompilationUnits());
      else Checks.checkCompileErrorsInAffectedFile(result, fField.getResource());

      if (getGetter() != null && fRenameGetter) {
        result.merge(checkAccessor(new SubProgressMonitor(pm, 1), getGetter(), getNewGetterName()));
        result.merge(
            Checks.checkIfConstructorName(
                getGetter(), getNewGetterName(), fField.getDeclaringType().getElementName()));
      } else {
        pm.worked(1);
      }

      if (getSetter() != null && fRenameSetter) {
        result.merge(checkAccessor(new SubProgressMonitor(pm, 1), getSetter(), getNewSetterName()));
        result.merge(
            Checks.checkIfConstructorName(
                getSetter(), getNewSetterName(), fField.getDeclaringType().getElementName()));
      } else {
        pm.worked(1);
      }

      result.merge(createChanges(new SubProgressMonitor(pm, 10)));
      if (result.hasFatalError()) return result;

      return result;
    } finally {
      pm.done();
    }
  }
 @Override
 public ArtifactKey identify(File file, IProgressMonitor monitor) throws CoreException {
   if (monitor == null) {
     monitor = new NullProgressMonitor();
   }
   IndexManager indexManager = MavenPlugin.getIndexManager();
   IIndex index = indexManager.getAllIndexes();
   IndexedArtifactFile info = null;
   try {
     if (monitor.isCanceled()) {
       return null;
     }
     monitor.setTaskName("Checking global m2e Nexus index for " + file.getName());
     info = index.identify(file);
   } catch (Exception e) {
     // ignore
   }
   ArtifactKey artifact = null;
   if (info != null) {
     artifact = info.getArtifactKey();
     if (artifact != null) {
       return artifact;
     }
   }
   if (indexManager instanceof NexusIndexManager) {
     NexusIndexManager nexusIndexManager = (NexusIndexManager) indexManager;
     for (IRepository repository : globalRepositories) {
       NexusIndex nexusIndex = nexusIndexManager.getIndex(repository);
       if (nexusIndex != null) {
         try {
           if (monitor.isCanceled()) {
             return null;
           }
           monitor.setTaskName(
               "Checking Nexus index of '"
                   + repository.getId()
                   + "' repository for "
                   + file.getName());
           info = nexusIndex.identify(file);
         } catch (Exception t) {
           // ignore
         }
         if (info != null) {
           artifact = info.getArtifactKey();
           if (artifact != null) {
             return artifact;
           }
         }
       }
     }
   }
   return artifact;
 }
예제 #7
0
 /**
  * Set the progress monitor done.
  *
  * @param progress The progress monitor or <code>null</code>.
  */
 public static final void done(IProgressMonitor progress) {
   if (progress != null) {
     progress.setTaskName(""); // $NON-NLS-1$
     progress.subTask(""); // $NON-NLS-1$
     progress.done();
   }
 }
  /** {@inheritDoc} */
  @Override
  protected IStatus run(IProgressMonitor pMonitor) {
    progressMonitor = pMonitor;
    progressMonitor.setTaskName("Waiting...");

    try {

      final Display display = Activator.getDefault().getWorkbench().getDisplay();
      display.syncExec(
          new Runnable() {

            public void run() {
              MessageBox turnOn = new MessageBox(new Shell(display), SWT.ICON_INFORMATION);
              if (serviceMode) {
                turnOn.setMessage("Turn On connected device in service mode and press OK.");
              } else {
                turnOn.setMessage("Turn On connected device in normal mode and press OK.");
              }
              if (turnOn.open() == SWT.OK) {
                result = "OK";
              } else {
                result = "CANCEL";
              }
            }
          });

      return new Status(IStatus.OK, Activator.PLUGIN_ID, result);
    } catch (Exception e) {
      return new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Command failed", e);
    } finally {
      progressMonitor.done();
    }

    // return null;
  }
예제 #9
0
  @Override
  public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
    try {
      monitor.setTaskName("Retrieving LOG file for procedure " + m_proc.getProcName());

      IFileManager fileMgr = (IFileManager) ServiceManager.get(IFileManager.class);
      String path =
          fileMgr.getServerFilePath(m_proc.getProcId(), ServerFileType.EXECUTOR_LOG, monitor);
      Logger.debug("LOG file path: '" + path + "'", Level.PROC, this);

      logFile = (LogFile) fileMgr.getServerFile(path, ServerFileType.EXECUTOR_LOG, null, monitor);

      List<IServerFileLine> lines = logFile.getLines();

      monitor.beginTask("Exporting log data", lines.size());

      PrintWriter writer =
          new PrintWriter(new OutputStreamWriter(new FileOutputStream(m_destinationFileName)));
      for (IServerFileLine line : lines) {
        writer.println(line.toString());
        monitor.worked(1);
        if (monitor.isCanceled()) break;
      }
      writer.close();
      monitor.done();
      result = CommandResult.SUCCESS;
    } catch (Exception e) {
      Logger.error("Could retrieve LOG:" + e.getLocalizedMessage(), Level.PROC, this);
    }
    monitor.done();
  }
  protected IStatus run(IProgressMonitor monitor) {
    ArrayList<IFile> files = new ArrayList<IFile>(10);

    for (IResource resource : resources) {
      getFilesFromResouce(resource, files);
    }

    int count = files.size();

    monitor.beginTask("Validating ...", count);

    int completed = 0;
    for (IFile file : files.toArray(new IFile[0])) {
      monitor.setTaskName(
          "Validating "
              + file.getProjectRelativePath().toString()
              + " ("
              + (completed + 1)
              + "/"
              + count
              + ")");

      validateFile(file, monitor);
      monitor.worked(++completed);

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

    return Status.OK_STATUS;
  }
예제 #11
0
  void doDebug(IProgressMonitor monitor) throws InterruptedException {
    monitor.setTaskName(
        "Connecting debugger "
            + session.getName()
            + " to "
            + session.getHost()
            + ":"
            + session.getJdb());

    Map<String, String> parameters = new HashMap<String, String>();
    parameters.put("hostname", session.getHost());
    parameters.put("port", session.getJdb() + "");
    parameters.put("timeout", session.getTimeout() + "");
    IVMConnector connector = JavaRuntime.getDefaultVMConnector();

    while (!monitor.isCanceled()) {

      try {
        connector.connect(parameters, monitor, launch);
        break;
      } catch (Exception e) {
        Thread.sleep(500);
      }
    }
  }
  public static IStatus assignPort(
      IShellProvider shellProvider, IProgressMonitor monitor, BTTargetPhone phone) {
    try {
      monitor.beginTask("Scanning BT device for OBEX service", 1);
      monitor.setTaskName("Scanning BT device for OBEX service");
      int port = ServiceSearch.search(phone.getAddress());
      if (port != -1) {
        phone.assignPort(port);
      } else {
        return new Status(
            IStatus.ERROR,
            TargetPhonePlugin.PLUGIN_ID,
            "The device connected to has no OBEX service");
      }

      return Status.OK_STATUS;
    } catch (Exception e) {
      return new Status(
          IStatus.ERROR,
          TargetPhonePlugin.PLUGIN_ID,
          "The device connected to has no OBEX service",
          e);
    } finally {
      monitor.worked(1);
    }
  }
예제 #13
0
  private void createBranch(final String textForBranch, RevCommit commit, IProgressMonitor monitor)
      throws CoreException, GitAPIException {
    monitor.setTaskName(UIText.FetchGerritChangePage_CreatingBranchTaskName);
    CreateLocalBranchOperation bop =
        new CreateLocalBranchOperation(repository, textForBranch, commit);
    bop.execute(monitor);
    CheckoutCommand co = new Git(repository).checkout();
    try {
      co.setName(textForBranch).call();
    } catch (CheckoutConflictException e) {
      final CheckoutResult result = co.getResult();

      if (result.getStatus() == Status.CONFLICTS) {
        final Shell shell = getWizard().getContainer().getShell();

        shell
            .getDisplay()
            .asyncExec(
                new Runnable() {
                  public void run() {
                    new CheckoutConflictDialog(shell, repository, result.getConflictList()).open();
                  }
                });
      }
    }
    monitor.worked(1);
  }
  protected IResource[] checkOverwriteOfDirtyResources(
      IResource[] resources, IProgressMonitor monitor) throws CVSException, InterruptedException {
    List dirtyResources = new ArrayList();
    IResource[] selectedResources = getSelectedResources();

    try {
      monitor = Policy.monitorFor(monitor);
      monitor.beginTask(null, selectedResources.length * 100);
      monitor.setTaskName(CVSUIMessages.ReplaceWithAction_calculatingDirtyResources);
      for (int i = 0; i < selectedResources.length; i++) {
        IResource resource = selectedResources[i];
        ICVSResource cvsResource = getCVSResourceFor(resource);
        if (cvsResource.isModified(Policy.subMonitorFor(monitor, 100))) {
          dirtyResources.add(resource);
        }
      }
    } finally {
      monitor.done();
    }

    PromptingDialog dialog =
        new PromptingDialog(
            getShell(),
            selectedResources,
            getPromptCondition(
                (IResource[]) dirtyResources.toArray(new IResource[dirtyResources.size()])),
            CVSUIMessages.ReplaceWithAction_confirmOverwrite);
    return dialog.promptForMultiple();
  }
예제 #15
0
 /**
  * Used to make the work communication (also checks to see if it has been cancelled)
  *
  * @param desc Some string to be shown in the progress
  */
 public synchronized void communicateWork(String desc) throws OperationCanceledException {
   IProgressMonitor monitor = getMonitor();
   if (monitor != null) {
     monitor.setTaskName(desc);
     monitor.worked(1);
     checkCancelled();
   }
 }
예제 #16
0
 /**
  * Set task name.
  *
  * @see IProgressMonitor#setTaskName(String)
  * @since 2.0
  */
 public void setTaskName(String name) {
   this.taskString = name;
   this.subTaskString = ""; // $NON-NLS-1$
   this.showDetails = false;
   this.totalCopyCount = 0;
   monitor.subTask(""); // $NON-NLS-1$
   monitor.setTaskName(name);
 }
예제 #17
0
파일: DCLBuilder.java 프로젝트: joyeliz/DCL
 protected void fullBuild(final IProgressMonitor monitor)
     throws CoreException, IOException, ParseException {
   monitor.setTaskName("Checking architecture");
   monitor.subTask("loading dependencies");
   final Architecture architecture = ArchitectureUtils.initializeArchitecture(getProject());
   monitor.beginTask("Checking architecture", architecture.getProjectClasses().size());
   getProject().accept(new FullBuildVisitor(architecture, monitor, true));
 }
  /**
   * Allows a given set or subset of runtime detectors the ability to search through a folder
   *
   * @param directory
   * @param runtimeCollector
   * @param depth
   * @param runtimeDetectors
   * @param monitor
   */
  public void searchDirectory(
      File directory,
      List<RuntimeDefinition> runtimeCollector,
      int depth,
      Set<IRuntimeDetector> runtimeDetectors,
      IProgressMonitor monitor) {

    if (depth == 0 || monitor.isCanceled() || directory == null || !directory.isDirectory()) {
      return;
    }

    int workSize = (1000 + (10 * runtimeDetectors.size()));
    monitor.beginTask(
        Messages.JBossRuntimeLocator_Searching + directory.getAbsolutePath(), workSize);
    monitor.setTaskName(Messages.JBossRuntimeLocator_Searching + directory.getAbsolutePath());

    for (IRuntimeDetector detector : runtimeDetectors) {
      if (monitor.isCanceled()) {
        return;
      }
      if (!detector.isEnabled()) {
        monitor.worked(10);
        continue;
      }
      RuntimeDefinition runtimeDefinition =
          detector.getRuntimeDefinition(directory, new SubProgressMonitor(monitor, 10));
      if (runtimeDefinition != null) {
        runtimeCollector.add(runtimeDefinition);
        monitor.done();
        return;
      }
    }

    File[] files =
        directory.listFiles(
            new FileFilter() {
              public boolean accept(File file) {
                return file.isDirectory();
              }
            });

    SubProgressMonitor childrenMonitor = new SubProgressMonitor(monitor, 1000);
    childrenMonitor.beginTask("", 100 * files.length);
    if (files != null) {
      int size = files.length;
      for (int i = 0; i < size; i++) {
        if (monitor.isCanceled()) return;
        searchDirectory(
            files[i],
            runtimeCollector,
            depth - 1,
            runtimeDetectors,
            new SubProgressMonitor(childrenMonitor, 100));
      }
    }
    childrenMonitor.done();
  }
 private void checkOverridden(RefactoringStatus status, IProgressMonitor pm)
     throws JavaModelException {
   pm.beginTask("", 9); // $NON-NLS-1$
   pm.setTaskName(RefactoringCoreMessages.InlineMethodRefactoring_checking_overridden);
   MethodDeclaration decl = fSourceProvider.getDeclaration();
   IMethod method = (IMethod) decl.resolveBinding().getJavaElement();
   if (method == null || Flags.isPrivate(method.getFlags())) {
     pm.worked(8);
     return;
   }
   IType type = method.getDeclaringType();
   ITypeHierarchy hierarchy = type.newTypeHierarchy(new SubProgressMonitor(pm, 6));
   checkSubTypes(status, method, hierarchy.getAllSubtypes(type), new SubProgressMonitor(pm, 1));
   checkSuperClasses(
       status, method, hierarchy.getAllSuperclasses(type), new SubProgressMonitor(pm, 1));
   checkSuperInterfaces(
       status, method, hierarchy.getAllSuperInterfaces(type), new SubProgressMonitor(pm, 1));
   pm.setTaskName(""); // $NON-NLS-1$
 }
예제 #20
0
  /* (non-Javadoc)
   * @see org.eclipse.egit.core.op.IEGitOperation#execute(org.eclipse.core.runtime.IProgressMonitor)
   */
  public void execute(IProgressMonitor m) throws CoreException {
    if (m == null) {
      m = new NullProgressMonitor();
    }

    m.beginTask(CoreText.ConnectProviderOperation_connecting, 100 * projects.size());
    try {

      for (Iterator iterator = projects.keySet().iterator(); iterator.hasNext(); ) {
        IProject project = (IProject) iterator.next();
        m.setTaskName(
            NLS.bind(CoreText.ConnectProviderOperation_ConnectingProject, project.getName()));
        // TODO is this the right location?
        if (GitTraceLocation.CORE.isActive())
          GitTraceLocation.getTrace()
              .trace(
                  GitTraceLocation.CORE.getLocation(),
                  "Locating repository for " + project); // $NON-NLS-1$

        Collection<RepositoryMapping> repos =
            new RepositoryFinder(project).find(new SubProgressMonitor(m, 40));
        File suggestedRepo = projects.get(project);
        RepositoryMapping actualMapping = findActualRepository(repos, suggestedRepo);
        if (actualMapping != null) {
          GitProjectData projectData = new GitProjectData(project);
          try {
            projectData.setRepositoryMappings(Arrays.asList(actualMapping));
            projectData.store();
          } catch (CoreException ce) {
            GitProjectData.delete(project);
            throw ce;
          } catch (RuntimeException ce) {
            GitProjectData.delete(project);
            throw ce;
          }
          RepositoryProvider.map(project, GitProvider.class.getName());
          projectData = GitProjectData.get(project);
          project.refreshLocal(IResource.DEPTH_INFINITE, new SubProgressMonitor(m, 50));
          m.worked(10);
        } else {
          // TODO is this the right location?
          if (GitTraceLocation.CORE.isActive())
            GitTraceLocation.getTrace()
                .trace(
                    GitTraceLocation.CORE.getLocation(),
                    "Attempted to share project without repository ignored :" //$NON-NLS-1$
                        + project);
          m.worked(60);
        }
      }
    } finally {
      m.done();
    }
  }
 private String[] runChildTest(
     int depth, TestProgressMonitor root, IProgressMonitor child, int ticks) {
   ArrayList results = new ArrayList();
   child.beginTask("beginTask" + depth, ticks);
   results.add(root.getTaskName());
   child.subTask("subTask" + depth);
   results.add(root.getSubTaskName());
   child.setTaskName("setTaskName" + depth);
   results.add(root.getTaskName());
   return (String[]) results.toArray(new String[results.size()]);
 }
예제 #22
0
  @Override
  protected boolean executeAnalysis(final IProgressMonitor monitor) throws TmfAnalysisException {
    /* Get the graph */
    TmfGraphBuilderModule graphModule = getGraph();
    if (graphModule == null) {
      Activator.getInstance()
          .logWarning("No graph was found to execute the critical path on"); // $NON-NLS-1$
      return true;
    }
    graphModule.schedule();

    monitor.setTaskName(
        NLS.bind(Messages.CriticalPathModule_waitingForGraph, graphModule.getName()));
    if (!graphModule.waitForCompletion(monitor)) {
      Activator.getInstance()
          .logInfo(
              "Critical path execution: graph building was cancelled.  Results may not be accurate."); //$NON-NLS-1$
      return false;
    }
    TmfGraph graph = graphModule.getGraph();
    if (graph == null) {
      throw new TmfAnalysisException(
          "Critical Path analysis: graph "
              + graphModule.getName()
              + " is null"); //$NON-NLS-1$//$NON-NLS-2$
    }

    /* Get the worker id */
    Object workerObj = getParameter(PARAM_WORKER);
    if (workerObj == null) {
      return false;
    }
    if (!(workerObj instanceof IGraphWorker)) {
      throw new IllegalStateException("Worker parameter must be an IGraphWorker"); // $NON-NLS-1$
    }
    IGraphWorker worker = (IGraphWorker) workerObj;

    TmfVertex head = graph.getHead(worker);
    if (head == null) {
      /* Nothing happens with this worker, return an empty graph */
      fCriticalPath = new TmfGraph();
      return true;
    }

    ICriticalPathAlgorithm cp = getAlgorithm(graph);
    try {
      fCriticalPath = cp.compute(head, null);
      return true;
    } catch (CriticalPathAlgorithmException e) {
      Activator.getInstance().logError(NonNullUtils.nullToEmptyString(e.getMessage()), e);
    }
    return false;
  }
예제 #23
0
  public static void buildKeysForRegularEntries(
      IProgressMonitor monitor,
      ModulesFoundStructure modulesFound,
      PyPublicTreeMap<ModulesKey, ModulesKey> keys,
      boolean includeOnlySourceModules) {
    String[] dottedValidSourceFiles = FileTypesPreferencesPage.getDottedValidSourceFiles();

    int j = 0;
    FastStringBuffer buffer = new FastStringBuffer();
    // now, create in memory modules for all the loaded files (empty modules).
    for (Iterator<Map.Entry<File, String>> iterator =
            modulesFound.regularModules.entrySet().iterator();
        iterator.hasNext() && monitor.isCanceled() == false;
        j++) {
      Map.Entry<File, String> entry = iterator.next();
      String m = entry.getValue();

      if (m != null) {
        if (j % 20 == 0) {
          // no need to report all the time (that's pretty fast now)
          buffer.clear();
          monitor.setTaskName(buffer.append("Module resolved: ").append(m).toString());
          monitor.worked(1);
        }

        // we don't load them at this time.
        File f = entry.getKey();

        if (includeOnlySourceModules) {
          // check if we should include only source modules
          if (!PythonPathHelper.isValidSourceFile(f.getName())) {
            continue;
          }
        }
        ModulesKey modulesKey = new ModulesKey(m, f);

        // no conflict (easy)
        if (!keys.containsKey(modulesKey)) {
          keys.put(modulesKey, modulesKey);

        } else {
          // we have a conflict, so, let's resolve which one to keep (the old one or this one)
          if (PythonPathHelper.isValidSourceFile(f.getName(), dottedValidSourceFiles)) {
            // source files have priority over other modules (dlls) -- if both are source, there is
            // no real way to resolve
            // this priority, so, let's just add it over.
            keys.put(modulesKey, modulesKey);
          }
        }
      }
    }
  }
 /** Run the collector. */
 @Override
 public void run() {
   clearCollector(this);
   if (taskName != null) {
     monitor.setTaskName(taskName);
   }
   if (subTask != null) {
     monitor.subTask(subTask);
   }
   if (worked > 0) {
     monitor.internalWorked(worked);
   }
 }
예제 #25
0
  private void createTag(
      final RefSpec spec, final String textForTag, RevCommit commit, IProgressMonitor monitor)
      throws CoreException {
    monitor.setTaskName(UIText.FetchGerritChangePage_CreatingTagTaskName);
    final TagBuilder tag = new TagBuilder();
    PersonIdent personIdent = new PersonIdent(repository);

    tag.setTag(textForTag);
    tag.setTagger(personIdent);
    tag.setMessage(NLS.bind(UIText.FetchGerritChangePage_GeneratedTagMessage, spec.getSource()));
    tag.setObjectId(commit);
    new TagOperation(repository, tag, false).execute(monitor);
    monitor.worked(1);
  }
예제 #26
0
    /** {@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();
    }
  @Override
  public void run(IProgressMonitor monitor) throws CoreException {
    if (monitor == null) monitor = new NullProgressMonitor();
    try {
      monitor.beginTask("", 1); // $NON-NLS-1$
      monitor.setTaskName(CodeGenerationMessages.GenerateToStringOperation_description);

      AbstractTypeDeclaration declaration =
          (AbstractTypeDeclaration)
              ASTNodes.findDeclaration(fContext.getTypeBinding(), fRewrite.getRoot());
      ListRewrite rewriter =
          fRewrite
              .getASTRewrite()
              .getListRewrite(declaration, declaration.getBodyDeclarationsProperty());
      if (fContext.getTypeBinding() != null && rewriter != null) {

        MethodDeclaration toStringMethod = fGenerator.generateToStringMethod();

        List<BodyDeclaration> list = declaration.bodyDeclarations();
        BodyDeclaration replace = findMethodToReplace(list, toStringMethod);
        if (replace == null
            || ((Boolean)
                    toStringMethod.getProperty(AbstractToStringGenerator.OVERWRITE_METHOD_PROPERTY))
                .booleanValue()) insertMethod(toStringMethod, rewriter, replace);

        List<MethodDeclaration> helperMethods = fGenerator.generateHelperMethods();
        for (Iterator<MethodDeclaration> iterator = helperMethods.iterator();
            iterator.hasNext(); ) {
          MethodDeclaration method = iterator.next();
          replace = findMethodToReplace(list, method);
          if (replace == null
              || ((Boolean) method.getProperty(AbstractToStringGenerator.OVERWRITE_METHOD_PROPERTY))
                  .booleanValue()) {
            insertMethod(method, rewriter, replace);
          }
        }

        JavaModelUtil.applyEdit(
            (ICompilationUnit) fUnit.getJavaElement(),
            fRewrite.createChange(true).getEdit(),
            false,
            monitor);
      }

    } finally {
      monitor.done();
    }
  }
    @Override
    public IStatus run(final IProgressMonitor monitor) {
      monitor.beginTask(Messages.LifecycleDeployHandler_Task_Starting, this.resources.length);
      for (final IResource resource : this.resources) {
        final IProject project = resource.getProject();
        monitor.setTaskName(Messages.LifecycleDeployHandler_Task_RunFor + project.getName());

        final IMavenJobData jobData =
            new IMavenJobData() {

              @Override
              public void manipulateRequest(final MavenExecutionRequest request) {
                // empty
              }

              @Override
              public IProject getProject() {
                return project;
              }

              @Override
              public String[] getMavenCommands() {
                return new String[] {"deploy"}; // $NON-NLS-1$
              }

              @Override
              public boolean canProcessRequest(
                  final MavenExecutionRequest request, final IMavenProjectFacade projectFacade) {
                return true;
              }
            };
        final MavenJob job = new MavenJob(jobData);
        final SubProgressMonitor subMonitor =
            new SubProgressMonitor(monitor, 1, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK);
        final IStatus mavenResult = job.execute(subMonitor);
        subMonitor.done();

        if (!mavenResult.isOK()) {
          monitor.done();
          this.done(mavenResult);
          return mavenResult;
        }
      }
      monitor.done();
      this.done(Status.OK_STATUS);
      return Status.OK_STATUS;
    }
  /** Performs the import. */
  public void performImport(final IProgressMonitor monitor) {

    // need to disable the workspace refreshing
    boolean refresh = RefreshJob.getInstance().isEnabled();
    if (refresh) {
      // disable resource refreshing during import
      //
      RefreshJob.getInstance().setEnabled(false);
    }

    try {
      if (monitor != null) {
        monitor.setTaskName(ImportResources.ConfigurationImportService_MSG3);
      }

      if (isSpecsOnly()) {
        specsMgr.doImport(data.specs);
      } else {
        LibraryImportManager importingMgr = new LibraryImportManager(diffMgr, data.importList);
        importingMgr.doMerge(data.replaceExisting, monitor);
      }

      // refresh library files in workspace
      //
      MethodLibrary lib = LibraryService.getInstance().getCurrentMethodLibrary();
      ResourceUtil.refreshResources(lib, monitor);

    } catch (Exception e) {
      ImportPlugin.getDefault().getLogger().logError(e);
    } finally {
      if (refresh) {
        // re-enable resource refreshing
        //
        RefreshJob.getInstance().setEnabled(true);
      }
      if (upGradeInfo != null) {
        upGradeInfo.removeCopiedLibrary();
        upGradeInfo = null;
      }
    }

    try {
      postImportOperation(monitor);
    } catch (Exception e) {
      ImportPlugin.getDefault().getLogger().logError(e);
    }
  }
  public void run() throws Exception {
    try {
      monitor.setTaskName("scanning Compilation Units");

      onPreRun();

      if (monitor.isCanceled()) {
        throw new OperationCanceledException();
      }

      // *** the biggy ***
      monitor.beginTask("treating files", compilationUnits.size());

      // Step 1 / 4: handle prepare compilation units
      for (ICompilationUnit unit : compilationUnits) {
        // monitor.setTaskName(unit.getElementName());

        if (isAcceptCompilationUnit(unit)) {
          countCompilationUnit++;

          IProgressMonitor subProgress = new NullProgressMonitor();
          // new SubProgressMonitor(monitor, 100);  ///??? does not work... blink on screen, display
          // last level?
          IProgressMonitor oldMonitor = monitor;
          monitor = subProgress; // HACK...
          try {

            handleCompilationUnit(unit);

          } finally {
            monitor = oldMonitor; // RESTORE from HACK...
          }
        }

        if (monitor.isCanceled()) {
          throw new OperationCanceledException();
        }

        monitor.worked(1);
      }

    } catch (Exception ex) {
      addErrorMsg("Failed :" + ex.toString());
    } finally {
      onFinishRun();
    }
  }