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

The following examples show how to use org.eclipse.core.runtime.SubMonitor#split() . 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
boolean blockUntilFirstConnection(IProgressMonitor monitor) {
	SubMonitor mon = SubMonitor.convert(monitor, 2500);
	final int delay = 100;
	final int timeout = 2500;
	int waited = 0;
	while(!hasConnected && waited < timeout) {
		mon.split(100);
		try {
			Thread.sleep(delay);
			waited += delay;

			if (waited % (5 * delay) == 0) {
				Logger.log("Waiting for CodewindSocket initial connection"); //$NON-NLS-1$
			}
		}
		catch(InterruptedException e) {
			Logger.logError(e);
		}
		if (mon.isCanceled()) {
			return false;
		}
	}
	Logger.log("CodewindSocket initialized in time ? " + hasConnected); //$NON-NLS-1$
	return hasConnected;
}
 
Example 2
public static void cleanup(String projectName, CodewindConnection connection) {
	Job job = new Job(NLS.bind(Messages.ProjectCleanupJobLabel, projectName)) {
		@Override
		protected IStatus run(IProgressMonitor monitor) {
			SubMonitor mon = SubMonitor.convert(monitor, 30);
			mon.split(10);
			connection.refreshApps(null);
			CodewindApplication app = connection.getAppByName(projectName);
			if (app != null) {
				try {
					ProjectUtil.removeProject(app.name, app.projectID, mon.split(20));
				} catch (Exception e) {
					Logger.logError("An error occurred while trying to remove the project after bind project terminated for: " + projectName, e);
					return new Status(IStatus.ERROR, CodewindUIPlugin.PLUGIN_ID, NLS.bind(Messages.ProjectCleanupError, projectName), null);
				}
			}
			return Status.OK_STATUS;
		}
	};
	job.schedule();
}
 
Example 3
/** 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 4
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 5
@Override
synchronized public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
	int projectsCount = ResourcesPlugin.getWorkspace().getRoot().getProjects().length;
	int estimate = projectsCount > 0 ? projectsCount : 100;
	final SubMonitor subMonitor = SubMonitor.convert(monitor, 3 * estimate);
	final SubMonitor subMonitor0 = subMonitor.split(estimate);
	refreshWorkspace(subMonitor0);

	final SubMonitor subMonitor1 = subMonitor.split(2 * estimate);
	files = ProjectsSettingsFilesLocator.findFiles(subMonitor1);

}
 
Example 6
/** Organize provided file. */
public static void organizeImportsInFile(IFile currentFile, final Interaction interaction, SubMonitor subMon)
		throws CoreException {
	SubMonitor subSubMon = subMon.split(1, SubMonitor.SUPPRESS_NONE);
	subSubMon.setTaskName(currentFile.getName());
	DocumentImportsOrganizer imortsOrganizer = getOrganizeImports(currentFile);
	imortsOrganizer.organizeFile(currentFile, interaction, subSubMon);
}
 
Example 7
Source Project: n4js   File: LibraryManager.java    License: Eclipse Public License 1.0 5 votes vote down vote up
/** Runs 'npm/yarn install' in a given folder. Afterwards, re-registers all npms. */
public IStatus runNpmYarnInstall(PlatformResourceURI target, IProgressMonitor monitor) {
	IN4JSProject project = n4jsCore.findProject(target.toURI()).orNull();
	File projectFolder = project.getLocation().toJavaIoFile();

	boolean usingYarn = npmCli.isYarnUsed(projectFolder);

	String msg = "Running '" + (usingYarn ? "yarn" : "npm") + " install' on " + project.getProjectName();
	MultiStatus status = statusHelper.createMultiStatus(msg);
	logger.logInfo(msg);

	IStatus binaryStatus = checkBinary(usingYarn);
	if (!binaryStatus.isOK()) {
		status.merge(binaryStatus);
		return status;
	}

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

	SubMonitor subMonitor1 = subMonitor.split(1);
	subMonitor1.setTaskName("Building installed packages...");

	// Calculate the folder in which npm/yarn should be executed, either local project folder
	// or yarn root folder
	NodeModulesFolder nmf = nodeModulesDiscoveryHelper.getNodeModulesFolder(projectFolder.toPath());
	File nmfFile = nmf.isYarnWorkspace() ? nmf.workspaceNodeModulesFolder : nmf.localNodeModulesFolder;
	File folderInWhichToExecute = nmfFile.getParentFile();

	npmCli.runNpmYarnInstall(folderInWhichToExecute);

	SubMonitor subMonitor2 = subMonitor.split(1);
	subMonitor2.setTaskName("Registering packages...");
	indexSynchronizer.reindexAllExternalProjects(subMonitor2);

	return status;
}
 
Example 8
private void addCommonPaths(IProject project, IProgressMonitor monitor) throws CoreException {
	SubMonitor subMonitor = SubMonitor.convert(monitor,COMMON_PATHS.length);
    for (String path : COMMON_PATHS) {
        IFolder folder = project.getFolder(path);
        if( !folder.exists()){
            createFolder(folder,subMonitor);
        }
        subMonitor.split(1);
    }
    subMonitor.done();
}
 
Example 9
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 10
/**
 * @since 2.7
 */
protected void doBuild(List<IResourceDescription.Delta> deltas, 
		Map<String, OutputConfiguration> outputConfigurations,
		Map<OutputConfiguration, Iterable<IMarker>> generatorMarkers, IBuildContext context,
		EclipseResourceFileSystemAccess2 access, IProgressMonitor progressMonitor) throws CoreException {
	final int numberOfDeltas = deltas.size();
	SubMonitor subMonitor = SubMonitor.convert(progressMonitor, numberOfDeltas);
	SubMonitor currentMonitor = null;
	int clusterIndex = 0;
	for (int i = 0; i < numberOfDeltas; i++) {
		IResourceDescription.Delta delta = deltas.get(i);
		
		if (subMonitor.isCanceled()) {
			throw new OperationCanceledException();
		}
		currentMonitor = subMonitor.split(1);
		access.setMonitor(currentMonitor);
		if (logger.isDebugEnabled()) {
			logger.debug("Compiling " + delta.getUri() + " (" + i + " of " + numberOfDeltas + ")");
		}
		if (delta.getNew() != null && !clusteringPolicy.continueProcessing(context.getResourceSet(), delta.getUri(), clusterIndex)) {
			clearResourceSet(context.getResourceSet());
			clusterIndex = 0;
		}

		Set<IFile> derivedResources = getDerivedResources(delta, outputConfigurations, generatorMarkers);
		access.setPostProcessor(getPostProcessor(delta, context, derivedResources));
		
		if (doGenerate(delta, context, access)) {
			clusterIndex++;
			access.flushSourceTraces();
		}
		
		cleanDerivedResources(delta, derivedResources, context, access, currentMonitor);
	}
}
 
Example 11
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 12
/**
 * 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 13
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);
}
 
Example 14
@Override
protected IProject[] build(int kind, @SuppressWarnings("rawtypes") Map args, IProgressMonitor monitor)
		throws CoreException {
	Stopwatch stopwatch = Stopwatch.createStarted();
	IProject project = getProject();
	try {
		RaceDetectionHelper.log("About to build %s", project);

		SubMonitor builderMonitor = toBuilderMonitor(monitor, 1100);

		/*
		 * Make sure that announced changes to the libraries have been actually processed
		 */
		externalLibraryBuildJobProvider.buildExternalProjectsNow(builderMonitor.split(50));

		IProject[] result = super.build(kind, args, builderMonitor.split(1000, SubMonitor.SUPPRESS_SETTASKNAME));
		/*
		 * Here we suffer from a race between the builder and the listener to project changes. The listener is
		 * supposed to update the project description on change. The build needs to return the references as
		 * configured in the project description.
		 *
		 * We cannot sync the builder with the listener due to limitations of the eclipse resource model thus we
		 * will bypass this mechanism and obtain the dependencies directly from the project.
		 *
		 * Dynamic references have been superseded in Eclipse Photon anyways :(
		 */
		List<IProject> dependencies = projectDependencyStrategy != null
				? projectDependencyStrategy.getProjectDependencies(project, true)
				: null;
		if (dependencies == null) {
			RaceDetectionHelper.log("Returning project results since dependencies cannot be determined");
			RaceDetectionHelper.log("%s depends on %s", project, Arrays.toString(result));
			return result;
		}
		/*
		 * And merge them with the static project references that are persisted to disc.
		 */
		IProject[] staticReferences = project.getDescription().getReferencedProjects();
		if (dependencies.isEmpty()) {
			RaceDetectionHelper.log("Returning static project results since dependencies are empty");
			RaceDetectionHelper.log("%s depends on %s", project, Arrays.toString(result));
			return staticReferences;
		}
		Set<IProject> asSet = Sets.newLinkedHashSet(FluentIterable.from(dependencies).append(staticReferences));
		result = asSet.toArray(new IProject[0]);
		RaceDetectionHelper.log("Returning computed results");
		RaceDetectionHelper.log("%s depends on %s", project, Arrays.toString(result));
		return result;
	} finally {
		stopwatch.stop();
		if (LOGGER.isDebugEnabled()) {
			final String msg = "Building " + project.getName() + " took " + stopwatch.elapsed(TimeUnit.SECONDS)
					+ " seconds";
			LOGGER.debug(msg);
		}
	}

}
 
Example 15
Source Project: n4js   File: LibraryManager.java    License: Eclipse Public License 1.0 4 votes vote down vote up
/**
 * NOTE: if the target points to a member project in a yarn workspace, this method will *NOT* switch to the yarn
 * workspace root folder for executing yarn! Rationale: in case an explicitly mentioned npm package is installed
 * (e.g. "yarn add lodash") it makes a difference whether that command is being executed in the member project's
 * root folder or the yarn workspace root folder (i.e. the newly installed npm package will be added to a different
 * package.json file in each case) and we want to support both cases.
 */
private IStatus installNPMsInternal(Map<N4JSProjectName, NPMVersionRequirement> versionedNPMs,
		boolean forceReloadAll,
		FileURI target, IProgressMonitor monitor) {

	String msg = getMessage(versionedNPMs);
	MultiStatus status = statusHelper.createMultiStatus(msg);
	logger.logInfo(msg);

	boolean usingYarn = npmCli.isYarnUsed(target);

	IStatus binaryStatus = checkBinary(usingYarn);
	if (!binaryStatus.isOK()) {
		status.merge(binaryStatus);
		return status;
	}

	try (Measurement mes = N4JSDataCollectors.dcLibMngr.getMeasurement("installDependenciesInternal");) {
		final int steps = forceReloadAll ? 3 : 2;
		SubMonitor subMonitor = SubMonitor.convert(monitor, steps + 4);
		Map<N4JSProjectName, NPMVersionRequirement> npmsToInstall = new LinkedHashMap<>(versionedNPMs);

		SubMonitor subMonitor1 = subMonitor.split(2);
		subMonitor1.setTaskName("Installing packages... [step 1 of " + steps + "]");

		List<LibraryChange> actualChanges = installNPMs(subMonitor1, status, npmsToInstall,
				target);

		if (!status.isOK()) {
			return status;
		}

		// if forceReloadAll, unregister all currently-registered projects from
		// the workspace and remove them from the index
		if (forceReloadAll) {
			SubMonitor subMonitor2 = subMonitor.split(1);
			subMonitor2.setTaskName("Clean all packages... [step 2 of 3]");
			externalLibraryWorkspace.deregisterAllProjects(subMonitor2);
		}

		try (Measurement m = N4JSDataCollectors.dcIndexSynchronizer.getMeasurement("synchronizeNpms")) {
			SubMonitor subMonitor3 = subMonitor.split(4);
			subMonitor3.setTaskName("Building installed packages... [step " + steps + " of " + steps + "]");
			indexSynchronizer.synchronizeNpms(subMonitor3, actualChanges);
		}

		return status;

	} finally {
		monitor.done();
	}
}
 
Example 16
/**
 * 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();
    }
}
 
Example 17
/**
 * Put all resources that depend on some changes onto the queue of resources to be processed.
 * Updates notInDelta by removing all URIs put into the queue.
 *
 * @param allRemainingURIs
 *            URIs that were not considered by prior operations.
 * @param oldState
 *            State before the build
 * @param newState
 *            The current state
 * @param changedDeltas
 *            the deltas that have changed {@link IEObjectDescription}s
 * @param allDeltas 
 *            All deltas 
 * @param buildData
 *            the underlying data for this build run.
 * @param monitor
 *            The progress monitor used for user feedback
 */
protected void queueAffectedResources(
        Set<URI> allRemainingURIs,
        IResourceDescriptions oldState,
        CurrentDescriptions newState,
        Collection<Delta> changedDeltas,
        Collection<Delta> allDeltas,
        BuildData buildData,
        final IProgressMonitor monitor) {
    if (allDeltas.isEmpty()) {
        return;
    }
    final SubMonitor progress = SubMonitor.convert(monitor, allRemainingURIs.size() + 1);
    Iterator<URI> iter = allRemainingURIs.iterator();
    while (iter.hasNext()) {
        if (progress.isCanceled()) {
            throw new OperationCanceledException();
        }
        final URI candidateURI = iter.next();
        final IResourceDescription candidateDescription = oldState.getResourceDescription(candidateURI);
        final IResourceDescription.Manager manager = getResourceDescriptionManager(candidateURI);
        if (candidateDescription == null || manager == null) {
            // If there is no description in the old state, there's no need to re-check this over and over.
            iter.remove();
        } else {
        	boolean affected;
        	if ((manager instanceof IResourceDescription.Manager.AllChangeAware)) {
        		affected = ((AllChangeAware) manager).isAffectedByAny(allDeltas, candidateDescription, newState);
        	} else {
        		if (changedDeltas.isEmpty()) {
        			affected = false;
        		} else {
        			affected = manager.isAffected(changedDeltas, candidateDescription, newState);
        		}
        	}
            if (affected) {
                buildData.queueURI(candidateURI);
                iter.remove();
            }
        }
        progress.split(1);
    }
}
 
Example 18
private static WorkspaceEdit computePackageRenameEdit(FileRenameEvent[] renameEvents, SourcePath[] sourcePaths, IProgressMonitor monitor) {
	WorkspaceEdit[] root = new WorkspaceEdit[1];
	SubMonitor submonitor = SubMonitor.convert(monitor, "Computing package rename updates...", 100 * renameEvents.length);
	for (FileRenameEvent event : renameEvents) {
		IPath oldLocation = ResourceUtils.filePathFromURI(event.oldUri);
		IPath newLocation = ResourceUtils.filePathFromURI(event.newUri);
		for (SourcePath sourcePath : sourcePaths) {
			IPath sourceLocation = Path.fromOSString(sourcePath.path);
			IPath sourceEntry = Path.fromOSString(sourcePath.classpathEntry);
			if (sourceLocation.isPrefixOf(oldLocation)) {
				SubMonitor renameMonitor = submonitor.split(100);
				try {
					IJavaProject javaProject = ProjectUtils.getJavaProject(sourcePath.projectName);
					if (javaProject == null) {
						break;
					}

					IPackageFragmentRoot packageRoot = javaProject.findPackageFragmentRoot(sourceEntry);
					if (packageRoot == null) {
						break;
					}

					String oldPackageName = String.join(".", oldLocation.makeRelativeTo(sourceLocation).segments());
					String newPackageName = String.join(".", newLocation.makeRelativeTo(sourceLocation).segments());
					IPackageFragment oldPackageFragment = packageRoot.getPackageFragment(oldPackageName);
					if (oldPackageFragment != null && !oldPackageFragment.isDefaultPackage() && oldPackageFragment.getResource() != null) {
						oldPackageFragment.getResource().refreshLocal(IResource.DEPTH_INFINITE, null);
						if (oldPackageFragment.exists()) {
							ResourcesPlugin.getWorkspace().run((pm) -> {
								WorkspaceEdit edit = getRenameEdit(oldPackageFragment, newPackageName, pm);
								root[0] = ChangeUtil.mergeChanges(root[0], edit, true);
							}, oldPackageFragment.getSchedulingRule(), IResource.NONE, renameMonitor);
						}
					}
				} catch (CoreException e) {
					JavaLanguageServerPlugin.logException("Failed to compute the package rename update", e);
				} finally {
					renameMonitor.done();
				}

				break;
			}
		}
	}

	submonitor.done();
	return ChangeUtil.hasChanges(root[0]) ? root[0] : null;
}
 
Example 19
@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 20
/**
 * Import a collection of file system elements into the workspace.
 */
private void importFileSystemElements(IProgressMonitor monitor, List<TraceFileSystemElement> fileSystemElements)
        throws InterruptedException, TmfTraceImportException, CoreException, InvocationTargetException {
    SubMonitor subMonitor = SubMonitor.convert(monitor, fileSystemElements.size());
    // Sort the elements in a sensible order to make it more predictable to
    // the user when there can be name clashes. Otherwise, the order can
    // seem pretty random depending on the OS/Filesystem.
    fileSystemElements.sort(new FileObjectPathComparator());

    ListIterator<TraceFileSystemElement> fileSystemElementsIter = fileSystemElements.listIterator();

    // Map to remember already imported directory traces
    final Map<String, TraceFileSystemElement> directoryTraces = new HashMap<>();
    while (fileSystemElementsIter.hasNext()) {
        ModalContext.checkCanceled(monitor);
        fCurrentPath = null;
        TraceFileSystemElement element = fileSystemElementsIter.next();
        IFileSystemObject fileSystemObject = element.getFileSystemObject();
        String resourcePath = element.getFileSystemObject().getAbsolutePath();
        element.setDestinationContainerPath(computeDestinationContainerPath(new Path(resourcePath)));

        fCurrentPath = resourcePath;
        SubMonitor sub = subMonitor.split(1, SubMonitor.SUPPRESS_BEGINTASK | SubMonitor.SUPPRESS_SUBTASK);
        if (element.isDirectory()) {
            if (!directoryTraces.containsKey(resourcePath) && isDirectoryTrace(element)) {
                directoryTraces.put(resourcePath, element);
                validateAndImportTrace(element, sub);
            }
        } else {
            TraceFileSystemElement parentElement = (TraceFileSystemElement) element.getParent();
            String parentPath = parentElement.getFileSystemObject().getAbsolutePath();
            parentElement.setDestinationContainerPath(computeDestinationContainerPath(new Path(parentPath)));
            fCurrentPath = parentPath;
            if (!directoryTraces.containsKey(parentPath)) {
                if (isDirectoryTrace(parentElement)) {
                    directoryTraces.put(parentPath, parentElement);
                    validateAndImportTrace(parentElement, sub);
                } else {
                    boolean validateFile = true;
                    TraceFileSystemElement grandParentElement = (TraceFileSystemElement) parentElement.getParent();
                    // Special case for LTTng trace that may contain index
                    // directory and files
                    if (grandParentElement != null) {
                        String grandParentPath = grandParentElement.getFileSystemObject().getAbsolutePath();
                        grandParentElement.setDestinationContainerPath(computeDestinationContainerPath(new Path(parentPath)));
                        fCurrentPath = grandParentPath;
                        if (directoryTraces.containsKey(grandParentPath)) {
                            validateFile = false;
                        } else if (isDirectoryTrace(grandParentElement)) {
                            directoryTraces.put(grandParentPath, grandParentElement);
                            validateAndImportTrace(grandParentElement, sub);
                            validateFile = false;
                        }
                    }
                    if (validateFile && (fileSystemObject.exists())) {
                        validateAndImportTrace(element, sub);
                    }
                }
            }
        }
    }
}