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

The following examples show how to use org.eclipse.core.runtime.SubMonitor#newChild() . 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: ReferenceFinder.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void findAllReferences(TargetURIs targetURIs, IResourceAccess resourceAccess,
		IResourceDescriptions indexData, Acceptor acceptor, IProgressMonitor monitor) {
	if (!targetURIs.isEmpty()) {
		Iterable<IResourceDescription> allResourceDescriptions = indexData.getAllResourceDescriptions();
		SubMonitor subMonitor = SubMonitor.convert(monitor, size(allResourceDescriptions) / MONITOR_CHUNK_SIZE + 1);
		IProgressMonitor useMe = subMonitor.newChild(1);
		int i = 0;
		for (IResourceDescription resourceDescription : allResourceDescriptions) {
			if (subMonitor.isCanceled())
				throw new OperationCanceledException();
			IReferenceFinder languageSpecific = getLanguageSpecificReferenceFinder(resourceDescription.getURI());
			languageSpecific.findReferences(targetURIs, resourceDescription, resourceAccess, acceptor, useMe);
			i++;
			if (i % MONITOR_CHUNK_SIZE == 0) {
				useMe = subMonitor.newChild(1);
			}
		}
	}
}
 
Example 2
Source File: ReferenceFinder.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void findReferences(
		TargetURIs targetURIs,
		Set<URI> candidates,
		IResourceAccess resourceAccess,
		IResourceDescriptions descriptions,
		Acceptor acceptor,
		IProgressMonitor monitor) {
	if (!targetURIs.isEmpty() && !candidates.isEmpty()) {
		SubMonitor subMonitor = SubMonitor.convert(monitor, targetURIs.size() / MONITOR_CHUNK_SIZE + 1);
		IProgressMonitor useMe = subMonitor.newChild(1);
		int i = 0;
		for (URI candidate : candidates) {
			if (subMonitor.isCanceled())
				throw new OperationCanceledException();
			IReferenceFinder languageSpecific = getLanguageSpecificReferenceFinder(candidate);
			doFindReferencesWith(languageSpecific, targetURIs, candidate, resourceAccess, descriptions, acceptor, useMe);
			i++;
			if (i % MONITOR_CHUNK_SIZE == 0) {
				useMe = subMonitor.newChild(1);
			}
		}
	}
}
 
Example 3
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 4
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 5
Source File: BuildSettingWizardPage.java    From sarl with Apache License 2.0 5 votes vote down vote up
private void keepExistingBuildPath(IProject project, OutParameter<IClasspathEntry[]> classpath,
		OutParameter<IPath> outputLocation, IProgressMonitor monitor)
		throws CoreException {
	final SubMonitor subMonitor = SubMonitor.convert(monitor, 3);
	IClasspathEntry[] entries = null;
	IPath outLocation = null;
	if (!project.getFile(FILENAME_CLASSPATH).exists()) {
		// Determine the default values
		if (classpath != null) {
			final List<IClasspathEntry> cpEntries = new ArrayList<>();
			final Collection<IClasspathEntry> originalEntries = SARLProjectConfigurator.getDefaultSourceClassPathEntries(
							new Path(this.firstPage.getProjectName()).makeAbsolute());
			cpEntries.addAll(originalEntries);
			this.firstPage.putDefaultClasspathEntriesIn(cpEntries);
			if (!cpEntries.isEmpty()) {
				classpath.set(cpEntries.toArray(new IClasspathEntry[cpEntries.size()]));
			}
		}
		if (outputLocation != null) {
			outputLocation.set(this.firstPage.getOutputLocation());
		}
		// Override with the existing configuration
		final SarlClassPathDetector detector = new SarlClassPathDetector(
				this.currProject, this.firstPage, subMonitor.newChild(1));
		entries = detector.getClasspath();
		outLocation = detector.getOutputLocation();
		if (entries.length == 0) {
			entries = null;
		}
	}
	subMonitor.worked(2);
	if (classpath != null && entries != null) {
		classpath.set(entries);
	}
	if (outputLocation != null && outLocation != null) {
		outputLocation.set(outLocation);
	}
	subMonitor.done();
}
 
Example 6
Source File: TraceValidateAndImportOperation.java    From tracecompass with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Extract all file system elements (File) to destination folder (typically
 * workspace/TraceProject/.traceImport)
 */
private void extractAllArchiveFiles(List<TraceFileSystemElement> fileSystemElements, IFolder destFolder, IPath baseSourceContainerPath, IProgressMonitor progressMonitor) throws InterruptedException, CoreException, InvocationTargetException {
    SubMonitor subMonitor = SubMonitor.convert(progressMonitor, fileSystemElements.size());
    ListIterator<TraceFileSystemElement> fileSystemElementsIter = fileSystemElements.listIterator();
    while (fileSystemElementsIter.hasNext()) {
        ModalContext.checkCanceled(subMonitor);

        SubMonitor elementProgress = subMonitor.newChild(1);
        TraceFileSystemElement element = fileSystemElementsIter.next();
        elementProgress.setTaskName(Messages.ImportTraceWizard_ExamineOperationTaskName + " " + element.getFileSystemObject().getAbsolutePath()); //$NON-NLS-1$
        File archiveFile = (File) element.getFileSystemObject().getRawFileSystemObject();
        boolean isArchiveFileElement = element.getFileSystemObject() instanceof FileFileSystemObject && ArchiveUtil.isArchiveFile(archiveFile);
        if (isArchiveFileElement) {
            elementProgress = SubMonitor.convert(elementProgress, 4);
            IPath makeAbsolute = baseSourceContainerPath.makeAbsolute();
            IPath relativeToSourceContainer = new Path(element.getFileSystemObject().getAbsolutePath()).makeRelativeTo(makeAbsolute);
            IFolder folder = safeCreateExtractedFolder(destFolder, relativeToSourceContainer, elementProgress.newChild(1));
            extractArchiveToFolder(archiveFile, folder, elementProgress.newChild(1));

            // Delete original archive, we don't want to import this, just
            // the extracted content
            IFile fileRes = destFolder.getFile(relativeToSourceContainer);
            fileRes.delete(true, elementProgress.newChild(1));
            IPath newPath = destFolder.getFullPath().append(relativeToSourceContainer);
            // Rename extracted folder (.extract) to original archive name
            folder.move(newPath, true, elementProgress.newChild(1));
            folder = ResourcesPlugin.getWorkspace().getRoot().getFolder(newPath);
            elementProgress.subTask(""); //$NON-NLS-1$

            // Create the new import provider and root element based on
            // the newly extracted temporary folder
            FileSystemObjectImportStructureProvider importStructureProvider = new FileSystemObjectImportStructureProvider(FileSystemStructureProvider.INSTANCE, null);
            IFileSystemObject rootElement = importStructureProvider.getIFileSystemObject(new File(folder.getLocation().toOSString()));
            TraceFileSystemElement newElement = TraceFileSystemElement.createRootTraceFileElement(rootElement, importStructureProvider);
            List<TraceFileSystemElement> extractedChildren = new ArrayList<>();
            newElement.getAllChildren(extractedChildren);
            extractAllArchiveFiles(extractedChildren, folder, folder.getLocation(), progressMonitor);
        }
    }
}
 
Example 7
Source File: CombinedJvmJdtRenameProcessor.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public RefactoringStatus checkFinalConditions(IProgressMonitor pm, CheckConditionsContext context)
		throws CoreException, OperationCanceledException {
	SubMonitor monitor = SubMonitor.convert(pm, jvmElements2jdtProcessors.size() + 1);
	RefactoringStatus status = super.checkFinalConditions(monitor.newChild(1), context);
	ResourceSet resourceSet = getResourceSet(getRenameElementContext());
	getRenameArguments().getRenameStrategy().applyDeclarationChange(getNewName(), resourceSet);
	for (Iterator<Map.Entry<URI, JavaRenameProcessor>> entryIterator = jvmElements2jdtProcessors.entrySet().iterator();
			entryIterator.hasNext();) {
		Map.Entry<URI, JavaRenameProcessor> jvmElement2jdtRefactoring = entryIterator.next();
		if (monitor.isCanceled()) {
			throw new OperationCanceledException();
		}
		URI renamedJvmElementURI = getRenameArguments().getNewElementURI(jvmElement2jdtRefactoring.getKey());
		EObject renamedJvmElement = resourceSet.getEObject(renamedJvmElementURI, false);
		if (!(renamedJvmElement instanceof JvmIdentifiableElement) || renamedJvmElement.eIsProxy()) {
			status.addError("Cannot find inferred JVM element after refactoring.");
		} else {
			JavaRenameProcessor jdtRefactoring = jvmElement2jdtRefactoring.getValue();
			String newName = ((JvmIdentifiableElement) renamedJvmElement).getSimpleName();
			if(jdtRefactoring.getCurrentElementName().equals(newName)) {
				entryIterator.remove();
			} else {
				jdtRefactoring.setNewElementName(newName);
				status.merge(jdtRefactoring.checkFinalConditions(monitor.newChild(1), context));
			}
		}
	}
	getRenameArguments().getRenameStrategy().revertDeclarationChange(resourceSet);
	return status;
}
 
Example 8
Source File: CombinedJvmJdtRenameProcessor.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, jvmElements2jdtProcessors.size() + 1);
	RefactoringStatus status = super.checkInitialConditions(monitor.newChild(1));
	for (JavaRenameProcessor processor : jvmElements2jdtProcessors.values()) {
		if (monitor.isCanceled()) {
			throw new OperationCanceledException();
		}
		status.merge(processor.checkInitialConditions(monitor.newChild(1)));
	}
	return status;
}
 
Example 9
Source File: DefaultReferenceFinder.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * @since 2.4
 */
protected void findAllIndexedReferences(
		IAcceptor<IReferenceDescription> referenceAcceptor,
		SubMonitor subMonitor,
		Set<URI> targetURIsAsSet,
		ILocalResourceAccess localResourceAccess) {
	TargetURIs targetURIs = converter.fromIterable(targetURIsAsSet);
	if (!targetURIs.isEmpty()) {
		subMonitor.setWorkRemaining(size(indexData.getAllResourceDescriptions()) / MONITOR_CHUNK_SIZE + 1);
		int i = 0;
		IProgressMonitor useMe = subMonitor.newChild(1);
		for (IResourceDescription resourceDescription : indexData.getAllResourceDescriptions()) {
			IResourceServiceProvider serviceProvider = getServiceProviderRegistry().getResourceServiceProvider(resourceDescription.getURI());
			if (serviceProvider != null) {
				IReferenceFinder referenceFinder = serviceProvider.get(IReferenceFinder.class);
				if (referenceFinder instanceof IReferenceFinderExtension1) {
					IReferenceFinderExtension1 extension1 = (IReferenceFinderExtension1) referenceFinder;
					extension1.findReferences(targetURIsAsSet, resourceDescription, referenceAcceptor, useMe, localResourceAccess);
				} else {
					// don't use the language specific reference finder here for backwards compatibility reasons
					findReferences(targetURIsAsSet, resourceDescription, referenceAcceptor, useMe, localResourceAccess);
				}
			}
			i++;
			if (i % MONITOR_CHUNK_SIZE == 0) {
				useMe = subMonitor.newChild(1);
			}
		}
	}
}
 
Example 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: GpeConvertJob.java    From google-cloud-eclipse with Apache License 2.0 5 votes vote down vote up
@Override
protected void convert(MultiStatus status, IProgressMonitor monitor) {
  SubMonitor progress = SubMonitor.convert(monitor, 100);

  // Updating project before installing App Engine facet to avoid
  // https://github.com/GoogleCloudPlatform/google-cloud-eclipse/issues/1155.
  try {
    GpeMigrator.removeObsoleteGpeRemnants(facetedProject, progress.newChild(20));
    super.convert(status, progress.newChild(20));
  } catch (CoreException ex) {
    status.add(StatusUtil.error(this, "Unable to remove GPE remains", ex));
  }
}
 
Example 12
Source File: PreloadingRepositoryHandler.java    From tmxeditor8 with GNU General Public License v2.0 4 votes vote down vote up
void doExecuteAndLoad() {
	if (preloadRepositories()) {
		// cancel any load that is already running
		final IStatus[] checkStatus = new IStatus[1];
		Job.getJobManager().cancel(LoadMetadataRepositoryJob.LOAD_FAMILY);
		final LoadMetadataRepositoryJob loadJob = new LoadMetadataRepositoryJob(getProvisioningUI()) {
			public IStatus runModal(IProgressMonitor monitor) {
				SubMonitor sub = SubMonitor.convert(monitor, getProgressTaskName(), 1000);
				IStatus status = super.runModal(sub.newChild(500));
				if (status.getSeverity() == IStatus.CANCEL)
					return status;
				if (status.getSeverity() != IStatus.OK) {
					// 记录检查错误
					checkStatus[0] = status;
					return Status.OK_STATUS;
				}
				try {
					doPostLoadBackgroundWork(sub.newChild(500));
				} catch (OperationCanceledException e) {
					return Status.CANCEL_STATUS;
				}
				return status;
			}
		};
		setLoadJobProperties(loadJob);
		loadJob.setName(P2UpdateUtil.CHECK_UPDATE_JOB_NAME);
		if (waitForPreload()) {
			loadJob.addJobChangeListener(new JobChangeAdapter() {
				public void done(IJobChangeEvent event) {
					if (PlatformUI.isWorkbenchRunning())
						if (event.getResult().isOK()) {
							PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
								public void run() {
									if (checkStatus[0] != null) {
										// 提示连接异常
										P2UpdateUtil.openConnectErrorInfoDialog(getShell(),
												P2UpdateUtil.INFO_TYPE_CHECK);
										return;
									}
									doExecute(loadJob);
								}
							});
						}
				}
			});
			loadJob.setUser(true);
			loadJob.schedule();

		} else {
			loadJob.setSystem(true);
			loadJob.setUser(false);
			loadJob.schedule();
			doExecute(null);
		}
	} else {
		doExecute(null);
	}
}
 
Example 13
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 14
Source File: LocalAppEngineServerLaunchConfigurationDelegate.java    From google-cloud-eclipse with Apache License 2.0 4 votes vote down vote up
@Override
public boolean finalLaunchCheck(ILaunchConfiguration configuration, String mode,
    IProgressMonitor monitor) throws CoreException {
  SubMonitor progress = SubMonitor.convert(monitor, 50);
  if (!super.finalLaunchCheck(configuration, mode, progress.newChild(10))) {
    return false;
  }
  IStatus status = validateCloudSdk(progress.newChild(20));
  if (!status.isOK()) {
    // Throwing a CoreException will result in the ILaunch hanging around in
    // an invalid state
    StatusManager.getManager().handle(status, StatusManager.SHOW | StatusManager.LOG);
    return false;
  }

  // If we're auto-publishing before launch, check if there may be stale
  // resources not yet published. See
  // https://github.com/GoogleCloudPlatform/google-cloud-eclipse/issues/1832
  if (ServerCore.isAutoPublishing() && ResourcesPlugin.getWorkspace().isAutoBuilding()) {
    // Must wait for any current autobuild to complete so resource changes are triggered
    // and WTP will kick off ResourceChangeJobs. Note that there may be builds
    // pending that are unrelated to our resource changes, so simply checking
    // <code>JobManager.find(FAMILY_AUTO_BUILD).length > 0</code> produces too many
    // false positives.
    try {
      Job.getJobManager().join(ResourcesPlugin.FAMILY_AUTO_BUILD, progress.newChild(20));
    } catch (InterruptedException ex) {
      /* ignore */
    }
    IServer server = ServerUtil.getServer(configuration);
    if (server.shouldPublish() || hasPendingChangesToPublish()) {
      IStatusHandler prompter = DebugPlugin.getDefault().getStatusHandler(promptStatus);
      if (prompter != null) {
        Object continueLaunch = prompter
            .handleStatus(StaleResourcesStatusHandler.CONTINUE_LAUNCH_REQUEST, configuration);
        if (!(Boolean) continueLaunch) {
          // cancel the launch so Server.StartJob won't raise an error dialog, since the
          // server won't have been started
          monitor.setCanceled(true);
          return false;
        }
      }
    }
  }
  return true;
}
 
Example 15
Source File: SaveHandler.java    From tracecompass with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {

    IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();

    if (window == null) {
        return false;
    }

    fLock.lock();
    try {

        final List<TraceSessionComponent> sessions = new ArrayList<>();
        sessions.addAll(fSessions);

        // Open dialog box for the save dialog path
        final ISaveDialog dialog = TraceControlDialogFactory.getInstance().getSaveDialog();
        if (dialog.open() != Window.OK) {
            return null;
        }

        Job job = new Job(Messages.TraceControl_SaveJob) {
            @Override
            protected IStatus run(IProgressMonitor monitor) {
                try {
                    for (TraceSessionComponent session : sessions) {
                        session.saveSession(null, null, dialog.isForce(), monitor);

                        final IRemoteConnection connection = session.getTargetNode().getRemoteSystemProxy().getRemoteConnection();
                        SubMonitor subMonitor = SubMonitor.convert(monitor, 3);
                        // create destination directory (if necessary)
                        IRemoteProcessService processService = connection.getService(IRemoteProcessService.class);
                        IPath path = null;
                        if (processService != null) {
                            String cwd = processService.getWorkingDirectory();
                            path = RemoteServicesUtils.posixPath(cwd);
                            path = path.append(LTTngControlServiceConstants.DEFAULT_PATH);
                        }

                        if (path == null) {
                            return Status.CANCEL_STATUS;
                        }

                        // upload file
                        IRemoteFileService fileService = connection.getService(IRemoteFileService.class);
                        if (fileService == null) {
                            return Status.CANCEL_STATUS;
                        }
                        IPath dest = LttngProfileManager.getProfilePath();
                        String profileName = session.getName() + ".lttng"; //$NON-NLS-1$
                        final Path destPath = FileSystems.getDefault().getPath(dest.toString()).resolve(profileName);
                        IFileStore destFileStore = EFS.getLocalFileSystem().fromLocalFile(destPath.toFile());
                        SubMonitor childMonitor = subMonitor.newChild(1);

                        IPath remotePath = RemoteServicesUtils.posixPath(path.toString()).append(profileName);
                        IFileStore remoteResource = fileService.getResource(remotePath.toString());
                        final boolean overwrite[] = new boolean[1];
                        if (destPath.toFile().exists()) {
                            Display.getDefault().syncExec(() -> overwrite[0] = MessageDialog.openConfirm(Display.getDefault().getActiveShell(),
                                    Messages.TraceControl_ProfileAlreadyExists,
                                    NLS.bind(Messages.TraceControl_OverwriteQuery, destPath.getFileName())));

                            if (!overwrite[0]) {
                                continue;
                            }
                        }
                        remoteResource.copy(destFileStore, EFS.OVERWRITE, childMonitor);
                    }
                } catch (ExecutionException | CoreException e) {
                    return new Status(IStatus.ERROR, Activator.PLUGIN_ID, Messages.TraceControl_SaveFailure, e);
                }
                return Status.OK_STATUS;
            }
        };
        job.setUser(true);
        job.schedule();
    } finally {
        fLock.unlock();
    }
    return null;
}
 
Example 16
Source File: ValidationOperation.java    From KaiZen-OpenAPI-Editor with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public void run(IProgressMonitor monitor) throws CoreException {
    // if the file is not part of a workspace it does not seems that it is a
    // IFileEditorInput
    // but instead a FileStoreEditorInput. Unclear if markers are valid for
    // such files.
    if (!(editorInput instanceof IFileEditorInput)) {
        YEditLog.logError("Marking errors not supported for files outside of a project.");
        YEditLog.logger.info("editorInput is not a part of a project.");
        return;
    }

    final IDocument document = documentProvider.getDocument(editorInput);
    if (document instanceof JsonDocument) {
        SubMonitor subMonitor = SubMonitor.convert(monitor, 100);
        final IFileEditorInput fileEditorInput = (IFileEditorInput) editorInput;
        final IFile file = fileEditorInput.getFile();

        if (parseFileContents) {
            // force parsing of yaml to init parsing errors
            // subMonitor.split() should NOT be executed before this code
            // as it checks for job cancellation and we want to be sure that
            // the document is parsed on opening
            ((JsonDocument) document).onChange();
        }
        if (subMonitor.isCanceled()) {
            throw new OperationCanceledException();
        }
        subMonitor.newChild(20);

        JsonEditor.clearMarkers(file);
        if (subMonitor.isCanceled()) {
            throw new OperationCanceledException();
        }
        subMonitor.newChild(30);

        validateYaml(file, (JsonDocument) document);
        if (subMonitor.isCanceled()) {
            throw new OperationCanceledException();
        }
        subMonitor.newChild(20);

        validateSwagger(file, (JsonDocument) document, fileEditorInput);
        if (subMonitor.isCanceled()) {
            throw new OperationCanceledException();
        }
        subMonitor.newChild(30);
    }
}
 
Example 17
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 18
Source File: AnalysisKickOff.java    From CogniCrypt with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * This method executes the actual analysis.
 */
public void run() {
	if (this.curProj == null)
		return;

	final Job analysis = new Job(Constants.ANALYSIS_LABEL) {

		@SuppressWarnings("deprecation")
		@Override
		protected IStatus run(final IProgressMonitor monitor) {
			int curSeed = 0;
			final SootThread sootThread = new SootThread(AnalysisKickOff.this.curProj, AnalysisKickOff.resultsReporter, depOnly);
			final MonitorReporter monitorThread = new MonitorReporter(AnalysisKickOff.resultsReporter, sootThread);
			monitorThread.start();
			sootThread.start();
			AnalysisKickOff.resultsReporter.setCgGenComplete(false);
			SubMonitor subMonitor = SubMonitor.convert(monitor, 100);
			SubMonitor cgGen = subMonitor.newChild(50);
			while (sootThread.isAlive()) {
				try {
					Thread.sleep(1);
				}
				catch (final InterruptedException e) {}

				if (!monitorThread.isCgGen()) {
					cgGen.setWorkRemaining(1000).split(1);
					cgGen.setTaskName("Constructing call Graphs...");
				} else {
					if (monitorThread.getProcessedSeeds() - curSeed != 0) {
						curSeed = monitorThread.getProcessedSeeds();
						subMonitor.split(monitorThread.getWorkUnitsCompleted() / 2);
						subMonitor.setTaskName("Completed " + monitorThread.getProcessedSeeds() + " of " + monitorThread.getTotalSeeds() + " seeds.");
					}
				}
				if (monitor.isCanceled()) {
					sootThread.stop();
					Activator.getDefault().logInfo("Static analysis job cancelled for " + curProj.getElementName() + ".");
					return Status.CANCEL_STATUS;
				}

			}
			monitor.done();
			AnalysisKickOff.resultsReporter.setPercentCompleted(0);
			AnalysisKickOff.resultsReporter.setProcessedSeeds(0);
			AnalysisKickOff.resultsReporter.setTotalSeeds(0);
			AnalysisKickOff.resultsReporter.setWorkUnitsCompleted(0);
			AnalysisKickOff.resultsReporter.setWork(0);
			if (sootThread.isSucc()) {
				Activator.getDefault().logInfo("Static analysis job successfully terminated for " + curProj.getElementName() + ".");
				return Status.OK_STATUS;
			} else {
				Activator.getDefault().logInfo("Static analysis failed for " + curProj.getElementName() + ".");
				return Status.CANCEL_STATUS;
			}

		}

		@Override
		protected void canceling() {
			cancel();
		}
	};
	analysis.setPriority(Job.LONG);
	analysis.schedule();
}
 
Example 19
Source File: AutomaticUpdate.java    From translationstudio8 with GNU General Public License v2.0 4 votes vote down vote up
public void checkForUpdates() throws OperationCanceledException {
	// 检查 propfile
	String profileId = getProvisioningUI().getProfileId();
	IProvisioningAgent agent = getProvisioningUI().getSession().getProvisioningAgent();
	IProfile profile = null;
	if (agent != null) {
		IProfileRegistry registry = (IProfileRegistry) agent.getService(IProfileRegistry.SERVICE_NAME);
		if (registry != null) {
			profile = registry.getProfile(profileId);
		}
	}
	if (profile == null) {
		// Inform the user nicely
		P2UpdateUtil.openConnectErrorInfoDialog(getShell(), P2UpdateUtil.INFO_TYPE_AUTO_CHECK);
		return;
	}

	// 开始检查前先确定是否有repository
	RepositoryTracker repoMan = getProvisioningUI().getRepositoryTracker();
	if (repoMan.getKnownRepositories(getProvisioningUI().getSession()).length == 0) {
		P2UpdateUtil.openConnectErrorInfoDialog(getShell(), P2UpdateUtil.INFO_TYPE_AUTO_CHECK);
		return;
	}

	final IStatus[] checkStatus = new IStatus[1];
	Job.getJobManager().cancel(LoadMetadataRepositoryJob.LOAD_FAMILY);
	final LoadMetadataRepositoryJob loadJob = new LoadMetadataRepositoryJob(getProvisioningUI()) {
		public IStatus runModal(IProgressMonitor monitor) {
			SubMonitor sub = SubMonitor.convert(monitor, P2UpdateUtil.CHECK_UPDATE_TASK_NAME, 1000);
			// load repository
			IStatus status = super.runModal(sub.newChild(500));
			if (status.getSeverity() == IStatus.CANCEL) {
				return status;
			}
			if (status.getSeverity() != Status.OK) {
				// load repository error
				checkStatus[0] = status;
			}
			operation = getProvisioningUI().getUpdateOperation(null, null);
			// check for updates
			IStatus resolveStatus = operation.resolveModal(sub.newChild(500));
			if (resolveStatus.getSeverity() == IStatus.CANCEL) {
				return Status.CANCEL_STATUS;
			}
			return Status.OK_STATUS;
		}
	};
	loadJob.setName(P2UpdateUtil.ATUO_CHECK_UPDATE_JOB_NAME);
	loadJob.setProperty(LoadMetadataRepositoryJob.ACCUMULATE_LOAD_ERRORS, Boolean.toString(true));
	loadJob.addJobChangeListener(new JobChangeAdapter() {
		public void done(IJobChangeEvent event) {
			if (PlatformUI.isWorkbenchRunning())
				if (event.getResult().isOK()) {
					PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
						public void run() {
							if (checkStatus[0] != null) {
								// 提示连接异常
								P2UpdateUtil.openConnectErrorInfoDialog(getShell(),
										P2UpdateUtil.INFO_TYPE_AUTO_CHECK);
								return;
							}
							doUpdate();
						}
					});
				}
		}
	});
	loadJob.setUser(true);
	loadJob.schedule();
}
 
Example 20
Source File: PreloadingRepositoryHandler.java    From translationstudio8 with GNU General Public License v2.0 4 votes vote down vote up
void doExecuteAndLoad() {
	if (preloadRepositories()) {
		// cancel any load that is already running
		final IStatus[] checkStatus = new IStatus[1];
		Job.getJobManager().cancel(LoadMetadataRepositoryJob.LOAD_FAMILY);
		final LoadMetadataRepositoryJob loadJob = new LoadMetadataRepositoryJob(getProvisioningUI()) {
			public IStatus runModal(IProgressMonitor monitor) {
				SubMonitor sub = SubMonitor.convert(monitor, getProgressTaskName(), 1000);
				IStatus status = super.runModal(sub.newChild(500));
				if (status.getSeverity() == IStatus.CANCEL)
					return status;
				if (status.getSeverity() != IStatus.OK) {
					// 记录检查错误
					checkStatus[0] = status;
					return Status.OK_STATUS;
				}
				try {
					doPostLoadBackgroundWork(sub.newChild(500));
				} catch (OperationCanceledException e) {
					return Status.CANCEL_STATUS;
				}
				return status;
			}
		};
		setLoadJobProperties(loadJob);
		loadJob.setName(P2UpdateUtil.CHECK_UPDATE_JOB_NAME);
		if (waitForPreload()) {
			loadJob.addJobChangeListener(new JobChangeAdapter() {
				public void done(IJobChangeEvent event) {
					if (PlatformUI.isWorkbenchRunning())
						if (event.getResult().isOK()) {
							PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
								public void run() {
									if (checkStatus[0] != null) {
										// 提示连接异常
										P2UpdateUtil.openConnectErrorInfoDialog(getShell(),
												P2UpdateUtil.INFO_TYPE_CHECK);
										return;
									}
									doExecute(loadJob);
								}
							});
						}
				}
			});
			loadJob.setUser(true);
			loadJob.schedule();

		} else {
			loadJob.setSystem(true);
			loadJob.setUser(false);
			loadJob.schedule();
			doExecute(null);
		}
	} else {
		doExecute(null);
	}
}