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

The following examples show how to use org.eclipse.core.runtime.SubMonitor#beginTask() . 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 File: ProjectsSettingsFilesLocator.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
/** performs shallow and then deep scan of the file system */
private void scan(Set<File> roots, Set<File> files, IProgressMonitor monitor) {
	final SubMonitor subMonitor = SubMonitor.convert(monitor, 100);
	final SubMonitor shallowMonitor = subMonitor.split(10);
	shallowMonitor.beginTask("Scanning workspace roots for config files", 10);
	shallowMonitor.beginTask("Shallow workspace scan...", files.size());
	for (File file : files) {
		if (monitor.isCanceled())
			break;
		processFile(file);
		shallowMonitor.worked(1);
	}

	Set<Path> actualRoots = getProjectsRoots(roots);

	final SubMonitor deepMonitor = subMonitor.split(90);
	deepMonitor.beginTask("Deep workspace scan...", roots.size());
	for (Path path : actualRoots) {
		if (monitor.isCanceled())
			break;
		File root = path.toFile();
		deepMonitor.setTaskName("Scanning " + root.getName() + "...");
		processContainer(root);
		deepMonitor.worked(1);
	}
}
 
Example 2
Source File: AbstractReferenceUpdater.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
protected void createReferenceUpdates(
		ElementRenameArguments elementRenameArguments,
		Iterable<IReferenceDescription> referenceDescriptions,
		IRefactoringUpdateAcceptor updateAcceptor,
		RefactoringResourceSetProvider resourceSetProvider,
		IProgressMonitor monitor) {
	SubMonitor progress = SubMonitor.convert(monitor, 100);
	progress.beginTask("Sort references by project", 1);
	Multimap<IProject, IReferenceDescription> project2references = sorter.sortByProject(referenceDescriptions);
	SubMonitor allProjectsProgress = progress.newChild(98).setWorkRemaining(project2references.keySet().size());
	for (IProject project : project2references.keySet()) {
		if (allProjectsProgress.isCanceled()) {
			throw new OperationCanceledException();
		}
		Multimap<URI, IReferenceDescription> resource2references = sorter.sortByResource(project2references
				.get(project));
		ResourceSet resourceSet = resourceSetProvider.get(project);
		StatusWrapper status = updateAcceptor.getRefactoringStatus();
		createClusteredReferenceUpdates(elementRenameArguments, resource2references, resourceSet, updateAcceptor,
				status, allProjectsProgress.newChild(1));
	}
}
 
Example 3
Source File: CliParserManager.java    From tracecompass with Eclipse Public License 2.0 6 votes vote down vote up
@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 4
Source File: ImportWizard.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
protected void applyDiff ( final IProgressMonitor parentMonitor ) throws InterruptedException, ExecutionException
{
    final SubMonitor monitor = SubMonitor.convert ( parentMonitor, 100 );
    monitor.setTaskName ( Messages.ImportWizard_TaskName );

    final Collection<DiffEntry> result = this.mergeController.merge ( wrap ( monitor.newChild ( 10 ) ) );
    if ( result.isEmpty () )
    {
        monitor.done ();
        return;
    }

    final Iterable<List<DiffEntry>> splitted = Iterables.partition ( result, Activator.getDefault ().getPreferenceStore ().getInt ( PreferenceConstants.P_DEFAULT_CHUNK_SIZE ) );

    final SubMonitor sub = monitor.newChild ( 90 );

    try
    {
        final int size = Iterables.size ( splitted );
        sub.beginTask ( Messages.ImportWizard_TaskName, size );

        int pos = 0;
        for ( final Iterable<DiffEntry> i : splitted )
        {
            sub.subTask ( String.format ( Messages.ImportWizard_SubTaskName, pos, size ) );
            final List<DiffEntry> entries = new LinkedList<DiffEntry> ();
            Iterables.addAll ( entries, i );
            final NotifyFuture<Void> future = this.connection.getConnection ().applyDiff ( entries, null, new DisplayCallbackHandler ( getShell (), "Apply diff", "Confirmation for applying diff is required" ) );
            future.get ();

            pos++;
            sub.worked ( 1 );
        }
    }
    finally
    {
        sub.done ();
    }

}
 
Example 5
Source File: ResourceRelocationProcessor.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
public Change createChange(String name, ResourceRelocationContext.ChangeType type, IProgressMonitor pm)
		throws CoreException, OperationCanceledException {
	if (uriChanges.isEmpty()) {
		return null;
	}

	SubMonitor subMonitor = SubMonitor.convert(pm);
	// Declaring the task and its effort in 'SubMonitor.convert(...)' doesn't yield the expected UI updates
	// so let's do it separately; the total effort of '5' is chosen for weighting the subsequent efforts
	subMonitor.beginTask("Preparing the refactoring...", 5);

	IChangeSerializer changeSerializer = changeSerializerProvider.get();
	ResourceSet resourceSet = resourceSetProvider.get(project);

	ResourceRelocationContext context = new ResourceRelocationContext(type, uriChanges, issues, changeSerializer, resourceSet);
	boolean persistedIndexUsageRequested = isPersistedIndexUsageRequested(context);

	// TODO check preconditions like all editors being saved if 'persistedIndexUsageRequested' == true

	initializeResourceSet(persistedIndexUsageRequested, context);
	executeParticipants(context, subMonitor.split(1));

	ChangeConverter changeConverter = changeConverterFactory.create(name, //
			(it) -> {
				return (!(it instanceof MoveResourceChange || it instanceof RenameResourceChange)
						|| !excludedResources.contains(it.getModifiedElement()));
			}, issues);

	SubMonitor modificationApplicationMonitor = subMonitor.split(4); // remaining effort is assigned to 'changeSerializer's work
	changeSerializer.setProgressMonitor(modificationApplicationMonitor);
	changeSerializer.applyModifications(changeConverter);
	modificationApplicationMonitor.done();
	return changeConverter.getChange();
}
 
Example 6
Source File: WorkbenchMarkerResolutionAdapter.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void run(IMarker[] markers, IProgressMonitor progressMonitor) {
	Map<IProject, List<IMarker>> markersByProject = Arrays.asList(markers).stream() //
			.collect(Collectors.groupingBy(marker -> marker.getResource().getProject()));

	SubMonitor monitor = SubMonitor.convert(progressMonitor);
	monitor.beginTask("Applying resolutions", markersByProject.size());

	markersByProject.forEach((key, value) -> {
		BatchModification batch = batchModificationProvider.get();
		batch.setProject(key);

		List<IBatchableModification> modifications = new ArrayList<>();
		List<IMarker> markersInProject = value;
		markersInProject.forEach(marker -> {
			IssueResolution resolution = resolution(marker);
			if (resolution != null) {
				IModification modification = resolution.getModification();
				if (modification instanceof IBatchableModification) {
					modifications.add((IBatchableModification) modification);
				}
			}
		});
		
		cancelIfNeeded(monitor);

		batch.apply(modifications, monitor.newChild(1));
		cancelIfNeeded(monitor);
	});

	monitor.done();
}
 
Example 7
Source File: TmfCheckpointIndexer.java    From tracecompass with Eclipse Public License 2.0 5 votes vote down vote up
@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 8
Source File: RemoteImportTracesOperation.java    From tracecompass with Eclipse Public License 2.0 5 votes vote down vote up
private IResource downloadFileTrace(IFileStore trace, IFolder traceFolder, IProgressMonitor monitor) throws CoreException, IOException, InterruptedException {

        IFolder folder = traceFolder;
        String traceName = trace.getName();

        traceName = TmfTraceCoreUtils.validateName(traceName);

        IResource resource = folder.findMember(traceName);
        if ((resource != null) && resource.exists()) {
            String newName = fConflictHandler.checkAndHandleNameClash(resource.getFullPath(), monitor);
            if (newName == null) {
                return null;
            }
            traceName = newName;
        }
        SubMonitor subMonitor = SubMonitor.convert(monitor, 1);
        subMonitor.beginTask(RemoteMessages.RemoteImportTracesOperation_DownloadTask, 1);

        IPath destination = folder.getLocation().addTrailingSeparator().append(traceName);
        IFileInfo info = trace.fetchInfo();
        subMonitor.setTaskName(RemoteMessages.RemoteImportTracesOperation_DownloadTask + ' ' + trace.getName() + '/' + trace.getName());
        try (InputStream in = trace.openInputStream(EFS.NONE, new NullProgressMonitor())) {
            copy(in, folder, destination, subMonitor, info.getLength());
        }
        folder.refreshLocal(IResource.DEPTH_INFINITE, null);
        return folder.findMember(traceName);
    }
 
Example 9
Source File: LoadHandler.java    From tracecompass with Eclipse Public License 2.0 5 votes vote down vote up
private static void loadRemoteProfile(final TraceSessionGroup sessionGroup, IProgressMonitor monitor, List<IFileStore> files, boolean isForce) throws ExecutionException, InterruptedException  {
    SubMonitor subMonitor = SubMonitor.convert(monitor, files.size());
        for (IFileStore file : files) {
            // Check if operation was cancelled.
            if (subMonitor.isCanceled()) {
                throw new InterruptedException();
            }
            subMonitor.beginTask(NLS.bind(Messages.TraceControl_LoadTask, file.getName()), 1);
            sessionGroup.loadSession(file.toURI().getPath(), isForce, subMonitor);
            subMonitor.done();
        }
}
 
Example 10
Source File: BuildSettingWizardPage.java    From sarl with Apache License 2.0 5 votes vote down vote up
private void doRemoveProject(IProgressMonitor monitor) throws InvocationTargetException {
	// Test if the project is inside the workspace
	final boolean noProgressMonitor = this.currProjectLocation == null;
	final SubMonitor subMonitor = SubMonitor.convert(noProgressMonitor ? null : monitor, 3);
	subMonitor.beginTask(NewWizardMessages.NewJavaProjectWizardPageTwo_operation_remove, 3);
	try {
		try {
			final URI projLoc = this.currProject.getLocationURI();

			final boolean removeContent = !this.keepContent
					&& this.currProject.isSynchronized(IResource.DEPTH_INFINITE);
			if (!removeContent) {
				restoreExistingFolders(projLoc);
			}
			this.currProject.delete(removeContent, false, subMonitor.newChild(2));

			restoreExistingFiles(projLoc, subMonitor.newChild(1));
		} finally {
			// fIsAutobuild must be set
			CoreUtility.setAutoBuilding(this.isAutobuild.booleanValue());
			this.isAutobuild = null;
		}
	} catch (CoreException e) {
		throw new InvocationTargetException(e);
	} finally {
		subMonitor.done();
		this.currProject = null;
		this.keepContent = false;
	}
}
 
Example 11
Source File: RemoteImportTracesOperation.java    From tracecompass with Eclipse Public License 2.0 4 votes vote down vote up
private IResource downloadDirectoryTrace(IFileStore trace, IFolder traceFolder, IProgressMonitor monitor) throws CoreException, IOException, InterruptedException {

        IFileStore[] sources = trace.childStores(EFS.NONE, monitor);

        // Don't import just the metadata file
        if (sources.length > 1) {
            String traceName = trace.getName();

            traceName = TmfTraceCoreUtils.validateName(traceName);

            IFolder folder = traceFolder.getFolder(traceName);
            String newName = fConflictHandler.checkAndHandleNameClash(folder.getFullPath(), monitor);
            if (newName == null) {
                return null;
            }

            folder = traceFolder.getFolder(newName);
            folder.create(true, true, null);

            SubMonitor subMonitor = SubMonitor.convert(monitor, sources.length);
            subMonitor.beginTask(RemoteMessages.RemoteImportTracesOperation_DownloadTask, sources.length);

            for (IFileStore source : sources) {
                if (subMonitor.isCanceled()) {
                    throw new InterruptedException();
                }

                IPath destination = folder.getLocation().addTrailingSeparator().append(source.getName());
                IFileInfo info = source.fetchInfo();
                // TODO allow for downloading index directory and files
                if (!info.isDirectory()) {
                    SubMonitor childMonitor = subMonitor.newChild(1);
                    childMonitor.setTaskName(RemoteMessages.RemoteImportTracesOperation_DownloadTask + ' ' + trace.getName() + '/' + source.getName());
                    try (InputStream in = source.openInputStream(EFS.NONE, new NullProgressMonitor())) {
                        copy(in, folder, destination, childMonitor, info.getLength());
                    }
                }
            }
            folder.refreshLocal(IResource.DEPTH_INFINITE, null);
            return folder;
        }
        return null;
    }
 
Example 12
Source File: GSWorker.java    From slr-toolkit with Eclipse Public License 1.0 4 votes vote down vote up
public IStatus work(SubMonitor mon) {
	this.monitor = mon;
	IStatus s;

	mon.setTaskName("Preparing Google Scholar Session");
	s = this.initSession();
	if (!s.isOK()) {
		out.print("@Comment { Status: " + s.getMessage() + " }\n");
		out.close();
		return s;
	}

	// set monitor to a maximum of 100 pages x 10 entries
	mon.beginTask("Loading Entries", 1000);

	int last = 10;
	int start = 0;
	while (last > 0) {
		// Update Monitor
		mon.subTask("Loading Page " + ((start / 10) + 1));

		try {
			// Load Page
			out.print("@Comment { PageLoad: Offset " + start + " } \n");
			HtmlPage Results = webClient.getPage((start > 0) ? base + "&start=" + start : base);

			// Timeouts
			s = waitLikeUser();
			if (!s.isOK()) {
				out.print("@Comment { Status: " + s.getMessage() + " }\n");
				out.close();
				return s;
			}
			s = waitForJs(Results);
			if (!s.isOK()) {
				out.print("@Comment { Status: " + s.getMessage() + " }\n");
				out.close();
				return s;
			}

			// preparing sub task monitor for entries
			SubMonitor entries = monitor.newChild(10);

			// search for bib links
			last = 0;
			for (HtmlAnchor a : Results.getAnchors()) {
				// update submonitor
				entries.subTask("Loading Page " + ((start / 10) + 1) + " - Entry " + (last + 1));

				if (a.getHrefAttribute().contains("scholar.bib")) {
					// Load entry
					TextPage Result = webClient.getPage(a.getHrefAttribute());

					// Write entry
					out.print(Result.getContent() + "\n");

					// Timeouts
					s = waitLikeUser();
					if (!s.isOK()) {
						out.print("@Comment { Status: " + s.getMessage() + " }\n");
						out.close();
						return s;
					}
					s = waitForJs(Results);
					if (!s.isOK()) {
						out.print("@Comment { Status: " + s.getMessage() + " }\n");
						out.close();
						return s;
					}

					// Increment Counter
					last++;

					// increment monitor
					entries.worked(1);
				}
			}
			entries.done();
		} catch (FailingHttpStatusCodeException | IOException e) {
			out.print("@Comment { Error: " + e.getLocalizedMessage() + " }");
			out.close();
			return new Status(Status.ERROR, "de.tudresden.slr.googlescholar", "Could not load page or entry", e);
		}

		// Increment Offset
		start += 10;
	}

	out.print("@Comment { Finished }");
	out.close();
	monitor.done();
	return Status.OK_STATUS;
}