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

The following examples show how to use org.eclipse.core.runtime.SubMonitor#setTaskName() . 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
public static IStatus[] publishExploded(IProject project, IPath destination,
    IPath safeWorkDirectory, IProgressMonitor monitor) throws CoreException {
  Preconditions.checkNotNull(project, "project is null"); //$NON-NLS-1$
  Preconditions.checkNotNull(destination, "destination is null"); //$NON-NLS-1$
  Preconditions.checkArgument(!destination.isEmpty(), "destination is empty path"); //$NON-NLS-1$
  Preconditions.checkNotNull(safeWorkDirectory, "safeWorkDirectory is null"); //$NON-NLS-1$
  if (monitor.isCanceled()) {
    throw new OperationCanceledException();
  }

  SubMonitor subMonitor = SubMonitor.convert(monitor, 100);
  subMonitor.setTaskName(Messages.getString("task.name.publish.war")); //$NON-NLS-1$

  IModuleResource[] resources =
      flattenResources(project, safeWorkDirectory, subMonitor.newChild(10));
  if (resources.length == 0) {
    IStatus error = StatusUtil.error(WarPublisher.class, project.getName()
        + " has no resources to publish"); //$NON-NLS-1$
    return new IStatus[] {error};
  }
  return PublishUtil.publishFull(resources, destination, subMonitor.newChild(90));
}
 
Example 2
/**
 * @param explodedWarDirectory the input of the staging operation
 * @param stagingDirectory where the result of the staging operation will be written
 * @param appEngineStandardStaging executes the staging operation
 * @throws AppEngineException when staging fails
 */
public static void stageStandard(IPath explodedWarDirectory, IPath stagingDirectory,
    AppEngineWebXmlProjectStaging appEngineStandardStaging, IProgressMonitor monitor)
        throws AppEngineException {
  if (monitor.isCanceled()) {
    throw new OperationCanceledException("canceled early");
  }

  SubMonitor progress = SubMonitor.convert(monitor, 1);
  progress.setTaskName(Messages.getString("task.name.stage.project")); //$NON-NLS-1$

  AppEngineWebXmlProjectStageConfiguration stagingConfig =
      AppEngineWebXmlProjectStageConfiguration.builder(
          explodedWarDirectory.toFile().toPath(), stagingDirectory.toFile().toPath())
          .enableJarSplitting(true)
          .disableUpdateCheck(true)
          .build();

  appEngineStandardStaging.stageStandard(stagingConfig);

  progress.worked(1);
}
 
Example 3
/**
 * Call this method after the {@link ExternalLibraryWorkspace#updateState()} adapted the changes of the
 * {@code node_modules} folder. Due to this adaption, new folders are already represented as external projects and
 * can be build and added to the index.
 */
private void buildChangesIndex(IProgressMonitor monitor, Collection<LibraryChange> changeSet,
		RegisterResult cleanResults) {

	SubMonitor subMonitor = convert(monitor, 10);
	try {

		Set<FileURI> toBeUpdated = getToBeBuildProjects(changeSet);
		for (FileURI cleanedPrjLoc : cleanResults.externalProjectsDone) {
			ExternalProject project = externalLibraryWorkspace.getProject(cleanedPrjLoc);
			if (project != null) {
				toBeUpdated.add(cleanedPrjLoc);
			}
		}

		subMonitor.setTaskName("Building new projects...");
		RegisterResult buildResult = externalLibraryWorkspace.registerProjects(subMonitor.split(9), toBeUpdated);
		printRegisterResults(buildResult, "built");

		Set<SafeURI<?>> toBeScheduled = new HashSet<>();
		toBeScheduled.addAll(cleanResults.affectedWorkspaceProjects);
		toBeScheduled.addAll(buildResult.affectedWorkspaceProjects);
		externalLibraryWorkspace.scheduleWorkspaceProjects(subMonitor.split(1), toBeScheduled);

	} finally {
		subMonitor.done();
	}
}
 
Example 4
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 5
Source Project: neoscada   File: ImportWizard.java    License: 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 6
@Override
public void run(IProgressMonitor parentMonitor) throws InvocationTargetException, InterruptedException {
    SubMonitor subMonitor = SubMonitor.convert(parentMonitor, 10);
    subMonitor.setTaskName(RunContainerMessages.getString("HaltRuntimeAction.Stoping")); //$NON-NLS-1$
    if (checkRunning()) {
        if (RuntimeServerController.getInstance().isRunning()) {
            try {
                RuntimeServerController.getInstance().stopRuntimeServer();
                int i = 0;
                String dot = "."; //$NON-NLS-1$
                // JMXUtil.connectToRuntime() != null
                while (RuntimeServerController.getInstance().isRunning() && i < 11 && !subMonitor.isCanceled()) {
                    subMonitor.setTaskName(RunContainerMessages.getString("HaltRuntimeAction.Task") + dot); //$NON-NLS-1$
                    dot += "."; //$NON-NLS-1$
                    subMonitor.worked(1);
                    Thread.sleep(3000);
                }
                if (RuntimeServerController.getInstance().isRunning()) {
                    throw new InterruptedException("Stop runtime server failed, please try again or stop it manually.");
                }
            } catch (Exception e) {
                ExceptionHandler.process(e);
                e.printStackTrace();
                throw new InvocationTargetException(e);
            }
        }
    }
}
 
Example 7
@Override
public void run(IProgressMonitor parentMonitor) throws InvocationTargetException, InterruptedException {
    if (parentMonitor != null) {
        SubMonitor subMonitor = SubMonitor.convert(parentMonitor, 1);
        subMonitor.setTaskName("Checking runtime bundles..."); //$NON-NLS-1$
        if (checkRunning()) {
            waitForActive(subMonitor);
            subMonitor.worked(1);
        }
    } else {
        waitForActive();
    }
}
 
Example 8
/**
 * @param optionalConfigurationFilesDirectory if not {@code null}, searches optional configuration
 *     files (such as {@code cron.yaml}) in this directory and deploys them together
 */
public IStatus deploy(IPath stagingDirectory, Path credentialFile,
    DeployPreferences deployPreferences, IPath optionalConfigurationFilesDirectory,
    MessageConsoleStream stdoutOutputStream, IProgressMonitor monitor) {
  if (monitor.isCanceled()) {
    throw new OperationCanceledException();
  }

  SubMonitor progress = SubMonitor.convert(monitor, 1);
  progress.setTaskName(Messages.getString("task.name.deploy.project")); //$NON-NLS-1$
  try {
    List<File> files =
        computeDeployables(stagingDirectory, optionalConfigurationFilesDirectory);
    List<Path> deployables = new ArrayList<>();
    for (File file : files) {
      deployables.add(file.toPath());
    }
    
    DeployConfiguration configuration =
        DeployPreferencesConverter.toDeployConfiguration(deployPreferences, deployables);
    try { 
      Deployment deployment =
          cloudSdkProcessWrapper.getAppEngineDeployment(credentialFile, stdoutOutputStream);
      deployment.deploy(configuration);
    } catch (AppEngineException ex) {
      return StatusUtil.error(this, "Error deploying project: " + ex.getMessage(), ex);
    }
    return cloudSdkProcessWrapper.getExitStatus();
  } finally {
    progress.worked(1);
  }
}
 
Example 9
@Override
public void run(IProgressMonitor parentMonitor) throws InvocationTargetException, InterruptedException {
    SubMonitor subMonitor = SubMonitor.convert(parentMonitor, 100);
    subMonitor.setTaskName(RunContainerMessages.getString("StartRuntimeAction.Starting")); //$NON-NLS-1$
    if (!checkRunning()) {
        try {
            IPreferenceStore store = ESBRunContainerPlugin.getDefault().getPreferenceStore();
            Process proc = RuntimeServerController.getInstance().startLocalRuntimeServer(
                    store.getString(RunContainerPreferenceInitializer.P_ESB_RUNTIME_LOCATION));
            int i = 0;
            String dot = "."; //$NON-NLS-1$
            while (JMXUtil.createJMXconnection() == null && ++i < 101 && !subMonitor.isCanceled() && proc.isAlive()) {
                subMonitor.subTask(RunContainerMessages.getString("StartRuntimeAction.Try") + dot); //$NON-NLS-1$
                dot += "."; //$NON-NLS-1$
                subMonitor.worked(1);
                Thread.sleep(3000);
            }
            if (!proc.isAlive()) {
                RuntimeServerController.getInstance().stopLocalRuntimeServer();
                throw new InterruptedException(RunContainerMessages.getString("RunContainerPreferencePage.InitailzeDialog8",
                        proc.exitValue()));
            }
            if (JMXUtil.createJMXconnection() == null) {
                throw new InterruptedException(RunContainerMessages.getString("RunContainerPreferencePage.InitailzeDialog5"));
            }
        } catch (Exception e) {
            ExceptionHandler.process(e);
            throw new InvocationTargetException(e, e.getMessage());
        }
    }
    loadConsole();
}
 
Example 10
@Override
protected IStatus run(final IProgressMonitor monitor) {
    int alreadyDone = 0;
    SubMonitor subMonitor = SubMonitor.convert(monitor);
    if (fTraceWithSize != null) {
        subMonitor.beginTask("", fTraceWithSize.size()); //$NON-NLS-1$
    } else {
        subMonitor.beginTask("", IProgressMonitor.UNKNOWN); //$NON-NLS-1$
    }
    while (!monitor.isCanceled()) {
        try {
            long prevNbEvents = fTrace.getNbEvents();
            Thread.sleep(250);
            long nbEvents = fTrace.getNbEvents();
            if (fTraceWithSize != null) {
                final int done = fTraceWithSize.progress();
                subMonitor.setWorkRemaining(fTraceWithSize.size() - done);
                subMonitor.worked(done - alreadyDone);
                alreadyDone = done;
            }
            setName(Messages.TmfCheckpointIndexer_Indexing + ' ' + fTrace.getName() + " (" + String.format("%,d", nbEvents) + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
            // setName doesn't refresh the UI, setTaskName does
            long rate = (nbEvents - prevNbEvents) * 4;
            TraceCompassLogUtils.traceCounter(LOGGER, Level.FINE, fTrace.getName(), "indexed", nbEvents - prevNbEvents); //$NON-NLS-1$
            subMonitor.setTaskName(String.format("%,d", rate) + " " + Messages.TmfCheckpointIndexer_EventsPerSecond); //$NON-NLS-1$ //$NON-NLS-2$
        } catch (final InterruptedException e) {
            return Status.OK_STATUS;
        }
    }
    subMonitor.done();
    monitor.done();
    return fException != null ? new Status(IStatus.ERROR, Activator.PLUGIN_ID, fException.getMessage(), fException) : Status.OK_STATUS;
}
 
Example 11
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 12
/**
 * Do the dirty work of actually extracting a {@link ZipEntry} to it's destination.
 * 
 * @param zip
 * @param entry
 * @param destinationPath
 * @param transformer
 * @param conflicts
 * @param howToResolve
 * @param monitor
 * @return
 */
private static IStatus extractEntry(ZipFile zip, ZipEntry entry, File destinationPath,
		IInputStreamTransformer transformer, Conflict howToResolve, IProgressMonitor monitor)
{
	// Return early since this is only supposed to handle files.
	if (entry.isDirectory())
	{
		return Status.OK_STATUS;
	}

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

				case SKIP:
					return Status.OK_STATUS;

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

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

	finally
	{
		subMonitor.done();
	}

	return Status.OK_STATUS;
}
 
Example 13
/**
 * Obtains {@link IXtextDocument} for the provided file and delegates to
 * {@link #organizeDocument(IXtextDocument, Interaction)}
 */
void organizeFile(IFile file, final Interaction interaction, IProgressMonitor mon)
		throws CoreException {

	SubMonitor subMon = SubMonitor.convert(mon, "Organizing " + file.getName(), IProgressMonitor.UNKNOWN);

	FileEditorInput fei = new FileEditorInput(file);

	docProvider.connect(fei); // without connecting no document will be provided
	IXtextDocument document = (IXtextDocument) docProvider.getDocument(fei);

	docProvider.aboutToChange(fei);

	organizeDocument(document, interaction);

	subMon.setTaskName("Saving " + file.getName());
	docProvider.saveDocument(subMon.split(0), fei, document, true);

	docProvider.changed(fei);
	docProvider.disconnect(fei);

}
 
Example 14
/**
   * This methods is used to update the Mendeley Folder that are stored in this client class 
   * by obtaining all Folders of a Mendeley profile including the respective Mendeley Documents.
   * The updated Mendeley Folders are a requirement for starting the Mendeley Sync Wizard
   * 
   * @param monitor 
   * @return Returns the IStatus of the Job that is used to inform the User about the current state
   * @throws MalformedURLException
   * @throws TokenMgrException
   * @throws IOException
   * @throws ParseException
   */
  public IStatus updateMendeleyFolders(IProgressMonitor monitor) throws MalformedURLException, TokenMgrException, IOException, ParseException{
  	refreshTokenIfNecessary();
  	
  	// Get all Folder IDs and Folder Names of your Mendeley profile
      String folders_str = this.getAllFolders();
      Gson gson = new Gson();
      
      // Parse JSON String of Folders into MendeleyFolder objects
      MendeleyFolder[] m_folders = gson.fromJson(folders_str, MendeleyFolder[].class);
      
      // Number of tasks equals number of Folder that are present in your Mendeley profile
      SubMonitor subMonitor = SubMonitor.convert(monitor, m_folders.length);

      for(int i = 0; i < m_folders.length;i++){
	subMonitor.setTaskName("Working on Folder " + String.valueOf(i+1) + " of " + String.valueOf(m_folders.length) +  ": " + m_folders[i].getName() );
	
	String folder_content_str;
	try {
		// get all documents of a specific folder
		folder_content_str = this.getDocumentsByFolderJSON(m_folders[i].getId());
		
		// get all BibTeXEntries of a specific folder
		BibTeXDatabase bibdb = this.getDocumentsByFolderBibTex(m_folders[i]);
		m_folders[i].setBibtexDatabase(bibdb);
		
		MendeleyDocument[] folder_content = gson.fromJson(folder_content_str, MendeleyDocument[].class);
		m_folders[i].setDocuments(folder_content);
		m_folders[i].setType("Folder");
		
		// get the notes of all Documents to find the 'classes' field that is missing in the Mendeley BibTeX response model
		for(MendeleyDocument md : m_folders[i].getDocuments()){
			subMonitor.subTask("Download Document \"" + md.getTitle() + "\"");
			String notes = md.getNotes();
			MendeleyAnnotation[] annotations = getAnnotations(md);
			for(MendeleyAnnotation annotation: annotations){
				if(annotation.getType().equals("note")){
					notes = annotation.getText();
				}
			}
			// add notes to the 'notes' variable
			md.setNotes(notes);
		}
	} catch (TokenMgrException | IOException | ParseException e) {
		e.printStackTrace();
	}
	subMonitor.worked(1);
	if (subMonitor.isCanceled()) return Status.CANCEL_STATUS;
      }
      mendeleyFolders = m_folders;
return Status.OK_STATUS;
  }
 
Example 15
@Override
public IStatus run(IProgressMonitor monitor) {
    SubMonitor subMonitor = SubMonitor.convert(monitor, fTraceBoundsToUpdate.size());
    while (!fTraceBoundsToUpdate.isEmpty()) {
        subMonitor.setTaskName(getName());
        if (subMonitor.isCanceled()) {
            return Status.CANCEL_STATUS;
        }

        TmfTraceElement tElement = fTraceBoundsToUpdate.remove();
        ITmfTimestamp start = tElement.getStartTime();
        ITmfTimestamp end = tElement.getEndTime();
        if (start != null && end != null) {
            /*
             * The start and end times are already known, no need to go any
             * further
             */
            subMonitor.worked(1);
            continue;
        }
        /*
         * Try to get the element bounds from the supplementary files.
         */
        IFolder folder = tElement.getTraceSupplementaryFolder(tElement.getSupplementaryFolderPath());
        tElement.refreshSupplementaryFolder();
        File f = folder.getFile(BOUNDS_FILE_NAME).getLocation().toFile();
        tryReadBoundsFile(tElement, f);

        start = tElement.getStartTime();
        end = tElement.getEndTime();
        if (start == null || end == null) {
            /*
             * We are missing a bound, we must go and read them from the
             * trace.
             */
            extractBoundsFromTrace(tElement);
            tryWriteBoundsFile(subMonitor.newChild(1), tElement, folder, f);
        } else {
            subMonitor.worked(1);
        }
    }
    return Status.OK_STATUS;
}
 
Example 16
Source Project: slr-toolkit   File: GSWorker.java    License: Eclipse Public License 1.0 4 votes vote down vote up
public IStatus work(SubMonitor mon) {
	this.monitor = mon;
	IStatus s;

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

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

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

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

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

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

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

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

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

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

					// Increment Counter
					last++;

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

		// Increment Offset
		start += 10;
	}

	out.print("@Comment { Finished }");
	out.close();
	monitor.done();
	return Status.OK_STATUS;
}
 
Example 17
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 18
@Override
public void run(IProgressMonitor monitor)
	throws InvocationTargetException, InterruptedException{
	List<Konsultation> initialList = query.execute();
	SubMonitor progress = SubMonitor.convert(monitor, 100);
	
	progress.setTaskName("Vorschlag filter");
	if (addSeries) {
		progress.setWorkRemaining(initialList.size() * 2);
	} else {
		progress.setWorkRemaining(initialList.size());
	}
	for (Konsultation konsultation : initialList) {
		if (progress.isCanceled()) {
			canceled = true;
			return;
		}
		if (!applyFilters(konsultation)) {
			progress.worked(1);
			continue;
		}
		proposal.add(konsultation);
		progress.worked(1);
	}
	if(addSeries) {
		progress.setTaskName("Behandlungsserien laden");
		HashSet<String> knownIds = new HashSet<>();
		knownIds.addAll(
			proposal.parallelStream().map(k -> k.getId()).collect(Collectors.toList()));
		ArrayList<Konsultation> proposalCopy = new ArrayList<>(proposal);
		proposalCopy.forEach(k -> {
			List<Konsultation> series = getSeries(k.getFall());
			// calculate money for kons series
			if (excludeKonsByMoney != null) {
				Money totalForKonsSerie = getSeriesTotal(series);
				if (excludeKonsByMoney.isMoreThan(totalForKonsSerie)) {
					// exclude whole series
					knownIds.addAll(series.parallelStream().map(sk -> sk.getId())
						.collect(Collectors.toList()));
					proposal.remove(k);
				}
			}
			series.forEach(sk -> {
				if (!knownIds.contains(sk.getId())) {
					// only look at sk once
					knownIds.add(sk.getId());
					if (applyFilters(sk)) {
						proposal.add(sk);
					}
				}
			});
			progress.worked(1);
			if (progress.isCanceled()) {
				canceled = true;
				return;
			}
		});
	}
	monitor.done();
}
 
Example 19
Source Project: tlaplus   File: Spec.java    License: MIT License 4 votes vote down vote up
/**
 * Associates the specified mapping with the specified filename (optional
 * operation). If the {@link Spec} previously contained a mapping for the
 * filename, the old mapping is replaced by the specified map.
 * 
 * @param mapping
 *            The {@link TLAtoPCalMapping} object for the given
 *            <tt>filename</tt>. <code>null</code>, will cause an
 *            {@link IllegalArgumentException}.
 * @param filename
 *            key with which the specified value is to be associated.
 *            <code>null</code>, will cause an
 *            {@link IllegalArgumentException}.
 * @param monitor
 *            A valid {@link IProgressMonitor}, <code>null</code>, will
 *            cause an {@link IllegalArgumentException}.
 * @return the previous value associated with <tt>filename</tt>, or
 *         <tt>null</tt> if there was no mapping for <tt>filename</tt>.
 * @throws NullPointerException
 *             if the specified key or value is null and this map does not
 *             permit null keys or values
 * @throws IllegalArgumentException
 *             if some property of the specified key or value prevents it
 *             from being stored in this map
 */
public TLAtoPCalMapping setTpMapping(final TLAtoPCalMapping mapping,
        final String filename, final IProgressMonitor monitor) {

    // Safeguard against inproper use of this API
    if (mapping == null || filename == null || monitor == null) {
        throw new IllegalArgumentException();
    }

    lock.lock();
    try {
        final TLAtoPCalMapping oldMapping = spec2mappings.put(filename,
                mapping);

        // Check if old and new mapping are identical to avoid disk flush.
        // This requires proper equals/hashcode in TLAtoPCalMapping and
        // nested.
        if (!mapping.equals(oldMapping)) {
            // Use a submonitor to show progress as well as failure
final SubMonitor subProgressMonitor = SubMonitor.convert(monitor, 1);
            subProgressMonitor
                    .setTaskName("Writing TLA+ to PCal mapping for "
                            + filename);
            // Eagerly flush mapping to its persistent disk storage
            // (overwriting
            // any previous mapping stored on disk). This is relatively
            // cheap
            // compared to how often a mapping is re-generated, but has the
            // advantage that the mapping doesn't get lost if the Toolbox
            // decides to
            // not shut down gracefully.
            try {
                Assert.isTrue(ResourceHelper.writeTLAtoPCalMapping(project,
                        filename, mapping, subProgressMonitor));
            } finally {
                subProgressMonitor.done();
            }
        }

        return oldMapping;
    } finally {
        lock.unlock();
    }
}
 
Example 20
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;
    }