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

The following examples show how to use org.eclipse.core.runtime.SubMonitor#convert() . 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: AbstractBuilderState.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@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 2
Source File: AbstractProjectCreator.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Override
protected void execute(final IProgressMonitor monitor)
		throws CoreException, InvocationTargetException, InterruptedException {
	SubMonitor subMonitor = SubMonitor.convert(monitor, 
			getCreateModelProjectMessage(), 
			2);
	try {
		final IProject project = createProject(subMonitor.newChild(1));
		if (project == null)
			return;
		enhanceProject(project, subMonitor.newChild(1));
		IFile modelFile = getModelFile(project);
		setResult(modelFile);
	} finally {
		subMonitor.done();
	}
}
 
Example 3
Source File: SyncUtil.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
private void doReconcileAndBuild(final boolean saveAll, IProgressMonitor monitor)
		throws InterruptedException {
	try {
		SubMonitor progress = SubMonitor.convert(monitor, 6);
		reconcileAllEditors(workbench, saveAll, progress.newChild(1));
		if (progress.isCanceled()) {
			throw new InterruptedException();
		}
		waitForBuild(progress.newChild(4));
		if (progress.isCanceled()) {
			throw new InterruptedException();
		}
		yieldToQueuedDisplayJobs(progress.newChild(1));
	} catch(OperationCanceledException e) {
		throw new InterruptedException(); 
	}
}
 
Example 4
Source File: LibraryClasspathContainerResolverService.java    From google-cloud-eclipse with Apache License 2.0 6 votes vote down vote up
@Override
public IStatus resolveAll(IJavaProject javaProject, IProgressMonitor monitor) {
  try {
    MultiStatus status =
        StatusUtil.multi(this, Messages.getString("TaskResolveLibrariesError")); // $NON-NLS-1$
    IClasspathEntry[] rawClasspath = javaProject.getRawClasspath();
    SubMonitor subMonitor =
        SubMonitor.convert(
            monitor,
            Messages.getString("TaskResolveLibraries"), // $NON-NLS-1$
            getTotalWork(rawClasspath));
    for (IClasspathEntry classpathEntry : rawClasspath) {
      String containerId = classpathEntry.getPath().segment(0);
      if (containerId.equals(LibraryClasspathContainer.CONTAINER_PATH_PREFIX)) {
        IStatus resolveContainerStatus =
            resolveContainer(javaProject, classpathEntry.getPath(), subMonitor.newChild(1));
        status.add(resolveContainerStatus);
      }
    }
    // rewrite if OK as otherwise Progress View shows the resolving error message
    return StatusUtil.filter(status);
  } catch (CoreException ex) {
    return StatusUtil.error(
        this, Messages.getString("TaskResolveLibrariesError"), ex); // $NON-NLS-1$
  }
}
 
Example 5
Source File: FileEventHandler.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private static WorkspaceEdit getRenameEdit(IJavaElement targetElement, String newName, IProgressMonitor monitor) throws CoreException {
	RenameSupport renameSupport = RenameSupport.create(targetElement, newName, RenameSupport.UPDATE_REFERENCES);
	if (renameSupport == null) {
		return null;
	}

	if (targetElement instanceof IPackageFragment) {
		((RenamePackageProcessor) renameSupport.getJavaRenameProcessor()).setRenameSubpackages(true);
	}

	RenameRefactoring renameRefactoring = renameSupport.getRenameRefactoring();
	RefactoringTickProvider rtp = renameRefactoring.getRefactoringTickProvider();
	SubMonitor submonitor = SubMonitor.convert(monitor, "Creating rename changes...", rtp.getAllTicks());
	CheckConditionsOperation checkConditionOperation = new CheckConditionsOperation(renameRefactoring, CheckConditionsOperation.ALL_CONDITIONS);
	checkConditionOperation.run(submonitor.split(rtp.getCheckAllConditionsTicks()));
	if (checkConditionOperation.getStatus().getSeverity() >= RefactoringStatus.FATAL) {
		JavaLanguageServerPlugin.logError(checkConditionOperation.getStatus().getMessageMatchingSeverity(RefactoringStatus.ERROR));
	}

	Change change = renameRefactoring.createChange(submonitor.split(rtp.getCreateChangeTicks()));
	change.initializeValidationData(new NotCancelableProgressMonitor(submonitor.split(rtp.getInitializeChangeTicks())));
	return ChangeUtil.convertToWorkspaceEdit(change);
}
 
Example 6
Source File: UnifiedBuilder.java    From APICloud-Studio with GNU General Public License v3.0 5 votes vote down vote up
private void buildEnding(List<IBuildParticipant> participants, IProgressMonitor monitor)
{
	if (participants == null)
	{
		return;
	}
	SubMonitor sub = SubMonitor.convert(monitor, participants.size());
	for (IBuildParticipant participant : participants)
	{
		participant.buildEnding(sub.newChild(1));
	}
	sub.done();
}
 
Example 7
Source File: ExternalLibrariesActionsHelper.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Streamlined process of calculating and installing the dependencies, npm cache cleaning forced by passed flag.
 * <p>
 * <b>IMPORTANT:</b> If <code>npmrcLocation</code> is given (and only then), this method will change the default
 * <code>.npmrc</code> location in the Eclipse preferences and this value will stay in effect after this method
 * returns. Rationale of original implementor:<br>
 * <cite>information about {@code .npmrc} is deep in the NodeProcessBuilder and by design it is not exposed. We
 * could redesign that part and expose it, but it makes sense to assume user selected {@code .npmrc} file while
 * setting up the workspace should be used for further dependencies setups (e.g. quick-fixes in manifests) in this
 * workspace hence we save provided {@code .npmrc} file in the preferences.</cite>
 *
 * @param npmrcLocation
 *            optional path to an <code>.npmrc</code> file to be used during installation of dependencies.
 */
public void cleanAndInstallAllDependencies(Optional<Path> npmrcLocation, SubMonitor monitor,
		MultiStatus multiStatus) {

	try (Measurement m = N4JSDataCollectors.dcInstallHelper.getMeasurement("Install Missing Dependencies")) {

		// configure .npmrc
		if (npmrcLocation.isPresent()) {
			configureNpmrc(npmrcLocation.get(), multiStatus);
		}

		SubMonitor subMonitor = SubMonitor.convert(monitor, 2);

		// remove npms
		multiStatus.merge(maintenanceDeleteNpms(subMonitor.split(1)));

		// install dependencies and force external library workspace reload
		try (Measurement mm = N4JSDataCollectors.dcInstallMissingDeps
				.getMeasurement("Install missing dependencies")) {

			IStatus status = libManager.runNpmYarnInstallOnAllProjects(subMonitor.split(1));
			if (!status.isOK()) {
				multiStatus.merge(status);
			}
		}
	}
}
 
Example 8
Source File: CompositeRefactoringProcessor.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException,
		OperationCanceledException {
	SubMonitor monitor = SubMonitor.convert(pm, processors.size());
	RefactoringStatus status = new RefactoringStatus();
	for (RefactoringProcessor processor : processors) {
		if (pm.isCanceled()) {
			throw new OperationCanceledException();
		}
		status.merge(processor.checkInitialConditions(monitor.newChild(1)));
	}
	return status;
}
 
Example 9
Source File: AbstractReferenceUpdater.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
protected void createReferenceUpdatesForCluster(ElementRenameArguments elementRenameArguments,
		Multimap<URI, IReferenceDescription> resource2references, ResourceSet resourceSet,
		IRefactoringUpdateAcceptor updateAcceptor, StatusWrapper status, IProgressMonitor monitor) {
	SubMonitor progress = SubMonitor.convert(monitor, 100);
	List<URI> unloadableResources = loadReferringResources(resourceSet, resource2references.keySet(), status,
			progress.newChild(10));
	if (progress.isCanceled()) {
		throw new OperationCanceledException();
	}
	for (URI unloadableResouce : unloadableResources)
		resource2references.removeAll(unloadableResouce);
	List<IReferenceDescription> unresolvableReferences = resolveReferenceProxies(resourceSet,
			resource2references.values(), status, progress.newChild(70));
	if (progress.isCanceled()) {
		throw new OperationCanceledException();
	}
	for (IReferenceDescription unresolvableReference : unresolvableReferences) {
		URI unresolvableReferringResource = unresolvableReference.getSourceEObjectUri().trimFragment();
		resource2references.remove(unresolvableReferringResource, unresolvableReference);
	}
	elementRenameArguments.getRenameStrategy().applyDeclarationChange(elementRenameArguments.getNewName(),
			resourceSet);
	if (progress.isCanceled()) {
		throw new OperationCanceledException();
	}
	createReferenceUpdates(elementRenameArguments, resource2references, resourceSet, updateAcceptor,
			progress.newChild(20));
	if (progress.isCanceled()) {
		throw new OperationCanceledException();
	}
	elementRenameArguments.getRenameStrategy().revertDeclarationChange(resourceSet);
}
 
Example 10
Source File: TextSearchVisitor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected IStatus run(IProgressMonitor inner) {
	MultiStatus multiStatus=
			new MultiStatus(IConstants.PLUGIN_ID, IStatus.OK, "Problems encountered during text search.", null);
	SubMonitor subMonitor= SubMonitor.convert(inner, fEnd - fBegin);
	this.fileCharSequenceProvider= new FileCharSequenceProvider();
	for (int i= fBegin; i < fEnd && !fFatalError; i++) {
		IStatus status= processFile(fFiles[i], subMonitor.split(1));
		// Only accumulate interesting status
		if (!status.isOK())
		 {
			multiStatus.add(status);
		// Group cancellation is propagated to this job's monitor.
		// Stop processing and return the status for the completed jobs.
		}
	}
	if (charsequenceForPreviousLocation != null) {
		try {
			fileCharSequenceProvider.releaseCharSequence(charsequenceForPreviousLocation);
		} catch (IOException e) {
			JavaLanguageServerPlugin.logException(e.getMessage(), e);
		} finally {
			charsequenceForPreviousLocation= null;
		}
	}
	fileCharSequenceProvider= null;
	previousLocationFromFile= null;
	occurencesForPreviousLocation= null;
	return multiStatus;
}
 
Example 11
Source File: SarlExampleInstallerWizard.java    From sarl with Apache License 2.0 5 votes vote down vote up
@Override
protected void installProject(ProjectDescriptor projectDescriptor, IProgressMonitor progressMonitor)
		throws Exception {
	final SubMonitor mon = SubMonitor.convert(progressMonitor, 2);
	super.installProject(projectDescriptor, mon.newChild(1));
	postProjectInstallation(projectDescriptor, mon.newChild(1));
}
 
Example 12
Source File: NewSarlEnumerationWizardPage.java    From sarl with Apache License 2.0 5 votes vote down vote up
@Override
protected void generateTypeContent(ISourceAppender appender, IJvmTypeProvider typeProvider,
		String comment, IProgressMonitor monitor) throws Exception {
	final SubMonitor mon = SubMonitor.convert(monitor, 2);
	final ScriptSourceAppender scriptBuilder = this.codeBuilderFactory.buildScript(
			getPackageFragment().getElementName(), typeProvider);
	final ISarlEnumerationBuilder annotation = scriptBuilder.addSarlEnumeration(getTypeName());
	annotation.setDocumentation(comment);
	mon.worked(1);
	scriptBuilder.build(appender);
	mon.done();
}
 
Example 13
Source File: NewSarlInterfaceWizardPage.java    From sarl with Apache License 2.0 5 votes vote down vote up
@Override
protected void generateTypeContent(ISourceAppender appender, IJvmTypeProvider typeProvider,
		String comment, IProgressMonitor monitor) throws Exception {
	final SubMonitor mon = SubMonitor.convert(monitor, 2);
	final ScriptSourceAppender scriptBuilder = this.codeBuilderFactory.buildScript(
			getPackageFragment().getElementName(), typeProvider);
	final ISarlInterfaceBuilder inter = scriptBuilder.addSarlInterface(getTypeName());
	for (final String type : getSuperInterfaces()) {
		inter.addExtends(type);
	}
	inter.setDocumentation(comment);
	mon.worked(1);
	scriptBuilder.build(appender);
	mon.done();
}
 
Example 14
Source File: BundleCacher.java    From APICloud-Studio with GNU General Public License v3.0 5 votes vote down vote up
private boolean anyFilesNewer(File cacheFile, List<File> bundleFiles, IProgressMonitor monitor)
{
	SubMonitor sub = SubMonitor.convert(monitor, bundleFiles.size());
	try
	{
		// Compare lastMod versus all the bundleFiles.
		long lastMod = cacheFile.lastModified();
		for (File file : bundleFiles)
		{
			sub.subTask(MessageFormat.format(Messages.BundleCacher_ComparingTimestampSubTaskName,
					file.getAbsolutePath()));
			// assume if there's exactly the same value then we should be safe and reload
			if (file.lastModified() >= lastMod)
			{
				// One of the files is newer, don't load cache! This will reload everything from disk and rewrite
				// the cache
				IdeLog.logInfo(ScriptingActivator.getDefault(),
						MessageFormat.format(Messages.BundleCacher_OutOfDateCacheMsg, file.getPath()));
				return true;
			}
		}
	}
	finally
	{
		sub.done();
	}
	return false;
}
 
Example 15
Source File: CreateAppEngineWtpProject.java    From google-cloud-eclipse with Apache License 2.0 5 votes vote down vote up
private static void enableMavenNature(IProject newProject, IProgressMonitor monitor)
    throws CoreException {
  SubMonitor subMonitor = SubMonitor.convert(monitor, 30);

  ResolverConfiguration resolverConfiguration = new ResolverConfiguration();
  MavenPlugin.getProjectConfigurationManager().enableMavenNature(newProject,
      resolverConfiguration, subMonitor.newChild(20));

  // M2E will cleverly set "target/<artifact ID>-<version>/WEB-INF/classes" as a new Java output
  // folder; delete the default old folder.
  newProject.getFolder("build").delete(true /* force */, subMonitor.newChild(2));
}
 
Example 16
Source File: ConnectionUtil.java    From codewind-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
private static ProcessResult runConnectionCmd(String[] command, String[] options, String[] args, boolean checkOutput, IProgressMonitor monitor) throws IOException, JSONException, TimeoutException {
	SubMonitor mon = SubMonitor.convert(monitor, 100);
	Process process = null;
	try {
		process = CLIUtil.runCWCTL(CLIUtil.GLOBAL_JSON_INSECURE, command, options, args);
		ProcessResult result = ProcessHelper.waitForProcess(process, 500, 60, mon);
		CLIUtil.checkResult(command, result, checkOutput);
		return result;
	} finally {
		if (process != null && process.isAlive()) {
			process.destroy();
		}
	}
}
 
Example 17
Source File: BuilderParticipant.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
protected void refreshOutputFolders(IBuildContext ctx, Map<String, OutputConfiguration> outputConfigurations,
		IProgressMonitor monitor) throws CoreException {
	SubMonitor subMonitor = SubMonitor.convert(monitor, outputConfigurations.size());
	for (OutputConfiguration config : outputConfigurations.values()) {
		SubMonitor split = subMonitor.split(1);
		final IProject project = ctx.getBuiltProject();
		for (IContainer container : getOutputs(project, config)) {
			if (monitor.isCanceled()) {
				throw new OperationCanceledException();
			}
			sync(container, IResource.DEPTH_INFINITE, split);
		}
	}
}
 
Example 18
Source File: ZipUtil.java    From APICloud-Studio with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Do the dirty work of actually extracting a {@link ZipEntry} to it's destination.
 * 
 * @param zip
 * @param entry
 * @param destinationPath
 * @param transformer
 * @param conflicts
 * @param howToResolve
 * @param monitor
 * @return
 */
private static IStatus extractEntry(ZipFile zip, ZipEntry entry, File destinationPath,
		IInputStreamTransformer transformer, Conflict howToResolve, IProgressMonitor monitor)
{
	// Return early since this is only supposed to handle files.
	if (entry.isDirectory())
	{
		return Status.OK_STATUS;
	}

	SubMonitor subMonitor = SubMonitor.convert(monitor, 100);
	String name = entry.getName();
	File file = new File(destinationPath, name);
	if (IdeLog.isInfoEnabled(CorePlugin.getDefault(), IDebugScopes.ZIPUTIL))
	{
		IdeLog.logInfo(CorePlugin.getDefault(),
				MessageFormat.format("Extracting {0} as {1}", name, file.getAbsolutePath()), IDebugScopes.ZIPUTIL); //$NON-NLS-1$
	}
	subMonitor.setTaskName(Messages.ZipUtil_extract_prefix_label + name);
	subMonitor.worked(2);
	try
	{
		if (file.exists())
		{
			switch (howToResolve)
			{
				case OVERWRITE:
					if (IdeLog.isInfoEnabled(CorePlugin.getDefault(), IDebugScopes.ZIPUTIL))
					{
						IdeLog.logInfo(
								CorePlugin.getDefault(),
								MessageFormat.format(
										"Deleting a file/directory before overwrite {0}", file.getAbsolutePath()), IDebugScopes.ZIPUTIL); //$NON-NLS-1$
					}
					FileUtil.deleteRecursively(file);
					break;

				case SKIP:
					return Status.OK_STATUS;

				case PROMPT:
					return new Status(IStatus.INFO, CorePlugin.PLUGIN_ID, ERR_CONFLICTS, name, null);
			}
		}
		subMonitor.setWorkRemaining(95);

		extractFile(zip, entry, destinationPath, file, transformer, subMonitor.newChild(95));
	}

	finally
	{
		subMonitor.done();
	}

	return Status.OK_STATUS;
}
 
Example 19
Source File: AbstractFoldingComputer.java    From APICloud-Studio with GNU General Public License v3.0 4 votes vote down vote up
public Map<ProjectionAnnotation, Position> emitFoldingRegions(boolean initialReconcile, IProgressMonitor monitor,
		IParseRootNode parseNode) throws BadLocationException
{
	this.initialReconcile = initialReconcile;
	fLines = new ArrayList<Integer>();
	int lineCount = getDocument().getNumberOfLines();
	if (lineCount <= 1) // Quick hack fix for minified files. We need at least two lines to have folding!
	{
		return Collections.emptyMap();
	}
	SubMonitor sub = null;
	try
	{
		if (parseNode == null)
		{
			return Collections.emptyMap();
		}
		int length = parseNode.getChildCount();
		if (parseNode instanceof IParseRootNode)
		{
			IParseRootNode prn = (IParseRootNode) parseNode;
			IParseNode[] comments = prn.getCommentNodes();
			if (comments != null && comments.length > 0)
			{
				length += comments.length;
			}
		}
		sub = SubMonitor.convert(monitor, Messages.CommonReconcilingStrategy_FoldingTaskName, length);
		SubMonitor subMonitor = sub.newChild(length);
		Map<ProjectionAnnotation, Position> positions = getPositions(subMonitor, parseNode);
		// In case the getPositions call canceled the monitor, we cancel the 'parent' monitor as well.
		// This will cause the system to skip a foldings update (see CommonReconcilingStrategy#calculatePositions).
		if (subMonitor.isCanceled())
		{
			monitor.setCanceled(true);
		}
		return positions;
	}
	finally
	{
		fLines = null;
		if (sub != null)
		{
			sub.done();
		}
	}
}
 
Example 20
Source File: CodewindConnection.java    From codewind-eclipse with Eclipse Public License 2.0 4 votes vote down vote up
public void connect(IProgressMonitor monitor) throws IOException, URISyntaxException, JSONException {
	if (isConnected) {
		return;
	}
	
	SubMonitor mon = SubMonitor.convert(monitor, 100);
	mon.setTaskName(NLS.bind(Messages.Connection_TaskLabel, this.baseUri));
	if (!waitForReady(mon.split(20))) {
		if (mon.isCanceled()) {
			return;
		}
		Logger.logError("Timed out waiting for Codewind to go into ready state.");
		onInitFail(Messages.Connection_ErrConnection_CodewindNotReady);
	}
	
	mon.split(25);
	env = new ConnectionEnv(getEnvData(this.baseUri));
	Logger.log("Codewind version is: " + env.getVersion());	// $NON-NLS-1$
	if (!isSupportedVersion(env.getVersion())) {
		Logger.logError("The detected version of Codewind is not supported: " + env.getVersion() + ", url: " + baseUri);	// $NON-NLS-1$	// $NON-NLS-2$
		onInitFail(NLS.bind(Messages.Connection_ErrConnection_OldVersion, env.getVersion(), InstallUtil.getDefaultInstallVersion()));
	}
	if (mon.isCanceled()) {
		return;
	}

	socket = new CodewindSocket(this);
	if(!socket.blockUntilFirstConnection(mon.split(35))) {
		Logger.logError("Socket failed to connect: " + socket.socketUri);
		disconnect();
		throw new CodewindConnectionException(socket.socketUri);
	}
	if (mon.isCanceled()) {
		socket.close();
		return;
	}
	
	File cwctl = new File(CLIUtil.getCWCTLExecutable());
	filewatcher = new CodewindFilewatcherdConnection(baseUri.toString(), cwctl, new ICodewindProjectTranslator() {
		@Override
		public Optional<String> getProjectId(IProject project) {
			if (project != null) {
				CodewindApplication app = getAppByLocation(project.getLocation());
				if (app != null) {
					return Optional.of(app.projectID);
				}
			}
			return Optional.empty();
		}
	}, getAuthManager());
	
	if (mon.isCanceled()) {
		disconnect();
		return;
	}
	
	isConnected = true;

	Logger.log("Connected to: " + this); //$NON-NLS-1$
	
	mon.split(20);
	refreshApps(null);
}