Пример #1
0
  @Override
  public void buildNow(IProgressMonitor monitor) throws CoreException {
    if (monitor.isCanceled()) {
      return;
    }
    try {
      monitor.beginTask(Messages.MSBuild_BuildProjectTask, 10);
      // TODO: use extension point to create the generator.
      WPProjectGenerator creator = new WPProjectGenerator(getProject(), null, WPProjectUtils.WP8);
      SubProgressMonitor generateMonitor = new SubProgressMonitor(monitor, 1);
      File vstudioProjectDir = creator.generateNow(generateMonitor);

      monitor.worked(4);
      if (monitor.isCanceled()) {
        return;
      }
      doBuildProject(vstudioProjectDir, generateMonitor);
      HybridProject hybridProject = HybridProject.getHybridProject(this.getProject());
      if (hybridProject == null) {
        throw new CoreException(
            new Status(IStatus.ERROR, WPCore.PLUGIN_ID, Messages.MSBuild_NoHybridError));
      }
      if (isRelease()) {
        setBuildArtifact(new File(getBuildDir(vstudioProjectDir), RELEASE_XAP_NAME));
      } else {
        setBuildArtifact(new File(getBuildDir(vstudioProjectDir), DEBUG_XAP_NAME));
      }
    } finally {
      monitor.done();
    }
  }
 private void removeFilesInIndex(
     List<Object> filesToRemove,
     List<IIndexFragmentFile> indexFilesToRemove,
     IProgressMonitor monitor)
     throws InterruptedException, CoreException {
   if (!filesToRemove.isEmpty() || !indexFilesToRemove.isEmpty()) {
     fIndex.acquireWriteLock();
     try {
       for (Object tu : filesToRemove) {
         if (monitor.isCanceled()) {
           return;
         }
         IIndexFileLocation ifl = fResolver.resolveFile(tu);
         if (ifl == null) continue;
         IIndexFragmentFile[] ifiles = fIndex.getWritableFiles(ifl);
         for (IIndexFragmentFile ifile : ifiles) {
           fIndex.clearFile(ifile);
         }
         incrementRequestedFilesCount(-1);
       }
       for (IIndexFragmentFile ifile : indexFilesToRemove) {
         if (monitor.isCanceled()) {
           return;
         }
         fIndex.clearFile(ifile);
         incrementRequestedFilesCount(-1);
       }
     } finally {
       fIndex.releaseWriteLock();
     }
   }
   filesToRemove.clear();
 }
Пример #3
0
  // filtering things...
  protected void setFilter(String text, IProgressMonitor monitor, boolean updateFilterMatcher) {
    if (monitor.isCanceled()) return;

    if (updateFilterMatcher) {
      // just so that subclasses may already treat it.
      if (fFilterMatcher.lastPattern.equals(text)) {
        // no actual change...
        return;
      }
      fFilterMatcher.setFilter(text);
      if (monitor.isCanceled()) return;
    }

    getTreeViewer().getTree().setRedraw(false);
    getTreeViewer().getTree().getParent().setRedraw(false);
    try {
      if (monitor.isCanceled()) return;
      getTreeViewer().refresh();
      if (monitor.isCanceled()) return;
      getTreeViewer().expandAll();
    } finally {
      getTreeViewer().getTree().setRedraw(true);
      getTreeViewer().getTree().getParent().setRedraw(true);
    }
  }
 /**
  * Maps for all nodes from a project their UUIDs to the name of its corresponding class to
  * generate
  *
  * @param project the project
  * @param basePath the base path
  * @throws StopConversionException
  */
 private void determineClassNamesForProject(IProjectPO project, String basePath)
     throws StopConversionException {
   String projectName = StringConstants.EMPTY;
   try {
     projectName = Utils.translateToPackageName(project);
   } catch (InvalidNodeNameException e) {
     displayErrorForInvalidName(project);
     throw new StopConversionException();
   }
   String projectPath = basePath + StringConstants.SLASH + projectName;
   for (INodePO node : project.getExecObjCont().getExecObjList()) {
     if (progressMonitor.isCanceled()) {
       throw new StopConversionException();
     }
     String path = projectPath + StringConstants.SLASH + EXEC_PATH;
     determineClassNamesForNode(node, path);
   }
   for (INodePO node : project.getSpecObjCont().getSpecObjList()) {
     if (progressMonitor.isCanceled()) {
       throw new StopConversionException();
     }
     String path = projectPath + StringConstants.SLASH + SPEC_PATH;
     determineClassNamesForNode(node, path);
   }
 }
Пример #5
0
  /** Job's main routine which starts and monitors WorkerThread */
  @Override
  protected IStatus run(final IProgressMonitor monitor) {
    if (item == null) return Status.OK_STATUS;

    monitor.beginTask(Messages.ArchiveFetchStart, IProgressMonitor.UNKNOWN);
    final WorkerThread worker = new WorkerThread();
    Future<?> done = Activator.getThreadPool().submit(worker);
    // Poll worker and progress monitor
    long seconds = 0;
    while (!done.isDone()) {
      try {
        Thread.sleep(POLL_PERIOD_MS);
      } catch (InterruptedException ex) {
        // Ignore
      }
      final String info =
          NLS.bind(Messages.ArchiveFetchProgressFmt, worker.getMessage(), ++seconds);
      monitor.subTask(info);
      // Try to cancel the worker in response to user's cancel request.
      // Continues to cancel the worker until isDone()
      if (monitor.isCanceled()) worker.cancel();
    }
    monitor.done();

    return monitor.isCanceled() ? Status.CANCEL_STATUS : Status.OK_STATUS;
  }
  /**
   * Reports progress by creating a balanced binary tree of progress monitors. Simulates mixed usage
   * of IProgressMonitor in a typical usage. Calls isCanceled once each time work is reported. Half
   * of the work is reported using internalWorked and half is reported using worked, to simulate
   * mixed usage of the progress monitor.
   *
   * @deprecated to suppress deprecation warnings
   * @param monitor progress monitor (callers are responsible for calling done() if necessary)
   * @param loopSize total size of the recursion tree
   */
  public static void reportWorkInBalancedTree(IProgressMonitor monitor, int loopSize) {
    monitor.beginTask("", 100);
    int leftBranch = loopSize / 2;
    int rightBranch = loopSize - leftBranch;

    if (leftBranch > 1) {
      SubProgressMonitor leftProgress = new SubProgressMonitor(monitor, 50);
      reportWorkInBalancedTree(leftProgress, leftBranch);
      leftProgress.done();
    } else {
      monitor.worked(25);
      monitor.internalWorked(25.0);
      monitor.isCanceled();
    }

    if (rightBranch > 1) {
      SubProgressMonitor rightProgress = new SubProgressMonitor(monitor, 50);
      reportWorkInBalancedTree(rightProgress, rightBranch);
      rightProgress.done();
    } else {
      monitor.worked(25);
      monitor.internalWorked(25.0);
      monitor.isCanceled();
    }
  }
Пример #7
0
  public void findIndexMatches(
      Index index,
      IndexQueryRequestor requestor,
      SearchParticipant participant,
      IJavaSearchScope scope,
      IProgressMonitor progressMonitor)
      throws IOException {
    if (progressMonitor != null && progressMonitor.isCanceled())
      throw new OperationCanceledException();

    resetQuery();
    SimpleSet intersectedNames = null;
    try {
      index.startQuery();
      do {
        SearchPattern pattern = currentPattern();
        EntryResult[] entries = pattern.queryIn(index);
        if (entries == null) return;

        SearchPattern decodedResult = pattern.getBlankPattern();
        SimpleSet newIntersectedNames = new SimpleSet(3);
        for (int i = 0, l = entries.length; i < l; i++) {
          if (progressMonitor != null && progressMonitor.isCanceled())
            throw new OperationCanceledException();

          EntryResult entry = entries[i];
          decodedResult.decodeIndexKey(entry.getWord());
          if (pattern.matchesDecodedKey(decodedResult)) {
            String[] names = entry.getDocumentNames(index);
            if (intersectedNames != null) {
              for (int j = 0, n = names.length; j < n; j++)
                if (intersectedNames.includes(names[j])) newIntersectedNames.add(names[j]);
            } else {
              for (int j = 0, n = names.length; j < n; j++) newIntersectedNames.add(names[j]);
            }
          }
        }

        if (newIntersectedNames.elementSize == 0) return;
        intersectedNames = newIntersectedNames;
      } while (hasNextQuery());
    } finally {
      index.stopQuery();
    }

    String containerPath = index.containerPath;
    char separator = index.separator;
    Object[] names = intersectedNames.values;
    for (int i = 0, l = names.length; i < l; i++)
      if (names[i] != null)
        acceptMatch(
            (String) names[i],
            containerPath,
            separator,
            null /*no pattern*/,
            requestor,
            participant,
            scope); // AndPatterns cannot provide the decoded result
  }
Пример #8
0
  /**
   * @param markOccurrencesRequest
   * @return true if the annotations were removed and added without any problems and false otherwise
   */
  @Override
  protected synchronized Map<Annotation, Position> getAnnotationsToAddAsMap(
      final BaseEditor baseEditor,
      IAnnotationModel annotationModel,
      MarkOccurrencesRequest markOccurrencesRequest,
      IProgressMonitor monitor)
      throws BadLocationException {
    PyEdit pyEdit = (PyEdit) baseEditor;
    PySourceViewer viewer = pyEdit.getPySourceViewer();
    if (viewer == null || monitor.isCanceled()) {
      return null;
    }
    if (viewer.getIsInToggleCompletionStyle() || monitor.isCanceled()) {
      return null;
    }

    PyMarkOccurrencesRequest pyMarkOccurrencesRequest =
        (PyMarkOccurrencesRequest) markOccurrencesRequest;
    Set<ASTEntry> occurrences = pyMarkOccurrencesRequest.getOccurrences();
    if (occurrences == null) {
      if (DEBUG) {
        System.out.println("Occurrences == null");
      }
      return null;
    }

    IDocument doc = pyEdit.getDocument();
    Map<Annotation, Position> toAddAsMap = new HashMap<Annotation, Position>();
    boolean markOccurrencesInStrings = MarkOccurrencesPreferencesPage.useMarkOccurrencesInStrings();

    // get the annotations to add
    for (ASTEntry entry : occurrences) {
      if (!markOccurrencesInStrings) {
        if (entry.node instanceof Name) {
          Name name = (Name) entry.node;
          if (name.ctx == Name.Artificial) {
            continue;
          }
        }
      }

      SimpleNode node = entry.getNameNode();
      IRegion lineInformation = doc.getLineInformation(node.beginLine - 1);

      try {
        Annotation annotation = new Annotation(getOccurrenceAnnotationsType(), false, "occurrence");
        Position position =
            new Position(
                lineInformation.getOffset() + node.beginColumn - 1,
                pyMarkOccurrencesRequest.getInitialName().length());
        toAddAsMap.put(annotation, position);

      } catch (Exception e) {
        Log.log(e);
      }
    }
    return toAddAsMap;
  }
  /**
   * 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();
  }
Пример #10
0
  public IStatus execute(
      IProgressMonitor monitor,
      ICommand command,
      IReturnValueConsumer returnValueConsumer,
      Options options) {
    monitor.beginTask(null, 100);

    monitor.subTask(Messages.DNSSDRemoteCommandService_ResolveRemoteCommandService);

    boolean doResolve = false;
    synchronized (info) {
      if (!resolving) {
        resolving = true;
        doResolve = true;
      }
    }

    DNSSDService resolver = null;
    if (doResolve) {
      try {
        resolver = DNSSD.resolve(flags, ifIndex, serviceName, regType, domain, this);
      } catch (DNSSDException e) {
        return new Status(
            IStatus.ERROR,
            LANRemoteCommandPlugin.ID,
            Messages.DNSSDRemoteCommandService_FailedResolveRemoteCommand,
            e);
      }
    }
    try {
      while (resolving) {
        if (monitor.isCanceled()) return Status.CANCEL_STATUS;
        Thread.sleep(0);
      }
    } catch (InterruptedException e) {
      return Status.CANCEL_STATUS;
    } finally {
      if (resolver != null) {
        resolver.stop();
      }
    }

    if (monitor.isCanceled()) return Status.CANCEL_STATUS;
    monitor.worked(10);

    monitor.subTask(Messages.DNSSDRemoteCommandService_SendCommand);
    IProgressMonitor handleMonitor = new SubProgressMonitor(monitor, 90);
    OutgoingSocketCommandHandler handler = new OutgoingSocketCommandHandler(info.getAddress());
    handler.setPluginId(LANRemoteCommandPlugin.ID);
    handler.setSocketPool(socketPool);
    IStatus handled =
        handler.handleOutgoingCommand(
            handleMonitor, command, returnValueConsumer, options.timeout());
    if (!handleMonitor.isCanceled()) handleMonitor.done();
    return handled;
  }
Пример #11
0
  /**
   * @return a tuple with the refactoring request, the processor and a boolean indicating if all
   *     pre-conditions succedded.
   * @throws MisconfigurationException
   */
  @Override
  protected MarkOccurrencesRequest createRequest(
      BaseEditor baseEditor, IDocumentProvider documentProvider, IProgressMonitor monitor)
      throws BadLocationException, OperationCanceledException, CoreException,
          MisconfigurationException {
    if (!MarkOccurrencesPreferencesPage.useMarkOccurrences()) {
      return new PyMarkOccurrencesRequest(false, null, null);
    }
    PyEdit pyEdit = (PyEdit) baseEditor;

    // ok, the editor is still there wit ha document... move on
    PyRefactorAction pyRefactorAction = getRefactorAction(pyEdit);

    final RefactoringRequest req =
        getRefactoringRequest(pyEdit, pyRefactorAction, PySelection.fromTextSelection(this.ps));

    if (req == null
        || !req.nature
            .getRelatedInterpreterManager()
            .isConfigured()) { // we check if it's configured because it may still be a stub...
      return new PyMarkOccurrencesRequest(false, null, null);
    }

    PyReferenceSearcher searcher = new PyReferenceSearcher(req);
    // to see if a new request was not created in the meantime (in which case this one will be
    // cancelled)
    if (monitor.isCanceled()) {
      return new PyMarkOccurrencesRequest(false, null, null);
    }

    try {
      searcher.prepareSearch(req);
      if (monitor.isCanceled()) {
        return new PyMarkOccurrencesRequest(false, null, null);
      }
      searcher.search(req);
      if (monitor.isCanceled()) {
        return new PyMarkOccurrencesRequest(false, null, null);
      }
      // Ok, search succeeded.
      return new PyMarkOccurrencesRequest(true, req, searcher);
    } catch (PyReferenceSearcher.SearchException e) {
      // Suppress search failures.
      return new PyMarkOccurrencesRequest(false, null, null);
    } catch (Throwable e) {
      throw new RuntimeException(
          "Error in occurrences while analyzing modName:"
              + req.moduleName
              + " initialName:"
              + req.initialName
              + " line (start at 0):"
              + req.ps.getCursorLine(),
          e);
    }
  }
Пример #12
0
    public void run() {
      try {
        if (PlatformUI.getWorkbench().isClosing()) {
          return;
        }
      } catch (IllegalStateException e) {
        // falko: IllegalStateException: outsite request cycle
      }
      boolean enabled = false;
      int hits = 0;

      for (Iterator iter = structured.iterator(); iter.hasNext(); ) {
        if (monitor.isCanceled()) return;
        @SuppressWarnings("unchecked")
        Object obj = iter.next();
        if (isValid(obj)) {
          hits++;
        } else {
          hits = -1;
          break;
        }
      }

      if (monitor.isCanceled()) return;

      if (hits >= enablesForData.minHits) {
        if (enablesForData.exactMatch && hits == enablesForData.minHits) enabled = true;
        else if (!enablesForData.exactMatch && hits >= enablesForData.minHits) enabled = true;
      }

      final boolean finalEnabled = enabled;
      final boolean oldEnabledState = isEnabled();
      Runnable runnable =
          new Runnable() {
            public void run() {
              if (structured.equals(OpAction.this.selection)) return;
              OpAction.this.selection = structured;

              setEnabled(finalEnabled);

              if (category != null && oldEnabledState != finalEnabled) category.enablementChanged();
            }
          };
      if (execSync) {
        if (Display.getCurrent() != null) {
          runnable.run();
        } else {
          Display.getDefault().syncExec(runnable);
        }
      } else {
        System.out.println("FIXME _p3: falko ...");
        // Display.getDefault().asyncExec(runnable);
      }
    }
 @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;
 }
Пример #14
0
    @Override
    public IStatus runInWorkspace(IProgressMonitor monitor) {
      Set<Repository> repos;
      synchronized (repositoriesChanged) {
        if (repositoriesChanged.isEmpty()) {
          return Status.OK_STATUS;
        }
        repos = new LinkedHashSet<>(repositoriesChanged);
        repositoriesChanged.clear();
      }
      IProject[] projects = ResourcesPlugin.getWorkspace().getRoot().getProjects();
      Set<IProject> toRefresh = new LinkedHashSet<>();
      for (IProject p : projects) {
        if (!p.isAccessible()) {
          continue;
        }
        RepositoryMapping mapping = RepositoryMapping.getMapping(p);
        if (mapping != null && repos.contains(mapping.getRepository())) {
          toRefresh.add(p);
        }
      }
      monitor.beginTask(UIText.Activator_refreshingProjects, toRefresh.size());

      for (IProject p : toRefresh) {
        if (monitor.isCanceled()) {
          return Status.CANCEL_STATUS;
        }
        ISchedulingRule rule = p.getWorkspace().getRuleFactory().refreshRule(p);
        try {
          getJobManager().beginRule(rule, monitor);
          // handle missing projects after branch switch
          if (p.isAccessible()) {
            p.refreshLocal(IResource.DEPTH_INFINITE, new SubProgressMonitor(monitor, 1));
          }
        } catch (CoreException e) {
          handleError(UIText.Activator_refreshFailed, e, false);
          return new Status(IStatus.ERROR, getPluginId(), e.getMessage());
        } finally {
          getJobManager().endRule(rule);
        }
      }
      if (!monitor.isCanceled()) {
        // re-schedule if we got some changes in the meantime
        synchronized (repositoriesChanged) {
          if (!repositoriesChanged.isEmpty()) {
            schedule(100);
          }
        }
      }
      monitor.done();
      return Status.OK_STATUS;
    }
Пример #15
0
    /**
     * Signals the end of problem reporting.
     *
     * @param reportedProblems the problems to report
     */
    private void reportProblems(List<IProblem> reportedProblems) {
      if (fProgressMonitor != null && fProgressMonitor.isCanceled()) return;

      boolean temporaryProblemsChanged = false;

      synchronized (getLockObject()) {
        boolean isCanceled = false;

        fPreviouslyOverlaid = fCurrentlyOverlaid;
        fCurrentlyOverlaid = new ArrayList<Annotation>();

        if (fGeneratedAnnotations.size() > 0) {
          temporaryProblemsChanged = true;
          removeAnnotations(fGeneratedAnnotations, false, true);
          fGeneratedAnnotations.clear();
        }

        if (reportedProblems != null && reportedProblems.size() > 0) {

          Iterator<IProblem> e = reportedProblems.iterator();
          while (e.hasNext()) {

            if (fProgressMonitor != null && fProgressMonitor.isCanceled()) {
              isCanceled = true;
              break;
            }

            IProblem problem = e.next();
            Position position = createPositionFromProblem(problem);
            if (position != null) {

              try {
                ProblemAnnotation annotation = new ApexProblemAnnotation(problem);
                overlayMarkers(position, annotation);
                addAnnotation(annotation, position, false);
                fGeneratedAnnotations.add(annotation);

                temporaryProblemsChanged = true;
              } catch (BadLocationException x) {
                // ignore invalid position
              }
            }
          }
        }

        removeMarkerOverlays(isCanceled);
        fPreviouslyOverlaid = null;
      }

      if (temporaryProblemsChanged) fireModelChanged();
    }
Пример #16
0
 /**
  * Handles the conversion for a node.
  *
  * @param node the test case
  * @throws StopConversionException
  */
 private void handleNode(INodePO node) throws StopConversionException {
   if (progressMonitor.isCanceled()) {
     throw new StopConversionException(true);
   }
   progressMonitor.worked(1);
   NodeInfo info = uuidToNodeInfoMap.get(node.getGuid());
   File file = new File(info.getFqFileName());
   if (node instanceof ICategoryPO) {
     file.mkdirs();
     for (INodePO child : node.getUnmodifiableNodeList()) {
       handleNode(child);
     }
   } else {
     try {
       file.getParentFile().mkdirs();
       file.createNewFile();
       NodeGenerator gen = new NodeGenerator();
       try {
         String content = gen.generate(info);
         writeContentToFile(file, content);
       } catch (MinorConversionException e) {
         Plugin.getDefault()
             .writeLineToConsole(
                 NLS.bind(Messages.InvalidNode, new String[] {node.getName(), e.getMessage()}),
                 true);
         file.delete();
       }
     } catch (IOException e) {
       ErrorHandlingUtil.createMessageDialog(
           new JBException(e.getMessage(), e, MessageIDs.E_FILE_NO_PERMISSION));
       throw new StopConversionException();
     }
   }
 }
  public IStatus run(IProgressMonitor monitor) throws OperationCanceledException {
    searchResult.reset();
    IProject[] projects = workspace.getRoot().getProjects();
    ResourceSet rs = null;

    for (IProject curProject : projects) {
      if (XtextProjectHelper.hasNature(curProject)) {
        rs = resourceSetProvider.get(curProject);
        break;
      }
    }
    Iterable<IEObjectDescription> result = doSearch(rs);
    int i = 0;
    for (IEObjectDescription ieObjDesc : result) {
      i++;
      searchResult.accept(ieObjDesc);
    }
    searchResult.finish();
    String message =
        MessageFormat.format(
            ServiceRepositorySearchMessages.ServiceRepositorySearchViewPage_resultLabel,
            new Object[] {String.valueOf(i)});
    return (monitor.isCanceled())
        ? Status.CANCEL_STATUS
        : new Status(Status.OK, ServiceRepositoryActivator.PLUGIN_ID, message);
  }
Пример #18
0
    public boolean visit(IResource resource) throws CoreException {
      if (resource.isDerived()) {
        return false;
      }

      handler.handleResourceStart(resource);

      if (resource.getType() == IResource.FILE
          && ContentTypeUtils.isGroovyLikeFileName(resource.getName())) {
        if (Util.isExcluded(resource, includes, excludes)) {
          return false;
        }

        GroovyCompilationUnit unit = (GroovyCompilationUnit) JavaCore.create((IFile) resource);
        if (unit != null && unit.isOnBuildPath()) {
          if (monitor.isCanceled()) {
            throw new OperationCanceledException();
          }
          monitor.subTask(resource.getName());
          handler.setResource((IFile) resource);
          Map<Integer, String> commentsMap = findComments(unit);
          StaticTypeCheckerRequestor requestor =
              new StaticTypeCheckerRequestor(handler, commentsMap, onlyAssertions);
          TypeInferencingVisitorWithRequestor visitor =
              new TypeInferencingVisitorFactory().createVisitor(unit);
          try {
            unit.becomeWorkingCopy(monitor);
            visitor.visitCompilationUnit(requestor);
          } finally {
            unit.discardWorkingCopy();
          }
        }
      }
      return true;
    }
  public void search(
      ISearchRequestor requestor, QuerySpecification querySpecification, IProgressMonitor monitor)
      throws CoreException {

    if (querySpecification.getLimitTo() != S_LIMIT_REF
        && querySpecification.getLimitTo() != S_LIMIT_ALL) return;

    String search;
    if (querySpecification instanceof ElementQuerySpecification) {
      IJavaElement element = ((ElementQuerySpecification) querySpecification).getElement();
      if (element instanceof IType) search = ((IType) element).getFullyQualifiedName('.');
      else search = element.getElementName();
      int type = element.getElementType();
      if (type == IJavaElement.TYPE) fSearchFor = S_FOR_TYPES;
      else if (type == IJavaElement.PACKAGE_FRAGMENT || type == IJavaElement.PACKAGE_FRAGMENT_ROOT)
        fSearchFor = S_FOR_PACKAGES;
    } else {
      fSearchFor = ((PatternQuerySpecification) querySpecification).getSearchFor();
      search = ((PatternQuerySpecification) querySpecification).getPattern();
    }
    if (fSearchFor != S_FOR_TYPES && fSearchFor != S_FOR_PACKAGES) return;
    fSearchPattern = PatternConstructor.createPattern(search, true);
    fSearchRequestor = requestor;

    IPath[] enclosingPaths = querySpecification.getScope().enclosingProjectsAndJars();
    IPluginModelBase[] pluginModels = PluginRegistry.getWorkspaceModels();
    monitor.beginTask(PDEUIMessages.ClassSearchParticipant_taskMessage, pluginModels.length);
    for (int i = 0; i < pluginModels.length; i++) {
      IProject project = pluginModels[i].getUnderlyingResource().getProject();
      if (!monitor.isCanceled() && encloses(enclosingPaths, project.getFullPath()))
        searchProject(project, monitor);
    }
  }
Пример #20
0
  public boolean execute(IProgressMonitor progressMonitor) {

    if (this.isCancelled || progressMonitor != null && progressMonitor.isCanceled()) return true;

    /* ensure no concurrent write access to index */
    Index index =
        this.manager.getIndex(
            this.containerPath, true /*reuse index file*/, false /*don't create if none*/);
    if (index == null) return true;
    ReadWriteMonitor monitor = index.monitor;
    if (monitor == null) return true; // index got deleted since acquired

    try {
      monitor.enterWrite(); // ask permission to write
      this.manager.saveIndex(index);
    } catch (IOException e) {
      if (JobManager.VERBOSE) {
        Util.verbose(
            "-> failed to save index "
                + this.containerPath
                + " because of the following exception:",
            System.err); // $NON-NLS-1$ //$NON-NLS-2$
        e.printStackTrace();
      }
      return false;
    } finally {
      monitor.exitWrite(); // free write lock
    }
    return true;
  }
      /*
       * @see org.eclipse.ui.texteditor.AbstractDocumentProvider.DocumentProviderOperation#execute(org.eclipse.core.runtime.IProgressMonitor)
       */
      protected void execute(IProgressMonitor pm) throws CoreException {
        ElementInfo info = (ElementInfo) fElementInfoMap.get(element);
        if (info != null) {
          if (info.fDocument != document) {
            Status status =
                new Status(
                    IStatus.WARNING,
                    TextEditorPlugin.PLUGIN_ID,
                    IStatus.ERROR,
                    EditorMessages.AbstractDocumentProvider_error_save_inuse,
                    null);
            throw new CoreException(status);
          }

          doSaveDocument(pm, element, document, overwrite);

          if (pm != null && pm.isCanceled()) return;

          info.fCanBeSaved = false;
          addUnchangedElementListeners(element, info);
          fireElementDirtyStateChanged(element, false);

        } else {
          doSaveDocument(pm, element, document, overwrite);
        }
      }
  @Override
  public void reconciled(DartUnit ast, boolean forced, IProgressMonitor progressMonitor) {
    // don't update semantic highlighting if there are parsing problems to avoid "flashing"
    if (ast != null && ast.hasParseErrors()) {
      return;
    }

    // ensure at most one thread can be reconciling at any time
    synchronized (fReconcileLock) {
      if (fIsReconciling) {
        return;
      } else {
        fIsReconciling = true;
      }
    }
    fJobPresenter = fPresenter;
    fJobSemanticHighlightings = fSemanticHighlightings;
    fJobHighlightings = fHighlightings;

    try {
      if (fJobPresenter == null || fJobSemanticHighlightings == null || fJobHighlightings == null) {
        return;
      }

      fJobPresenter.setCanceled(progressMonitor.isCanceled());

      if (ast == null || ast.getLibrary() == null || fJobPresenter.isCanceled()) {
        return;
      }

      DartNode[] subtrees = getAffectedSubtrees(ast);
      if (subtrees.length == 0) {
        return;
      }

      startReconcilingPositions();

      if (!fJobPresenter.isCanceled()) {
        reconcilePositions(subtrees);
      }

      TextPresentation textPresentation = null;
      if (!fJobPresenter.isCanceled()) {
        textPresentation = fJobPresenter.createPresentation(fAddedPositions, fRemovedPositions);
      }

      if (!fJobPresenter.isCanceled()) {
        updatePresentation(textPresentation, fAddedPositions, fRemovedPositions);
      }

      stopReconcilingPositions();
    } finally {
      fJobPresenter = null;
      fJobSemanticHighlightings = null;
      fJobHighlightings = null;
      synchronized (fReconcileLock) {
        fIsReconciling = false;
      }
    }
  }
  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;
  }
  private IProject createProject(final GridProjectProperties props, final IProgressMonitor monitor)
      throws CoreException {

    monitor.subTask(Messages.getString("GridProjectCreationOperation.init_task")); // $NON-NLS-1$

    String projectName = props.getProjectName();
    IPath projectPath = props.getProjectLocation();
    IProject[] referencesProjects = props.getReferencesProjects();

    IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();
    IProject project = workspaceRoot.getProject(projectName);

    IStatus status = ResourcesPlugin.getWorkspace().validateProjectLocation(project, projectPath);
    if (status.getSeverity() != IStatus.OK) {
      throw new CoreException(status);
    }

    IProjectDescription desc = project.getWorkspace().newProjectDescription(projectName);
    desc.setLocation(projectPath);
    if (referencesProjects != null) {
      desc.setReferencedProjects(referencesProjects);
    }
    project.create(desc, new SubProgressMonitor(monitor, 50));
    project.open(new SubProgressMonitor(monitor, 50));

    createProjectStructure(project, props);
    setProjectProperties(project, props);

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

    return project;
  }
Пример #25
0
 private void compileFiles(BuildContext[] contexts, IProgressMonitor monitor)
     throws CoreException {
   SubMonitor sub =
       SubMonitor.convert(monitor, "Analyzing Files...", fParticipants.length + contexts.length);
   if (fParticipants != null) {
     for (int i = 0; i < fParticipants.length; i++) {
       if (monitor.isCanceled()) throw new OperationCanceledException();
       try {
         long start = System.currentTimeMillis();
         fParticipants[i].buildStarting(contexts, true, sub.newChild(1));
         if (RubyBuilder.DEBUG)
           System.out.println(
               fParticipants[i].getClass().getSimpleName()
                   + " took "
                   + (System.currentTimeMillis() - start)
                   + "ms");
       } catch (Exception e) {
         RubyCore.log(e);
       }
     }
   }
   for (int i = 0; i < contexts.length; i++) {
     CategorizedProblem[] problems = contexts[i].getProblems();
     if (problems == null || problems.length == 0) {
       sub.worked(1);
       continue;
     }
     for (int j = 0; j < problems.length; j++) {
       markerManager.addProblem(contexts[i].getFile(), problems[j]);
     }
     sub.worked(1);
   }
   sub.done();
 }
  private void addProjectNature(final IProject proj, final IProgressMonitor monitor)
      throws CoreException {

    monitor.subTask(Messages.getString("GridProjectCreationOperation.nature_task")); // $NON-NLS-1$

    IProjectDescription desc = proj.getDescription();
    String[] natureIDs = desc.getNatureIds();
    String gridNatureID = GridProjectNature.getID();

    boolean found = false;
    for (int i = 0; (i < natureIDs.length) && (!found); i++) {
      if (natureIDs[i].equals(gridNatureID)) {
        found = true;
      }
    }

    if (!found) {
      String[] newNatureIDs = new String[natureIDs.length + 1];
      System.arraycopy(natureIDs, 0, newNatureIDs, 1, natureIDs.length);
      newNatureIDs[0] = gridNatureID;
      desc.setNatureIds(newNatureIDs);
      proj.setDescription(desc, new SubProgressMonitor(monitor, 100));
    }

    if (monitor.isCanceled()) {
      throw new OperationCanceledException();
    }
  }
Пример #27
0
 public ASTReader(IJavaProject iJavaProject, IProgressMonitor monitor) {
   if (monitor != null)
     monitor.beginTask("Parsing selected Java Project", getNumberOfCompilationUnits(iJavaProject));
   systemObject = new SystemObject();
   examinedProject = iJavaProject;
   try {
     IPackageFragmentRoot[] iPackageFragmentRoots = iJavaProject.getPackageFragmentRoots();
     for (IPackageFragmentRoot iPackageFragmentRoot : iPackageFragmentRoots) {
       IJavaElement[] children = iPackageFragmentRoot.getChildren();
       for (IJavaElement child : children) {
         if (child.getElementType() == IJavaElement.PACKAGE_FRAGMENT) {
           IPackageFragment iPackageFragment = (IPackageFragment) child;
           ICompilationUnit[] iCompilationUnits = iPackageFragment.getCompilationUnits();
           for (ICompilationUnit iCompilationUnit : iCompilationUnits) {
             if (monitor != null && monitor.isCanceled()) throw new OperationCanceledException();
             systemObject.addClasses(parseAST(iCompilationUnit));
             if (monitor != null) monitor.worked(1);
           }
         }
       }
     }
   } catch (JavaModelException e) {
     e.printStackTrace();
   }
   if (monitor != null) monitor.done();
 }
 public ArtifactKey identify(File file, IProgressMonitor monitor) throws CoreException {
   if (file == null || !file.exists()) {
     return null;
   }
   if (monitor == null) {
     monitor = new NullProgressMonitor();
   }
   ArtifactKey artifactKey = null;
   // long start = System.currentTimeMillis();
   for (ArtifactIdentifier identifier : artifactIdentifiers) {
     if (monitor.isCanceled()) {
       return null;
     }
     artifactKey = identifier.identify(file, monitor);
     if (artifactKey != null) {
       // long stop = System.currentTimeMillis();
       // System.err.println(file.getName() + " identified as " + artifactKey + " in " +
       // (stop-start) + " ms");
       break;
     }
   }
   // if (artifactKey == null)
   // System.err.println("Could not identify "+file);
   return artifactKey;
 }
Пример #29
0
 /**
  * Perform the operation by creating the project, the library, and the type as specified by the
  * user.
  *
  * @param monitor the operation progress monitor (not <code>null</code>)
  */
 protected void performOperation(IProgressMonitor monitor)
     throws CoreException, InterruptedException {
   if (monitor.isCanceled()) {
     throw new InterruptedException();
   }
   appGenerator.execute(monitor);
 }
  private void searchForRuntimes(
      List<RuntimeDefinition> runtimeCollector, IPath path, IProgressMonitor monitor) {

    File[] files = null;
    if (path != null) {
      File root = path.toFile();
      if (root.isDirectory()) files = new File[] {root};
      else return;
    } else files = File.listRoots();

    if (files != null) {
      int size = files.length;
      monitor.beginTask("Searching " + path.toOSString(), size * 100);
      int work = 100 / size;
      for (int i = 0; i < size; i++) {
        if (monitor.isCanceled()) return;
        if (files[i] != null && files[i].isDirectory())
          searchDirectory(files[i], runtimeCollector, DEPTH, new SubProgressMonitor(monitor, 80));
        monitor.worked(20);
      }
      monitor.done();
    } else {
      monitor.beginTask("Searching " + path.toOSString(), 1);
      monitor.worked(1);
      monitor.done();
    }
  }