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

The following examples show how to use org.eclipse.core.runtime.SubMonitor#worked() . 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: IDETypeScriptProject.java    From typescript.java with MIT License 6 votes vote down vote up
/**
 * Collect ts files to compile from the given ts files list.
 * 
 * @param updatedTsFiles
 *            list of TypeScript files which have changed.
 * @param tsFilesToCompile
 *            list of collected ts files to compile.
 * @param tsFilesToClose
 *            list of ts files to close.
 * @param client
 * @param subMonitor
 * @throws Exception
 */
private void collectTsFilesToCompile(List<IFile> updatedTsFiles, List<String> tsFilesToCompile,
		List<IFile> tsFilesToClose, ITypeScriptServiceClient client, SubMonitor subMonitor) throws Exception {
	SubMonitor loopMonitor = subMonitor.split(50).setWorkRemaining(updatedTsFiles.size());
	loopMonitor.subTask(TypeScriptCoreMessages.IDETypeScriptProject_compile_collecting_step);
	for (IFile tsFile : updatedTsFiles) {
		if (loopMonitor.isCanceled()) {
			throw new OperationCanceledException();
		}
		String filename = WorkbenchResourceUtil.getFileName(tsFile);
		loopMonitor
				.subTask(NLS.bind(TypeScriptCoreMessages.IDETypeScriptProject_compile_collecting_file, filename));
		if (!tsFilesToCompile.contains(filename)) {
			collectTsFilesToCompile(filename, client, tsFilesToCompile, tsFilesToClose, loopMonitor);
		}
		loopMonitor.worked(1);
		// loopMonitor.split(1);
	}
	// subMonitor.setWorkRemaining(50);
}
 
Example 2
Source File: TraceValidateAndImportOperation.java    From tracecompass with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Safely create a folder meant to receive extracted content by making sure
 * there is no name clash.
 */
private static IFolder safeCreateExtractedFolder(IFolder destinationFolder, IPath relativeContainerRelativePath, IProgressMonitor monitor) throws CoreException {
    SubMonitor subMonitor = SubMonitor.convert(monitor, 2);
    IFolder extractedFolder;
    String suffix = ""; //$NON-NLS-1$
    int i = 2;
    while (true) {
        IPath fullPath = destinationFolder.getFullPath().append(relativeContainerRelativePath + ".extract" + suffix); //$NON-NLS-1$
        IFolder folder = ResourcesPlugin.getWorkspace().getRoot().getFolder(fullPath);
        if (!folder.exists()) {
            extractedFolder = folder;
            break;
        }
        suffix = "(" + i + ")"; //$NON-NLS-1$//$NON-NLS-2$
        i++;
    }
    subMonitor.worked(1);

    TraceUtils.createFolder(extractedFolder, subMonitor.newChild(1));
    return extractedFolder;
}
 
Example 3
Source File: IDETypeScriptProject.java    From typescript.java with MIT License 6 votes vote down vote up
/**
 * Compile ts files list with tsserver.
 * 
 * @param tsFilesToCompile
 * @param client
 * @param subMonitor
 * @throws Exception
 */
private void compileTsFiles(List<String> tsFilesToCompile, ITypeScriptServiceClient client, SubMonitor subMonitor)
		throws Exception {
	SubMonitor loopMonitor = subMonitor.newChild(50).setWorkRemaining(tsFilesToCompile.size());// subMonitor.split(50).setWorkRemaining(tsFilesToCompile.size());
	loopMonitor.subTask(TypeScriptCoreMessages.IDETypeScriptProject_compile_compiling_step);
	for (String filename : tsFilesToCompile) {
		try {
			if (loopMonitor.isCanceled()) {
				throw new OperationCanceledException();
			}
			loopMonitor.subTask(
					NLS.bind(TypeScriptCoreMessages.IDETypeScriptProject_compile_compiling_file, filename));
			compileTsFile(filename, client);
			loopMonitor.worked(1);
			// loopMonitor.split(1);
		} catch (ExecutionException e) {
			if (e.getCause() instanceof TypeScriptNoContentAvailableException) {
				// Ignore "No content available" error.
			} else {
				throw e;
			}
		}
	}
	// subMonitor.setWorkRemaining(100);
}
 
Example 4
Source File: UnifiedBuilder.java    From APICloud-Studio with GNU General Public License v3.0 6 votes vote down vote up
private void addMarkers(Collection<IProblem> items, String markerType, IFile file, IProgressMonitor monitor)
		throws CoreException
{
	if (CollectionsUtil.isEmpty(items))
	{
		return;
	}
	SubMonitor sub = SubMonitor.convert(monitor, items.size() * 2);
	for (IProblem item : items)
	{
		IMarker marker = file.createMarker(markerType);
		sub.worked(1);
		marker.setAttributes(item.createMarkerAttributes());
		sub.worked(1);
	}
	sub.done();
}
 
Example 5
Source File: BaseDataProviderTimeGraphView.java    From tracecompass with Eclipse Public License 2.0 6 votes vote down vote up
@Override
protected void zoomEntries(@NonNull Iterable<@NonNull TimeGraphEntry> entries, long zoomStartTime, long zoomEndTime, long resolution, boolean fullSearch, @NonNull IProgressMonitor monitor) {
    if (resolution < 0) {
        // StateSystemUtils.getTimes would throw an illegal argument exception.
        return;
    }

    long start = Long.min(zoomStartTime, zoomEndTime);
    long end = Long.max(zoomStartTime, zoomEndTime);
    Sampling sampling = new Sampling(start, end, resolution);
    Multimap<ITimeGraphDataProvider<? extends TimeGraphEntryModel>, Long> providersToModelIds = filterGroupEntries(entries, zoomStartTime, zoomEndTime);
    SubMonitor subMonitor = SubMonitor.convert(monitor, getClass().getSimpleName() + "#zoomEntries", providersToModelIds.size()); //$NON-NLS-1$

    for (Entry<ITimeGraphDataProvider<? extends TimeGraphEntryModel>, Collection<Long>> entry : providersToModelIds.asMap().entrySet()) {
        ITimeGraphDataProvider<? extends TimeGraphEntryModel> dataProvider = entry.getKey();
        Map<@NonNull String, @NonNull Object> parameters = getFetchRowModelParameters(start, end, resolution, fullSearch, entry.getValue());
        TmfModelResponse<TimeGraphModel> response = dataProvider.fetchRowModel(parameters, monitor);

        TimeGraphModel model = response.getModel();
        if (model != null) {
            zoomEntries(fEntries.row(dataProvider), model.getRows(), response.getStatus() == ITmfResponse.Status.COMPLETED, sampling);
        }
        subMonitor.worked(1);
    }
}
 
Example 6
Source File: BuildPath.java    From google-cloud-eclipse with 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 7
Source File: FastReferenceSearchResultContentProvider.java    From dsl-devkit with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public IStatus runInUIThread(final IProgressMonitor monitor) {
  List<ReferenceSearchViewTreeNode> nodes;
  synchronized (batchAddNodes) {
    nodes = Lists.newArrayList(batchAddNodes);
    batchAddNodes.clear();
  }
  SubMonitor progress = SubMonitor.convert(monitor, nodes.size());
  for (ReferenceSearchViewTreeNode node : nodes) {
    viewer.add(viewer.getInput(), node);
    progress.worked(1);
  }
  viewer.refresh();
  if (!batchAddNodes.isEmpty()) {
    schedule(JOB_RESCHEDULE_DELAY);
  } else {
    isUIUpdateScheduled = false;
  }
  return Status.OK_STATUS;
}
 
Example 8
Source File: ResourceUtils.java    From google-cloud-eclipse with Apache License 2.0 6 votes vote down vote up
/**
 * Create the components of the provided folder as required. Assumes the containing project
 * already exists.
 *
 * @param folder the path to be created if it does not already exist
 * @param monitor may be {@code null}
 * @throws CoreException on error
 */
public static void createFolders(IContainer folder, IProgressMonitor monitor)
    throws CoreException {

  IPath path = folder.getProjectRelativePath();
  IContainer current = folder.getProject();
  SubMonitor progress = SubMonitor.convert(monitor, path.segmentCount());
  for (String segment : path.segments()) {
    IFolder child = current.getFolder(new Path(segment));
    if (!child.exists()) {
      child.create(true, true, progress.newChild(1));
    } else {
      progress.worked(1);
    }
    current = child;
  }
}
 
Example 9
Source File: NewSarlBehaviorWizardPage.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, 4);
	final ScriptSourceAppender scriptBuilder = this.codeBuilderFactory.buildScript(
			getPackageFragment().getElementName(), typeProvider);
	final ISarlBehaviorBuilder behavior = scriptBuilder.addSarlBehavior(getTypeName());
	behavior.setExtends(getSuperClass());
	behavior.setDocumentation(comment);
	mon.worked(1);
	createStandardSARLEventTemplates(Messages.NewSarlBehaviorWizardPage_4,
		name -> behavior.addSarlBehaviorUnit(name),
		name -> behavior.addSarlCapacityUses(name));
	mon.worked(2);
	if (behavior.getSarlBehavior().getExtends() != null) {
		createInheritedMembers(
			Behavior.class.getCanonicalName(),
			behavior.getSarlBehavior(),
			true,
			() -> behavior.addSarlConstructor(),
			name -> behavior.addOverrideSarlAction(name),
			getSuperClass());
	}
	mon.worked(3);
	scriptBuilder.build(appender);
	mon.done();
}
 
Example 10
Source File: LibraryClasspathContainerResolverService.java    From google-cloud-eclipse with Apache License 2.0 5 votes vote down vote up
private LibraryClasspathContainer resolveLibraryFiles(
    IJavaProject javaProject,
    IPath containerPath,
    Library library,
    List<Job> sourceAttacherJobs,
    IProgressMonitor monitor)
    throws CoreException {

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

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

  return container;
}
 
Example 11
Source File: NewSarlClassWizardPage.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, 3);
	final ScriptSourceAppender scriptBuilder = this.codeBuilderFactory.buildScript(
			getPackageFragment().getElementName(), typeProvider);
	final ISarlClassBuilder clazz = scriptBuilder.addSarlClass(getTypeName());
	final String superType = getSuperClass();
	// Do not add the "Object" type because it is the default.
	if (Strings.isNullOrEmpty(superType) || Object.class.getName().equals(superType)) {
		clazz.setExtends(null);
	} else {
		clazz.setExtends(superType);
	}
	for (final String type : getSuperInterfaces()) {
		clazz.addImplements(type);
	}
	clazz.setDocumentation(comment);
	mon.worked(1);
	createInheritedMembers(
		Object.class.getCanonicalName(),
		clazz.getSarlClass(),
		true,
		() -> clazz.addSarlConstructor(),
		name -> clazz.addOverrideSarlAction(name),
		superType,
		getSuperInterfaces());
	mon.worked(2);
	scriptBuilder.build(appender);
	mon.done();
}
 
Example 12
Source File: NewSarlAgentWizardPage.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, 4);
	final ScriptSourceAppender scriptBuilder = this.codeBuilderFactory.buildScript(
			getPackageFragment().getElementName(), typeProvider);
	final ISarlAgentBuilder agent = scriptBuilder.addSarlAgent(getTypeName());
	agent.setExtends(getSuperClass());
	agent.setDocumentation(comment);
	mon.worked(1);
	createStandardSARLEventTemplates(Messages.NewSarlAgentWizardPage_3,
		name -> agent.addSarlBehaviorUnit(name),
		name -> agent.addSarlCapacityUses(name));
	mon.worked(2);
	if (agent.getSarlAgent().getExtends() != null) {
		createInheritedMembers(
			Agent.class.getCanonicalName(),
			agent.getSarlAgent(),
			true,
			() -> agent.addSarlConstructor(),
			name -> agent.addOverrideSarlAction(name),
			getSuperClass());
	}
	mon.worked(3);
	scriptBuilder.build(appender);
	mon.done();
}
 
Example 13
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 14
Source File: DefaultLinkedPositionGroupCalculator2.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
protected LinkedPositionGroup createLinkedGroupFromReplaceEdits(List<ReplaceEdit> edits, XtextEditor xtextEditor, String originalName,
		SubMonitor progress) {
	if (edits == null) {
		return null;
	}

	IXtextDocument document = xtextEditor.getDocument();
	LinkedPositionGroup group = new LinkedPositionGroup();
	List<LinkedPosition> linkedPositions = new ArrayList<>();
	edits.forEach(replaceEdit -> {
		try {
			String textToReplace = document.get(replaceEdit.getOffset(), replaceEdit.getLength());
			int indexOf = textToReplace.indexOf(originalName);
			if (indexOf != -1) {
				int calculatedOffset = replaceEdit.getOffset() + indexOf;
				linkedPositions.add(new LinkedPosition(document, calculatedOffset, originalName.length()));
			}
		} catch (BadLocationException exc) {
			LOG.error("Skipping invalid text edit " + replaceEdit, exc);
		}
	});

	progress.worked(10);

	int invocationOffset = xtextEditor.getInternalSourceViewer().getSelectedRange().x;
	int i = 0;
	for (LinkedPosition position : sortPositions(linkedPositions, invocationOffset)) {
		try {
			position.setSequenceNumber(i);
			i++;
			group.addPosition(position);
		} catch (BadLocationException e) {
			LOG.error(e.getMessage(), e);
			return null;
		}
	}
	return group;
}
 
Example 15
Source File: AppEngineStandardJre7ProjectFacetDetector.java    From google-cloud-eclipse with Apache License 2.0 4 votes vote down vote up
@Override
public void detect(IFacetedProjectWorkingCopy workingCopy, IProgressMonitor monitor)
    throws CoreException {
  String projectName = workingCopy.getProjectName();
  SubMonitor progress = SubMonitor.convert(monitor, 5);

  if (workingCopy.hasProjectFacet(AppEngineStandardFacet.FACET)) {
    return;
  }

  // Check if there are some fundamental conflicts with AESv7 other than Java and DWP versions
  if (FacetUtil.conflictsWith(workingCopy, AppEngineStandardFacet.JRE7,
      Arrays.asList(JavaFacet.FACET, WebFacetUtils.WEB_FACET))) {
    logger.warning(
        "skipping " + projectName + ": project conflicts with AES Java 7 runtime");
    return;
  }

  IFile appEngineWebXml =
      AppEngineConfigurationUtil.findConfigurationFile(
          workingCopy.getProject(), new Path("appengine-web.xml"));
  progress.worked(1);
  if (appEngineWebXml == null || !appEngineWebXml.exists()) {
    logger.fine("skipping " + projectName + ": cannot find appengine-web.xml");
    return;
  }
  try (InputStream content = appEngineWebXml.getContents()) {
    AppEngineDescriptor descriptor = AppEngineDescriptor.parse(content);
    progress.worked(1);
    if (descriptor.getRuntime() != null && !"java7".equals(descriptor.getRuntime())) {
      logger.fine("skipping " + projectName + ": appengine-web.xml is not java7");
      return;
    }
    
    workingCopy.addProjectFacet(AppEngineStandardFacet.JRE7);
    progress.worked(1);

    if (!workingCopy.hasProjectFacet(JavaFacet.VERSION_1_7)) {
      if (workingCopy.hasProjectFacet(JavaFacet.FACET)) {
        workingCopy.changeProjectFacetVersion(JavaFacet.VERSION_1_7);
      } else {
        Object javaModel = FacetUtil.createJavaDataModel(workingCopy.getProject());
        workingCopy.addProjectFacet(JavaFacet.VERSION_1_7);
        workingCopy.setProjectFacetActionConfig(JavaFacet.FACET, javaModel);
      }
      progress.worked(1);
    }

    if (!workingCopy.hasProjectFacet(WebFacetUtils.WEB_25)) {
      if (workingCopy.hasProjectFacet(WebFacetUtils.WEB_FACET)) {
        workingCopy.changeProjectFacetVersion(WebFacetUtils.WEB_25);
      } else {
        Object webModel =
            FacetUtil.createWebFacetDataModel(appEngineWebXml.getParent().getParent());
        workingCopy.addProjectFacet(WebFacetUtils.WEB_25);
        workingCopy.setProjectFacetActionConfig(WebFacetUtils.WEB_FACET, webModel);
      }
      progress.worked(1);
    }
    AppEngineStandardFacet.installAllAppEngineRuntimes(workingCopy, progress.newChild(1));
  } catch (SAXException | IOException | AppEngineException ex) {
    throw new CoreException(StatusUtil.error(this, "Unable to retrieve appengine-web.xml", ex));
  }
}
 
Example 16
Source File: BundleCacher.java    From APICloud-Studio with GNU General Public License v3.0 4 votes vote down vote up
private boolean anyFileDeleted(BundleElement be, IProgressMonitor monitor)
{
	if (be == null)
	{
		return false;
	}
	// FIXME If a file is deleted, remove all the elements contributed from that path and rewrite the cache!
	// (i.e. just update the diff!)
	List<AbstractBundleElement> children = be.getChildren();
	if (children == null)
	{
		return false;
	}
	SubMonitor sub = SubMonitor.convert(monitor, children.size());
	try
	{
		for (AbstractBundleElement abe : be.getChildren())
		{
			String path = abe.getPath();
			if (!new File(path).exists())
			{
				IdeLog.logInfo(
						ScriptingActivator.getDefault(),
						MessageFormat.format(Messages.BundleCacher_FileReferencedInCacheMissingMsg, path,
								abe.toString()));
				return true;
			}
			if (abe instanceof MenuElement)
			{
				MenuElement menu = (MenuElement) abe;
				return anyFileDeleted(menu);
			}
			sub.worked(1);
		}
	}
	finally
	{
		sub.done();
	}
	return false;
}
 
Example 17
Source File: RemoveIndexOfFilesOfProjectJob.java    From APICloud-Studio with GNU General Public License v3.0 4 votes vote down vote up
@Override
public IStatus run(IProgressMonitor monitor)
{
	SubMonitor sub = SubMonitor.convert(monitor, files.size());
	if (sub.isCanceled())
	{
		return Status.CANCEL_STATUS;
	}
	if (!project.isAccessible() || getContainerURI() == null)
	{
		return Status.CANCEL_STATUS;
	}

	Index index = getIndex();
	if (index == null)
	{
		IdeLog.logError(IndexPlugin.getDefault(),
				MessageFormat.format("Index is null for container: {0}", getContainerURI())); //$NON-NLS-1$
		return Status.CANCEL_STATUS;
	}
	try
	{
		// Cleanup indices for files
		for (IFile file : files)
		{
			if (monitor.isCanceled())
			{
				return Status.CANCEL_STATUS;
			}
			index.remove(file.getLocationURI());
			sub.worked(1);
		}
	}
	finally
	{
		try
		{
			index.save();
		}
		catch (IOException e)
		{
			IdeLog.logError(IndexPlugin.getDefault(), e);
		}
		sub.done();
	}
	return Status.OK_STATUS;
}
 
Example 18
Source File: JSSymbolTypeInferrer.java    From APICloud-Studio with GNU General Public License v3.0 4 votes vote down vote up
/**
 * processProperties
 * 
 * @param property
 * @param types
 */
public void processProperties(JSPropertyCollection property, Set<String> types, IProgressMonitor monitor)
{
	SubMonitor sub = SubMonitor.convert(monitor, 100);
	if (property.hasProperties())
	{
		List<String> additionalProperties = this.getAdditionalProperties(property, types);

		if (!additionalProperties.isEmpty())
		{
			// create new type
			TypeElement subType = generateType(property, types);
			sub.worked(5);

			// Preserve function return types and add to property type
			List<String> returnTypes = new ArrayList<String>();

			if (!CollectionsUtil.isEmpty(types))
			{
				int unit = 20 / types.size();
				for (String type : types)
				{
					if (JSTypeUtil.isFunctionPrefix(type))
					{
						returnTypes.addAll(JSTypeUtil.getFunctionSignatureReturnTypeNames(type));
					}
					sub.worked(unit);
				}
			}
			sub.setWorkRemaining(75);

			String propertyType = subType.getName();

			// FIXME What if propertyType is already Function<Something> here?!
			if (!JSTypeUtil.isFunctionPrefix(propertyType) && !returnTypes.isEmpty())
			{
				propertyType += JSTypeUtil.toFunctionType(returnTypes);
			}

			// reset list to contain only this newly generated type
			types.clear();
			types.add(propertyType);

			// go ahead and cache this new type to prevent possible recursion
			property.addType(propertyType);

			// infer types of the additional properties
			if (!CollectionsUtil.isEmpty(additionalProperties))
			{
				int work = 70 / additionalProperties.size();
				for (String pname : additionalProperties)
				{
					PropertyElement pe = this.getSymbolPropertyElement(property, pname, sub.newChild(work));
					subType.addProperty(pe);
				}
			}
			sub.setWorkRemaining(5);

			// push type to the current index
			this.writeType(subType);
			sub.worked(5);
		}
	}
	else
	{
		for (String typeName : types)
		{
			property.addType(typeName);
		}
	}
}
 
Example 19
Source File: SARLProjectConfigurator.java    From sarl with Apache License 2.0 4 votes vote down vote up
/** Configure the SARL project.
 *
 * <p>This function does the following:<ul>
 * <li>Add the SARL nature to the project;</li>
 * <li>Create the standard SARL folders if {@code createFolders} is evaluated to true;</li>
 * <li>Set the output configuration of the project from the
 * {@link SARLPreferences#setSpecificSARLConfigurationFor(IProject, IPath) general SARL configuration};</li>
 * <li>Reset the Java configuration in order to follow the SARL configuration, if {@code configureJabvaNature}
 * is evaluated to true.</li>
 * </ul>
 *
 * @param project the project.
 * @param addNatures indicates if the natures must be added to the project by calling {@link #addSarlNatures(IProject, IProgressMonitor)}.
 * @param configureJavaNature indicates if the Java configuration elements must be configured.
 * @param createFolders indicates if the folders must be created or not.
 * @param monitor the monitor.
 * @see #addSarlNatures(IProject, IProgressMonitor)
 * @see #configureSARLSourceFolders(IProject, boolean, IProgressMonitor)
 */
public static void configureSARLProject(IProject project, boolean addNatures,
		boolean configureJavaNature, boolean createFolders, IProgressMonitor monitor) {
	try {
		final SubMonitor subMonitor = SubMonitor.convert(monitor, 11);
		// Add Natures
		final IStatus status = Status.OK_STATUS;
		if (addNatures) {
			addSarlNatures(project, subMonitor.newChild(1));
			if (status != null && !status.isOK()) {
				SARLEclipsePlugin.getDefault().getLog().log(status);
			}
		}

		// Ensure SARL specific folders.
		final OutParameter<IFolder[]> sourceFolders = new OutParameter<>();
		final OutParameter<IFolder[]> testSourceFolders = new OutParameter<>();
		final OutParameter<IFolder[]> generationFolders = new OutParameter<>();
		final OutParameter<IFolder[]> testGenerationFolders = new OutParameter<>();
		final OutParameter<IFolder> generationFolder = new OutParameter<>();
		final OutParameter<IFolder> testGenerationFolder = new OutParameter<>();
		final OutParameter<IFolder> outputFolder = new OutParameter<>();
		final OutParameter<IFolder> testOutputFolder = new OutParameter<>();
		ensureSourceFolders(project, createFolders, subMonitor,
				sourceFolders, testSourceFolders,
				generationFolders, testGenerationFolders,
				generationFolder, testGenerationFolder,
				outputFolder, testOutputFolder);

		// SARL specific configuration
		final IFolder testGenerationFolderFolder = testGenerationFolder.get();
		final IPath testGenerationFolderPath = testGenerationFolderFolder == null ? null
				: testGenerationFolderFolder.getProjectRelativePath();
		SARLPreferences.setSpecificSARLConfigurationFor(project,
				generationFolder.get().getProjectRelativePath(),
				testGenerationFolderPath);
		subMonitor.worked(1);

		// Create the Java project
		if (configureJavaNature) {

			if (!addNatures) {
				addNatures(project, subMonitor.newChild(1), JavaCore.NATURE_ID);
			}

			final IJavaProject javaProject = JavaCore.create(project);
			subMonitor.worked(1);

			// Build path
			BuildPathsBlock.flush(
					buildClassPathEntries(javaProject,
							sourceFolders.get(),
							testSourceFolders.get(),
							generationFolders.get(),
							testGenerationFolders.get(),
							testOutputFolder.get().getFullPath(),
							false, true),
					outputFolder.get().getFullPath(), javaProject, null, subMonitor.newChild(1));
		}
		subMonitor.done();
	} catch (CoreException exception) {
		SARLEclipsePlugin.getDefault().log(exception);
	}
}
 
Example 20
Source File: XmlTimeGraphView.java    From tracecompass with Eclipse Public License 2.0 4 votes vote down vote up
@Override
protected void buildEntryList(ITmfTrace trace, ITmfTrace parentTrace, IProgressMonitor monitor) {
    /*
     * Get the view element from the XML file. If the element can't be found,
     * return.
     */
    Element viewElement = fViewInfo.getViewElement(TmfXmlStrings.TIME_GRAPH_VIEW);
    if (viewElement == null) {
        return;
    }
    // Empty the additional state values
    fStringValueMap.clear();
    ITimeGraphPresentationProvider pres = this.getPresentationProvider();
    if (pres instanceof XmlPresentationProvider) {
        /*
         * TODO: Each entry of a line could have their own states/color. That will
         * require an update to the presentation provider
         */
        ((XmlPresentationProvider) pres).loadNewStates(viewElement);
        Display.getDefault().asyncExec(() -> {
            TimeGraphViewer timeGraphViewer = getTimeGraphViewer();
            if (timeGraphViewer.getTimeGraphControl().isDisposed()) {
                return;
            }
            timeGraphViewer.getTimeGraphControl().colorSettingsChanged(timeGraphViewer.getTimeGraphProvider().getStateTable());
        });
    }

    String title = fViewInfo.getViewTitle(viewElement);
    setViewTitle(title != null ? title : Messages.XmlTimeGraphView_DefaultTitle);

    SubMonitor subMonitor = SubMonitor.convert(monitor);
    boolean complete = false;
    ITimeGraphDataProvider<@NonNull TimeGraphEntryModel> provider = XmlDataProviderManager.getInstance().getTimeGraphProvider(trace, viewElement);
    if (provider == null) {
        return;
    }
    while (!complete && !subMonitor.isCanceled()) {
        TmfModelResponse<TmfTreeModel<@NonNull TimeGraphEntryModel>> response = provider.fetchTree(FetchParametersUtils.timeQueryToMap(new TimeQueryFilter(0, Long.MAX_VALUE, 2)), subMonitor);
        if (response.getStatus() == ITmfResponse.Status.FAILED) {
            Activator.logError("XML Time Graph Data Provider failed: " + response.getStatusMessage()); //$NON-NLS-1$
            return;
        } else if (response.getStatus() == ITmfResponse.Status.CANCELLED) {
            return;
        }
        complete = response.getStatus() == ITmfResponse.Status.COMPLETED;

        TmfTreeModel<@NonNull TimeGraphEntryModel> model = response.getModel();
        if (model != null) {
            synchronized (fEntries) {
                /*
                 * Ensure that all the entries exist and are up to date.
                 */
                for (TimeGraphEntryModel entry : model.getEntries()) {
                    TimeGraphEntry tgEntry = fEntries.get(provider, entry.getId());
                    if (tgEntry == null) {
                        if (entry.getParentId() == -1) {
                            tgEntry = new TraceEntry(entry, trace, provider);
                            addToEntryList(parentTrace, Collections.singletonList(tgEntry));
                        } else {
                            tgEntry = new TimeGraphEntry(entry);
                        }
                        fEntries.put(provider, entry.getId(), tgEntry);
                    } else {
                        tgEntry.updateModel(entry);
                    }
                    if (entry.getParentId() == -1) {
                        setStartTime(Long.min(getStartTime(), entry.getStartTime()));
                        setEndTime(Long.max(getEndTime(), entry.getEndTime()));
                    }
                }
            }
            /*
             * set the correct child / parent relation
             */
            for (TimeGraphEntry child : fEntries.row(provider).values()) {
                TimeGraphEntry parent = fEntries.get(provider, child.getEntryModel().getParentId());
                if (parent != null) {
                    parent.addChild(child);
                }
            }
            long start = getStartTime();
            long end = getEndTime();
            final long resolution = Long.max(1, (end - start) / getDisplayWidth());
            zoomEntries(fEntries.row(provider).values(), start, end, resolution, subMonitor);
        }
        if (parentTrace.equals(getTrace())) {
            refresh();
        }
        subMonitor.worked(1);

        if (!complete) {
            try {
                Thread.sleep(BUILD_UPDATE_TIMEOUT);
            } catch (InterruptedException e) {
                Activator.logError("Failed to wait for data provider", e); //$NON-NLS-1$
            }
        }
    }
}