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

The following examples show how to use org.eclipse.core.runtime.IProgressMonitor#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
Source File: MemberVisibilityAdjustor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Returns a cached type hierarchy for the specified type.
 *
 * @param type the type to get the hierarchy for
 * @param monitor the progress monitor to use
 * @return the type hierarchy
 * @throws JavaModelException if the type hierarchy could not be created
 */
private ITypeHierarchy getTypeHierarchy(final IType type, final IProgressMonitor monitor) throws JavaModelException {
	ITypeHierarchy hierarchy= null;
	try {
		monitor.beginTask("", 1); //$NON-NLS-1$
		monitor.setTaskName(RefactoringCoreMessages.MemberVisibilityAdjustor_checking);
		try {
			hierarchy= fTypeHierarchies.get(type);
			if (hierarchy == null) {
				if (fOwner == null) {
					hierarchy= type.newSupertypeHierarchy(new SubProgressMonitor(monitor, 1, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL));
				} else {
					hierarchy= type.newSupertypeHierarchy(fOwner, new SubProgressMonitor(monitor, 1, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL));
				}
				fTypeHierarchies.put(type, hierarchy);
			}
		} finally {
			monitor.done();
		}
	} finally {
		monitor.done();
	}
	return hierarchy;
}
 
Example 2
Source File: ILCDExportWizard.java    From olca-app with Mozilla Public License 2.0 6 votes vote down vote up
private void runExport(IProgressMonitor monitor, ExportConfig config,
		List<Descriptor> descriptors) throws InvocationTargetException {
	monitor.beginTask(M.Export, descriptors.size());
	int worked = 0;
	ILCDExport export = new ILCDExport(config);
	for (var d : descriptors) {
		if (monitor.isCanceled())
			break;
		monitor.setTaskName(d.name);
		try {
			Object obj = Daos.root(
					config.db, d.type).getForId(d.id);
			if (obj instanceof CategorizedEntity)
				export.export((CategorizedEntity) obj);
		} catch (Exception e) {
			throw new InvocationTargetException(e);
		} finally {
			monitor.worked(++worked);
		}
	}
	export.close();
}
 
Example 3
Source File: UseSuperTypeProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public final RefactoringStatus checkFinalConditions(final IProgressMonitor monitor, final CheckConditionsContext context) throws CoreException, OperationCanceledException {
	Assert.isNotNull(monitor);
	Assert.isNotNull(context);
	final RefactoringStatus status= new RefactoringStatus();
	fChangeManager= new TextEditBasedChangeManager();
	try {
		monitor.beginTask("", 200); //$NON-NLS-1$
		monitor.setTaskName(RefactoringCoreMessages.UseSuperTypeProcessor_checking);
		fChangeManager= createChangeManager(new SubProgressMonitor(monitor, 200), status);
		if (!status.hasFatalError()) {
			Checks.addModifiedFilesToChecker(ResourceUtil.getFiles(fChangeManager.getAllCompilationUnits()), context);
		}
	} finally {
		monitor.done();
	}
	return status;
}
 
Example 4
Source File: SVNWorkspaceSubscriber.java    From APICloud-Studio with GNU General Public License v3.0 6 votes vote down vote up
private IStatus refresh(IResource resource, int depth, IProgressMonitor monitor) {
		try {
//			monitor.setTaskName(Policy.bind("SVNWorkspaceSubscriber.refreshingSynchronizationData", resource.getFullPath().toString()));
			monitor.worked(100);
//			SVNProviderPlugin.getPlugin().getStatusCacheManager().refreshStatus(resource, IResource.DEPTH_INFINITE);
//			monitor.worked(300);

			monitor.setTaskName(Policy.bind("SVNWorkspaceSubscriber.retrievingSynchronizationData"));
			IResource[] lastChangedResources = (IResource[])changesMap.get(resource);
			IResource[] changedResources = findChanges(resource, depth, Policy.infiniteSubMonitorFor(monitor, 400));
			changesMap.put(resource, changedResources);
			fireTeamResourceChange(SubscriberChangeEvent.asSyncChangedDeltas(this, changedResources));
			if (lastChangedResources != null && lastChangedResources.length > 0) fireTeamResourceChange(SubscriberChangeEvent.asSyncChangedDeltas(this, lastChangedResources));
			monitor.worked(400);
			return Status.OK_STATUS;
		} catch (TeamException e) {
			return new TeamStatus(IStatus.ERROR, SVNProviderPlugin.ID, 0, Policy.bind("SVNWorkspaceSubscriber.errorWhileSynchronizing.2", resource.getFullPath().toString(), e.getMessage()), e, resource); //$NON-NLS-1$
		} 
	}
 
Example 5
Source File: AbstractAnalysisWizard.java    From depan with Apache License 2.0 6 votes vote down vote up
/**
 * Save the graph generated by the
 * {@link AbstractAnalysisWizard#createNewDocument(IProgressMonitor)}}
 *  method.
 */
@Override
protected void saveNewDocument(
    IProgressMonitor monitor, GraphDocument graph)
    throws CoreException {
  monitor.setTaskName("Getting File...");

  final IFile file = getOutputFile();
  monitor.worked(1);

  monitor.setTaskName("Writing file...");

  ResourceCache.storeGraphDocument(file, graph);

  monitor.worked(1);
}
 
Example 6
Source File: ExternalizeStringsAction.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private List<NonNLSElement> analyze(IPackageFragment pack, IProgressMonitor pm) throws CoreException {
	try{
		if (pack == null)
			return new ArrayList<NonNLSElement>(0);

		ICompilationUnit[] cus= pack.getCompilationUnits();

		pm.beginTask("", cus.length); //$NON-NLS-1$
		pm.setTaskName(pack.getElementName());

		List<NonNLSElement> l= new ArrayList<NonNLSElement>(cus.length);
		for (int i= 0; i < cus.length; i++){
			pm.subTask(BasicElementLabels.getFileName(cus[i]));
			NonNLSElement element= analyze(cus[i]);
			if (element != null)
				l.add(element);
			pm.worked(1);
			if (pm.isCanceled())
				throw new OperationCanceledException();
		}
		return l;
	} finally {
		pm.done();
	}
}
 
Example 7
Source File: EclipseExternalIndexSynchronizer.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Call this method when the content of the {@code node_modules} folder changed. It must be called before
 * {@link ExternalLibraryWorkspace#updateState()} adapted these changes. Otherwise the clean operation is not
 * possible anymore, since the projects to clean will be removed from the {@link ExternalLibraryWorkspace} instance.
 */
private RegisterResult cleanChangesIndex(IProgressMonitor monitor, Collection<LibraryChange> changeSet) {
	try {
		monitor.setTaskName("Cleaning new projects...");
		Set<FileURI> toBeRemovedProjects = getToBeRemovedProjects(changeSet);
		RegisterResult cleanResults = externalLibraryWorkspace.deregisterProjects(monitor, toBeRemovedProjects);
		printRegisterResults(cleanResults, "cleaned");

		return cleanResults;
	} finally {
		monitor.done();
	}
}
 
Example 8
Source File: ExtractInterfaceProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Creates the text change manager for this processor.
 *
 * @param monitor
 *            the progress monitor to display progress
 * @param status
 *            the refactoring status
 * @return the created text change manager
 * @throws JavaModelException
 *             if the method declaration could not be found
 * @throws CoreException
 *             if the changes could not be generated
 */
protected final TextEditBasedChangeManager createChangeManager(final IProgressMonitor monitor, final RefactoringStatus status) throws JavaModelException, CoreException {
	Assert.isNotNull(status);
	Assert.isNotNull(monitor);
	try {
		monitor.beginTask("", 300); //$NON-NLS-1$
		monitor.setTaskName(RefactoringCoreMessages.ExtractInterfaceProcessor_creating);
		resetEnvironment();
		final TextEditBasedChangeManager manager= new TextEditBasedChangeManager();
		final CompilationUnitRewrite sourceRewrite= new CompilationUnitRewrite(fSubType.getCompilationUnit());
		final AbstractTypeDeclaration declaration= ASTNodeSearchUtil.getAbstractTypeDeclarationNode(fSubType, sourceRewrite.getRoot());
		if (declaration != null) {
			createTypeSignature(sourceRewrite, declaration, status, new SubProgressMonitor(monitor, 20));
			final IField[] fields= getExtractedFields(fSubType.getCompilationUnit());
			if (fields.length > 0)
				ASTNodeDeleteUtil.markAsDeleted(fields, sourceRewrite, sourceRewrite.createCategorizedGroupDescription(RefactoringCoreMessages.ExtractInterfaceProcessor_remove_field_label, SET_EXTRACT_INTERFACE));
			if (fSubType.isInterface()) {
				final IMethod[] methods= getExtractedMethods(fSubType.getCompilationUnit());
				if (methods.length > 0)
					ASTNodeDeleteUtil.markAsDeleted(methods, sourceRewrite, sourceRewrite.createCategorizedGroupDescription(RefactoringCoreMessages.ExtractInterfaceProcessor_remove_method_label, SET_EXTRACT_INTERFACE));
			}
			final String name= JavaModelUtil.getRenamedCUName(fSubType.getCompilationUnit(), fSuperName);
			final ICompilationUnit original= fSubType.getPackageFragment().getCompilationUnit(name);
			final ICompilationUnit copy= getSharedWorkingCopy(original.getPrimary(), new SubProgressMonitor(monitor, 20));
			fSuperSource= createTypeSource(copy, fSubType, fSuperName, sourceRewrite, declaration, status, new SubProgressMonitor(monitor, 40));
			if (fSuperSource != null) {
				copy.getBuffer().setContents(fSuperSource);
				JavaModelUtil.reconcile(copy);
			}
			final Set<String> replacements= new HashSet<String>();
			if (fReplace)
				rewriteTypeOccurrences(manager, sourceRewrite, copy, replacements, status, new SubProgressMonitor(monitor, 220));
			rewriteSourceMethods(sourceRewrite, replacements);
			manager.manage(fSubType.getCompilationUnit(), sourceRewrite.createChange(true));
		}
		return manager;
	} finally {
		monitor.done();
	}
}
 
Example 9
Source File: AddSarlNatureHandler.java    From sarl with Apache License 2.0 5 votes vote down vote up
/** Convert the given project.
 *
 * @param project the project to convert..
 * @param monitor the progress monitor.
 * @throws ExecutionException if something going wrong.
 */
protected void doConvert(IProject project, IProgressMonitor monitor) throws ExecutionException {
	monitor.setTaskName(MessageFormat.format(Messages.AddSarlNatureHandler_2, project.getName()));
	final SubMonitor mon = SubMonitor.convert(monitor, 2);
	if (this.configurator.canConfigure(project, Collections.emptySet(), mon.newChild(1))) {
		this.configurator.configure(project, Collections.emptySet(), mon.newChild(1));
	}
	monitor.done();
}
 
Example 10
Source File: LoopNodesImportProgressDialog.java    From hop with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings( "unchecked" )
private String[] doScan( IProgressMonitor monitor ) throws Exception {
  monitor.beginTask( BaseMessages.getString( PKG, "GetXMLDateLoopNodesImportProgressDialog.Task.ScanningFile",
      filename ), 1 );

  SAXReader reader = XmlParserFactoryProducer.getSAXReader( null );
  monitor.worked( 1 );
  if ( monitor.isCanceled() ) {
    return null;
  }
  // Validate XML against specified schema?
  if ( meta.isValidating() ) {
    reader.setValidation( true );
    reader.setFeature( "http://apache.org/xml/features/validation/schema", true );
  } else {
    // Ignore DTD
    reader.setEntityResolver( new IgnoreDtdEntityResolver() );
  }
  monitor.worked( 1 );
  monitor
      .beginTask( BaseMessages.getString( PKG, "GetXMLDateLoopNodesImportProgressDialog.Task.ReadingDocument" ), 1 );
  if ( monitor.isCanceled() ) {
    return null;
  }
  InputStream is = null;
  try {
    Document document = null;
    if ( !Utils.isEmpty( filename ) ) {
      is = HopVfs.getInputStream( filename );
      document = reader.read( is, encoding );
    } else {
      if ( !Utils.isEmpty( xml ) ) {
        document = reader.read( new StringReader( xml ) );
      } else {
        document = reader.read( new URL( url ) );
      }
    }
    monitor.worked( 1 );
    monitor.beginTask( BaseMessages.getString( PKG, "GetXMLDateLoopNodesImportProgressDialog.Task.DocumentOpened" ),
        1 );
    monitor.worked( 1 );
    monitor.beginTask( BaseMessages.getString( PKG, "GetXMLDateLoopNodesImportProgressDialog.Task.ReadingNode" ), 1 );

    if ( monitor.isCanceled() ) {
      return null;
    }
    List<Node> nodes = document.selectNodes( document.getRootElement().getName() );
    monitor.worked( 1 );
    monitor.subTask( BaseMessages.getString( PKG, "GetXMLDateLoopNodesImportProgressDialog.Task.FetchNodes" ) );

    if ( monitor.isCanceled() ) {
      return null;
    }
    for ( Node node : nodes ) {
      if ( monitor.isCanceled() ) {
        return null;
      }
      if ( !listpath.contains( node.getPath() ) ) {
        nr++;
        monitor.subTask( BaseMessages.getString( PKG, "GetXMLDateLoopNodesImportProgressDialog.Task.FetchNodes",
            String.valueOf( nr ) ) );
        monitor.subTask( BaseMessages.getString( PKG, "GetXMLDateLoopNodesImportProgressDialog.Task.AddingNode", node
            .getPath() ) );
        listpath.add( node.getPath() );
        addLoopXPath( node, monitor );
      }
    }
    monitor.worked( 1 );
  } finally {
    try {
      if ( is != null ) {
        is.close();
      }
    } catch ( Exception e ) { /* Ignore */
    }
  }
  String[] list_xpath = listpath.toArray( new String[listpath.size()] );

  monitor.setTaskName( BaseMessages.getString( PKG, "GetXMLDateLoopNodesImportProgressDialog.Task.NodesReturned" ) );

  monitor.done();

  return list_xpath;

}
 
Example 11
Source File: NewGoFileWizard.java    From goclipse with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * The worker method. It will find the container, create the file if missing or just replace its
 * contents, and open the editor on the newly created file.
 */
private void doFinish(String containerName, String fileName, IProgressMonitor monitor)
    throws CoreException {
  // create a sample file
  monitor.beginTask("Creating " + fileName, 2);
  
  IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
  IResource resource = root.findMember(new Path(containerName));
  
  if (!resource.exists() || !(resource instanceof IContainer)) {
    throwCoreException("Container \"" + containerName + "\" does not exist.");
  }
  
  IContainer container = (IContainer) resource;
  
  final IFile file = container.getFile(new Path(fileName));
  InputStream stream = openContentStream(file);
  
  if (file.exists()) {
    file.setContents(stream, true, true, monitor);
  } else {
    file.create(stream, true, monitor);
  }
  
  monitor.worked(1);
  monitor.setTaskName("Opening file for editing...");
  
  getShell().getDisplay().asyncExec(new Runnable() {
    @Override
    public void run() {
      IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
      try {
        IDE.openEditor(page, file, true);
      } catch (PartInitException e) {
        LangCore.logError("Error opening editor", e);
      }
    }
  });
  
  monitor.worked(1);
}
 
Example 12
Source File: PythonPathHelper.java    From Pydev with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * @param root the zip file to analyze
 * @param monitor the monitor, to keep track of what is happening
 * @return a list with the name of the found modules in the jar
 */
protected static ModulesFoundStructure.ZipContents getFromZip(File root, IProgressMonitor monitor) {

    String fileName = root.getName();
    if (root.isFile() && FileTypesPreferences.isValidZipFile(fileName)) { //ok, it may be a jar file, so let's get its contents and get the available modules

        //the major difference from handling jars from regular python files is that we don't have to check for __init__.py files
        ModulesFoundStructure.ZipContents zipContents = new ModulesFoundStructure.ZipContents(root);

        //by default it's a zip (for python) -- may change if a .class is found.
        zipContents.zipContentsType = ZipContents.ZIP_CONTENTS_TYPE_PY_ZIP;

        try {
            String zipFileName = root.getName();

            ZipFile zipFile = new ZipFile(root);
            try {
                Enumeration<? extends ZipEntry> entries = zipFile.entries();

                int i = 0;
                FastStringBuffer buffer = new FastStringBuffer();
                //ok, now that we have the zip entries, let's map them to modules
                while (entries.hasMoreElements()) {
                    ZipEntry entry = entries.nextElement();
                    String name = entry.getName();
                    if (!entry.isDirectory()) {
                        if (isValidFileMod(name) || name.endsWith(".class")) {

                            if (name.endsWith(".class")) {
                                zipContents.zipContentsType = ZipContents.ZIP_CONTENTS_TYPE_JAR;
                            }

                            //it is a valid python file
                            if (i % 15 == 0) {
                                if (monitor.isCanceled()) {
                                    return null;
                                }
                                buffer.clear();
                                monitor.setTaskName(buffer.append("Found in ").append(zipFileName)
                                        .append(" module ").append(name).toString());
                                monitor.worked(1);
                            }

                            zipContents.pyFilesLowerToRegular.put(name.toLowerCase(), name);
                        }

                    } else { //!isDirectory
                        zipContents.pyfoldersLower.add(name.toLowerCase());
                    }
                    i++;
                }
            } finally {
                zipFile.close();
            }

            //now, on to actually filling the structure if we have a zip file (just add the ones that are actually under
            //the pythonpath)
            zipContents.consolidatePythonpathInfo(monitor);

            return zipContents;

        } catch (Exception e) {
            //that's ok, it is probably not a zip file after all...
            Log.log(e);
        }
    }
    return null;
}
 
Example 13
Source File: LoopNodesImportProgressDialog.java    From pentaho-kettle with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings( "unchecked" )
private String[] doScan( IProgressMonitor monitor ) throws Exception {
  monitor.beginTask( BaseMessages.getString( PKG, "GetXMLDateLoopNodesImportProgressDialog.Task.ScanningFile",
      filename ), 1 );

  SAXReader reader = XMLParserFactoryProducer.getSAXReader( null );
  monitor.worked( 1 );
  if ( monitor.isCanceled() ) {
    return null;
  }
  // Validate XML against specified schema?
  if ( meta.isValidating() ) {
    reader.setValidation( true );
    reader.setFeature( "http://apache.org/xml/features/validation/schema", true );
  } else {
    // Ignore DTD
    reader.setEntityResolver( new IgnoreDTDEntityResolver() );
  }
  monitor.worked( 1 );
  monitor
      .beginTask( BaseMessages.getString( PKG, "GetXMLDateLoopNodesImportProgressDialog.Task.ReadingDocument" ), 1 );
  if ( monitor.isCanceled() ) {
    return null;
  }
  InputStream is = null;
  try {
    Document document = null;
    if ( !Utils.isEmpty( filename ) ) {
      is = KettleVFS.getInputStream( filename );
      document = reader.read( is, encoding );
    } else {
      if ( !Utils.isEmpty( xml ) ) {
        document = reader.read( new StringReader( xml ) );
      } else {
        document = reader.read( new URL( url ) );
      }
    }
    monitor.worked( 1 );
    monitor.beginTask( BaseMessages.getString( PKG, "GetXMLDateLoopNodesImportProgressDialog.Task.DocumentOpened" ),
        1 );
    monitor.worked( 1 );
    monitor.beginTask( BaseMessages.getString( PKG, "GetXMLDateLoopNodesImportProgressDialog.Task.ReadingNode" ), 1 );

    if ( monitor.isCanceled() ) {
      return null;
    }
    List<Node> nodes = document.selectNodes( document.getRootElement().getName() );
    monitor.worked( 1 );
    monitor.subTask( BaseMessages.getString( PKG, "GetXMLDateLoopNodesImportProgressDialog.Task.FetchNodes" ) );

    if ( monitor.isCanceled() ) {
      return null;
    }
    for ( Node node : nodes ) {
      if ( monitor.isCanceled() ) {
        return null;
      }
      if ( !listpath.contains( node.getPath() ) ) {
        nr++;
        monitor.subTask( BaseMessages.getString( PKG, "GetXMLDateLoopNodesImportProgressDialog.Task.FetchNodes",
            String.valueOf( nr ) ) );
        monitor.subTask( BaseMessages.getString( PKG, "GetXMLDateLoopNodesImportProgressDialog.Task.AddingNode", node
            .getPath() ) );
        listpath.add( node.getPath() );
        addLoopXPath( node, monitor );
      }
    }
    monitor.worked( 1 );
  } finally {
    try {
      if ( is != null ) {
        is.close();
      }
    } catch ( Exception e ) { /* Ignore */
    }
  }
  String[] list_xpath = listpath.toArray( new String[listpath.size()] );

  monitor.setTaskName( BaseMessages.getString( PKG, "GetXMLDateLoopNodesImportProgressDialog.Task.NodesReturned" ) );

  monitor.done();

  return list_xpath;

}
 
Example 14
Source File: LabResetPathologic.java    From elexis-3-core with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public String executeMaintenance(IProgressMonitor pm, String DBVersion){
	Query<LabResult> qlr = new Query<LabResult>(LabResult.class);
	List<LabResult> results = qlr.execute();
	int size = results.size();
	pm.beginTask(getMaintenanceDescription() +" ("+size+" Laborwerte)", results.size());
	int allCount = 0;
	int changedCount = 0;
	for (LabResult labResult : results) {
		if (pm.isCanceled()) {
			addProblem("Cancelled.", labResult);
			return getProblemsString() + "\n" + changedCount + " Werte wurden geändert.\n "
				+ allCount + " Werte insgesamt.";
		}
		
		LockResponse result = LocalLockServiceHolder.get().acquireLockBlocking(labResult, 50,
			new NullProgressMonitor());
		if (result.isOk()) {
			boolean wasPathologic = labResult.isFlag(LabResultConstants.PATHOLOGIC);
			// reset patholgic by resetting ref values
			labResult.setRefFemale(labResult.getRefFemale());
			labResult.setRefMale(labResult.getRefMale());
			boolean isPathologic = labResult.isFlag(LabResultConstants.PATHOLOGIC);
			if (wasPathologic != isPathologic) {
				changedCount++;
			}
			LockResponse releaseLock =
				LocalLockServiceHolder.get().releaseLock(result.getLockInfo());
			if (!releaseLock.isOk()) {
				addProblem("Could not release lock for LabResult [" + labResult.getLabel() + "]"
					+ "[" + labResult.getId() + "]", labResult);
			}
		} else {
			addProblem("Could not acquire lock for LabResult [" + labResult.getLabel() + "]"
				+ "[" + labResult.getId() + "]", labResult);
		}
		
		allCount++;
		if ((allCount % 1000) == 0) {
			// cache Map in SoftCache is a memory leak on heavy use ... so resetCache 
			PersistentObject.resetCache();
			pm.setTaskName(getMaintenanceDescription() +" ("+size+" Laborwerte => "+allCount +" bearbeitet)");
		}
		pm.worked(1);
		try {
			Thread.sleep(25);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	pm.done();
	return changedCount + " Werte wurden geändert.\n " + allCount + " Werte insgesamt.";
}
 
Example 15
Source File: MonitorUtil.java    From TranskribusCore with GNU General Public License v3.0 4 votes vote down vote up
public static void setTaskName(IProgressMonitor monitor, String name) {
	if (monitor != null) {
		monitor.setTaskName(name);
	}
}
 
Example 16
Source File: EclipseRemoteProgressIndicatorImpl.java    From saros with GNU General Public License v2.0 4 votes vote down vote up
private void mainloop(final IProgressMonitor monitor) {
  int worked = 0;
  boolean firstTime = true;

  update:
  while (true) {

    final ProgressActivity activity;

    try {
      if (monitor.isCanceled()) break update;

      // poll so this monitor can be closed locally
      activity = activities.poll(1000, TimeUnit.MILLISECONDS);

      if (activity == null) continue update;

    } catch (InterruptedException e) {
      return;
    }

    final String taskName = activity.getTaskName();

    int newWorked;

    if (log.isTraceEnabled()) log.trace("executing progress activity: " + activity);

    switch (activity.getAction()) {
      case BEGINTASK:
        monitor.beginTask(taskName, activity.getWorkTotal());
        continue update;
      case SETTASKNAME:
        monitor.setTaskName(taskName);
        continue update;
      case SUBTASK:
        if (taskName != null) monitor.subTask(taskName);
        newWorked = activity.getWorkCurrent();
        if (newWorked > worked) {
          monitor.worked(newWorked - worked);
          worked = newWorked;
        }
        continue update;
      case UPDATE:
        if (firstTime) {
          monitor.beginTask(taskName, activity.getWorkTotal());
          firstTime = false;
        } else {
          if (taskName != null) monitor.subTask(taskName);

          newWorked = activity.getWorkCurrent();
          if (newWorked > worked) {
            monitor.worked(newWorked - worked);
            worked = newWorked;
          }
        }
        continue update;
      case DONE:
        monitor.done();
        break update;
      case CANCEL:
        log.debug("progress was canceled by remote user");
        monitor.setCanceled(true);
        break update;
    }
  }
}
 
Example 17
Source File: NewJavaBytecodeWizard.java    From depan with Apache License 2.0 4 votes vote down vote up
/**
 * Create an analysis graph by analyzing the .class files on the classpath.
 */
@Override
protected GraphDocument createNewDocument(IProgressMonitor monitor)
    throws IOException {

  // Step 1) Create the GraphModel to hold the analysis results
  String classPath = page.getClassPath();
  String directoryFilter = page.getDirectoryFilter();
  String packageFilter = page.getPackageFilter();

  // TODO(leeca): Extend UI to allow lists of packages.
  ElementFilter filter = DefaultElementFilter.build(packageFilter);

  GraphBuilder graphBuilder = GraphBuilders.createGraphModelBuilder();
  DependenciesListener builder =
      new DependenciesDispatcher(filter, graphBuilder);

  // TODO(leeca): Extend UI to allow lists of directories.
  Collection<String> directoryWhitelist = splitFilter(directoryFilter);

  monitor.worked(1);

  // Step 2) Read in the class files, depending on the source
  monitor.setTaskName("Load Classes...");
  AsmFactory asmFactory = page.getAsmFactory();

  ProgressListener baseProgress = new ProgressListenerMonitor(monitor);
  ProgressListener quickProgress = new QuickProgressListener(
      baseProgress, 300);

  if (classPath.endsWith(".jar") || classPath.endsWith(".zip")) {
    readZipFile(classPath, asmFactory, builder, quickProgress);
  } else {
    readTree(classPath, asmFactory, builder, quickProgress);
  }

  LOG.info(
      "{}/{} classes loaded. {} failed.",
      analysisStats.getClassesLoaded(), analysisStats.getClassesTotal(),
      analysisStats.getClassesFailed());

  monitor.worked(1);

  GraphModel resultGraph = graphBuilder.createGraphModel();
  return new GraphDocument(JavaPluginActivator.JAVA_MODEL, resultGraph);
}
 
Example 18
Source File: TraceValidateAndImportOperation.java    From tracecompass with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Imports a trace resource to project. In case of name collision the user
 * will be asked to confirm overwriting the existing trace, overwriting or
 * skipping the trace to be imported.
 *
 * @param fileSystemElement
 *            trace file system object to import
 * @param monitor
 *            a progress monitor
 * @return the imported resource or null if no resource was imported
 *
 * @throws InvocationTargetException
 *             if problems during import operation
 * @throws InterruptedException
 *             if cancelled
 * @throws CoreException
 *             if problems with workspace
 */
private IResource importResource(TraceFileSystemElement fileSystemElement, IProgressMonitor monitor)
        throws InvocationTargetException, InterruptedException, CoreException {

    IPath tracePath = getInitialDestinationPath(fileSystemElement);
    String newName = fConflictHandler.checkAndHandleNameClash(tracePath, monitor);

    if (newName == null) {
        return null;
    }
    fileSystemElement.setLabel(newName);

    List<TraceFileSystemElement> subList = new ArrayList<>();

    FileSystemElement parentFolder = fileSystemElement.getParent();

    IPath containerPath = fileSystemElement.getDestinationContainerPath();
    tracePath = containerPath.addTrailingSeparator().append(fileSystemElement.getLabel());
    boolean createLinksInWorkspace = (fImportOptionFlags & ImportTraceWizardPage.OPTION_CREATE_LINKS_IN_WORKSPACE) != 0;
    if (fileSystemElement.isDirectory() && !createLinksInWorkspace) {
        containerPath = tracePath;

        Object[] array = fileSystemElement.getFiles().getChildren();
        for (int i = 0; i < array.length; i++) {
            subList.add((TraceFileSystemElement) array[i]);
        }
        parentFolder = fileSystemElement;

    } else {
        if (!fileSystemElement.isDirectory()) {
            // File traces
            IFileInfo info = EFS.getStore(new File(fileSystemElement.getFileSystemObject().getAbsolutePath()).toURI()).fetchInfo();
            if (info.getLength() == 0) {
                // Don't import empty traces
                return null;
            }
        }
        subList.add(fileSystemElement);
    }

    ImportProvider fileSystemStructureProvider = new ImportProvider();

    IOverwriteQuery myQueryImpl = file -> IOverwriteQuery.NO_ALL;

    monitor.setTaskName(Messages.ImportTraceWizard_ImportOperationTaskName + " " + fileSystemElement.getFileSystemObject().getAbsolutePath()); //$NON-NLS-1$
    ImportOperation operation = new ImportOperation(containerPath, parentFolder, fileSystemStructureProvider, myQueryImpl, subList);
    operation.setContext(fShell);

    operation.setCreateContainerStructure(false);
    operation.setOverwriteResources(false);
    operation.setCreateLinks(createLinksInWorkspace);
    operation.setVirtualFolders(false);

    operation.run(SubMonitor.convert(monitor).newChild(1));
    String sourceLocation = fileSystemElement.getSourceLocation();
    IResource resource = ResourcesPlugin.getWorkspace().getRoot().findMember(tracePath);
    if ((sourceLocation != null) && (resource != null)) {
        resource.setPersistentProperty(TmfCommonConstants.SOURCE_LOCATION, sourceLocation);
    }

    return resource;
}
 
Example 19
Source File: FileAnalysisHandler.java    From translationstudio8 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * 解析所有的xliff文件
 * @param handler
 * @param monitor
 * @return
 */
public boolean openXliff(QAXmlHandler handler, IProgressMonitor monitor) {
	for (int fileIndex = 0; fileIndex < model.getAnalysisIFileList().size(); fileIndex++) {
		IProgressMonitor subMonitor = new SubProgressMonitor(monitor, 1,
				SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK);

		final IFile iFile = model.getAnalysisIFileList().get(fileIndex);
		subMonitor.setTaskName(MessageFormat.format(Messages.getString("qa.handlers.FileAnalysisHandler.tip5"),
				new Object[] { title, iFile.getFullPath().toString() }));

		continuResponse = QAConstant.QA_ZERO;
		try {
			Map<String, Object> newResultMap = handler.openFile(iFile.getLocation().toOSString(), subMonitor);
			// 针对退出解析
			if (newResultMap != null
					&& QAConstant.RETURNVALUE_RESULT_RETURN.equals(newResultMap.get(QAConstant.RETURNVALUE_RESULT))) {
				return false;
			}

			if (newResultMap == null
					|| QAConstant.RETURNVALUE_RESULT_SUCCESSFUL != (Integer) newResultMap
							.get(QAConstant.RETURNVALUE_RESULT)) {
				model.getErrorIFileList().add(iFile);
				// 针对文件解析出错
				Display.getDefault().syncExec(new Runnable() {
					public void run() {
						boolean response = MessageDialog.openConfirm(shell, Messages
								.getString("qa.all.dialog.error"), MessageFormat.format(Messages
								.getString("qa.all.tip.openXliffError"), new Object[] { iFile.getFullPath()
								.toOSString() }));
						if (response) {
							continuResponse = QAConstant.QA_FIRST;
						} else {
							continuResponse = QAConstant.QA_TWO;
						}
					}
				});
			}

			if (continuResponse == QAConstant.QA_FIRST) {
				model.getAnalysisIFileList().remove(fileIndex);
				fileIndex--;
				continue;
			} else if (continuResponse == QAConstant.QA_TWO) {
				return false;
			}

			allTUSize += handler.getTuSizeMap().get(iFile.getLocation().toOSString());
		} catch (Exception e) {
			MessageDialog.openError(shell, Messages.getString("qa.all.dialog.info"),
					Messages.getString("qa.all.log.openXmlError") + e);
			logger.error(Messages.getString("qa.all.log.openXmlError"), e);
			return false;
		}
	}
	return true;

}
 
Example 20
Source File: SimpleIronpythonRunner.java    From Pydev with Eclipse Public License 1.0 3 votes vote down vote up
/**
 * Execute the string and format for windows if we have spaces...
 *
 * The interpreter can be specified.
 *
 * @param interpreter the interpreter we want to use for executing
 * @param script the python script to execute
 * @param args the arguments to the script
 * @param workingDir the directory where the script should be executed
 *
 * @return the stdout of the run (if any)
 */
public Tuple<String, String> runAndGetOutputWithInterpreter(String interpreter, String script, String[] args,
        File workingDir, IProject project, IProgressMonitor monitor, String encoding) {
    monitor.setTaskName("Mounting executable string...");
    monitor.worked(5);

    String[] s = preparePythonCallParameters(interpreter, script, args, true);
    monitor.worked(1);
    return runAndGetOutput(s, workingDir, PythonNature.getPythonNature(project), monitor, encoding);
}