Java Code Examples for org.eclipse.core.runtime.IProgressMonitor

The following are top voted examples for showing how to use org.eclipse.core.runtime.IProgressMonitor. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: gemoc-studio   File: EclipseMessagingSystem.java   Source Code and License 6 votes vote down vote up
@Override
public void progress(String progressGroup, String msg, String msgGroup, int workedUnit) {
	boolean mustLog = false;
	IProgressMonitor progressMonitor = getProgressMonitor(progressGroup);		
	if(progressMonitor != null){
		progressMonitor.subTask(msg);
		progressMonitor.worked(workedUnit*progressBarScale);
	}
	else{
		mustLog = true;
	}
	
	// for the moment forward all messages to usual log
	Kind logLevel;
	if(mustLog){
		logLevel = Kind.UserINFO;
	}
	else logLevel = Kind.DevINFO;
	this.log(logLevel, "["+progressGroup+"]"+ msg+getIntermediateElapsedTime(progressGroup), msgGroup);
	
}
 
Example 2
Project: n4js   File: NpmManager.java   Source Code and License 6 votes vote down vote up
private Collection<File> adaptNPMPackages(final IProgressMonitor monitor, final MultiStatus status,
		final Collection<String> addedDependencies) {

	logger.logInfo(LINE_SINGLE);
	logger.logInfo("Adapting npm package structure to N4JS project structure... [step 3 of 4]");
	monitor.setTaskName("Adapting npm package structure to N4JS project structure... [step 3 of 4]");
	final Pair<IStatus, Collection<File>> result = npmPackageToProjectAdapter.adaptPackages(addedDependencies);
	final IStatus adaptionStatus = result.getFirst();

	// log possible errors, but proceed with the process
	// assume that at least some packages were installed correctly and can be adapted
	if (!adaptionStatus.isOK()) {
		logger.logError(adaptionStatus);
		status.merge(adaptionStatus);
	}

	final Collection<File> adaptedPackages = result.getSecond();
	logger.logInfo("Packages structures has been adapted to N4JS project structure.");
	monitor.worked(2);

	logger.logInfo(LINE_SINGLE);
	return adaptedPackages;
}
 
Example 3
Project: gw4e.project   File: BuildPolicyManager.java   Source Code and License 6 votes vote down vote up
/**
 * @param project
 * @param buildPolicyFile
 * @param graphFilePath
 * @param updatedGenerators
 * @throws IOException
 * @throws CoreException
 * @throws InterruptedException
 */
public static void update(IProject project, IFile buildPolicyFile, String graphFilePath,
		List<String> updatedGenerators) throws IOException, CoreException, InterruptedException {
	Job job = new WorkspaceJob("Updating policies") {
		public IStatus runInWorkspace(IProgressMonitor monitor) throws CoreException {
			try {
				_update(project, buildPolicyFile, graphFilePath, updatedGenerators, monitor);
			} catch (FileNotFoundException e) {
				ResourceManager.logException(e);
			}
			return Status.OK_STATUS;
		}
	};
	job.setRule(buildPolicyFile.getProject());
	job.setUser(true);
	job.schedule();
}
 
Example 4
Project: gemoc-studio-modeldebugging   File: AddDebugLayerHandler.java   Source Code and License 6 votes vote down vote up
public static void addStringCoupleIfNeeded(IFile classFile, String languageName,
		String layerName, IProgressMonitor monitor) throws IOException,
		CoreException {
	String content = getContent(classFile.getContents(), "UTF8");
	final String statement = "res.add(new StringCouple(\"" + languageName
			+ "\", \"" + layerName + "\"));";
	if (!content.contains(statement)) {
		int index = content.lastIndexOf("res.add(new StringCouple(");
		if (index >= 0) {
			index = index + "res.add(new StringCouple(".length();
			while (content.charAt(index) != ';') {
				++index;
			}
			String newContent = content.substring(0, index) + "\n\t\t"
					+ statement + "\n"
					+ content.substring(index, content.length());
			setContent(classFile.getFullPath().toFile(), "UTF8", newContent);
			classFile.refreshLocal(1, monitor);
		} else {
			// TODO notify : add statement manually
		}
	}
}
 
Example 5
Project: gw4e.project   File: ResourceManager.java   Source Code and License 6 votes vote down vote up
/**
 * Create a file in a folder with the specified name and content
 * 
 * @param fullpath
 * @param filename
 * @param content
 * @throws CoreException
 * @throws InterruptedException
 */
public static IFile createFileDeleteIfExists(String fullpath, String filename, String content,
		IProgressMonitor monitor) throws CoreException, InterruptedException {
	SubMonitor subMonitor = SubMonitor.convert(monitor, 100);
	subMonitor.setTaskName("Create file delete if it exists " + fullpath);
	IFile newFile;
	try {
		IWorkspaceRoot wroot = ResourcesPlugin.getWorkspace().getRoot();
		IContainer container = (IContainer) wroot.findMember(new Path(fullpath));
		newFile = container.getFile(new Path(filename));
		if (newFile.exists()) {
			JDTManager.rename(newFile, new NullProgressMonitor());
			newFile.delete(true, new NullProgressMonitor());
		}
		subMonitor.split(30);
		byte[] source = content.getBytes(Charset.forName("UTF-8"));
		newFile.create(new ByteArrayInputStream(source), true, new NullProgressMonitor());
		subMonitor.split(70);
	} finally {
		subMonitor.done();
	}
	return newFile;
}
 
Example 6
Project: solidity-ide   File: SolidityBuilderParticipant.java   Source Code and License 6 votes vote down vote up
@Override
public void build(IBuildContext context, IProgressMonitor monitor) throws CoreException {
	SubMonitor progress = SubMonitor.convert(monitor);
	if (!prefs.isCompilerEnabled()) {
		return;
	}
	final List<IResourceDescription.Delta> deltas = getRelevantDeltas(context);
	if (deltas.isEmpty()) {
		return;
	}
	if (progress.isCanceled()) {
		throw new OperationCanceledException();
	}
	progress.beginTask("Compiling solidity...", deltas.size());

	List<URI> uris = deltas.stream().map(delta -> delta.getUri()).collect(Collectors.toList());
	compiler.compile(uris, progress);
	context.getBuiltProject().refreshLocal(IProject.DEPTH_INFINITE, progress);
	progress.done();

}
 
Example 7
Project: codelens-eclipse   File: LSPCodeLensProvider.java   Source Code and License 6 votes vote down vote up
@Override
public CompletableFuture<ICodeLens> resolveCodeLens(ICodeLensContext context, ICodeLens codeLens,
		IProgressMonitor monitor) {
	ITextEditor textEditor = ((IEditorCodeLensContext) context).getTextEditor();

	LSPDocumentInfo info = null;
	Collection<LSPDocumentInfo> infos = LanguageServiceAccessor.getLSPDocumentInfosFor(
			LSPEclipseUtils.getDocument((ITextEditor) textEditor),
			capabilities -> capabilities.getCodeLensProvider() != null
					&& capabilities.getCodeLensProvider().isResolveProvider());
	if (!infos.isEmpty()) {
		info = infos.iterator().next();
	} else {
		info = null;
	}
	if (info != null) {
		LSPCodeLens lscl = ((LSPCodeLens) codeLens);
		CodeLens unresolved = lscl.getCl();
		return info.getLanguageClient().getTextDocumentService().resolveCodeLens(unresolved).thenApply(resolved -> {
			lscl.update(resolved);
			return lscl;
		});
	}
	return null;
}
 
Example 8
Project: n4js   File: ResourceUIValidatorExtension.java   Source Code and License 6 votes vote down vote up
private void addMarkers(IFile file, Resource resource, CheckMode mode, IProgressMonitor monitor)
		throws OperationCanceledException {
	try {
		List<Issue> list = getValidator(resource).validate(resource, mode, getCancelIndicator(monitor));
		if (monitor.isCanceled()) {
			throw new OperationCanceledException();
		}
		deleteMarkers(file, mode, monitor);
		if (monitor.isCanceled()) {
			throw new OperationCanceledException();
		}
		createMarkers(file, list, getMarkerCreator(resource), getMarkerTypeProvider(resource));
	} catch (OperationCanceledError error) {
		throw error.getWrapped();
	} catch (CoreException e) {
		LOGGER.error(e.getMessage(), e);
	}
}
 
Example 9
Project: neoscada   File: AlarmsInformationProcessor.java   Source Code and License 6 votes vote down vote up
@Override
protected void processContext ( final MasterContext masterContext, final IProgressMonitor monitor ) throws Exception
{
    // FIXME: this must be set from external

    if ( masterContext.getImplementation ().getAeServerInformationPrefix () == null || masterContext.getImplementation ().getAeServerInformationPrefix ().isEmpty () )
    {
        return;
    }

    createInternalItem ( masterContext, "ae.server.info.ALERT_ACTIVE", "Alert active" );
    createInternalItem ( masterContext, "ae.server.info.ALERT_DISABLED", "Alert disabled" );
    createInternalItem ( masterContext, "ae.server.info.OK", "Summarized state OK" );
    createInternalItem ( masterContext, "ae.server.info.NOT_OK", "Summarized state NOT_OK_AKN" );
    createInternalItem ( masterContext, "ae.server.info.UNSAFE", "Summarized state UNSAFE" );
    createInternalItem ( masterContext, "ae.server.info.INACTIVE", "Summarized state INACTIVE" );
    createInternalItem ( masterContext, "ae.server.info.INIT", "Summarized state INIT" );
    createInternalItem ( masterContext, "ae.server.info.NOT_OK_AKN", "Summarized state NOT_OK_AKN" );
    createInternalItem ( masterContext, "ae.server.info.NOT_OK_NOT_AKN", "Summarized state NOT_OK_NOT_AKN" );
    createInternalItem ( masterContext, "ae.server.info.NOT_AKN", "Summarized state NOT_OK_AKN" );
}
 
Example 10
Project: Equella   File: NewJPFPluginWizardPageOne.java   Source Code and License 6 votes vote down vote up
public void customizeManifest(Element rootElem, IProject project, IProgressMonitor monitor) throws CoreException
{
	if( equella.isLanguageStrings() )
	{
		Element runtime = rootElem.getChild("runtime");
		addLibrary(runtime, "resources", "resources/", "resources");
		JPFProject.getResourcesFolder(project).create(true, true, monitor);
	}
	Element requires = rootElem.getChild("requires");
	if( equella.isGuiceModule() )
	{
		addImport(requires, "com.tle.core.guice");
		addExtension(rootElem, "com.tle.core.guice", "module", "guiceModules");
	}
	if( equella.isLanguageStrings() )
	{
		addImport(requires, "com.tle.common.i18n");
		Element ext = addExtension(rootElem, "com.tle.common.i18n", "bundle", "strings");
		addParameter(ext, "file", "lang/i18n.properties");
		IFolder langFolder = JPFProject.getResourcesFolder(project).getFolder("lang");
		langFolder.create(true, true, monitor);
		langFolder.getFile("i18n.properties").create(new ByteArrayInputStream("# add your strings".getBytes()),
			true, monitor);
	}

}
 
Example 11
Project: EclipseMinifyBuilder   File: MinifyBuilder.java   Source Code and License 6 votes vote down vote up
@Override
protected IProject[] build(int kind, @SuppressWarnings("rawtypes") Map args,
		IProgressMonitor monitor) throws CoreException {
	ProjectScope projectScope = new ProjectScope(getProject());
	IEclipsePreferences prefs = projectScope.getNode(BUILDER_ID);
	if (kind == FULL_BUILD) {
		fullBuild(prefs, monitor);
	} else {
		IResourceDelta delta = getDelta(getProject());
		if (delta == null) {
			fullBuild(prefs, monitor);
		} else {
			incrementalBuild(delta, prefs, monitor);
		}
	}
	return null;
}
 
Example 12
Project: rtc-workitem-bulk-mover-service   File: BulkMoveOperation.java   Source Code and License 6 votes vote down vote up
/**
    * make sure that all attachments will be moved to the new project area
    * @param sourceWorkItem the original work item to which the attachments have belonged to
    * @param targetWorkItem work item object is it will be available in the target pa after movement
    * @param workItemCommon common service
    * @param progressMonitor progress monitor
    * @throws TeamRepositoryException whenever an attachment can't be moved
    */
@Override
protected void handleAttachments(IWorkItem sourceWorkItem, IWorkItem targetWorkItem, IWorkItemCommon workItemCommon,
		IProgressMonitor progressMonitor) throws TeamRepositoryException {
	ILinkServiceLibrary lsl = (ILinkServiceLibrary) this.service.getService(ILinkService.class)
               .getServiceLibrary(ILinkServiceLibrary.class);
	IWorkItemReferences references = workItemCommon.resolveWorkItemReferences(sourceWorkItem, monitor);
       for (IReference attachmentReference : references.getReferences(WorkItemEndPoints.ATTACHMENT)) {
           if (!attachmentReference.isItemReference()) continue;
           IAttachmentHandle attachmentHandle = (IAttachmentHandle)((IItemReference)attachmentReference)
                   .getReferencedItem();
           IAttachment attachment = workItemCommon.getAuditableCommon()
                   .resolveAuditable(attachmentHandle, IAttachment.SMALL_PROFILE, monitor);
           if (commitChanges) {
               this.moveAttachment(targetWorkItem, workItemCommon, attachment);
               continue;
           }
           this.checkAttachmentReferences(attachmentReference, lsl.findLinksBySource(attachmentReference), sourceWorkItem);
           this.checkAttachmentReferences(attachmentReference, lsl.findLinksByTarget(attachmentReference), sourceWorkItem);
       }
}
 
Example 13
Project: rtc-workitem-bulk-mover-service   File: ResolutionHelpers.java   Source Code and License 6 votes vote down vote up
static List<AttributeValue> addResolutionsAsValues(IProjectAreaHandle pa,
                                                   IWorkItemServer workItemServer, IProgressMonitor monitor) throws TeamRepositoryException {
    List<AttributeValue> values = new ArrayList<AttributeValue>();
    ICombinedWorkflowInfos workFlowInfo = workItemServer.findCachedCombinedWorkflowInfos(pa);
    if (workFlowInfo == null) {
        workFlowInfo = workItemServer.findCombinedWorkflowInfos(pa, monitor);
    }
    Identifier<IResolution>[] arridentifier = workFlowInfo.getAllResolutionIds();
    int n = arridentifier.length;
    int n2 = 0;
    while (n2 < n) {
        Identifier<IResolution> resolutionId = arridentifier[n2];
        String name = workFlowInfo.getResolutionName(resolutionId);
        String id = resolutionId.getStringIdentifier();
        values.add(new AttributeValue(id, name));
        ++n2;
    }
    return values;
}
 
Example 14
Project: convertigo-eclipse   File: JscriptStatementEditor.java   Source Code and License 6 votes vote down vote up
public void doSave(IProgressMonitor monitor) {
	jsEditor.doSave(monitor);
	try {
		// Get the jsEditor content and transfer it to the statement object
		statement.setExpression(IOUtils.toString(file.getContents(), "UTF-8")); 
	} catch (Exception e) {
		ConvertigoPlugin.logWarning("Error writing statement jscript code '" + eInput.getName() + "' : " + e.getMessage());
	}
	
	statement.hasChanged = true;
	// Refresh tree
	ProjectExplorerView projectExplorerView = ConvertigoPlugin.getDefault().getProjectExplorerView();
	if (projectExplorerView != null) {
		projectExplorerView.updateDatabaseObject(statement);
	}
}
 
Example 15
Project: neoscada   File: ModbusExporterProcessor.java   Source Code and License 6 votes vote down vote up
@Override
public void process ( final OscarContext ctx, final EquinoxApplication application, final IProgressMonitor monitor )
{
    try
    {
        final Collection<Object> exporters = EcoreUtil.getObjectsByType ( application.getModules (), ModbusPackage.Literals.MODBUS_EXPORTER );
        for ( final Object exp : exporters )
        {
            assert exp instanceof ModbusExporter;
            processExporter ( ctx, application, (ModbusExporter)exp, monitor );
        }
    }
    finally
    {
        monitor.done ();
    }
}
 
Example 16
Project: gemoc-studio-modeldebugging   File: AddDebugLayerHandler.java   Source Code and License 6 votes vote down vote up
public static Layer getOrCreateDebugLayer(
		DiagramExtensionDescription descriptionExtension, UserColor instructionColor,
		String layerName, IProgressMonitor monitor) {
	final Layer res;

	Layer existingLayer = null;
	for (Layer layer : descriptionExtension.getLayers()) {
		if ("Debug".equals(layer.getName())) {
			existingLayer = layer;
			break;
		}
	}

	if (existingLayer != null) {
		res = existingLayer;
	} else {
		res = createLayer(descriptionExtension, instructionColor, layerName, monitor);
	}

	return res;
}
 
Example 17
Project: n4js   File: RebuildWorkspaceProjectsJob.java   Source Code and License 5 votes vote down vote up
@Override
public IStatus runInWorkspace(IProgressMonitor monitor) throws CoreException {
	try {
		ResourcesPlugin.getWorkspace().build(configs, CLEAN_BUILD, true, monitor);
		return OK_STATUS;
	} catch (final CoreException e) {
		final String message = "Error while rebuilding workspace content.";
		LOGGER.error(message, e);
		return new Status(ERROR, N4JS_PLUGIN_ID, message, e);
	}
}
 
Example 18
Project: OCCI-Studio   File: GenerateAll.java   Source Code and License 5 votes vote down vote up
/**
 * Launches the generation.
 *
 * @param monitor
 *            This will be used to display progress information to the user.
 * @throws IOException
 *             Thrown when the output cannot be saved.
 * @generated
 */
public void doGenerate(IProgressMonitor monitor) throws IOException {
	if (!targetFolder.getLocation().toFile().exists()) {
		targetFolder.getLocation().toFile().mkdirs();
	}

	monitor.subTask("Loading...");
	org.eclipse.cmf.occi.core.gen.connector.main.Main gen0 = new org.eclipse.cmf.occi.core.gen.connector.main.Main(modelURI, targetFolder.getLocation().toFile(), arguments);
	monitor.worked(1);
	String generationID = org.eclipse.acceleo.engine.utils.AcceleoLaunchingUtil.computeUIProjectID("org.eclipse.cmf.occi.core.gen.connector", "org.eclipse.cmf.occi.core.gen.connector.main.Main", modelURI.toString(), targetFolder.getFullPath().toString(), new ArrayList<String>());
	gen0.setGenerationID(generationID);
	gen0.doGenerate(BasicMonitor.toMonitor(monitor));
}
 
Example 19
Project: gw4e.project   File: TemplateProvider.java   Source Code and License 5 votes vote down vote up
protected IRunnableWithProgress createResourceOperation(IFolder folder,InitialBuildPolicies policies) {
	WorkspaceModifyOperation operation = new WorkspaceModifyOperation() {
		@Override
		protected void execute(IProgressMonitor monitor) {
			String resource = "";
			String targetFile = "";
			try {
				for (int i = 0; i < resources.length; i++) {
					resource = resources[i];
					targetFile =  targetFiles[i];
					IFile file =  create(folder, resource, targetFile, monitor);
					if (file != null) {
						createdResources.add(file);
						policies.setFile(file);
						policies.run();
						BasicNewResourceWizard.selectAndReveal(file,
								PlatformUI.getWorkbench().getActiveWorkbenchWindow());
					}
				}			
			} catch (Exception exception) {
				ResourceManager.logException(exception, "Unable to create " + resource);
			} finally {
				monitor.done();
			}
		}
	};
	return operation;
}
 
Example 20
Project: neoscada   File: DeploymentEditor.java   Source Code and License 5 votes vote down vote up
/**
 * <!-- begin-user-doc -->
 * <!-- end-user-doc -->
 * @generated
 */
protected void doSaveAs ( URI uri, IEditorInput editorInput )
{
    ( editingDomain.getResourceSet ().getResources ().get ( 0 ) ).setURI ( uri );
    setInputWithNotify ( editorInput );
    setPartName ( editorInput.getName () );
    IProgressMonitor progressMonitor = getActionBars ().getStatusLineManager () != null ? getActionBars ().getStatusLineManager ().getProgressMonitor () : new NullProgressMonitor ();
    doSave ( progressMonitor );
}
 
Example 21
Project: gemoc-studio-modeldebugging   File: AddDebugLayerHandler.java   Source Code and License 5 votes vote down vote up
public static UserColorsPalette getOrCreateColotPalette(
		DiagramExtensionDescription descriptionExtension, String languageName,
		IProgressMonitor monitor) {
	final UserColorsPalette res;
	final String paletteName = languageName + " Palette";

	final Group group = (Group) descriptionExtension.eContainer().eContainer();
	UserColorsPalette existingPalette = null;
	for (UserColorsPalette palette : group.getUserColorsPalettes()) {
		if (paletteName.equals(palette.getName())) {
			existingPalette = palette;
			break;
		}
	}

	if (existingPalette != null) {
		res = existingPalette;
	} else {
		res = DescriptionPackage.eINSTANCE.getDescriptionFactory()
				.createUserColorsPalette();

		res.setName(paletteName);
		group.getUserColorsPalettes().add(res);
	}

	return res;
}
 
Example 22
Project: gw4e.project   File: GraphWalkerContextManager.java   Source Code and License 5 votes vote down vote up
/**
 * @param file
 * @throws InvocationTargetException
 * @throws CoreException
 * @throws InterruptedException
 */
public static void generateDefaultGraphConversion(IWorkbenchWindow ww, IFile file, IProgressMonitor monitor)
		throws InvocationTargetException, InterruptedException, CoreException {
	AbstractPostConversion converter = getDefaultGraphConversion(file,false);
	ConversionRunnable runnable = converter.createConversionRunnable(ww);
	runnable.run(monitor);
}
 
Example 23
Project: Tarski   File: FetchSoftwareRequirements.java   Source Code and License 5 votes vote down vote up
@Override
  public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
      int totalUnitsOfWork = IProgressMonitor.UNKNOWN;
      monitor.beginTask("Performing read. Please wait...", totalUnitsOfWork);
      // This only performs the tasks
try {
	client.setCredentials(Constants.USERNAME, Constants.PASSWORD);
	System.out.println(getClient().getUser());
	issues = loadRequirements();
} catch (IOException e) {
	e.printStackTrace();
}
      monitor.done();
  }
 
Example 24
Project: Open_Source_ECOA_Toolset_AS5   File: IntFinalAssemblyEditor.java   Source Code and License 5 votes vote down vote up
@Override
public void doSave(IProgressMonitor monitor) {
	try {
		CompositeNode node = (CompositeNode) root.getModel();
		FileEditorInput inp = (FileEditorInput) getEditorInput();
		inp.getFile().setContents(new StringBufferInputStream(ParseUtil.getIntFinalAssemblyEditorContent(node)), IFile.FORCE, monitor);
		getCommandStack().markSaveLocation();
	} catch (Exception e) {
		e.printStackTrace();
	}
}
 
Example 25
Project: n4js   File: N4JSToBeBuiltComputer.java   Source Code and License 5 votes vote down vote up
@Override
public void removeProject(ToBeBuilt toBeBuilt, IProject project, IProgressMonitor monitor) {
	storageMapper.collectNfarURIs(project, toBeBuilt.getToBeDeleted());
	Iterator<Map.Entry<String, Set<URI>>> iterator = knownEntries.entrySet().iterator();
	String keyPrefix = project.getName() + "|";
	while (iterator.hasNext()) {
		String key = iterator.next().getKey();
		if (key.startsWith(keyPrefix)) {
			iterator.remove();
		}
	}
}
 
Example 26
Project: gemoc-studio   File: FsmEditor.java   Source Code and License 5 votes vote down vote up
/**
 * <!-- begin-user-doc -->
 * <!-- end-user-doc -->
 * @generated
 */
protected void doSaveAs(URI uri, IEditorInput editorInput) {
	(editingDomain.getResourceSet().getResources().get(0)).setURI(uri);
	setInputWithNotify(editorInput);
	setPartName(editorInput.getName());
	IProgressMonitor progressMonitor =
		getActionBars().getStatusLineManager() != null ?
			getActionBars().getStatusLineManager().getProgressMonitor() :
			new NullProgressMonitor();
	doSave(progressMonitor);
}
 
Example 27
Project: n4js   File: NpmManager.java   Source Code and License 5 votes vote down vote up
private void cleanBuildDependencies(final IProgressMonitor monitor, final MultiStatus status,
		final Iterable<java.net.URI> toBeDeleted, final Collection<File> adaptedPackages,
		boolean triggerCleanbuild) {

	logger.logInfo("Registering new projects... [step 4 of 4]");
	monitor.setTaskName("Registering new projects... [step 4 of 4]");
	// nothing to do in the headless case. TODO inject logic instead?
	if (Platform.isRunning()) {
		logger.logInfo("Platform is running.");
		final Iterable<java.net.URI> toBeUpdated = from(adaptedPackages).transform(file -> file.toURI());
		final NpmProjectAdaptionResult adaptionResult = NpmProjectAdaptionResult.newOkResult(toBeUpdated,
				toBeDeleted);
		logger.logInfo("Call " + externalLibraryWorkspace + " to register " + toBeUpdated + " and de-register "
				+ toBeDeleted);

		externalLibraryWorkspace.registerProjects(adaptionResult, monitor, triggerCleanbuild);
	} else {
		logger.logInfo("Platform is not running.");
	}
	logger.logInfo("Finished registering projects.");

	if (status.isOK())
		logger.logInfo("Successfully finished installing  packages.");
	else
		logger.logInfo("There were errors during installation, see logs for details.");

	logger.logInfo(LINE_DOUBLE);
}
 
Example 28
Project: time4sys   File: DesignEditor.java   Source Code and License 5 votes vote down vote up
/**
 * <!-- begin-user-doc -->
 * <!-- end-user-doc -->
 * @generated
 */
protected void doSaveAs(URI uri, IEditorInput editorInput) {
	(editingDomain.getResourceSet().getResources().get(0)).setURI(uri);
	setInputWithNotify(editorInput);
	setPartName(editorInput.getName());
	IProgressMonitor progressMonitor =
		getActionBars().getStatusLineManager() != null ?
			getActionBars().getStatusLineManager().getProgressMonitor() :
			new NullProgressMonitor();
	doSave(progressMonitor);
}
 
Example 29
Project: time4sys   File: GqamEditor.java   Source Code and License 5 votes vote down vote up
/**
 * <!-- begin-user-doc -->
 * <!-- end-user-doc -->
 * @generated
 */
protected void doSaveAs(URI uri, IEditorInput editorInput) {
	(editingDomain.getResourceSet().getResources().get(0)).setURI(uri);
	setInputWithNotify(editorInput);
	setPartName(editorInput.getName());
	IProgressMonitor progressMonitor =
		getActionBars().getStatusLineManager() != null ?
			getActionBars().getStatusLineManager().getProgressMonitor() :
			new NullProgressMonitor();
	doSave(progressMonitor);
}
 
Example 30
Project: Equella   File: JPFPluginModelManager.java   Source Code and License 5 votes vote down vote up
@Override
protected IStatus run(IProgressMonitor monitor)
{
	try
	{
		boolean more = false;
		do
		{
			IJavaProject[] projects = null;
			IClasspathContainer[] containers = null;
			synchronized( fProjects )
			{
				projects = fProjects.toArray(new IJavaProject[fProjects.size()]);
				containers = fContainers.toArray(new IClasspathContainer[fContainers.size()]);
				fProjects.clear();
				fContainers.clear();
			}
			JavaCore.setClasspathContainer(JPFClasspathPlugin.CONTAINER_PATH, projects, containers, monitor);
			synchronized( fProjects )
			{
				more = !fProjects.isEmpty();
			}
		}
		while( more );

	}
	catch( JavaModelException e )
	{
		return e.getStatus();
	}
	return Status.OK_STATUS;
}
 
Example 31
Project: gw4e.project   File: InvalidPathGeneratorMarkerResolution.java   Source Code and License 5 votes vote down vote up
@Override
protected void doRun(IMarker marker,IProgressMonitor monitor) {
	try {
		String key = this.getEntryKey(marker);
		String value = p.getProperty(key);
		String pathGenerator = this.getPathGenerator(marker);
		value = value.replace(pathGenerator, this.getTargetGeneratorPath());
		this.setValue(key, value);
	} catch (Exception e) {
		ResourceManager.logException(e);
	}
}
 
Example 32
Project: gemoc-studio-modeldebugging   File: DSLDebugEventDispatcher.java   Source Code and License 5 votes vote down vote up
@Override
protected IStatus run(IProgressMonitor monitor) {
	while (!terminated) {
		// wait for new events
		if (events.isEmpty()) {
			try {
				synchronized(this) {
					wait();
				}
			} catch (InterruptedException e) {
				// nothing to do here
			}
		}

		if (!monitor.isCanceled()) {
			IDSLDebugEvent event = null;
			synchronized(events) {
				if (!events.isEmpty()) {
					event = events.remove(0);
				}
			}

			if (event != null) {
				handleEvent(event);
			}
		} else {
			terminate();
		}
	}

	return Status.OK_STATUS;
}
 
Example 33
Project: codelens-eclipse   File: JavaCodeLensProvider.java   Source Code and License 5 votes vote down vote up
private List<Location> findImplementations(IType type, IProgressMonitor monitor) throws JavaModelException {
	IType[] results = type.newTypeHierarchy(monitor).getAllSubtypes(type);
	final List<Location> result = new ArrayList<>();
	for (IType t : results) {
		ICompilationUnit compilationUnit = (ICompilationUnit) t.getAncestor(IJavaElement.COMPILATION_UNIT);
		if (compilationUnit == null) {
			continue;
		}
		Location location = null; // JDTUtils.toLocation(t);
		result.add(location);
	}
	return result;
}
 
Example 34
Project: Hydrograph   File: RenameJobParticipant.java   Source Code and License 5 votes vote down vote up
@Override
public RefactoringStatus checkConditions(IProgressMonitor pm,
		CheckConditionsContext context) throws OperationCanceledException {
	String newName = getArguments().getNewName();
	String newExt = newName.substring(newName.lastIndexOf(".")+1);
	
	if("job".equals(modifiedResource.getFileExtension())) {
		if(!("job".equals(newExt))) {
			return RefactoringStatus.createFatalErrorStatus("Changing extension of job file is not allowed");
		}
	}
	else if("job".equals(newExt)) {
		return RefactoringStatus.createFatalErrorStatus("Changing extension to .job not allowed." +
				"Please create a new job file.");
	}
	else if(CustomMessages.ProjectSupport_JOBS.equals(modifiedResource.getFullPath().segment(1))
			&& !newExt.matches("job|xml")) {
		return RefactoringStatus.createFatalErrorStatus("Only .job and .xml files can be stored in this folder" );
	}
	else if(modifiedResource.getFileExtension().matches("xml|properties")
			|| (newExt.matches("xml|properties"))){
		if(ResourceChangeUtil.isGeneratedFile(modifiedResource.getName()
										,modifiedResource.getProject())) {
			return RefactoringStatus.createFatalErrorStatus(
					".xml or .properties file cannot be renamed. " +
					"Rename the .job file to rename the xml and properties file");
			
		}
		else if(ResourceChangeUtil.isGeneratedFile(newName,modifiedResource.getProject())) {
			return RefactoringStatus.createFatalErrorStatus("Generated file with same name exists.Please choose a different name");
		}
		else if(("properties".equals(modifiedResource.getFileExtension()) 
				|| "properties".equals(newExt))
				&& !modifiedResource.getFullPath().segment(1).equals(CustomMessages.ProjectSupport_PARAM)) {
			return RefactoringStatus.createFatalErrorStatus("properties file can only be saved in param folder.");
		}
	}
	return new RefactoringStatus();
}
 
Example 35
Project: neoscada   File: SummariesItemsGenerator.java   Source Code and License 5 votes vote down vote up
@Override
public void processContext ( final MasterContext app, final IProgressMonitor monitor ) throws Exception
{
    final AbstractComponentItemCreator creator = new SummariesItemCreatorImpl ( app, null, this.system );
    new TypeWalker<> ( SummaryGroup.class ).walk ( app.getImplementation (), new TypeVisitor<SummaryGroup> () {

        @Override
        public void visit ( final SummaryGroup group ) throws Exception
        {
            processGroup ( app.getImplementation (), group, creator );
        }
    } );
}
 
Example 36
Project: neoscada   File: ProtocolEditor.java   Source Code and License 5 votes vote down vote up
/**
 * <!-- begin-user-doc -->
 * <!-- end-user-doc -->
 * @generated
 */
protected void doSaveAs ( URI uri, IEditorInput editorInput )
{
    ( editingDomain.getResourceSet ().getResources ().get ( 0 ) ).setURI ( uri );
    setInputWithNotify ( editorInput );
    setPartName ( editorInput.getName () );
    IProgressMonitor progressMonitor =
            getActionBars ().getStatusLineManager () != null ?
                    getActionBars ().getStatusLineManager ().getProgressMonitor () :
                    new NullProgressMonitor ();
    doSave ( progressMonitor );
}
 
Example 37
Project: rtc-workitem-bulk-mover-service   File: CategoryHelpers.java   Source Code and License 5 votes vote down vote up
static AttributeValue getCategory(Object t_val,
                                  IWorkItemServer workItemServer, TeamRawService service, IProgressMonitor monitor) throws TeamRepositoryException {
    IRepositoryItemService itemService = service.getService(IRepositoryItemService.class);
    ICategoryHandle catHandle = (ICategoryHandle)t_val;
    ICategory category = (ICategory) itemService.fetchItem(catHandle, null);
    CategoryId id = category.getCategoryId();
    String idString = id.getInternalRepresentation();
    String fullPathname = workItemServer.resolveHierarchicalName(category, monitor);
    return new AttributeValue(idString, fullPathname);
}
 
Example 38
Project: n4js   File: ExternalLibrariesReloadHelper.java   Source Code and License 5 votes vote down vote up
/**
 * Reloads the external libraries by re-indexing all registered external projects that are do not exist in the
 * workspace.
 *
 * @param refreshNpmDefinitions
 *            if {@code true}, then the type definition files will be reloaded/refreshed for all {@code npm}
 *            packages.
 * @param monitor
 *            the monitor for the process.
 * @throws InvocationTargetException
 *             if any unexpected error occurs during the refresh process.
 */
public void reloadLibraries(final boolean refreshNpmDefinitions, final IProgressMonitor monitor)
		throws InvocationTargetException {

	final ISchedulingRule rule = builderHelper.getRule();
	try {
		Job.getJobManager().beginRule(rule, monitor);
		reloadLibrariesInternal(refreshNpmDefinitions, monitor);
	} catch (final OperationCanceledException e) {
		LOGGER.info("User abort.");
	} finally {
		Job.getJobManager().endRule(rule);
	}
}
 
Example 39
Project: OCCI-Studio   File: OCCIDocumentProvider.java   Source Code and License 5 votes vote down vote up
@Override
protected void doSaveDocument(IProgressMonitor monitor, Object element, IDocument document, boolean overwrite)
		throws CoreException {
	try {
		//System.out.println("doSaveDocument ");
		ResourceSet resourceSet = createResourceSet();
		XtextResource xtextResource = (XtextResource) resourceSet.createResource(URI.createURI("temp.occi"));
		InputStream is = new ByteArrayInputStream(document.get().getBytes());
		xtextResource.load(is, Collections.EMPTY_MAP);
		is.close();
		URI uri = URI.createPlatformResourceURI(
				((org.eclipse.ui.part.FileEditorInput) element).getFile().getFullPath().toString(), true);
		//resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("*", new XMIResourceFactoryImpl());
		//System.out.println("uriii "+uri);
		Resource xmiResource = resourceSet.getResource(uri, true);
		((XMLResource) xmiResource).getDefaultSaveOptions().put(XMLResource.OPTION_URI_HANDLER,
				new URIHandlerImpl.PlatformSchemeAware());
		xmiResource.getContents().clear();
		xmiResource.getContents().addAll(xtextResource.getContents());
		// SUPER IMPORTANT to avoid to have references to temp.occi
		EcoreUtil.resolveAll(xmiResource);			
		xmiResource.save(Collections.EMPTY_MAP);
	} catch (IOException e) {
		throw new CoreException(
				new Status(IStatus.ERROR, "org.occiware.clouddesigner.occi.xtext.ui", "Failed to save", e));
	}
}
 
Example 40
Project: gw4e.project   File: AbstractBuildPoliciesMarkerResolution.java   Source Code and License 5 votes vote down vote up
@Override
public void run(IMarker marker) {
	Job job = new WorkspaceJob("GW4E Fix Job") {
		@Override
		public IStatus runInWorkspace(IProgressMonitor monitor) throws CoreException {
			fix(marker, monitor);
			return Status.OK_STATUS;
		}
	};
	job.setRule(marker.getResource().getProject());
	job.setUser(true);
	job.schedule();
}
 
Example 41
Project: n4js   File: BuildInstruction.java   Source Code and License 5 votes vote down vote up
@Override
public void finish(List<Delta> deltas, IProgressMonitor progressMonitor) throws CoreException {
	for (Delta delta : deltas) {
		if (delta.getNew() == null) {
			String uri = delta.getUri().toString();
			recordDerivedResources(uri);
			deleteObsoleteResources(uri, progressMonitor);
		}
	}
	deleteEmptyDirectories(progressMonitor);
}
 
Example 42
Project: neoscada   File: ExporterProcessor.java   Source Code and License 5 votes vote down vote up
private void processDevice ( final OscarContext ctx, final EquinoxApplication application, final Device device, final IProgressMonitor monitor )
{
    final String id = device.getId ();

    final Map<String, String> data = new HashMap<String, String> ();
    data.put ( "port", Integer.toString ( device.getEndpoint ().getPortNumber () ) ); //$NON-NLS-1$

    if ( device.getSpontaneousBufferWindow () != null && device.getSpontaneousBufferWindow () > 0 )
    {
        data.put ( "spontaneousBufferWindow", device.getSpontaneousBufferWindow ().toString () ); //$NON-NLS-1$
    }

    Configurations.encode ( data, null, device.getProtocolOptions () );
    Configurations.encode ( data, null, device.getDataModuleOptions () );

    // Add hive properties
    for ( final PropertyEntry property : device.getHiveProperties () )
    {
        final String key = "hive." + property.getKey (); //$NON-NLS-1$
        data.put ( key, property.getValue () );
    }

    // Add item data
    for ( final Item item : device.getItems () )
    {
        processItem ( data, item );
    }
    ctx.addData ( DEVICE_FACTORY_ID, id, data );
}
 
Example 43
Project: n4js   File: CleanInstruction.java   Source Code and License 5 votes vote down vote up
@Override
public void finish(List<Delta> deltas, IProgressMonitor progressMonitor) throws CoreException {
	SubMonitor cleanMonitor = SubMonitor.convert(progressMonitor, outputConfigurations.size());
	for (OutputConfiguration config : outputConfigurations.values()) {
		cleanOutput(project, config, cleanMonitor.newChild(1));
	}
}
 
Example 44
Project: neoscada   File: SetupEditor.java   Source Code and License 5 votes vote down vote up
/**
 * <!-- begin-user-doc -->
 * <!-- end-user-doc -->
 * @generated
 */
protected void doSaveAs ( URI uri, IEditorInput editorInput )
{
    ( editingDomain.getResourceSet ().getResources ().get ( 0 ) ).setURI ( uri );
    setInputWithNotify ( editorInput );
    setPartName ( editorInput.getName () );
    IProgressMonitor progressMonitor = getActionBars ().getStatusLineManager () != null ? getActionBars ().getStatusLineManager ().getProgressMonitor () : new NullProgressMonitor ();
    doSave ( progressMonitor );
}
 
Example 45
Project: time4sys   File: GrmEditor.java   Source Code and License 5 votes vote down vote up
/**
 * <!-- begin-user-doc -->
 * <!-- end-user-doc -->
 * @generated
 */
protected void doSaveAs(URI uri, IEditorInput editorInput) {
	(editingDomain.getResourceSet().getResources().get(0)).setURI(uri);
	setInputWithNotify(editorInput);
	setPartName(editorInput.getName());
	IProgressMonitor progressMonitor =
		getActionBars().getStatusLineManager() != null ?
			getActionBars().getStatusLineManager().getProgressMonitor() :
			new NullProgressMonitor();
	doSave(progressMonitor);
}
 
Example 46
Project: gw4e.project   File: RenameGraphParticipant.java   Source Code and License 5 votes vote down vote up
@Override
public Change createChange(IProgressMonitor pm) throws CoreException, OperationCanceledException {
	final CompositeChange changes = new CompositeChange(getName());
	for (RenameChange renameOperation : renameOperations) {
		
		// Update build.policies file
		changes.add(renameOperation);
		// Rename the test compilation unit
		Change ci = renameOperation.createRenameChangeForTestImplementation(pm);
		if (ci != null)
			changes.add(ci);
		// rename the interface compilation unit
		Change cti = renameOperation.createRenameChangeForTestInterface(pm);
		if (cti != null)
			changes.add(cti);
		
		// Update the Generated annotation
		Change renameGeneratedAnnotationChange  = new RenameGeneratedAnnotation (originalFile.getProject(),originalFile.getFullPath(),newName);
		changes.add(renameGeneratedAnnotationChange);
		
		// Update the Model annotation
		Change renameModelAnnotationChange = new RenameModelAnnotation (originalFile.getProject(),originalFile.getFullPath(),newName);
		changes.add(renameModelAnnotationChange);
		
		// Update Path Usage such as Path.get("foo/bar/Test.json")
		Change renamePathUsageChange = new RenamePathUsage (originalFile.getProject(),originalFile.getFullPath(),newName);
		changes.add(renamePathUsageChange);
		
		// Open/Close editors 
		changes.add(renameOperation.createEditorChangeForGraph(pm)); 
	}
	
	// When renaming a folder, it becomes a Move...
	MoveGraphParticipant  mgp = new MoveGraphParticipant(moveOperations);
	Change moveChange = mgp.createChange(new NullProgressMonitor ());
	changes.add(moveChange);
	
	return changes;
}
 
Example 47
Project: pgcodekeeper   File: NewProjWizard.java   Source Code and License 5 votes vote down vote up
@Override
public void run(IProgressMonitor monitor)
        throws InvocationTargetException, InterruptedException {

    JdbcConnector connector = new JdbcConnector(dbinfo.getDbHost(), dbinfo.getDbPort(),
            dbinfo.getDbUser(), dbinfo.getDbPass(), dbinfo.getDbName(), ApgdiffConsts.UTC);

    try (Connection conn = connector.getConnection(); Statement s = conn.createStatement()) {
        ResultSet rs = s.executeQuery(QUERY_TZ);
        timezone = rs.next() ? rs.getString("setting") : null; //$NON-NLS-1$
    } catch (SQLException | IOException e) {
        throw new InvocationTargetException(e, e.getLocalizedMessage());
    }
}
 
Example 48
Project: OCCI-Studio   File: OCCIEditor.java   Source Code and License 5 votes vote down vote up
/**
 * <!-- begin-user-doc -->
 * <!-- end-user-doc -->
 * @generated
 */
protected void doSaveAs(URI uri, IEditorInput editorInput) {
	(editingDomain.getResourceSet().getResources().get(0)).setURI(uri);
	setInputWithNotify(editorInput);
	setPartName(editorInput.getName());
	IProgressMonitor progressMonitor =
		getActionBars().getStatusLineManager() != null ?
			getActionBars().getStatusLineManager().getProgressMonitor() :
			new NullProgressMonitor();
	doSave(progressMonitor);
}
 
Example 49
Project: openaudible   File: ProgressDialog.java   Source Code and License 5 votes vote down vote up
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
    // DebugLog.println("Running task");
    monitor.beginTask("Running task ", IProgressMonitor.UNKNOWN);
    if (simpleThread != null) {
        simpleThread.start();
        simpleThread.join();
    }
    // DebugLog.println("Task complete.");
    monitor.done();
    if (monitor.isCanceled())
        throw new InterruptedException("The operation was cancelled");
}
 
Example 50
Project: n4js   File: NpmManager.java   Source Code and License 5 votes vote down vote up
/**
 * Batch install / uninstall of npm packages based on provided names. Provided boolean flag switches between install
 * and uninstall operations. Method does not return early, it will try to process all packages, even if there are
 * errors during processing of a specific package. All encountered errors are logged and added as children to the
 * returned multi status.
 *
 * @param monitor
 *            used to track progress
 * @param packageNames
 *            names of the packages to install or uninstall
 * @param install
 *            used to switch between install and uninstall operations
 * @return multi status with children for each issue during processing
 */
private MultiStatus batchInstallUninstall(IProgressMonitor monitor, final Collection<String> packageNames,
		final boolean install) {

	final MultiStatus batchStatus = statusHelper
			.createMultiStatus("Status of " + (install ? "installing" : "uninstalling") + " npm packages.");

	final int packagesCount = packageNames.size();
	final SubMonitor subMonitor = SubMonitor.convert(monitor, packagesCount + 1);
	final File installPath = new File(locationProvider.getTargetPlatformInstallLocation());

	final AtomicInteger index = new AtomicInteger(0);
	packageNames.forEach(packageName -> {
		final String msg = (install ? "Fetching '" : "Removing '") + packageName + "' package... [package "
				+ index.incrementAndGet() + " of " + packagesCount + "]";
		logger.logInfo(msg);
		subMonitor.setTaskName(msg);
		subMonitor.worked(1);

		// switch between install and uninstall
		IStatus packageProcessingStatus = install
				? install(packageName, installPath)
				: uninstall(packageName, installPath);

		if (packageProcessingStatus.isOK()) {
			logger.logInfo(
					"Package '" + packageName + "' has been successfully " + (install ? "fetched." : "removed"));
		} else {
			logger.logError(packageProcessingStatus);
			batchStatus.merge(packageProcessingStatus);
		}
	});

	return batchStatus;
}
 
Example 51
Project: time4sys   File: NfpEditor.java   Source Code and License 5 votes vote down vote up
/**
 * <!-- begin-user-doc -->
 * <!-- end-user-doc -->
 * @generated
 */
protected void doSaveAs(URI uri, IEditorInput editorInput) {
	(editingDomain.getResourceSet().getResources().get(0)).setURI(uri);
	setInputWithNotify(editorInput);
	setPartName(editorInput.getName());
	IProgressMonitor progressMonitor =
		getActionBars().getStatusLineManager() != null ?
			getActionBars().getStatusLineManager().getProgressMonitor() :
			new NullProgressMonitor();
	doSave(progressMonitor);
}
 
Example 52
Project: vertigo-chroma-kspplugin   File: KspPluginStartup.java   Source Code and License 5 votes vote down vote up
@Override
public void earlyStartup() {

	/* Analyse les projets pour deviner la version du framework de chacun. */
	LegacyManager.getInstance().init();

	/* Liste et instancie les singletons des managers de ressources. */
	Manager[] managers = new Manager[] { KspManager.getInstance(), DaoManager.getInstance(), DtoManager.getInstance(), ServiceManager.getInstance(),
			WsRouteManager.getInstance(), JavaClassManager.getInstance() };

	/* Créé et programme un job pour démarrer chacun des managers de ressources. */
	for (Manager pluginManager : managers) {

		Job job = new Job("KspPluginInit" + pluginManager.getClass().getSimpleName()) {

			@Override
			protected IStatus run(IProgressMonitor monitor) {
				pluginManager.init();
				return Status.OK_STATUS;
			}

		};

		job.setPriority(Job.SHORT);
		job.schedule();
	}
}
 
Example 53
Project: bdf2   File: Jbpm4Designer.java   Source Code and License 5 votes vote down vote up
@Override
public void doSave(IProgressMonitor monitor) {
	monitor.beginTask("保存流程模版", IProgressMonitor.UNKNOWN);
	if(graphicalEditorPage.isDirty()){
		graphicalEditorPage.doSave(monitor);
	}
	if(this.xmlEditor.isDirty()){
		xmlEditor.doSave(monitor);
		updateGraphical();
	}
	monitor.done();
}
 
Example 54
Project: com.onpositive.prefeditor   File: ReschedulableJob.java   Source Code and License 5 votes vote down vote up
@Override
protected IStatus run(IProgressMonitor arg0) {
	synchronized (this) {
		scheduledTimestamp = 0;
		return execute();
	}
}
 
Example 55
Project: pgcodekeeper   File: PgDbParser.java   Source Code and License 5 votes vote down vote up
public void getObjFromProjFile(IFile file, IProgressMonitor monitor)
        throws InterruptedException, IOException, CoreException {
    PgDiffArguments args = new PgDiffArguments();
    args.setInCharsetName(file.getCharset());
    try (PgUIDumpLoader loader = new PgUIDumpLoader(file, args, monitor)) {
        loader.setLoadSchema(false);
        loader.setLoadReferences(true);
        PgDatabase db = loader.loadFile(new PgDatabase());
        objDefinitions.putAll(db.getObjDefinitions());
        objReferences.putAll(db.getObjReferences());
        fillFunctionBodies(loader.getFuncBodyReferences());
    }
    notifyListeners();
}
 
Example 56
Project: neoscada   File: WriteOperationWizard.java   Source Code and License 5 votes vote down vote up
private void doFinish ( final IProgressMonitor monitor, final Item item, final Variant value ) throws Exception
{
    monitor.beginTask ( "Writing value to item", 2 );

    monitor.worked ( 1 );

    try
    {

        final DataItemHolder itemHolder = new DataItemHolder ( Activator.getDefault ().getBundle ().getBundleContext (), item, null );
        if ( !itemHolder.waitForConnection ( 5 * 1000 ) )
        {
            handleError ( new RuntimeException ( "No available connection" ).fillInStackTrace () );
            return;
        }

        final NotifyFuture<WriteResult> future = itemHolder.startWrite ( value, null, new DisplayCallbackHandler ( getShell (), "Write operation", "Write operation" ) );

        try
        {
            future.get ();
        }
        catch ( final Throwable e )
        {
            handleError ( e );
        }

    }
    finally
    {
        monitor.done ();
    }
}
 
Example 57
Project: vertigo-chroma-kspplugin   File: PropertyUtils.java   Source Code and License 5 votes vote down vote up
private void setValue(IProject project, String propertyValue) {
	/*
	 * On fait l'action dans un job asynchrone pour éviter une ResourceException: The resource tree is locked for modifications
	 */

	Job job = new Job("KspPreferenceSaving") {

		@Override
		protected IStatus run(IProgressMonitor monitor) {
			IEclipsePreferences node = getProjectPluginNode(project);
			if (node == null) {
				LogUtils.info("Set " + propertyName + " : node null !");
				return Status.OK_STATUS;
			}
			if (VertigoStringUtils.isEmpty(propertyValue)) {
				node.remove(propertyName);
			} else {
				node.put(propertyName, propertyValue);
			}

			try {
				node.flush();
			} catch (BackingStoreException e) {
				ErrorUtils.handle(e);
			}
			return Status.OK_STATUS;
		}
	};

	job.setPriority(Job.SHORT);
	job.schedule();
}
 
Example 58
Project: neoscada   File: CommonPackageHandler.java   Source Code and License 5 votes vote down vote up
@Override
protected void handleProcess ( final IFolder nodeDir, final IProgressMonitor monitor, final Map<String, String> properties ) throws Exception
{
    if ( this.deploymentContext != null )
    {
        runSetup ( this.deploy, this.deploymentContext, new SubProgressMonitor ( monitor, 1 ) );

        if ( !makeEquinoxList ().isEmpty () )
        {
            final String data = StringHelper.join ( makeEquinoxList (), "\n" ) + "\n";
            this.deploymentContext.addFile ( new StaticContentProvider ( data ), "/etc/eclipsescada/applications", new FileInformation ( 0644, null, null, FileOptions.CONFIGURATION ) );
        }
    }
}
 
Example 59
Project: OCCI-Studio   File: GenerateAll.java   Source Code and License 5 votes vote down vote up
/**
 * Launches the generation.
 *
 * @param monitor
 *            This will be used to display progress information to the user.
 * @throws IOException
 *             Thrown when the output cannot be saved.
 * @generated
 */
public void doGenerate(IProgressMonitor monitor) throws IOException {
	if (!targetFolder.getLocation().toFile().exists()) {
		targetFolder.getLocation().toFile().mkdirs();
	}
	
	monitor.subTask("Loading...");
	org.eclipse.cmf.occi.core.gen.xml.main.Generate gen0 = new org.eclipse.cmf.occi.core.gen.xml.main.Generate(modelURI, targetFolder.getLocation().toFile(), arguments);
	monitor.worked(1);
	String generationID = org.eclipse.acceleo.engine.utils.AcceleoLaunchingUtil.computeUIProjectID("org.eclipse.cmf.occi.core.gen.xml", "org.eclipse.cmf.occi.core.gen.xml.main.Generate", modelURI.toString(), targetFolder.getFullPath().toString(), new ArrayList<String>());
	gen0.setGenerationID(generationID);
	gen0.doGenerate(BasicMonitor.toMonitor(monitor));
		
	
}
 
Example 60
Project: n4js   File: ManualAssociationAwareWorkingSetManager.java   Source Code and License 5 votes vote down vote up
@Override
public IStatus restoreState(final IProgressMonitor monitor) {
	final IStatus superRestoreResult = super.restoreState(monitor);

	if (superRestoreResult.isOK()) {

		final Preferences node = getPreferences();
		final String orderedFilters = node.get(ORDERED_ASSOCIATIONS_KEY, EMPTY_STRING);
		if (!Strings.isNullOrEmpty(orderedFilters)) {
			try {
				final ProjectAssociation association = mapper.readValue(orderedFilters, ProjectAssociation.class);
				projectAssociations.clear();
				projectAssociations.putAll(association);
			} catch (final IOException e) {
				final String message = "Error occurred while deserializing project associations.";
				LOGGER.error(message, e);
				return statusHelper.createError(message, e);
			}
		}

		discardWorkingSetCaches();

		return statusHelper.OK();

	}

	return superRestoreResult;
}