Java Code Examples for org.eclipse.core.runtime.SubMonitor#subTask()

The following examples show how to use org.eclipse.core.runtime.SubMonitor#subTask() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
@Override
protected IStatus run(@Nullable IProgressMonitor monitor) {
    SubMonitor subMonitor = SubMonitor.convert(monitor);
    Collection<ICliParser> cliParsers = getCliParsers();
    subMonitor.beginTask("Executing CLI Parsers", cliParsers.size()); //$NON-NLS-1$
    for (ICliParser parser : cliParsers) {
        if (subMonitor.isCanceled()) {
            return Status.CANCEL_STATUS;
        }
        subMonitor.subTask("Executing parser :" + parser.getCmdLineOptions().toString()); //$NON-NLS-1$
        IStatus status = parser.workspaceLoading(fCommandLine, subMonitor);
        if (!status.isOK()) {
            Activator.getInstance().getLog().log(status);
        }
    }
    return Status.OK_STATUS;
}
 
Example 2
@Override
public void run(IMarker[] markers, IProgressMonitor parentMonitor) {
	int count = markers.length;
	Comparator<IMarker> c1 = Comparator.comparing(e -> e.getResource().toString());
	Comparator<IMarker> c2 = Comparator.comparing(e -> Integer.valueOf(-e.getAttribute("charEnd", 0)));
	Arrays.sort(markers, c1.thenComparing(c2));
	SubMonitor monitor = SubMonitor.convert(parentMonitor, count);
	int i = 1;
	for (IMarker m : markers) {
		if (parentMonitor.isCanceled()) {
			return;
		}
		monitor.subTask("fixing (" + i + "/" + count + ") in " + m.getResource().getName() + " Line "
				+ Util.getProperty(IMarker.LINE_NUMBER, m));
		processUIEvents(0);
		run(m);
		monitor.worked(1);
		i++;
	}
}
 
Example 3
/**
 * Recovery build was triggered, remove all cached information for resources that are no
 * longer contained in the project.
 */
public ToBeBuilt updateProjectNewResourcesOnly(IProject project, IProgressMonitor monitor) throws CoreException {
	SubMonitor progress = SubMonitor.convert(monitor, Messages.ToBeBuiltComputer_CollectingResources, 1);
	progress.subTask(Messages.ToBeBuiltComputer_CollectingResources);
	ToBeBuilt toBeBuilt = updateProject(project, progress.split(1));
	Iterable<URI> existingURIs = Iterables.transform(builderState.getAllResourceDescriptions(),
			new Function<IResourceDescription, URI>() {
				@Override
				public URI apply(IResourceDescription from) {
					return from.getURI();
				}
			});
	for (URI existingURI : existingURIs) {
		toBeBuilt.getToBeDeleted().remove(existingURI);
		toBeBuilt.getToBeUpdated().remove(existingURI);
	}
	return toBeBuilt;
}
 
Example 4
/**
 * @param monitor the progress monitor to use for reporting progress to the user. It is the caller's responsibility
 *        to call done() on the given monitor. Accepts null, indicating that no progress should be
 *        reported and that the operation cannot be cancelled.
 */
protected void incrementalBuild(IResourceDelta delta, final IProgressMonitor monitor) throws CoreException {
	final SubMonitor progress = SubMonitor.convert(monitor, Messages.XtextBuilder_CollectingResources, 10);
	progress.subTask(Messages.XtextBuilder_CollectingResources);
	
	pollQueuedBuildData();

	final ToBeBuilt toBeBuilt = new ToBeBuilt();
	IResourceDeltaVisitor visitor = createDeltaVisitor(toBeBuiltComputer, toBeBuilt, progress);
	delta.accept(visitor);

	if (progress.isCanceled()) {
		throw new OperationCanceledException();
	}
	progress.worked(2);
	Task task = closedProjectsQueue.exhaust();
	try {
		addInfosFromTaskAndBuild(task, toBeBuilt, BuildType.INCREMENTAL, progress.split(8));
	} catch(Exception e) {
		task.reschedule();
		throw e;
	}
}
 
Example 5
@Override
public synchronized ImmutableList<IResourceDescription.Delta> update(BuildData buildData, IProgressMonitor monitor) {
	ensureLoaded();
	final SubMonitor subMonitor = SubMonitor.convert(monitor, Messages.AbstractBuilderState_0, 1);
	subMonitor.subTask(Messages.AbstractBuilderState_0);
	if (buildData.isEmpty())
		return ImmutableList.of();
	if (monitor.isCanceled())
		throw new OperationCanceledException();

	final ResourceDescriptionsData newData = getCopiedResourceDescriptionsData();
	final Collection<IResourceDescription.Delta> result = doUpdate(buildData, newData, subMonitor.split(1));

	if (monitor.isCanceled())
		throw new OperationCanceledException();
	final ResourceDescriptionChangeEvent event = new ResourceDescriptionChangeEvent(result);
	// update the reference
	setResourceDescriptionsData(newData);
	notifyListeners(event);
	return event.getDeltas();
}
 
Example 6
Source Project: typescript.java   File: IDETypeScriptProject.java    License: MIT License 6 votes vote down vote up
/**
 * Collect ts files to compile from the given ts files list.
 * 
 * @param updatedTsFiles
 *            list of TypeScript files which have changed.
 * @param tsFilesToCompile
 *            list of collected ts files to compile.
 * @param tsFilesToClose
 *            list of ts files to close.
 * @param client
 * @param subMonitor
 * @throws Exception
 */
private void collectTsFilesToCompile(List<IFile> updatedTsFiles, List<String> tsFilesToCompile,
		List<IFile> tsFilesToClose, ITypeScriptServiceClient client, SubMonitor subMonitor) throws Exception {
	SubMonitor loopMonitor = subMonitor.split(50).setWorkRemaining(updatedTsFiles.size());
	loopMonitor.subTask(TypeScriptCoreMessages.IDETypeScriptProject_compile_collecting_step);
	for (IFile tsFile : updatedTsFiles) {
		if (loopMonitor.isCanceled()) {
			throw new OperationCanceledException();
		}
		String filename = WorkbenchResourceUtil.getFileName(tsFile);
		loopMonitor
				.subTask(NLS.bind(TypeScriptCoreMessages.IDETypeScriptProject_compile_collecting_file, filename));
		if (!tsFilesToCompile.contains(filename)) {
			collectTsFilesToCompile(filename, client, tsFilesToCompile, tsFilesToClose, loopMonitor);
		}
		loopMonitor.worked(1);
		// loopMonitor.split(1);
	}
	// subMonitor.setWorkRemaining(50);
}
 
Example 7
/**
 * Builds all other registered (non-language specific) {@link IXtextBuilderParticipant}s.
 *
 * @param buildContext
 *          the {@link IBuildContext}, must not be {@code null}
 * @param monitor
 *          the {@link IProgressMonitor}, must not be {@code null}
 * @throws CoreException
 *           caused by an {@link IXtextBuilderParticipant}
 */
protected void buildOtherParticipants(final IBuildContext buildContext, final IProgressMonitor monitor) throws CoreException {
  ImmutableList<IXtextBuilderParticipant> otherBuilderParticipants = getParticipants();
  if (otherBuilderParticipants.isEmpty()) {
    return;
  }
  SubMonitor progress = SubMonitor.convert(monitor, otherBuilderParticipants.size());
  progress.subTask(Messages.RegistryBuilderParticipant_InvokingBuildParticipants);
  for (final IXtextBuilderParticipant participant : otherBuilderParticipants) {
    if (progress.isCanceled()) {
      throw new OperationCanceledException();
    }
    try {
      if (initializeParticipant(participant)) {
        participant.build(buildContext, progress.newChild(1));
      }
      // CHECKSTYLE:CHECK-OFF IllegalCatchCheck we need to recover from any exception and continue the build
    } catch (Throwable throwable) {
      // CHECKSTYLE:CHECK-ON IllegalCatchCheck
      LOG.error("Error occurred during build of builder participant: " //$NON-NLS-1$
          + participant.getClass().getName(), throwable);
    }
  }
}
 
Example 8
/**
 * Extract all file system elements (File) to destination folder (typically
 * workspace/TraceProject/.traceImport)
 */
private void extractAllArchiveFiles(List<TraceFileSystemElement> fileSystemElements, IFolder destFolder, IPath baseSourceContainerPath, IProgressMonitor progressMonitor) throws InterruptedException, CoreException, InvocationTargetException {
    SubMonitor subMonitor = SubMonitor.convert(progressMonitor, fileSystemElements.size());
    ListIterator<TraceFileSystemElement> fileSystemElementsIter = fileSystemElements.listIterator();
    while (fileSystemElementsIter.hasNext()) {
        ModalContext.checkCanceled(subMonitor);

        SubMonitor elementProgress = subMonitor.newChild(1);
        TraceFileSystemElement element = fileSystemElementsIter.next();
        elementProgress.setTaskName(Messages.ImportTraceWizard_ExamineOperationTaskName + " " + element.getFileSystemObject().getAbsolutePath()); //$NON-NLS-1$
        File archiveFile = (File) element.getFileSystemObject().getRawFileSystemObject();
        boolean isArchiveFileElement = element.getFileSystemObject() instanceof FileFileSystemObject && ArchiveUtil.isArchiveFile(archiveFile);
        if (isArchiveFileElement) {
            elementProgress = SubMonitor.convert(elementProgress, 4);
            IPath makeAbsolute = baseSourceContainerPath.makeAbsolute();
            IPath relativeToSourceContainer = new Path(element.getFileSystemObject().getAbsolutePath()).makeRelativeTo(makeAbsolute);
            IFolder folder = safeCreateExtractedFolder(destFolder, relativeToSourceContainer, elementProgress.newChild(1));
            extractArchiveToFolder(archiveFile, folder, elementProgress.newChild(1));

            // Delete original archive, we don't want to import this, just
            // the extracted content
            IFile fileRes = destFolder.getFile(relativeToSourceContainer);
            fileRes.delete(true, elementProgress.newChild(1));
            IPath newPath = destFolder.getFullPath().append(relativeToSourceContainer);
            // Rename extracted folder (.extract) to original archive name
            folder.move(newPath, true, elementProgress.newChild(1));
            folder = ResourcesPlugin.getWorkspace().getRoot().getFolder(newPath);
            elementProgress.subTask(""); //$NON-NLS-1$

            // Create the new import provider and root element based on
            // the newly extracted temporary folder
            FileSystemObjectImportStructureProvider importStructureProvider = new FileSystemObjectImportStructureProvider(FileSystemStructureProvider.INSTANCE, null);
            IFileSystemObject rootElement = importStructureProvider.getIFileSystemObject(new File(folder.getLocation().toOSString()));
            TraceFileSystemElement newElement = TraceFileSystemElement.createRootTraceFileElement(rootElement, importStructureProvider);
            List<TraceFileSystemElement> extractedChildren = new ArrayList<>();
            newElement.getAllChildren(extractedChildren);
            extractAllArchiveFiles(extractedChildren, folder, folder.getLocation(), progressMonitor);
        }
    }
}
 
Example 9
@Override
public void run(IProgressMonitor parentMonitor) throws InvocationTargetException, InterruptedException {
    SubMonitor subMonitor = SubMonitor.convert(parentMonitor, 100);
    subMonitor.setTaskName(RunContainerMessages.getString("StartRuntimeAction.Starting")); //$NON-NLS-1$
    if (!checkRunning()) {
        try {
            IPreferenceStore store = ESBRunContainerPlugin.getDefault().getPreferenceStore();
            Process proc = RuntimeServerController.getInstance().startLocalRuntimeServer(
                    store.getString(RunContainerPreferenceInitializer.P_ESB_RUNTIME_LOCATION));
            int i = 0;
            String dot = "."; //$NON-NLS-1$
            while (JMXUtil.createJMXconnection() == null && ++i < 101 && !subMonitor.isCanceled() && proc.isAlive()) {
                subMonitor.subTask(RunContainerMessages.getString("StartRuntimeAction.Try") + dot); //$NON-NLS-1$
                dot += "."; //$NON-NLS-1$
                subMonitor.worked(1);
                Thread.sleep(3000);
            }
            if (!proc.isAlive()) {
                RuntimeServerController.getInstance().stopLocalRuntimeServer();
                throw new InterruptedException(RunContainerMessages.getString("RunContainerPreferencePage.InitailzeDialog8",
                        proc.exitValue()));
            }
            if (JMXUtil.createJMXconnection() == null) {
                throw new InterruptedException(RunContainerMessages.getString("RunContainerPreferencePage.InitailzeDialog5"));
            }
        } catch (Exception e) {
            ExceptionHandler.process(e);
            throw new InvocationTargetException(e, e.getMessage());
        }
    }
    loadConsole();
}
 
Example 10
/**
 * Perform the upgrade.
 */
private IStatus upgradeProjects(Collection<IProject> projects, SubMonitor progress) {
  progress.setWorkRemaining(projects.size());
  MultiStatus status = StatusUtil.multi(this, Messages.getString("updating.projects.jobname")); //$NON-NLS-1$
  for (IProject project : projects) {
    progress.subTask(Messages.getString("updating.project", project.getName())); //$NON-NLS-1$
    IStatus result = CloudToolsEclipseProjectUpdater.updateProject(project, progress.newChild(1));
    status.merge(result);
  }
  // rewrite if OK as otherwise Progress View shows the "Updating projects for..." message
  return StatusUtil.filter(status);
}
 
Example 11
private LibraryClasspathContainer resolveLibraryFiles(
    IJavaProject javaProject,
    IPath containerPath,
    Library library,
    List<Job> sourceAttacherJobs,
    IProgressMonitor monitor)
    throws CoreException {

  List<LibraryFile> libraryFiles = library.getAllDependencies();
  SubMonitor subMonitor = SubMonitor.convert(monitor, libraryFiles.size());
  subMonitor.subTask(Messages.getString("TaskResolveArtifacts", getLibraryDescription(library)));
  SubMonitor child = subMonitor.newChild(libraryFiles.size());

  List<IClasspathEntry> entries = new ArrayList<>();
  for (LibraryFile libraryFile : libraryFiles) {
    IClasspathEntry newLibraryEntry =
        resolveLibraryFileAttachSourceAsync(
            javaProject, containerPath, libraryFile, sourceAttacherJobs, monitor);
    entries.add(newLibraryEntry);
    child.worked(1);
  }
  monitor.done();
  LibraryClasspathContainer container =
      new LibraryClasspathContainer(
          containerPath, getLibraryDescription(library), entries, libraryFiles);

  return container;
}
 
Example 12
/**
 * Ensure all bundles must be activated/resolved before running script
 *
 * @param subMonitor
 */
private void waitForActive(SubMonitor subMonitor) {
    int bundles = 0;
    int activeCount = 0;
    do {
        try {
            Thread.sleep(1000);
            subMonitor.subTask(JMXUtil.getBundlesList().length + " bundles have been activated");
            if (JMXUtil.getBundlesList().length < 80) {
                Thread.sleep(1000);
                continue;
            }

            if (bundles != JMXUtil.getBundlesList().length) {
                bundles = JMXUtil.getBundlesList().length;
                Thread.sleep(1000);
                continue;
            }

            int active = 0;
            Thread.sleep(4000);
            for (long id : JMXUtil.getBundlesList()) {
                if ("Active".equals(JMXUtil.getBundleStatus(id))) {
                    active++;
                }
            }
            if (activeCount != active) {
                activeCount = active;
                Thread.sleep(1000);
                continue;
            } else {
                break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    } while (!subMonitor.isCanceled());
}
 
Example 13
public IProject createProject(IProgressMonitor monitor, Shell shell) {
	final SubMonitor subMonitor = SubMonitor.convert(monitor, 10);
	try {
		final IProjectDescription description = createProjectDescription();
		subMonitor.subTask(Messages.ProjectFactory_0 + description.getName());
		final IProject project = workspace.getRoot().getProject(projectName);
		if (!deleteExistingProject(project, shell, subMonitor)) {
			return null;
		}

		project.create(description, subMonitor.newChild(1));
		project.open(subMonitor.newChild(1));
		project.setDescription(description, subMonitor.newChild(1));
		project.setDefaultCharset(defaultCharset, subMonitor.newChild(1));
		createFolders(project, subMonitor, shell);

		IFileCreator fileCreator = new IFileCreator() {
			@Override
			public IFile writeToFile(CharSequence chars, String fileName) {
				return ProjectFactory.this.writeToFile(chars, fileName, project, subMonitor);
			}
		};

		runContributors(earlyContributors, project, fileCreator);
		enhanceProject(project, subMonitor, shell);
		runContributors(contributors, project, fileCreator);

		return project;
	} catch (final CoreException exception) {
		logger.error(exception.getMessage(), exception);
		return null;
	} finally {
		subMonitor.done();
	}
}
 
Example 14
@Override
@SuppressWarnings("PMD.AvoidInstanceofChecksInCatchClause")
public synchronized ImmutableList<Delta> update(final BuildData buildData, final IProgressMonitor monitor) {
  ensureLoaded();
  final SubMonitor subMonitor = SubMonitor.convert(monitor, org.eclipse.xtext.builder.builderState.Messages.AbstractBuilderState_0, 1);
  subMonitor.subTask(org.eclipse.xtext.builder.builderState.Messages.AbstractBuilderState_0);

  checkForCancellation(monitor);

  final ResourceDescriptionsData newData = getCopiedResourceDescriptionsData();
  Collection<IResourceDescription.Delta> result = null;
  try {
    result = doUpdate(buildData, newData, subMonitor.newChild(1));
    // update the reference
    setResourceDescriptionsData(newData, monitor);
    // CHECKSTYLE:CHECK-OFF IllegalCatch
  } catch (Throwable t) {
    // CHECKSTYLE:CHECK-ON IllegalCatch
    if (!operationCanceledManager.isOperationCanceledException(t)) {
      LOGGER.error("Failed to update index. Executing rollback.", t); //$NON-NLS-1$
    }
    if (newData instanceof AbstractResourceDescriptionsData) {
      ((AbstractResourceDescriptionsData) newData).rollbackChanges();
    }
    throw t;
  }

  final ResourceDescriptionChangeEvent event = new ResourceDescriptionChangeEvent(result);
  notifyListeners(event);
  return event.getDeltas();
}
 
Example 15
@Override
public void build(IBuildContext buildContext, IProgressMonitor monitor) throws CoreException {
	ImmutableList<IXtextBuilderParticipant> participants = getParticipants();
	if (participants.isEmpty())
		return;
	SubMonitor progress = SubMonitor.convert(monitor, participants.size());
	progress.subTask(Messages.RegistryBuilderParticipant_InvokingBuildParticipants);
	for (IXtextBuilderParticipant participant : participants) {
		if (progress.isCanceled())
			throw new OperationCanceledException();
		participant.build(buildContext, progress.split(1));
	}
	if (progress.isCanceled())
		throw new OperationCanceledException();
}
 
Example 16
/**
 * Full build was triggered. Update all information that is available for the given project.
 * All contained resources are processed by {@link #updateStorage(IProgressMonitor, ToBeBuilt, IStorage)}.
 * 
 * @see #updateStorage(IProgressMonitor, ToBeBuilt, IStorage)
 * @see #isHandled(IFolder)
 * @see IToBeBuiltComputerContribution#updateProject(ToBeBuilt, IProject, IProgressMonitor)
 */
public ToBeBuilt updateProject(IProject project, IProgressMonitor monitor) throws CoreException, OperationCanceledException {
	final SubMonitor progress = SubMonitor.convert(monitor, Messages.ToBeBuiltComputer_CollectingResources, 10);
	progress.subTask(Messages.ToBeBuiltComputer_CollectingResources);

	final ToBeBuilt toBeBuilt = doRemoveProject(project, progress.split(8));
	if (!project.isAccessible())
		return toBeBuilt;
	if (progress.isCanceled())
		throw new OperationCanceledException();
	final SubMonitor childMonitor = progress.split(1);
	project.accept(new IResourceVisitor() {
		@Override
		public boolean visit(IResource resource) throws CoreException {
			if (progress.isCanceled())
				throw new OperationCanceledException();
			if (resource instanceof IStorage) {
				return updateStorage(childMonitor, toBeBuilt, (IStorage) resource);
			}
			if (resource instanceof IFolder) {
				return isHandled((IFolder) resource);
			}
			return true;
		}
	});
	if (progress.isCanceled())
		throw new OperationCanceledException();
	contribution.updateProject(toBeBuilt, project, progress.split(1));
	return toBeBuilt;
}
 
Example 17
public void search(URI uri, IProgressMonitor monitor) {
	int numResources = Iterables.size(resourceDescriptions.getAllResourceDescriptions());
	SubMonitor subMonitor = SubMonitor.convert(monitor, numResources / 10);
	subMonitor.subTask("Find references in EMF resources");
	try {
		int i = 0;
		for (IResourceDescription resourceDescription : resourceDescriptions.getAllResourceDescriptions()) {
			URI resourceURI = resourceDescription.getURI();
			IResourceServiceProvider resourceServiceProvider = serviceProviderRegistry.getResourceServiceProvider(resourceURI);
			if(resourceServiceProvider != null) {
				IJavaSearchParticipation javaSearchParticipation = resourceServiceProvider
						.get(IJavaSearchParticipation.class);
				if(javaSearchParticipation == null || javaSearchParticipation.canContainJvmReferences(resourceURI))
					searchIn(uri, resourceDescription);
			}
			if (++i % 10 == 0) {
				if (subMonitor.isCanceled()) {
					return; // not throwing OperationCanceledException, as the client in JDT doesn't seem to handle it properly
				}
				subMonitor.worked(1);
			}
		}
		for(ResourceSet resourceSet: projectToResourceSet.values()) {
			resourceSet.getResources().clear();
			resourceSet.eAdapters().clear();
		}
	} finally {
		subMonitor.done();
	}
}
 
Example 18
void checkTsv(final Collection<IFile> files, IProgressMonitor monitor) throws CoreException {
	final SubMonitor subMonitor = SubMonitor.convert(monitor, files.size() * 5);
	final ItemsXmlValidator validator = getValidator();
	for (final IFile file : files) {
		if (subMonitor.isCanceled()) {
			throw new OperationCanceledException("TSV Check cancelled");
		}
		subMonitor.subTask("Checking typesystem: " + file.getFullPath());
		
		processResults(file, validator.analyze(file, subMonitor.newChild(4)), subMonitor.newChild(1));
		
	}
}
 
Example 19
public IStatus run(IProgressMonitor monitor)
{
	List<File> bundleScripts = getBundleScripts(bundleDirectory);
	SubMonitor sub = SubMonitor.convert(monitor, bundleScripts.size() + 1);
	try
	{
		if (bundleScripts.size() > 0)
		{
			boolean useCache = Boolean.valueOf(System.getProperty(USE_BUNDLE_CACHE, Boolean.TRUE.toString()));

			BundleElement be = null;
			if (useCache)
			{
				showBundleLoadInfo("attempting to read cache: " + bundleDirectory); //$NON-NLS-1$
				// include the localization files in the arg we pass here, so that we blow out the cache if
				// translations change!
				List<File> filesTocheckTimestamp = new ArrayList<File>(bundleScripts);
				filesTocheckTimestamp.addAll(localizationFiles(bundleDirectory));
				be = getCacher().load(bundleDirectory, filesTocheckTimestamp,
						sub.newChild(bundleScripts.size()));
			}
			if (be != null)
			{
				showBundleLoadInfo("cache succeeded"); //$NON-NLS-1$

				addBundle(be);
			}
			else
			{
				showBundleLoadInfo("cached failed, loading files directly: " + bundleDirectory); //$NON-NLS-1$

				List<String> bundleLoadPaths = getBundleLoadPaths(bundleDirectory);

				// first script is always bundle.rb, so go ahead
				// and process that
				File bundleScript = bundleScripts.get(0);
				sub.subTask(bundleScript.getAbsolutePath());
				loadScript(bundleScript, true, bundleLoadPaths);
				sub.worked(1);

				// some new scripts may have come in while we were
				// processing bundle.rb, so recalculate the list of
				// scripts to process
				bundleScripts = getBundleScripts(bundleDirectory);

				if (bundleScripts.size() > 0)
				{
					// we've already loaded bundle.rb, so remove it from
					// the list. Note that at this point we have a
					// bundle element for this bundle, so any file
					// events that occur now correctly update the bundle
					// element
					bundleScripts.remove(0);

					// process the rest of the scripts in the bundle
					for (File script : bundleScripts)
					{
						sub.subTask(script.getAbsolutePath());
						loadScript(script, true, bundleLoadPaths);
						sub.worked(1);
					}
				}

				if (useCache)
				{
					getCacher().cache(bundleDirectory, sub.newChild(1));
				}

			}
		}
	}
	finally
	{
		sub.done();
	}
	return Status.OK_STATUS;
}
 
Example 20
/**
 * Create new resource descriptions for a set of resources given by their URIs.
 *
 * @param buildData
 *            The underlying data for the write operation.
 * @param oldState
 *            The old index
 * @param newState
 *            The new index
 * @param monitor
 *            The progress monitor used for user feedback
 */
protected void writeNewResourceDescriptions(
        BuildData buildData,
        IResourceDescriptions oldState,
        CurrentDescriptions newState,
        final IProgressMonitor monitor) {
    int index = 0;
    ResourceSet resourceSet = buildData.getResourceSet();
    Set<URI> toBeUpdated = buildData.getToBeUpdated();
    final SubMonitor subMonitor = SubMonitor.convert(monitor, "Write new resource descriptions", toBeUpdated.size() + 1); // TODO: NLS
    IProject currentProject = getBuiltProject(buildData);
    LoadOperation loadOperation = null;
    try {
    	compilerPhases.setIndexing(resourceSet, true);
        loadOperation = globalIndexResourceLoader.create(resourceSet, currentProject);
        loadOperation.load(toBeUpdated);

        while (loadOperation.hasNext()) {
            if (subMonitor.isCanceled()) {
                loadOperation.cancel();
                throw new OperationCanceledException();
            }

            if (!clusteringPolicy.continueProcessing(resourceSet, null, index)) {
                clearResourceSet(resourceSet);
            }

            URI uri = null;
            Resource resource = null;
            try {
                LoadResult loadResult = loadOperation.next();
                uri = loadResult.getUri();
                resource = addResource(loadResult.getResource(), resourceSet);
                subMonitor.subTask("Writing new resource description " + resource.getURI().lastSegment());
                if (LOGGER.isDebugEnabled()) {
                	LOGGER.debug("Writing new resource description " + uri);
                }

                final IResourceDescription.Manager manager = getResourceDescriptionManager(uri);
                if (manager != null) {
                    // We don't care here about links, we really just want the exported objects so that we can link in the
                    // next phase.
                    final IResourceDescription description = manager.getResourceDescription(resource);
                    final IResourceDescription copiedDescription = new CopiedResourceDescription(description);
                    // We also don't care what kind of Delta we get here; it's just a temporary transport vehicle. That interface
                    // could do with some clean-up, too, because all we actually want to do is register the new resource
                    // description, not the delta.
                    newState.register(new DefaultResourceDescriptionDelta(oldState.getResourceDescription(uri), copiedDescription));
                    buildData.queueURI(uri);
                }
            } catch (final RuntimeException ex) {
                if(ex instanceof LoadOperationException) {
                    uri = ((LoadOperationException) ex).getUri();
                }
                if (uri == null) {
                    LOGGER.error("Error loading resource", ex); //$NON-NLS-1$
                } else {
                    if (resourceSet.getURIConverter().exists(uri, Collections.emptyMap())) {
                        LOGGER.error("Error loading resource from: " + uri.toString(), ex); //$NON-NLS-1$
                    }
                    if (resource != null) {
                        resourceSet.getResources().remove(resource);
                    }
                    final IResourceDescription oldDescription = oldState.getResourceDescription(uri);
                    if (oldDescription != null) {
                        newState.register(new DefaultResourceDescriptionDelta(oldDescription, null));
                    }
                }
                // If we couldn't load it, there's no use trying again: do not add it to the queue
            }
            index++;
            subMonitor.split(1);
        }
    } finally {
    	compilerPhases.setIndexing(resourceSet, false);
        if(loadOperation != null) loadOperation.cancel();
    }
}