Java Code Examples for org.eclipse.core.runtime.jobs.Job

The following are top voted examples for showing how to use org.eclipse.core.runtime.jobs.Job. 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: gw4e.project   File: ResourceManager.java   Source Code and License 7 votes vote down vote up
/**
 * @param folder
 * @param filetorefresh
 * @return
 * @throws CoreException
 * @throws InterruptedException
 */
public static IResource resfreshFileInContainer(IContainer folder, String filetorefresh)
		throws CoreException, InterruptedException {
	final IResource buildfile = find(folder, filetorefresh);
	Job job = new WorkspaceJob("Refresh folders") {
		public IStatus runInWorkspace(IProgressMonitor monitor) throws CoreException {
			if (buildfile != null && buildfile.exists()) {
				try {
					buildfile.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor());
				} catch (CoreException e) {
					ResourceManager.logException(e);
				}
			}
			return Status.OK_STATUS;
		}
	};
	job.setUser(true);
	job.schedule();

	return buildfile;
}
 
Example 2
Project: gw4e.project   File: ResourceManager.java   Source Code and License 7 votes vote down vote up
/**
 * @param file
 */
public static void updateBuildPolicyFileFor(IFile file) {
	Job job = new WorkspaceJob("Updating Build Policies from " + file.getName()) {
		@Override
		public IStatus runInWorkspace(IProgressMonitor monitor) throws CoreException {
			ICompilationUnit compilationUnit = JavaCore.createCompilationUnitFrom(file);
			if (compilationUnit != null) {
				if (JDTManager.isGraphWalkerExecutionContextClass(compilationUnit)) {
					updateBuildPolicyFileForCompilatioUnit(compilationUnit);
				}
			}
			return Status.OK_STATUS;
		}
	};
	job.setUser(true);
	job.setRule(file.getProject());
	job.schedule();
}
 
Example 3
Project: google-cloud-eclipse   File: BuildPath.java   Source Code and License 7 votes vote down vote up
public static void runContainerResolverJob(IJavaProject javaProject) {
  IEclipseContext context = EclipseContextFactory.getServiceContext(
      FrameworkUtil.getBundle(BuildPath.class).getBundleContext());
  final IEclipseContext childContext =
      context.createChild(LibraryClasspathContainerResolverJob.class.getName());
  childContext.set(IJavaProject.class, javaProject);
  Job job =
      ContextInjectionFactory.make(LibraryClasspathContainerResolverJob.class, childContext);
  job.addJobChangeListener(new JobChangeAdapter() {
    @Override
    public void done(IJobChangeEvent event) {
      childContext.dispose();
    }
  });
  job.schedule();
}
 
Example 4
Project: n4js   File: N4JSAllContainersState.java   Source Code and License 6 votes vote down vote up
private void tryValidateManifest(final IResourceDelta delta) {
	final String fullPath = delta.getFullPath().toString();
	final URI folderUri = URI.createPlatformResourceURI(fullPath, true);
	final IN4JSProject project = core.findProject(folderUri).orNull();
	if (null != project && project.exists()) {
		final URI manifestLocation = project.getManifestLocation().orNull();
		if (null != manifestLocation) {
			final IFile manifest = delta.getResource().getProject().getFile(N4MF_MANIFEST);
			final ResourceSet resourceSet = core.createResourceSet(Optional.of(project));
			final Resource resource = resourceSet.getResource(manifestLocation, true);
			final Job job = Job.create("", monitor -> {
				validatorExtension.updateValidationMarkers(manifest, resource, ALL, monitor);
				return OK_STATUS;
			});
			job.setPriority(INTERACTIVE);
			job.schedule();
		}
	}
}
 
Example 5
Project: Equella   File: JPFProjectNature.java   Source Code and License 6 votes vote down vote up
@Override
public void configure() throws CoreException
{
	IProjectDescription description = project.getDescription();
	JPFManifestBuilder.addBuilderToProject(description);
	project.setDescription(description, null);
	JPFClasspathContainer.addToProject(JavaCore.create(project));
	new Job("Check JPF Manifest")
	{
		@Override
		protected IStatus run(IProgressMonitor monitor)
		{
			try
			{
				project.build(IncrementalProjectBuilder.FULL_BUILD, JPFManifestBuilder.BUILDER_ID, null, monitor);
			}
			catch( CoreException e )
			{
				JPFClasspathLog.logError(e);
			}
			return Status.OK_STATUS;
		}
	}.schedule();
}
 
Example 6
Project: gw4e.project   File: GraphWalkerContextManager.java   Source Code and License 6 votes vote down vote up
public static void generateOffline(final IResource resource, IPackageFragment pkg, String classfile , BuildPolicy[]  generators, int timeout, IWorkbenchWindow aww) {
	Job job = new Job("GW4E Offline Generation Source Job") {
		@Override
		public IStatus run(IProgressMonitor monitor) {
			try {
				if (resource instanceof IFile) {
					SubMonitor subMonitor = SubMonitor.convert(monitor, 120);
					IFile file = (IFile) resource;
					if (PreferenceManager.isGraphModelFile(file)) {
						AbstractPostConversion converter = getOfflineConversion(file,pkg,classfile,generators,timeout);
						ConversionRunnable runnable = converter.createConversionRunnable(aww);
						subMonitor.subTask("Processing converter ");
						SubMonitor child = subMonitor.split(1);
						runnable.run(child);
					}						
				}
			} catch (Exception e) {
				e.printStackTrace();
				ResourceManager.logException(e);
			}
			return Status.OK_STATUS;
		}
	};
	job.setUser(true);
	job.schedule();
}
 
Example 7
Project: gw4e.project   File: UITask.java   Source Code and License 6 votes vote down vote up
/**
 * @param jobname
 * @param tasks
 * @return
 */
public static Job createJob(String jobname, List<UITask.Task> tasks) {
	Job job = new Job(jobname) {
		@Override
		protected IStatus run(IProgressMonitor monitor) {
			SubMonitor subMonitor = SubMonitor.convert(monitor, tasks.size());
			for (UITask.Task task : tasks) {
				try {
					subMonitor.setTaskName(task.getSummary());
					workOnTask(task, subMonitor.split(1));
				} catch (Exception e) {
					return Status.CANCEL_STATUS;
				}
			}
			return Status.OK_STATUS;
		}
	};
	job.setUser(true);
	return job;
}
 
Example 8
Project: gw4e.project   File: TestConvertor.java   Source Code and License 6 votes vote down vote up
public void apply() throws CoreException {
	Job job = new WorkspaceJob("GW4E Conversion Job") {
		@Override
		public IStatus runInWorkspace(IProgressMonitor monitor) throws CoreException {
			try {
				_apply(monitor);
			} catch (Exception e) {
				DialogManager.displayErrorMessage(MessageUtil.getString("project_conversion"), MessageUtil.getString("an_error_has_occured_while_configuring_the_project"), e);
				ResourceManager.logException(e);
			}
			return Status.OK_STATUS;
		}
	};
	job.setRule(testInterface.getJavaProject().getProject());
	job.setUser(true);
	job.schedule();
}
 
Example 9
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 10
Project: Hydrograph   File: DataViewerListeners.java   Source Code and License 6 votes vote down vote up
private void executeJumpPageJob(String statusMessage, final Long pageNumberToJump) {
	Job job = new Job(statusMessage) {
		@Override
		protected IStatus run(IProgressMonitor monitor) {

			final StatusMessage status = dataViewerAdapter.jumpToPage(pageNumberToJump);
			dataViewLoader.updateDataViewLists();

			Display.getDefault().asyncExec(new Runnable() {
				@Override
				public void run() {
					refreshDataViewerWindow(status);
					DataViewerUtility.INSTANCE.resetSort(debugDataViewer);
					debugDataViewer.redrawTableCursor();
				}
			});
			return Status.OK_STATUS;
		}

	};
	job.schedule();
}
 
Example 11
Project: google-cloud-eclipse   File: ConversionTests.java   Source Code and License 6 votes vote down vote up
@Test
public void appEngineWebWithNoRuntime_Java7_Web25()
    throws CoreException, IOException, InterruptedException, SAXException {
  IFacetedProject project = projectCreator
      .withFacetVersions(JavaFacet.VERSION_1_7, WebFacetUtils.WEB_25).getFacetedProject();
  createAppEngineWebWithNoRuntime(project);

  Job conversionJob = new AppEngineStandardProjectConvertJob(project);
  conversionJob.schedule();
  conversionJob.join();
  assertIsOk("conversion should never fail", conversionJob.getResult());

  assertFacetVersions(project, JavaFacet.VERSION_1_7, WebFacetUtils.WEB_25,
      AppEngineStandardFacet.JRE7);
  assertNoJava8Runtime(project);
}
 
Example 12
Project: google-cloud-eclipse   File: ConversionTests.java   Source Code and License 6 votes vote down vote up
@Test
public void appEngineWebWithNoRuntime_Java8_Web25()
    throws CoreException, IOException, InterruptedException, SAXException {
  IFacetedProject project = projectCreator
      .withFacetVersions(JavaFacet.VERSION_1_8, WebFacetUtils.WEB_25).getFacetedProject();
  createAppEngineWebWithNoRuntime(project);

  Job conversionJob = new AppEngineStandardProjectConvertJob(project);
  conversionJob.schedule();
  conversionJob.join();
  assertIsOk("conversion should never fail", conversionJob.getResult());

  assertFacetVersions(project, JavaFacet.VERSION_1_7, WebFacetUtils.WEB_25,
      AppEngineStandardFacet.JRE7);
  assertNoJava8Runtime(project);
}
 
Example 13
Project: eclipse.jdt.ls   File: MavenBuildSupportTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testIgnoreInnerPomChanges() throws Exception {
	IProject project = importMavenProject("archetyped");
	assertEquals("The inner pom should not have been imported", 2, WorkspaceHelper.getAllProjects().size());

	IFile innerPom = project.getFile("src/main/resources/archetype-resources/pom.xml");

	preferences.setUpdateBuildConfigurationStatus(FeatureStatus.automatic);
	boolean[] updateTriggered = new boolean[1];
	IJobChangeListener listener = new JobChangeAdapter() {
		@Override
		public void scheduled(IJobChangeEvent event) {
			if (event.getJob().getName().contains("Update project")) {
				updateTriggered[0] = true;
			}
		}
	};
	try {
		Job.getJobManager().addJobChangeListener(listener);
		projectsManager.fileChanged(innerPom.getRawLocationURI().toString(), CHANGE_TYPE.CHANGED);
		waitForBackgroundJobs();
		assertFalse("Update project should not have been triggered", updateTriggered[0]);
	} finally {
		Job.getJobManager().removeJobChangeListener(listener);
	}
}
 
Example 14
Project: termsuite-ui   File: JobInfo.java   Source Code and License 6 votes vote down vote up
@Override
public Image getDisplayImage() {
       int done = getPercentDone();
       if (done > 0) {
           return super.getDisplayImage();
       }
       if (isBlocked()) {
		return JFaceResources.getImage(ProgressManager.BLOCKED_JOB_KEY);
	}
       int state = getJob().getState();
       if (state == Job.SLEEPING) {
		return JFaceResources.getImage(ProgressManager.SLEEPING_JOB_KEY);
	}
       if (state == Job.WAITING) {
		return JFaceResources.getImage(ProgressManager.WAITING_JOB_KEY);
	}
       //By default return the first progress image
       return super.getDisplayImage();

   }
 
Example 15
Project: termsuite-ui   File: JobInfo.java   Source Code and License 6 votes vote down vote up
/**
   * Get the display string based on the current status and the name of the
   * job.
   * @param showProgress a boolean to indicate if we should
   * show progress or not.
   *
   * @return String
   */
  private String getDisplayStringWithStatus(boolean showProgress) {
      if (isCanceled()) {
	return NLS.bind(ProgressMessages.JobInfo_Cancelled, (new Object[] { getJob().getName() }));
}
      if (isBlocked()) {
	return NLS.bind(ProgressMessages.JobInfo_Blocked, (new Object[] { getJob().getName(),
	blockedStatus.getMessage() }));
}
      if (getJob().getState() == Job.RUNNING) {
      	TaskInfo info = getTaskInfo();
          if (info == null) {
		return getJob().getName();
	}
          return info.getDisplayString(showProgress);
      }
      if (getJob().getState() == Job.SLEEPING) {
	return NLS.bind(ProgressMessages.JobInfo_Sleeping, (new Object[] { getJob().getName() }));
}

      return NLS.bind(ProgressMessages.JobInfo_Waiting, (new Object[] { getJob().getName() }));

  }
 
Example 16
Project: team-explorer-everywhere   File: TFSRepository.java   Source Code and License 6 votes vote down vote up
/**
 * Refreshes the local data for this TFS Repository. This will NOT contact
 * the server.
 *
 * @param async
 *        <code>true</code> to refresh asynchronously, <code>false</code>
 *        otherwise
 */
public void refreshLocal(final boolean async) {
    if (!async) {
        refreshLocal(new NullProgressMonitor());
    } else {
        final String messageFormat = Messages.getString("TFSRepository.ProgressTextFormat"); //$NON-NLS-1$
        final String message = MessageFormat.format(messageFormat, workspace.getServerName());
        final Job refreshJob = new Job(message) {
            @Override
            protected IStatus run(final IProgressMonitor monitor) {
                refreshLocal(monitor);
                return Status.OK_STATUS;
            }
        };
        refreshJob.schedule();
    }
}
 
Example 17
Project: google-cloud-eclipse   File: GpeConversionTest.java   Source Code and License 6 votes vote down vote up
private void convertGpeProject(URL zipFile)
    throws CoreException, IOException, InterruptedException {
  List<IProject> projects =
      ProjectUtils.importProjects(zipFile,
      false /* checkBuildErrors */, null);
  assertEquals(1, projects.size());
  project = projects.get(0);
  IFacetedProject facetedProject = ProjectFacetsManager.create(project,
      true /* convert to faceted project if necessary */, null /* no monitor here */);

  Job conversionJob = new AppEngineStandardProjectConvertJob(facetedProject);
  conversionJob.schedule();
  conversionJob.join();
  assertTrue("conversion should not have failed", conversionJob.getResult().isOK());

  // ensure facet versions haven't been downgraded
  assertEquals(JavaFacet.VERSION_1_7, facetedProject.getProjectFacetVersion(JavaFacet.FACET));
  assertEquals(WebFacetUtils.WEB_25,
      facetedProject.getProjectFacetVersion(WebFacetUtils.WEB_FACET));
  assertEquals(AppEngineStandardFacet.JRE7,
      facetedProject.getProjectFacetVersion(AppEngineStandardFacet.FACET));
}
 
Example 18
Project: eclipse.jdt.ls   File: JDTLanguageServer.java   Source Code and License 6 votes vote down vote up
@Override
public CompletableFuture<List<? extends Location>> definition(TextDocumentPositionParams position) {
	logInfo(">> document/definition");
	NavigateToDefinitionHandler handler = new NavigateToDefinitionHandler(this.preferenceManager);
	return computeAsync((cc) -> {
		IProgressMonitor monitor = toMonitor(cc);
		try {
			Job.getJobManager().join(DocumentLifeCycleHandler.DOCUMENT_LIFE_CYCLE_JOBS, monitor);
		} catch (OperationCanceledException ignorable) {
			// No need to pollute logs when query is cancelled
		} catch (InterruptedException e) {
			JavaLanguageServerPlugin.logException(e.getMessage(), e);
		}
		return handler.definition(position, toMonitor(cc));
	});
}
 
Example 19
Project: google-cloud-eclipse   File: ConvertJobSuspender.java   Source Code and License 6 votes vote down vote up
static void suspendJob(Job job, long scheduleDelay) {
  if (!isConvertJob.apply(job)) {
    return;
  }
  synchronized (suspendedJobs) {
    if (!suspended.get()) {
      return;
    }
  }
  // cancel() must be done outside of our synchronization barrier as may trigger events
  // (and even scheduling other jobs)
  if (job.cancel()) {
    // Cancel should always succeed since the job is not running yet
    synchronized (suspendedJobs) {
      // check in case the situation has changed during the cancellation
      if (suspended.get()) {
        suspendedJobs.add(new SuspendedJob(job, scheduleDelay));
      } else {
        // we've since been resumed, so reschedule this job right away
        job.schedule(scheduleDelay);
      }
    }
  } else {
    logger.log(Level.SEVERE, "job already running: " + job);
  }
}
 
Example 20
Project: hybris-commerce-eclipse-plugin   File: YPlatformCleanAndBuildHandler.java   Source Code and License 6 votes vote down vote up
@Override
public Object execute(ExecutionEvent event) {

	Job job = new Job("[y] Clean and Build") {
		@Override
		protected IStatus run(IProgressMonitor monitor) {
			IProject platform = ResourcesPlugin.getWorkspace().getRoot().getProject(PLATFORM_NAME);
			try {
				BuildUtils.refreshAndBuild(monitor, CFG_NAME, platform);
				monitor.done();
				return Status.OK_STATUS;
			} catch (Exception e) {
				Activator.logError("Failed to synchronize with the platform, see workspace logs for more details", e);
				throw new IllegalStateException("Failed to synchronize with the platform", e);
			}

		}
	};
	job.setUser(true);
	job.schedule();
	return null;
}
 
Example 21
Project: google-cloud-eclipse   File: ConversionTests.java   Source Code and License 6 votes vote down vote up
@Test
public void appEngineWebWithJava8Runtime_Java8()
    throws CoreException, IOException, InterruptedException, SAXException {
  IFacetedProject project =
      projectCreator.withFacetVersions(JavaFacet.VERSION_1_8).getFacetedProject();
  createAppEngineWebWithJava8Runtime(project);

  Job conversionJob = new AppEngineStandardProjectConvertJob(project);
  conversionJob.schedule();
  conversionJob.join();
  assertIsOk("conversion should never fail", conversionJob.getResult());

  assertFacetVersions(project, JavaFacet.VERSION_1_8, WebFacetUtils.WEB_31,
      AppEngineStandardFacetChangeListener.APP_ENGINE_STANDARD_JRE8);
  assertJava8Runtime(project);
}
 
Example 22
Project: eclipse.jdt.ls   File: JDTLanguageServer.java   Source Code and License 6 votes vote down vote up
@Override
public CompletableFuture<List<? extends CodeLens>> codeLens(CodeLensParams params) {
	logInfo(">> document/codeLens");
	CodeLensHandler handler = new CodeLensHandler(preferenceManager);
	return computeAsync((cc) -> {
		IProgressMonitor monitor = toMonitor(cc);
		try {
			Job.getJobManager().join(DocumentLifeCycleHandler.DOCUMENT_LIFE_CYCLE_JOBS, monitor);
		} catch (OperationCanceledException ignorable) {
			// No need to pollute logs when query is cancelled
		} catch (InterruptedException e) {
			JavaLanguageServerPlugin.logException(e.getMessage(), e);
		}
		return handler.getCodeLensSymbols(params.getTextDocument().getUri(), monitor);
	});
}
 
Example 23
Project: turnus   File: InternalVariablePipeliningAnalysisWizard.java   Source Code and License 6 votes vote down vote up
@Override
public boolean performFinish() {

	final Configuration configuration = new Configuration();
	configuration.setValue(TRACE_FILE, optionsPage.getTraceFile());

	final Job job = new Job("Pipeling analysis with variable utilisation") {

		@Override
		protected IStatus run(IProgressMonitor monitor) {
			try {
				new InternalVariablePipeliningAnalysisCli().start(configuration, monitor);
				EclipseUtils.refreshWorkspace(monitor);
			} catch (TurnusException e) {
				Logger.error(e.getMessage());
			}
			return Status.OK_STATUS;
		}

	};

	job.setUser(true);
	job.schedule();

	return true;
}
 
Example 24
Project: termsuite-ui   File: ProgressManager.java   Source Code and License 6 votes vote down vote up
/**
 * Return the listeners for the job.
 *
 * @param job
 * @return Collection of IJobBusyListener
 */
@SuppressWarnings("unchecked")
   private Collection<IJobBusyListener> busyListenersForJob(Job job) {
	if (job.isSystem()) {
		return Collections.EMPTY_LIST;
	}
	synchronized (familyListeners) {

		if (familyListeners.isEmpty()) {
			return Collections.EMPTY_LIST;
		}

		Iterator<Object> families = familyListeners.keySet().iterator();
		Collection<IJobBusyListener> returnValue = new HashSet<>();
		while (families.hasNext()) {
			Object next = families.next();
			if (job.belongsTo(next)) {
				Collection<IJobBusyListener> currentListeners = familyListeners
						.get(next);
				returnValue.addAll(currentListeners);
			}
		}
		return returnValue;
	}
}
 
Example 25
Project: google-cloud-eclipse   File: FacetUtil.java   Source Code and License 6 votes vote down vote up
/**
 * Modifies the set of project facets in the configured project by performing the series of
 * configured facets actions.
 *
 * @param monitor a progress monitor, or null if progress reporting and cancellation are not desired
 * @throws CoreException if anything goes wrong while applying facet actions
 */
public void install(IProgressMonitor monitor) throws CoreException {
  SubMonitor subMonitor = SubMonitor.convert(monitor, 100);

  // Workaround deadlock bug described in Eclipse bug (https://bugs.eclipse.org/511793).
  // There are graph update jobs triggered by the completion of the CreateProjectOperation
  // above (from resource notifications) and from other resource changes from modifying the
  // project facets. So we force the dependency graph to defer updates
  try {
    IDependencyGraph.INSTANCE.preUpdate();
    try {
      Job.getJobManager().join(DependencyGraphImpl.GRAPH_UPDATE_JOB_FAMILY,
          subMonitor.newChild(10));
    } catch (OperationCanceledException | InterruptedException ex) {
      logger.log(Level.WARNING, "Exception waiting for WTP Graph Update job", ex);
    }

    facetedProject.modify(facetInstallSet, subMonitor.newChild(90));
  } finally {
    IDependencyGraph.INSTANCE.postUpdate();
  }
}
 
Example 26
Project: google-cloud-eclipse   File: ConversionTests.java   Source Code and License 6 votes vote down vote up
@Test
public void appEngineWebWithJava8Runtime_Java7_Web31()
    throws CoreException, IOException, InterruptedException, SAXException {
  IFacetedProject project = projectCreator
      .withFacetVersions(JavaFacet.VERSION_1_7, WebFacetUtils.WEB_31).getFacetedProject();
  createAppEngineWebWithJava8Runtime(project);

  Job conversionJob = new AppEngineStandardProjectConvertJob(project);
  conversionJob.schedule();
  conversionJob.join();
  assertIsOk("conversion should never fail", conversionJob.getResult());

  assertFacetVersions(project, JavaFacet.VERSION_1_8, WebFacetUtils.WEB_31,
      AppEngineStandardFacetChangeListener.APP_ENGINE_STANDARD_JRE8);
  assertJava8Runtime(project);
}
 
Example 27
Project: termsuite-ui   File: GroupInfo.java   Source Code and License 6 votes vote down vote up
/**
 * Update the receiver in the progress manager. If all of the jobs are
 * finished and the receiver is not being kept then remove it.
 */
private void updateInProgressManager() {
	Iterator<JobInfo> infoIterator = infos.iterator();
	while (infoIterator.hasNext()) {
		JobInfo next = infoIterator.next();
		if (!(next.getJob().getState() == Job.NONE)) {
			progressManager.refreshGroup(this);
			return;
		}
	}

	if (finishedJobs.isKept(this))
		progressManager.refreshGroup(this);
	else
		progressManager.removeGroup(this);
}
 
Example 28
Project: google-cloud-eclipse   File: CloudToolsEclipseProjectNotifier.java   Source Code and License 6 votes vote down vote up
@Override
public void earlyStartup() {
  workbench = PlatformUI.getWorkbench();
  workspace = ResourcesPlugin.getWorkspace();

  Job projectUpdater = new WorkspaceJob(Messages.getString("updating.projects.jobname")) { //$NON-NLS-1$
    @Override
    public IStatus runInWorkspace(IProgressMonitor monitor) throws CoreException {
      SubMonitor progress = SubMonitor.convert(monitor, 40);
      progress.subTask(Messages.getString("searching.for.projects")); //$NON-NLS-1$
      Collection<IProject> projects = findCandidates(progress.newChild(10));
      if (projects.isEmpty()) {
        return Status.OK_STATUS;
      }
      projects = promptUser(projects, progress.newChild(5));
      if (projects.isEmpty()) {
        return Status.OK_STATUS;
      }
      progress.subTask(Messages.getString("updating.projects")); //$NON-NLS-1$
      return upgradeProjects(projects, progress.newChild(25));
    }
  };
  projectUpdater.setRule(workspace.getRoot());
  projectUpdater.setUser(true);
  projectUpdater.schedule(500);
}
 
Example 29
Project: turnus   File: AlgorithmicPartialCriticalPathAnalysWizard.java   Source Code and License 6 votes vote down vote up
@Override
public boolean performFinish() {
	final Configuration configuration = new Configuration();
	configuration.setValue(TRACE_FILE, optionsPage.getTraceFile());
	configuration.setValue(ACTION_WEIGHTS, optionsPage.getWeightsFile());

	final Job job = new Job("Algorithmic bottleneck analysis") {

		@Override
		protected IStatus run(IProgressMonitor monitor) {
			try {
				new AlgorithmicPartialCriticalPathAnalysisCli().start(configuration, monitor);
				EclipseUtils.refreshWorkspace(monitor);
			} catch (Exception e) {
				Logger.error(e.getMessage());
			}
			return Status.OK_STATUS;
		}
	};

	job.setUser(true);
	job.schedule();

	return true;
}
 
Example 30
Project: eclemma   File: DumpExecutionDataHandler.java   Source Code and License 6 votes vote down vote up
public static void requestDump(final ICoverageLaunch launch) {
  new Job(UIMessages.DumpExecutionData_task) {
    @Override
    protected IStatus run(IProgressMonitor monitor) {
      try {
        final boolean reset = EclEmmaUIPlugin.getInstance()
            .getPreferenceStore()
            .getBoolean(UIPreferences.PREF_RESET_ON_DUMP);
        launch.requestDump(reset);
      } catch (CoreException e) {
        return EclEmmaStatus.DUMP_REQUEST_ERROR.getStatus(e);
      }
      return Status.OK_STATUS;
    }
  }.schedule();
}
 
Example 31
Project: EarthquakeBulletin   File: ShowMapListener.java   Source Code and License 6 votes vote down vote up
@Override
public void handleEvent(final Event event) {
	final TableViewer tableViewer = gui.getResultsTable().getTableViewer();
	if (tableViewer != null && !tableViewer.getTable().isDisposed() && tableViewer.getStructuredSelection() != null) {
		final Earthquake selectedItem = (Earthquake) tableViewer.getStructuredSelection().getFirstElement();
		if (selectedItem != null) {
			final String guid = selectedItem.getGuid();
			final MapCanvas mapCanvas = gui.getMapCanvas();
			final MapCache cache = mapCanvas.getCache();
			if (mapCanvas.getDownloadMapJob() == null || mapCanvas.getDownloadMapJob().getState() == Job.NONE) {
				if (cache.contains(guid) && cache.get(guid).getEtag() != null) {
					mapCanvas.setDownloadMapJob(new DownloadMapJob(gui, selectedItem, cache.get(guid).getEtag()));
				}
				else {
					mapCanvas.setDownloadMapJob(new DownloadMapJob(gui, selectedItem));
				}
			}
			mapCanvas.getDownloadMapJob().schedule();
		}
	}
}
 
Example 32
Project: DarwinSPL   File: HymappingBackgroundParsingStrategy.java   Source Code and License 6 votes vote down vote up
/**
 * Schedules a task for background parsing that will be started after a delay.
 */
public void parse(final String contents, final eu.hyvar.feature.mapping.resource.hymapping.IHymappingTextResource resource, final eu.hyvar.feature.mapping.resource.hymapping.ui.HymappingEditor editor, long delay) {
	if (resource == null) {
		return;
	}
	if (contents == null) {
		return;
	}
	
	// this synchronization is needed to avoid the creation of multiple tasks. without
	// the synchronization this could easily happen, when this method is accessed by
	// multiple threads. the creation of multiple tasks would imply that multiple
	// background parsing threads for one editor are created, which is not desired.
	synchronized (lock) {
		if (job == null || job.getState() != Job.RUNNING) {
			// schedule new task
			job = new ParsingJob();
			job.resource = resource;
			job.editor = editor;
			job.newContents = contents;
			job.schedule();
		} else {
			job.newContents = contents;
		}
	}
}
 
Example 33
Project: eclipse.jdt.ls   File: DocumentLifeCycleHandlerTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testDidOpenNotOnClasspath() throws Exception {
	importProjects("eclipse/hello");
	IProject project = WorkspaceHelper.getProject("hello");
	URI uri = project.getFile("nopackage/Test2.java").getRawLocationURI();
	ICompilationUnit cu = JDTUtils.resolveCompilationUnit(uri);
	String source = FileUtils.readFileToString(FileUtils.toFile(uri.toURL()));
	openDocument(cu, source, 1);
	Job.getJobManager().join(DocumentLifeCycleHandler.DOCUMENT_LIFE_CYCLE_JOBS, monitor);
	assertEquals(project, cu.getJavaProject().getProject());
	assertEquals(source, cu.getSource());
	List<PublishDiagnosticsParams> diagnosticReports = getClientRequests("publishDiagnostics");
	assertEquals(1, diagnosticReports.size());
	PublishDiagnosticsParams diagParam = diagnosticReports.get(0);
	assertEquals(1, diagParam.getDiagnostics().size());
	closeDocument(cu);
	Job.getJobManager().join(DocumentLifeCycleHandler.DOCUMENT_LIFE_CYCLE_JOBS, monitor);
	diagnosticReports = getClientRequests("publishDiagnostics");
	assertEquals(2, diagnosticReports.size());
	diagParam = diagnosticReports.get(1);
	assertEquals(0, diagParam.getDiagnostics().size());
}
 
Example 34
Project: google-cloud-eclipse   File: ConversionTests.java   Source Code and License 6 votes vote down vote up
@Test
public void appEngineWebWithNoRuntime_Java7_Web31()
    throws CoreException, IOException, InterruptedException, SAXException {
  IFacetedProject project = projectCreator
      .withFacetVersions(JavaFacet.VERSION_1_7, WebFacetUtils.WEB_31).getFacetedProject();
  createAppEngineWebWithNoRuntime(project);

  Job conversionJob = new AppEngineStandardProjectConvertJob(project);
  conversionJob.schedule();
  conversionJob.join();
  assertIsOk("conversion should never fail", conversionJob.getResult());

  assertFacetVersions(project, JavaFacet.VERSION_1_7, WebFacetUtils.WEB_25,
      AppEngineStandardFacet.JRE7);
  assertNoJava8Runtime(project);
}
 
Example 35
Project: google-cloud-eclipse   File: ConversionTests.java   Source Code and License 6 votes vote down vote up
@Test
public void appEngineWebWithNoRuntime_Java8_Web31()
    throws CoreException, IOException, InterruptedException, SAXException {
  IFacetedProject project = projectCreator
      .withFacetVersions(JavaFacet.VERSION_1_8, WebFacetUtils.WEB_31).getFacetedProject();
  createAppEngineWebWithNoRuntime(project);

  Job conversionJob = new AppEngineStandardProjectConvertJob(project);
  conversionJob.schedule();
  conversionJob.join();
  assertIsOk("conversion should never fail", conversionJob.getResult());

  assertFacetVersions(project, JavaFacet.VERSION_1_7, WebFacetUtils.WEB_25,
      AppEngineStandardFacet.JRE7);
  assertNoJava8Runtime(project);
}
 
Example 36
Project: eclipse.jdt.ls   File: JDTLanguageServer.java   Source Code and License 6 votes vote down vote up
@Override
public CompletableFuture<CodeLens> resolveCodeLens(CodeLens unresolved) {
	logInfo(">> codeLens/resolve");
	CodeLensHandler handler = new CodeLensHandler(preferenceManager);
	return computeAsync((cc) -> {
		IProgressMonitor monitor = toMonitor(cc);
		try {
			Job.getJobManager().join(DocumentLifeCycleHandler.DOCUMENT_LIFE_CYCLE_JOBS, monitor);
		} catch (OperationCanceledException ignorable) {
			// No need to pollute logs when query is cancelled
		} catch (InterruptedException e) {
			JavaLanguageServerPlugin.logException(e.getMessage(), e);
		}
		return handler.resolve(unresolved, monitor);
	});
}
 
Example 37
Project: team-explorer-everywhere   File: SynchronizeSubscriber.java   Source Code and License 6 votes vote down vote up
private final void refreshBackground(final IResource[] resources) {
    new Job(Messages.getString("SynchronizeSubscriber.ExaminingSynchronizationState")) //$NON-NLS-1$
    {
        @Override
        protected IStatus run(final IProgressMonitor monitor) {
            try {
                refresh(resources, IResource.DEPTH_INFINITE, monitor);

                return Status.OK_STATUS;
            } catch (final CoreException e) {
                log.warn(Messages.getString("SynchronizeSubscriber.CouldNotRefreshSynchronizationState"), e); //$NON-NLS-1$

                return new Status(
                    IStatus.ERROR,
                    TFSEclipseClientPlugin.PLUGIN_ID,
                    0,
                    e.getLocalizedMessage(),
                    null);
            }
        }
    }.schedule();
}
 
Example 38
Project: team-explorer-everywhere   File: RefreshRepositoryPendingChangesAction.java   Source Code and License 6 votes vote down vote up
@Override
public void run() {
    final TFSRepository repository = this.repository;

    final String messageFormat =
        Messages.getString("RefreshRepositoryPendingChangesAction.RefreshingPendingChangesJobFormat"); //$NON-NLS-1$
    final String message = MessageFormat.format(messageFormat, this.repository.getWorkspace().getName());

    final Job refreshJob = new Job(message) {
        @Override
        protected IStatus run(final IProgressMonitor monitor) {
            repository.getPendingChangeCache().refresh();

            CodeMarkerDispatch.dispatch(CODEMARKER_PENDING_CHANGES_VIEW_REFRESHED);
            return Status.OK_STATUS;
        }
    };

    refreshJob.schedule();
}
 
Example 39
Project: google-cloud-eclipse   File: CreateAppEngineWtpProject.java   Source Code and License 6 votes vote down vote up
private static void enableMavenNature(IProject newProject, IProgressMonitor monitor)
    throws CoreException {
  SubMonitor subMonitor = SubMonitor.convert(monitor, 30);

  // Workaround deadlock bug described in Eclipse bug (https://bugs.eclipse.org/511793).
  try {
    IDependencyGraph.INSTANCE.preUpdate();
    try {
      Job.getJobManager().join(DependencyGraphImpl.GRAPH_UPDATE_JOB_FAMILY,
          subMonitor.newChild(8));
    } catch (OperationCanceledException | InterruptedException ex) {
      logger.log(Level.WARNING, "Exception waiting for WTP Graph Update job", ex);
    }

    ResolverConfiguration resolverConfiguration = new ResolverConfiguration();
    MavenPlugin.getProjectConfigurationManager().enableMavenNature(newProject,
        resolverConfiguration, subMonitor.newChild(20));
  } finally {
    IDependencyGraph.INSTANCE.postUpdate();
  }

  // M2E will cleverly set "target/<artifact ID>-<version>/WEB-INF/classes" as a new Java output
  // folder; delete the default old folder.
  newProject.getFolder("build").delete(true /* force */, subMonitor.newChild(2));
}
 
Example 40
Project: team-explorer-everywhere   File: QueueEditorPage.java   Source Code and License 6 votes vote down vote up
public void updateResults() {
    if (selectedBuildDefinition == null) {
        return;
    }

    String message;
    if (selectedBuildDefinition.getName() != null && !selectedBuildDefinition.getName().equals("*")) //$NON-NLS-1$
    {
        final String messageFormat = Messages.getString("QueueEditorPage.QuerySpecificBuildQueueTextFormat"); //$NON-NLS-1$
        message = MessageFormat.format(messageFormat, selectedBuildDefinition.getName());
    } else {
        message = Messages.getString("QueueEditorPage.QueryAllBuildQueueText"); //$NON-NLS-1$
    }

    final Job populateJob = new Job(message) {
        @Override
        protected IStatus run(final IProgressMonitor monitor) {
            query(selectedBuildDefinition, selectedQueueStatus, selectedBuildController, selectedUser, false);
            CodeMarkerDispatch.dispatch(QueueEditorPage.CODEMARKER_TABLE_UPDATED);
            return Status.OK_STATUS;
        }
    };
    populateJob.setUser(false);
    populateJob.setPriority(Job.SHORT);
    populateJob.schedule();
}
 
Example 41
Project: dsl-devkit   File: ErrorLogListenerTest.java   Source Code and License 6 votes vote down vote up
/**
 * Test that {@link NullPointerException}'s are ignored.
 *
 * @throws InterruptedException
 *           the exception that is thrown if the test job was interrupted
 */
@Test
public void testIgnoringExceptionLocations() throws InterruptedException {
  assertFalse("NullPointerException must not have been logged.", errorLogListener.isExceptionLogged(NullPointerException.class));
  errorLogListener.ignoreException(NullPointerException.class, "com.avaloq.tools.ddk.test.core.util.ErrorLogListenerTest");

  final Job job = new Job("testIgnoringExceptionLocations") {

    @Override
    @SuppressWarnings("PMD.AvoidThrowingNullPointerException")
    protected IStatus run(final IProgressMonitor monitor) {
      // We really want to thrown a null pointer exception here because we test that such exceptions are ignored.
      throw new NullPointerException();
    }
  };
  job.schedule();
  job.join();

  assertTrue("NullPointerException must have been logged.", errorLogListener.isExceptionLogged(NullPointerException.class));
  assertFalse("NullPointerException must have been ignored.", errorLogListener.getLoggedExceptions().contains(NullPointerException.class));
}
 
Example 42
Project: hybris-commerce-eclipse-plugin   File: EclipseRefreshAndBuildHandler.java   Source Code and License 6 votes vote down vote up
@Override
public Object execute(ExecutionEvent event) {
   
    Job job = new Job("[y] Platform Refresh and Build"){
        @Override
        protected IStatus run(IProgressMonitor monitor){
            
        	try
        	{
        		refreshAndFullBuild(monitor);
        		monitor.done();
	            return Status.OK_STATUS;
        	}
        	catch (Exception e)
        	{
        		throw new IllegalStateException("Failed to synchronize with the platform, see workspace logs for details", e);
        	}
        	
        }
    };
    job.setUser(true);
    job.schedule();
    return null;
}
 
Example 43
Project: google-cloud-eclipse   File: AppEngineStandardProjectConvertJobTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testAppEngineFacetAdded() throws CoreException, InterruptedException {
  IProject project = projectCreator.getProject();
  IFacetedProject facetedProject = ProjectFacetsManager.create(project);
  Job convertJob = new AppEngineStandardProjectConvertJob(facetedProject);
  convertJob.schedule();
  convertJob.join();
  assertTrue(AppEngineStandardFacet.hasFacet(facetedProject));

  // verify App Engine standard files are present
  IFile webXml = WebProjectUtil.findInWebInf(project, new Path("web.xml"));
  assertTrue(webXml.exists());
  assertTrue(WebProjectUtil.findInWebInf(project, new Path("appengine-web.xml")).exists());

  // verify no overlap in WEB-INF and source paths
  // Java 1.7 facet sets the source path to src/ which will overlap with the
  // default src/main/webapp used in the AppEngineStandardFacet installer
  IFolder webInfFolder = (IFolder) webXml.getParent();
  assertEquals("WEB-INF", webInfFolder.getName());
  IPath webInfPath = webInfFolder.getProjectRelativePath();
  List<IPath> sourcePaths = WebProjectUtil.getJavaSourcePaths(project);
  for (IPath sourcePath : sourcePaths) {
    assertFalse(sourcePath.isPrefixOf(webInfPath));
  }
}
 
Example 44
Project: n4js   File: AbstractBuilderTest.java   Source Code and License 5 votes vote down vote up
/**
 * Performs some general validity checks on the Xtext index. Only intended to be used in tests (e.g. no support for
 * cancellation).
 */
protected void assertXtextIndexIsValid() {
	// ensure no build is running while we examine the Xtext index
	final ISchedulingRule rule = externalLibraryBuilderHelper.getRule();
	try {
		Job.getJobManager().beginRule(rule, null);
		assertXtextIndexIsValidInternal();
	} finally {
		Job.getJobManager().endRule(rule);
	}
}
 
Example 45
Project: n4js   File: AbstractPluginUITest.java   Source Code and License 5 votes vote down vote up
/**
 * Wait until all background tasks are complete then makes sure that the UI thread is idle as well.
 */
protected void waitForIdleState() {
	final IJobManager manager = Job.getJobManager();
	while (manager.currentJob() != null) {
		waitForUiThread();
	}
	waitForUiThread();
}
 
Example 46
Project: n4js   File: EclipseExternalLibraryWorkspace.java   Source Code and License 5 votes vote down vote up
@Override
public void storeUpdated(final ExternalLibraryPreferenceStore store, final IProgressMonitor monitor) {
	final ISchedulingRule rule = builderHelper.getRule();
	try {
		Job.getJobManager().beginRule(rule, monitor);
		storeUpdatedInternal(store, monitor);
	} finally {
		Job.getJobManager().endRule(rule);
	}
}
 
Example 47
Project: n4js   File: EclipseExternalLibraryWorkspace.java   Source Code and License 5 votes vote down vote up
@Override
public void registerProjects(NpmProjectAdaptionResult result, IProgressMonitor monitor, boolean triggerCleanbuild) {
	final ISchedulingRule rule = builderHelper.getRule();
	try {
		Job.getJobManager().beginRule(rule, monitor);
		registerProjectsInternal(result, monitor, triggerCleanbuild);
	} finally {
		Job.getJobManager().endRule(rule);
	}
}
 
Example 48
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 49
Project: n4js   File: N4JSBuilderPreferencePage.java   Source Code and License 5 votes vote down vote up
/**
 * This method has been copied from org.eclipse.xtext.builder.preferences.BuilderConfigurationBlock.
 *
 * @param projectToBuild
 *            the project to build
 * @return the configured build job
 */
protected Job getBuildJob(IProject projectToBuild) {
	Job buildJob = new OptionsConfigurationBlock.BuildJob(Messages.BuilderConfigurationBlock_BuildJob_Title0,
			projectToBuild);
	buildJob.setRule(ResourcesPlugin.getWorkspace().getRuleFactory().buildRule());
	buildJob.setUser(true);
	return buildJob;
}
 
Example 50
Project: n4js   File: NpmManager.java   Source Code and License 5 votes vote down vote up
private static <T> T runWithWorkspaceLock(Supplier<T> operation) {
	if (Platform.isRunning()) {
		final ISchedulingRule rule = ResourcesPlugin.getWorkspace().getRoot();
		try {
			Job.getJobManager().beginRule(rule, null);
			return operation.get();
		} finally {
			Job.getJobManager().endRule(rule);
		}
	} else {
		// locking not available/required in headless case
		return operation.get();
	}
}
 
Example 51
Project: neoscada   File: FactoryEditor.java   Source Code and License 5 votes vote down vote up
private void insertEntry ( final String value )
{
    final Job job = this.factoryInput.createCreateJob ( value );
    job.addJobChangeListener ( new JobChangeAdapter () {
        @Override
        public void done ( final IJobChangeEvent event )
        {
            refresh ();
        }
    } );
    job.schedule ();
}
 
Example 52
Project: neoscada   File: FactoryEditorInput.java   Source Code and License 5 votes vote down vote up
public Job createDeleteJob ( final Collection<String> items )
{
    final List<DiffEntry> diffEntries = new LinkedList<DiffEntry> ();

    for ( final String configurationId : items )
    {
        diffEntries.add ( new DiffEntry ( this.factoryId, configurationId, Operation.DELETE, null, null, null ) );
    }

    return new DiffJob ( "Delete configurations", this.connectionService, diffEntries );
}
 
Example 53
Project: scanning   File: PathInfoCalculatorJob.java   Source Code and License 5 votes vote down vote up
public PathInfoCalculatorJob(final PlottingController controller) {
	super("Calculating scan path");
	this.controller = controller;
	setSystem(true);
	setUser(false);
	setPriority(Job.INTERACTIVE);
	this.pointGeneratorFactory = ServiceHolder.getGeneratorService();
	this.vservice              = ServiceHolder.getValidatorService();
}
 
Example 54
Project: RxSWT   File: EclipseScheduler.java   Source Code and License 5 votes vote down vote up
private static void executeRunnable(String title, long delay, TimeUnit unit, ScheduledRunnable scheduled) {
	Job job = Job.create(title, monitor -> {
		scheduled.run();
		return Status.OK_STATUS;
	});
	job.schedule(unit.toMillis(delay));
}
 
Example 55
Project: Equella   File: ConvertJPFProjects.java   Source Code and License 5 votes vote down vote up
protected void run()
{
	new Job("Convert JPF projects")
	{
		@Override
		protected IStatus run(IProgressMonitor monitor)
		{
			IProject[] projects = ResourcesPlugin.getWorkspace().getRoot().getProjects();
			for( IProject project : projects )
			{
				if( project.isOpen() && !JPFProjectNature.hasNature(project)
					&& JPFProject.getManifest(project).exists() )
				{
					IProjectDescription description;
					try
					{
						description = project.getDescription();
						JPFProjectNature.addNature(description);
						project.setDescription(description, monitor);
					}
					catch( CoreException e )
					{
						JPFClasspathLog.logError(e);
					}
				}
			}
			return Status.OK_STATUS;
		}
	}.schedule();
}
 
Example 56
Project: gw4e.project   File: GraphWalkerContextManager.java   Source Code and License 5 votes vote down vote up
public static void generateInterface(final IResource resource, IWorkbenchWindow aww) {
	Job job = new Job("GW4E Generation Source Job") {
		@Override
		public IStatus run(IProgressMonitor monitor) {
			try {
				if (resource instanceof IFile) {
					SubMonitor subMonitor = SubMonitor.convert(monitor, 120);
					IFile file = (IFile) resource;
					if (PreferenceManager.isGraphModelFile(file)) {
						AbstractPostConversion converter = getDefaultGraphConversion(file, true);
						ConversionRunnable runnable = converter.createConversionRunnable(aww);
						subMonitor.subTask("Processing converter ");
						SubMonitor child = subMonitor.split(1);
						runnable.run(child);
					}						
				} else {
					if (resource instanceof IFolder) {
						generateFromFolder(resource, true, aww);
					}
				}

			} catch (Exception e) {
				e.printStackTrace();
				ResourceManager.logException(e);
			}
			return Status.OK_STATUS;
		}
	};
	job.setUser(true);
	job.schedule();
}
 
Example 57
Project: gw4e.project   File: ResourceManager.java   Source Code and License 5 votes vote down vote up
/**
 * Touch the files located in the folder of the passed file
 * 
 * @param file
 */
public static void touchFolderForRebuild(final IFile file) {
	Job job = new WorkspaceJob("Touch folders") {
		public IStatus runInWorkspace(IProgressMonitor monitor) throws CoreException {
			ResourceManager.touchFolderResources(file);
			return Status.OK_STATUS;
		}
	};
	job.schedule();
}
 
Example 58
Project: gw4e.project   File: SettingsManager.java   Source Code and License 5 votes vote down vote up
/**
 * Return the the preference values for the passed project and key
 * 
 * @param project
 * @param key
 * @return
 */
public static String[] getValues(IProject project, String key, boolean projectScoped) {

	IEclipsePreferences projectPreferences = null;
	if (projectScoped) {
		projectPreferences = getProjectPreference(project);
	} else {
		projectPreferences = getGlobalPreference();
	}
	String values = projectPreferences.get(key, "");
	if ((values == null) || (values.trim().length() == 0) && projectScoped) {
		IEclipsePreferences globalPreferences = getGlobalPreference();
		values = globalPreferences.get(key, "");
		final String gloablValues = values;

		Job job = new WorkspaceJob("GW4E Configure Project Preference Job") {
			@Override
			public IStatus runInWorkspace(IProgressMonitor monitor) throws CoreException {
				SubMonitor subMonitor = SubMonitor.convert(monitor, 60);
				try {
					putValues(project, key, fromString(gloablValues), projectScoped);
					return Status.OK_STATUS;
				} catch (Exception e) {
					ResourceManager.logException(e);
					return Status.CANCEL_STATUS;
				} finally {
					subMonitor.done();
				}
			}
		};
		job.setRule(project);
		job.setUser(true);
		job.schedule();
	}
	String[] ret = fromString(values);
	return ret;
}
 
Example 59
Project: gw4e.project   File: BuildPoliciesCache.java   Source Code and License 5 votes vote down vote up
/**
 * @param graphFile
 * @throws CoreException
 * @throws IOException
 * @throws InterruptedException
 */
public void update(List<BuildPolicy> policies) throws CoreException, IOException, InterruptedException {
	Job job = new WorkspaceJob("Updating cache") {
		public IStatus runInWorkspace(IProgressMonitor monitor) throws CoreException {
			try {
				IFile fileCache = getCache();
				Properties p = ResourceManager.loadIFileAsProperties(fileCache,
						getFileCacheName(resource.getProject().getName()));
				String serialized = serialize(policies);
				if (serialized == null) {
					log("BuildPoliciesCache.update " + fileCache + " failed to updated for resource " + resource
							+ " " + policies.toString());
					return Status.OK_STATUS;
				}
				p.put(resource.getName(), System.currentTimeMillis() + ":" + serialized);
				log("BuildPoliciesCache.update " + fileCache + " updated for resource " + resource + " "
						+ p.toString());
				save(p, monitor);
				return Status.OK_STATUS;
			} catch (Exception e) {
				ResourceManager.logException(e);
				return Status.CANCEL_STATUS;
			}
		}
	};
	job.setRule(resource.getProject());
	job.setUser(true);
	job.schedule();
}
 
Example 60
Project: gw4e.project   File: SetSyncPoliciesForFileMarkerResolution.java   Source Code and License 5 votes vote down vote up
@Override
public void run(IMarker marker) {
	Job job = new WorkspaceJob("GW4E QuickFix 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();
}