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

The following examples show how to use org.eclipse.core.runtime.SubMonitor#setWorkRemaining() . 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
Source Project: thym   File: HybridProject.java    License: Eclipse Public License 1.0 6 votes vote down vote up
public void prepare(IProgressMonitor monitor, final String...options) throws CoreException{
	ISchedulingRule rule = ResourcesPlugin.getWorkspace().getRuleFactory().modifyRule(getProject());
	try{
		Job.getJobManager().beginRule(rule, monitor);
	
		SubMonitor sm = SubMonitor.convert(monitor);
		sm.setWorkRemaining(100);
		ErrorDetectingCLIResult status = getProjectCLI().prepare(sm.newChild(70),options).convertTo(ErrorDetectingCLIResult.class);
		getProject().refreshLocal(IResource.DEPTH_INFINITE, sm.newChild(30));
		if(status.asStatus().getSeverity() == IStatus.ERROR){
			throw new CoreException(status.asStatus());
		}
	} finally {
		Job.getJobManager().endRule(rule);
	}
}
 
Example 2
Source Project: google-cloud-eclipse   File: BuildPath.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Load the list of library dependencies saved for this project.
 */
public static List<Library> loadLibraryList(IJavaProject project, IProgressMonitor monitor)
    throws CoreException {
  SubMonitor progress = SubMonitor.convert(monitor, 10);
  LibraryClasspathContainerSerializer serializer = new LibraryClasspathContainerSerializer();
  List<String> savedLibraryIds;
  try {
    savedLibraryIds = serializer.loadLibraryIds(project);
    progress.worked(3);
  } catch (IOException ex) {
    throw new CoreException(
        StatusUtil.error(BuildPath.class, "Error retrieving project library list", ex)); //$NON-NLS-1$
  }
  List<Library> selectedLibraries = new ArrayList<>();
  progress.setWorkRemaining(savedLibraryIds.size());
  for (String libraryId : savedLibraryIds) {
    Library library = CloudLibraries.getLibrary(libraryId);
    if (library != null) {
      selectedLibraries.add(library);
    }
    progress.worked(1);
  }
  return selectedLibraries;
}
 
Example 3
protected void executeParticipants(ResourceRelocationContext context, SubMonitor monitor) {
	List<? extends IResourceRelocationStrategy> strategies = strategyRegistry.getStrategies();
	if (context.getChangeType() == ResourceRelocationContext.ChangeType.COPY) {
		context.getChangeSerializer().setUpdateRelatedFiles(false);
	}

	monitor.setWorkRemaining(strategies.size());

	for (IResourceRelocationStrategy strategy : strategies) {
		try {
			monitor.split(1);
			strategy.applyChange(context);
		} catch (OperationCanceledException t) {
			issues.add(ERROR, "Operation was cancelled while applying resource changes", t);
			LOG.error(t.getMessage(), t);
			break;
		}
	}
}
 
Example 4
private static void copy(InputStream in, File intermediateFile, long length, SubMonitor monitor) throws IOException {
    try (OutputStream out = new FileOutputStream(intermediateFile)) {
        monitor.setWorkRemaining((int) (length / BYTES_PER_KB));
        byte[] buf = new byte[BYTES_PER_KB * BUFFER_IN_KB];
        int counter = 0;
        for (;;) {
            int n = in.read(buf);
            if (n <= 0) {
                break;
            }
            out.write(buf, 0, n);
            counter = (counter % BYTES_PER_KB) + n;
            monitor.worked(counter / BYTES_PER_KB);
        }
    }
}
 
Example 5
/**
 * Scan the current projects to identify those requiring upgrading.
 */
private Collection<IProject> findCandidates(SubMonitor progress) {
  List<IProject> projects = new ArrayList<>();

  IProject[] allProjects = workspace.getRoot().getProjects();
  progress.setWorkRemaining(allProjects.length);
  for (IProject project : allProjects) {
    if (CloudToolsEclipseProjectUpdater.hasOldContainers(project)) {
      projects.add(project);
    }
    progress.worked(1);
  }
  Collections.sort(projects, Ordering.usingToString());
  return projects;
}
 
Example 6
/**
 * 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 7
/**
 * @since 2.4
 */
protected void findAllIndexedReferences(
		IAcceptor<IReferenceDescription> referenceAcceptor,
		SubMonitor subMonitor,
		Set<URI> targetURIsAsSet,
		ILocalResourceAccess localResourceAccess) {
	TargetURIs targetURIs = converter.fromIterable(targetURIsAsSet);
	if (!targetURIs.isEmpty()) {
		subMonitor.setWorkRemaining(size(indexData.getAllResourceDescriptions()) / MONITOR_CHUNK_SIZE + 1);
		int i = 0;
		IProgressMonitor useMe = subMonitor.newChild(1);
		for (IResourceDescription resourceDescription : indexData.getAllResourceDescriptions()) {
			IResourceServiceProvider serviceProvider = getServiceProviderRegistry().getResourceServiceProvider(resourceDescription.getURI());
			if (serviceProvider != null) {
				IReferenceFinder referenceFinder = serviceProvider.get(IReferenceFinder.class);
				if (referenceFinder instanceof IReferenceFinderExtension1) {
					IReferenceFinderExtension1 extension1 = (IReferenceFinderExtension1) referenceFinder;
					extension1.findReferences(targetURIsAsSet, resourceDescription, referenceAcceptor, useMe, localResourceAccess);
				} else {
					// don't use the language specific reference finder here for backwards compatibility reasons
					findReferences(targetURIsAsSet, resourceDescription, referenceAcceptor, useMe, localResourceAccess);
				}
			}
			i++;
			if (i % MONITOR_CHUNK_SIZE == 0) {
				useMe = subMonitor.newChild(1);
			}
		}
	}
}
 
Example 8
private void installSelectedPlugins(IProject project, IProgressMonitor monitor) throws CoreException{
	SubMonitor subMonitor = SubMonitor.convert(monitor);
	Assert.isNotNull(project);
	HybridProject hybridProject = HybridProject.getHybridProject(project);
	
	CordovaPluginManager pm = new CordovaPluginManager(hybridProject);
	switch (pageThree.getPluginSourceType()){
	case PLUGIN_SOURCE_DIRECTORY:
		File directory = new File(pageThree.getSelectedDirectory());
		pm.installPlugin(directory, subMonitor);
		break;
	case PLUGIN_SOURCE_GIT:
		URI uri = URI.create(pageThree.getSpecifiedGitURL());
		pm.installPlugin(uri, subMonitor);
		break;
	case PLUGIN_SOURCE_REGISTRY:
		List<CordovaRegistryPluginVersion> plugins = pageFour.getSelectedPluginVersions();
		if(!plugins.isEmpty()){
			subMonitor.setWorkRemaining(plugins.size());
			for (CordovaRegistryPluginVersion cordovaRegistryPluginVersion : plugins) {
				pm.installPlugin(cordovaRegistryPluginVersion, subMonitor.split(1));
			}
		}
		break;
	default:
		Assert.isTrue(false, "No valid plugin source can be determined");
		break;
	}

}
 
Example 9
@Override
public void updateProject(ToBeBuilt toBeBuilt, IProject project, IProgressMonitor monitor) throws CoreException {
	SubMonitor progress = SubMonitor.convert(monitor, 2);
	if (progress.isCanceled()) {
		throw new OperationCanceledException();
	}
	if (!project.isAccessible())
		return;
	IJavaProject javaProject = JavaCore.create(project);
	if (javaProject.exists()) {
		IPackageFragmentRoot[] roots = javaProject.getPackageFragmentRoots();
		progress.setWorkRemaining(roots.length);
		final Map<String, Long> updated = Maps.newHashMap();
		ProjectOrder orderedProjects = workspace.computeProjectOrder(workspace.getRoot().getProjects());
		for (final IPackageFragmentRoot root : roots) {
			if (progress.isCanceled())
				throw new OperationCanceledException();
			if (shouldHandle(root) && !isBuiltByUpstream(root, project, orderedProjects.projects)) {
				Map<URI, IStorage> rootData = jdtUriMapperExtension.getAllEntries(root);
				for (Map.Entry<URI, IStorage> e : rootData.entrySet())
					if (uriValidator.canBuild(e.getKey(), e.getValue())) {
						toBeBuilt.getToBeDeleted().add(e.getKey());
						toBeBuilt.getToBeUpdated().add(e.getKey());
					}
			}
			progress.worked(1);
		}
		synchronized (modificationStampCache) {
			modificationStampCache.projectToModificationStamp.putAll(updated);
		}
	}
}
 
Example 10
@Override
protected IStatus run(final IProgressMonitor monitor) {
    int alreadyDone = 0;
    SubMonitor subMonitor = SubMonitor.convert(monitor);
    if (fTraceWithSize != null) {
        subMonitor.beginTask("", fTraceWithSize.size()); //$NON-NLS-1$
    } else {
        subMonitor.beginTask("", IProgressMonitor.UNKNOWN); //$NON-NLS-1$
    }
    while (!monitor.isCanceled()) {
        try {
            long prevNbEvents = fTrace.getNbEvents();
            Thread.sleep(250);
            long nbEvents = fTrace.getNbEvents();
            if (fTraceWithSize != null) {
                final int done = fTraceWithSize.progress();
                subMonitor.setWorkRemaining(fTraceWithSize.size() - done);
                subMonitor.worked(done - alreadyDone);
                alreadyDone = done;
            }
            setName(Messages.TmfCheckpointIndexer_Indexing + ' ' + fTrace.getName() + " (" + String.format("%,d", nbEvents) + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
            // setName doesn't refresh the UI, setTaskName does
            long rate = (nbEvents - prevNbEvents) * 4;
            TraceCompassLogUtils.traceCounter(LOGGER, Level.FINE, fTrace.getName(), "indexed", nbEvents - prevNbEvents); //$NON-NLS-1$
            subMonitor.setTaskName(String.format("%,d", rate) + " " + Messages.TmfCheckpointIndexer_EventsPerSecond); //$NON-NLS-1$ //$NON-NLS-2$
        } catch (final InterruptedException e) {
            return Status.OK_STATUS;
        }
    }
    subMonitor.done();
    monitor.done();
    return fException != null ? new Status(IStatus.ERROR, Activator.PLUGIN_ID, fException.getMessage(), fException) : Status.OK_STATUS;
}
 
Example 11
/**
 * Download the remote content.
 * 
 * @param monitor
 */
protected IStatus download(IProgressMonitor monitor)
{
	SubMonitor subMonitor = SubMonitor.convert(monitor, Messages.DownloadManager_downloadingContent,
			downloads.size());
	MultiStatus multi = new MultiStatus(CoreIOPlugin.PLUGIN_ID, IStatus.OK, null, null);
	completedDownloadsPaths = new ArrayList<IPath>(downloads.size());
	for (Iterator<ContentDownloadRequest> iterator = downloads.iterator(); iterator.hasNext();)
	{
		if (subMonitor.isCanceled())
		{
			// TODO Append to multi status and return that?
			return Status.CANCEL_STATUS;
		}

		ContentDownloadRequest request = iterator.next();
		request.execute(subMonitor.newChild(1));
		IStatus result = request.getResult();
		if (result != null)
		{
			if (result.isOK())
			{
				completedDownloadsPaths.add(request.getDownloadLocation());
				iterator.remove();
			}
			multi.add(result);
		}
		subMonitor.setWorkRemaining(downloads.size());
	}

	return multi;
}
 
Example 12
@Override
protected void execute(IProgressMonitor monitor) throws CoreException,
		InvocationTargetException, InterruptedException {
	SubMonitor sm = SubMonitor.convert(monitor);
	sm.setWorkRemaining(delegates.size()*10);
	for (AbstractNativeBinaryBuildDelegate delegate : delegates) {
		if(monitor.isCanceled()){ 
			break; 
		}
		delegate.setRelease(true);
		delegate.buildNow(sm.newChild(10));
		try {
			File buildArtifact = delegate.getBuildArtifact();
			File destinationFile = new File(destinationDir, buildArtifact.getName());
			if(destinationFile.exists()){
				String callback = overwriteQuery.queryOverwrite(destinationFile.toString());
				if(IOverwriteQuery.NO.equals(callback)){
					continue;
				}
				if(IOverwriteQuery.CANCEL.equals(callback)){
					break;
				}
			}
			File artifact = delegate.getBuildArtifact();
			if(artifact.isDirectory()){
				FileUtils.copyDirectoryToDirectory(artifact, destinationDir);
			}else{
				FileUtils.copyFileToDirectory(artifact, destinationDir);
			}
			sm.done();
		} catch (IOException e) {
			HybridCore.log(IStatus.ERROR, "Error on NativeBinaryExportOperation", e);
		}
	}
	monitor.done(); 
}
 
Example 13
/**
 * Import the Eclipse projects found within the bundle containing {@code clazz} at the {@code
 * relativeLocation}. Return the list of projects imported.
 *
 * @throws IOException if the zip cannot be accessed
 * @throws CoreException if a project cannot be imported
 */
public static Map<String, IProject> importProjects(
    URL fileLocation, boolean checkBuildErrors, IProgressMonitor monitor)
    throws IOException, CoreException {
  SubMonitor progress = SubMonitor.convert(monitor, 100);
  URL zipLocation = FileLocator.toFileURL(fileLocation);
  if (!zipLocation.getProtocol().equals("file")) {
    throw new IOException("could not resolve location to a file");
  }
  File zippedFile = new File(zipLocation.getPath());
  assertTrue(zippedFile.exists());
  progress.worked(5);

  IWorkspaceRoot root = getWorkspace().getRoot();
  // extract projects into our workspace using WTP internal utility class
  // assumes projects are contained in subdirectories within the zip
  IStatus status = ZipUtil.unzip(zippedFile, root.getLocation().toFile(), progress.newChild(10));
  assertTrue("failed to extract: " + status, status.isOK());

  List<IPath> projectFiles = new ArrayList<>();
  try (ZipFile zip = new ZipFile(zippedFile)) {
    for (Enumeration<? extends ZipEntry> it = zip.entries(); it.hasMoreElements();) {
      ZipEntry entry = it.nextElement();
      if (entry.getName().endsWith("/.project")) {
        IPath projectFileLocation = root.getLocation().append(new Path(entry.getName()));
        projectFiles.add(projectFileLocation);
      }
    }
    progress.worked(5);
  }

  // import the projects
  progress.setWorkRemaining(10 * projectFiles.size() + 10);
  Map<String, IProject> projects = new LinkedHashMap<>();
  System.out.printf("Importing %d projects:\n", projectFiles.size());
  for (IPath projectFile : projectFiles) {
    System.out.println("    " + projectFile);
    IProjectDescription descriptor = root.getWorkspace().loadProjectDescription(projectFile);
    IProject project = root.getProject(descriptor.getName());
    // bring in the project to the workspace
    project.create(descriptor, progress.newChild(2));
    project.open(progress.newChild(8));
    projects.put(project.getName(), project);
  }

  // wait for any post-import operations too
  waitForProjects(projects.values());
  if (checkBuildErrors) {
    waitUntilNoBuildErrors();
    // changed from specific projects to see all possible errors
    failIfBuildErrors("Imported projects have errors");
  }

  return projects;
}
 
Example 14
Source Project: google-cloud-eclipse   File: ZipUtil.java    License: Apache License 2.0 4 votes vote down vote up
/** Unzip the contents into the specified destination directory. */
public static IStatus unzip(File zip, File destination, IProgressMonitor monitor) {
  SubMonitor progress = SubMonitor.convert(monitor);
  if (!destination.exists()) {
    if (!destination.mkdirs()) {
      return StatusUtil.error(ZipUtil.class, "Unable to create destination: " + destination);
    }
  } else if (!destination.isDirectory()) {
    return StatusUtil.error(ZipUtil.class, "Destination is not a directory: " + destination);
  }

  try (ZipFile zipFile = new ZipFile(zip)) {
    String canonicalDestination = destination.getCanonicalPath();

    progress.setWorkRemaining(zipFile.size());
    for (Enumeration<? extends ZipEntry> entries = zipFile.entries(); entries.hasMoreElements()
        && !progress.isCanceled();) {
      ZipEntry entry = entries.nextElement();
      File entryLocation = new File(destination, entry.getName());
      if (!entryLocation.getCanonicalPath().startsWith(canonicalDestination + File.separator)) {
        return StatusUtil.error(
            ZipUtil.class, "Blocked unzipping file outside the destination: " + entry.getName());
      }

      if (entry.isDirectory()) {
        if (!entryLocation.exists()) {
          if (!entryLocation.mkdirs()) {
            return StatusUtil.error(ZipUtil.class,
                "Unable to create destination: " + entryLocation);
          }
        } else if (!entryLocation.isDirectory()) {
          return StatusUtil.error(ZipUtil.class,
              "Destination is not a directory: " + entryLocation);
        }
      } else {
        try (InputStream input = zipFile.getInputStream(entry);
            FileOutputStream output = new FileOutputStream(entryLocation)) {
          ByteStreams.copy(input, output);
        }
      }
      progress.worked(1);
    }
    return Status.OK_STATUS;
  } catch (IOException ex) {
    return StatusUtil.error(ZipUtil.class, "Unable to extract zip file: " + zip, ex);
  }
}
 
Example 15
@Override
public void applyModifications(IAcceptor<IEmfResourceChange> changeAcceptor) {
	Set<Resource> resources = Sets.newLinkedHashSet();
	for (Pair<Notifier, IModification<? extends Notifier>> p : modifications) {
		Notifier context = p.getFirst();
		if (context instanceof EObject)
			resources.add(((EObject) context).eResource());
		else if (context instanceof Resource)
			resources.add((Resource) context);
		else if (context instanceof ResourceSet) {
			throw new IllegalStateException("Not supported");
		}
	}
	
	// in the following effort calculation, the amount of resources is doubled for the sake of reflecting
	//  the usually higher effort of indexing the contents of a resource compared to applying a modification
	final int weightedPrepareAndApplyEffort = 2 * resources.size() + modifications.size();
	
	// here, the amount of resources is doubled for the sake of reflecting the still unknown amount of
	//  related resources to be updated later on, too; the additional effort is a rough approximation of
	//  the effort required to determine the (affected) related resources
	final int weightedCreateTextChangesEffort = 2 * resources.size() + additionalEffortInEndRecordChanges;
	
	final SubMonitor monitorInAll = SubMonitor.convert(this.monitor,
			weightedPrepareAndApplyEffort + weightedCreateTextChangesEffort);
	final SubMonitor monitorPrepareAndApply = SubMonitor.convert(
			monitorInAll.split(weightedPrepareAndApplyEffort, SubMonitor.SUPPRESS_NONE),
			"Preparing and applying file changes...", weightedPrepareAndApplyEffort);
	
	for (Resource res : resources) {
		monitorPrepareAndApply.split(2);
		// TODO: use the exact context
		beginRecordChanges(res);
	}
	for (Pair<Notifier, IModification<? extends Notifier>> entry : modifications) {
		monitorPrepareAndApply.split(1);
		apply(entry.getFirst(), entry.getSecond());
	}
	final SubMonitor monitorCreateTextChanges = monitorInAll.split(weightedCreateTextChangesEffort, SubMonitor.SUPPRESS_NONE);
	monitorCreateTextChanges.setWorkRemaining(weightedCreateTextChangesEffort);
	endRecordChanges(changeAcceptor, monitorCreateTextChanges);
}
 
Example 16
@Override
public synchronized IStatus runInUIThread(IProgressMonitor monitor)
{
	SubMonitor sub = SubMonitor.convert(monitor, 4);
	if (sub.isCanceled())
	{
		return Status.CANCEL_STATUS;
	}

	// manage being a part listener
	IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
	if (window != null && window.getActivePage() != null)
	{
		if (fIsPartListener && !applyToAllEditors() && !applyToViews())
		{
			window.getActivePage().removePartListener(this);
			fIsPartListener = false;
		}
		else if (!fIsPartListener)
		{
			window.getActivePage().addPartListener(this);
			fIsPartListener = true;
		}
	}

	if (sub.isCanceled())
	{
		return Status.CANCEL_STATUS;
	}
	sub.setWorkRemaining(3);

	// Apply to editors
	applyThemeToEclipseEditors(getCurrentTheme(), !applyToAllEditors(), sub.newChild(1));
	if (sub.isCanceled())
	{
		return Status.CANCEL_STATUS;
	}

	// Apply to consoles
	applyThemeToConsole(getCurrentTheme(), !applyToViews(), sub.newChild(1));
	if (sub.isCanceled())
	{
		return Status.CANCEL_STATUS;
	}

	// Apply to views
	hijackCurrentViews(window, !applyToViews(), sub.newChild(1));

	sub.done();
	return Status.OK_STATUS;
}
 
Example 17
/**
 * applyDocumentation
 * 
 * @param property
 * @param object
 * @param monitor
 */
private void applyDocumentation(PropertyElement property, JSPropertyCollection object, IProgressMonitor monitor)
{
	if (property == null || object == null)
	{
		return;
	}

	Queue<JSNode> queue = new LinkedList<JSNode>();
	Set<IParseNode> visitedSymbols = new HashSet<IParseNode>();

	// prime the queue
	queue.addAll(object.getValues());
	SubMonitor sub = SubMonitor.convert(monitor, queue.size());

	while (!queue.isEmpty())
	{
		sub.setWorkRemaining(queue.size());
		JSNode node = queue.poll();

		if (!visitedSymbols.contains(node))
		{
			visitedSymbols.add(node);
			// If we have docs for a value, apply it to the property we created.
			DocumentationBlock docs = node.getDocumentation();
			if (docs != null)
			{
				JSTypeUtil.applyDocumentation(property, node, docs);
				break;
			}
			// Otherwise I guess we try to track the values back to find docs?

			// If a value of the property collection is a function and the property is a function
			// Then add the parameters of the value as parameters of the property. WHY?!?!?!
			if (property instanceof FunctionElement && node instanceof JSFunctionNode)
			{
				FunctionElement functionElement = (FunctionElement) property;
				JSFunctionNode functionNode = (JSFunctionNode) node;

				for (IParseNode parameterNode : functionNode.getParameters())
				{
					ParameterElement parameterElement = new ParameterElement();

					parameterElement.setName(parameterNode.getText());
					parameterElement.addType(JSTypeConstants.OBJECT_TYPE);

					functionElement.addParameter(parameterElement);
				}
			}
			// Track an identifier back to it's definition...
			else if (node instanceof JSIdentifierNode)
			{
				// grab name
				String symbol = node.getText();

				JSPropertyCollection p = this.getSymbolProperty(activeScope.getObject(), symbol);

				if (p != null)
				{
					for (JSNode value : p.getValues())
					{
						queue.offer(value);
					}
				}
			}
			// Track an assignment to it's assigned value...
			else if (node instanceof JSAssignmentNode)
			{
				IParseNode rhs = node.getLastChild();

				if (rhs instanceof JSNode)
				{
					queue.offer((JSNode) rhs);
				}
			}
		}
		sub.worked(1);
	}
}
 
Example 18
/**
 * Return a PropertyElement for the specified symbol in the specified property collection. This method uses cached
 * values as it can, creating new elements if none exists in the cache
 * 
 * @param symbol
 *            The property collection to use when processing the specified symbol
 * @param monitor
 *            The name of the symbol to process
 * @return Returns a new PropertyElement (or FunctionElement). This value will not be null
 * @throws OperationCanceledException
 *             When user cancels the long-running operation
 */
public PropertyElement getSymbolPropertyElement(JSPropertyCollection activeObject, String symbol,
		IProgressMonitor monitor) throws OperationCanceledException
{
	JSPropertyCollection property = this.getSymbolProperty(activeObject, symbol);
	PropertyElement result = null;
	SubMonitor sub = SubMonitor.convert(monitor, 50);
	if (property != null)
	{
		// Try to use a cached copy of the PropertyElement we created for this collection!
		if (property.hasElement())
		{
			return property.getElement();
		}

		// Using linked hash set to preserve add order
		Set<String> types = new LinkedHashSet<String>();

		if (property.hasTypes())
		{
			// used cached types
			types.addAll(property.getTypes());
		}
		else
		{
			if (sub.isCanceled())
			{
				throw new OperationCanceledException();
			}
			// infer value types
			this.processValues(property, types, sub.newChild(10));

			if (sub.isCanceled())
			{
				throw new OperationCanceledException();
			}
			// process additional properties, possibly generating a new type
			this.processProperties(property, types, sub.newChild(10));
		}

		sub.setWorkRemaining(30);

		// add types to property
		result = this.createPropertyElement(types);

		if (!CollectionsUtil.isEmpty(types))
		{
			int part = 20 / types.size();
			for (String typeName : types)
			{
				if (sub.isCanceled())
				{
					throw new OperationCanceledException();
				}
				JSTypeUtil.applySignature(result, typeName);
				sub.worked(part);
			}
		}
		sub.setWorkRemaining(10);

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

		// apply any docs info we have to the property
		this.applyDocumentation(result, property, sub.newChild(10));

		// Cache the property we generated for this collection!
		property.setElement(result);
	}
	else
	{
		result = new PropertyElement();
	}

	// set name
	result.setName(symbol);

	return result;
}
 
Example 19
@Override
public void run(IProgressMonitor monitor)
	throws InvocationTargetException, InterruptedException{
	List<Konsultation> initialList = query.execute();
	SubMonitor progress = SubMonitor.convert(monitor, 100);
	
	progress.setTaskName("Vorschlag filter");
	if (addSeries) {
		progress.setWorkRemaining(initialList.size() * 2);
	} else {
		progress.setWorkRemaining(initialList.size());
	}
	for (Konsultation konsultation : initialList) {
		if (progress.isCanceled()) {
			canceled = true;
			return;
		}
		if (!applyFilters(konsultation)) {
			progress.worked(1);
			continue;
		}
		proposal.add(konsultation);
		progress.worked(1);
	}
	if(addSeries) {
		progress.setTaskName("Behandlungsserien laden");
		HashSet<String> knownIds = new HashSet<>();
		knownIds.addAll(
			proposal.parallelStream().map(k -> k.getId()).collect(Collectors.toList()));
		ArrayList<Konsultation> proposalCopy = new ArrayList<>(proposal);
		proposalCopy.forEach(k -> {
			List<Konsultation> series = getSeries(k.getFall());
			// calculate money for kons series
			if (excludeKonsByMoney != null) {
				Money totalForKonsSerie = getSeriesTotal(series);
				if (excludeKonsByMoney.isMoreThan(totalForKonsSerie)) {
					// exclude whole series
					knownIds.addAll(series.parallelStream().map(sk -> sk.getId())
						.collect(Collectors.toList()));
					proposal.remove(k);
				}
			}
			series.forEach(sk -> {
				if (!knownIds.contains(sk.getId())) {
					// only look at sk once
					knownIds.add(sk.getId());
					if (applyFilters(sk)) {
						proposal.add(sk);
					}
				}
			});
			progress.worked(1);
			if (progress.isCanceled()) {
				canceled = true;
				return;
			}
		});
	}
	monitor.done();
}
 
Example 20
/**
 * Indexes a set of {@link IFileStore}s with the appropriate {@link IFileStoreIndexingParticipant}s that apply to
 * the content types (matching is done via filename/extension).
 * 
 * @param index
 * @param fileStores
 * @param monitor
 * @throws CoreException
 */
protected void indexFileStores(Index index, Set<IFileStore> fileStores, IProgressMonitor monitor)
		throws CoreException
{
	if (index == null)
	{
		return;
	}

	fileStores = filterFileStores(fileStores);
	if (CollectionsUtil.isEmpty(fileStores))
	{
		return;
	}

	int remaining = fileStores.size();
	SubMonitor sub = SubMonitor.convert(monitor, remaining * 11);
	try
	{
		for (IFileStore file : fileStores)
		{
			if (sub.isCanceled())
			{
				throw new CoreException(Status.CANCEL_STATUS);
			}
			// First cleanup old index entries for file
			index.remove(file.toURI());
			sub.worked(1);

			// Now run indexers on file
			List<IFileStoreIndexingParticipant> indexers = getIndexParticipants(file);
			if (!CollectionsUtil.isEmpty(indexers))
			{
				int work = 10 / indexers.size();
				BuildContext context = new FileStoreBuildContext(file);
				for (IFileStoreIndexingParticipant indexer : indexers)
				{
					if (sub.isCanceled())
					{
						throw new CoreException(Status.CANCEL_STATUS);
					}
					try
					{
						indexer.index(context, index, sub.newChild(work));
					}
					catch (CoreException e)
					{
						IdeLog.logError(IndexPlugin.getDefault(), e);
					}
				}
			}
			// Update remaining units
			remaining--;
			sub.setWorkRemaining(remaining * 11);
		}
	}
	finally
	{
		sub.done();
	}
}