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

The following examples show how to use org.eclipse.core.runtime.jobs.Job. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
	if (fgFirstTime) {
		// Join the initialize after load job.
		IJobManager manager= Job.getJobManager();
		manager.join(JavaUI.ID_PLUGIN, monitor);
	}
	OpenTypeHistory history= OpenTypeHistory.getInstance();
	if (fgFirstTime || history.isEmpty()) {
		if (history.needConsistencyCheck()) {
			monitor.beginTask(JavaUIMessages.TypeSelectionDialog_progress_consistency, 100);
			refreshSearchIndices(new SubProgressMonitor(monitor, 90));
			history.checkConsistency(new SubProgressMonitor(monitor, 10));
		} else {
			refreshSearchIndices(monitor);
		}
		monitor.done();
		fgFirstTime= false;
	} else {
		history.checkConsistency(monitor);
	}
}
 
Example 2
@Override
public void buildComplete() {
	IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(name);
   	if (project != null && project.isAccessible()) {
   		Job job = new Job(NLS.bind(Messages.RefreshResourceJobLabel, project.getName())) {
			@Override
			protected IStatus run(IProgressMonitor monitor) {
				try {
					project.refreshLocal(IResource.DEPTH_INFINITE, monitor);
		            return Status.OK_STATUS;
				} catch (Exception e) {
					Logger.logError("An error occurred while refreshing the resource: " + project.getLocation()); //$NON-NLS-1$
					return new Status(IStatus.ERROR, CodewindCorePlugin.PLUGIN_ID,
							NLS.bind(Messages.RefreshResourceError, project.getLocation()), e);
				}
			}
		};
		job.setPriority(Job.LONG);
		job.schedule();
   	}
}
 
Example 3
public static void cleanup(String projectName, CodewindConnection connection) {
	Job job = new Job(NLS.bind(Messages.ProjectCleanupJobLabel, projectName)) {
		@Override
		protected IStatus run(IProgressMonitor monitor) {
			SubMonitor mon = SubMonitor.convert(monitor, 30);
			mon.split(10);
			connection.refreshApps(null);
			CodewindApplication app = connection.getAppByName(projectName);
			if (app != null) {
				try {
					ProjectUtil.removeProject(app.name, app.projectID, mon.split(20));
				} catch (Exception e) {
					Logger.logError("An error occurred while trying to remove the project after bind project terminated for: " + projectName, e);
					return new Status(IStatus.ERROR, CodewindUIPlugin.PLUGIN_ID, NLS.bind(Messages.ProjectCleanupError, projectName), null);
				}
			}
			return Status.OK_STATUS;
		}
	};
	job.schedule();
}
 
Example 4
Source Project: codewind-eclipse   Source File: BaseTest.java    License: Eclipse Public License 2.0 6 votes vote down vote up
public CodewindConnection getLocalConnection() throws Exception {
	TestUtil.print("Setting up a local connection");
	
	// Check that Codewind is installed
   	CodewindManager.getManager().refreshInstallStatus(new NullProgressMonitor());
   	if (!CodewindManager.getManager().getInstallStatus().isInstalled()) {
   		installCodewind();
   		startCodewind();
   	} else if (!CodewindManager.getManager().getInstallStatus().isStarted()) {
   		startCodewind();
   	}
   	assertTrue("Codewind must be installed and started before the tests can be run", CodewindManager.getManager().getInstallStatus().isStarted());
   	
   	// Get the local Codewind connection
       CodewindConnection conn = CodewindConnectionManager.getLocalConnection();
       if (conn == null) {
           IJobManager jobManager = Job.getJobManager();
           Job[] jobs = jobManager.find(CodewindConnectionManager.RESTORE_CONNECTIONS_FAMILY);
           for (Job job : jobs) {
           	job.join();
           }
           conn = CodewindConnectionManager.getLocalConnection();
       }
       assertNotNull("The connection should not be null.", conn);
       return conn;
}
 
Example 5
@Test
public void testRun_blockedUntilWritable() throws InterruptedException {
  assertTrue(readWriteLock.readLock().tryLock());
  boolean locked = true;

  try {
    FakeModifyJob job = new FakeModifyJob(true /* blockOnStart */);
    job.schedule();
    while (job.getState() != Job.RUNNING) {
      Thread.sleep(50);
    }
    // Incomplete test, but if it ever fails, something is surely broken.
    assertFalse(job.modifiedSdk);

    readWriteLock.readLock().unlock();
    locked = false;
    job.unblock();
    job.join();
  } finally {
    if (locked) {
      readWriteLock.readLock().unlock();
    }
  }
}
 
Example 6
@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 7
public void scheduleFetchChangePathJob(ILogEntry logEntry) {
  if(fetchChangePathJob == null) {
    fetchChangePathJob = new FetchChangePathJob();
  }
  if(fetchChangePathJob.getState() != Job.NONE) {
    fetchChangePathJob.cancel();
    try {
      fetchChangePathJob.join();
    } catch(InterruptedException e) {
  	SVNUIPlugin.log(IStatus.ERROR, e.getMessage(), e);  
      // SVNUIPlugin.log(new
      // SVNException(Policy.bind("HistoryView.errorFetchingEntries",
      // remoteResource.getName()), e)); //$NON-NLS-1$
    }
  }
  fetchChangePathJob.setLogEntry(logEntry);
  Utils.schedule(fetchChangePathJob, getSite());
}
 
Example 8
Source Project: hadoop-gpu   Source File: DFSFolder.java    License: Apache License 2.0 6 votes vote down vote up
public DFSContent[] getChildren() {
  if (children == null) {
    new Job("Connecting to DFS " + location) {
      @Override
      protected IStatus run(IProgressMonitor monitor) {
        try {
          loadDFSFolderChildren();
          return Status.OK_STATUS;

        } catch (IOException ioe) {
          children =
              new DFSContent[] { new DFSMessage("Error: "
                  + ioe.getLocalizedMessage()) };
          return Status.CANCEL_STATUS;

        } finally {
          // Under all circumstances, update the UI
          provider.refresh(DFSFolder.this);
        }
      }
    }.schedule();

    return new DFSContent[] { new DFSMessage("Listing folder content...") };
  }
  return this.children;
}
 
Example 9
public Object execute(ExecutionEvent event) throws ExecutionException
{
	UIJob job = new UIJob("Open Theme Preferences") //$NON-NLS-1$
	{

		@Override
		public IStatus runInUIThread(IProgressMonitor monitor)
		{
			final PreferenceDialog dialog = PreferencesUtil.createPreferenceDialogOn(UIUtils.getActiveShell(),
					ThemePreferencePage.ID, null, null);
			dialog.open();
			return Status.OK_STATUS;
		}
	};
	job.setPriority(Job.INTERACTIVE);
	job.setRule(PopupSchedulingRule.INSTANCE);
	job.schedule();
	return null;
}
 
Example 10
public void run(final CountDownLatch threadSignal) {
	for(Control c :composite.getChildren()) {
		if(c instanceof SyncApplicationComposite) {
			final SyncApplicationComposite sac = (SyncApplicationComposite)c;
			Job job = new WorkspaceJob("")
			{
				@Override
				public IStatus runInWorkspace(IProgressMonitor monitor)
						throws CoreException {
					try {
						sac.run(threadSignal);
					} catch (Exception e) {
						return Status.CANCEL_STATUS;
					}
					return Status.OK_STATUS;
				}
			};
			job.schedule();
		}
	}
	
}
 
Example 11
public void execute(IProgressMonitor monitor) throws SVNException, InterruptedException {
	Map table = getProviderMapping(getResources());
	Set keySet = table.keySet();
	monitor.beginTask(null, keySet.size() * 1000);
	Iterator iterator = keySet.iterator();
	while (iterator.hasNext()) {
		IProgressMonitor subMonitor = new SubProgressMonitor(monitor, 1000);
		SVNTeamProvider provider = (SVNTeamProvider)iterator.next();
		List list = (List)table.get(provider);
		IResource[] providerResources = (IResource[])list.toArray(new IResource[list.size()]);
		ISchedulingRule rule = getSchedulingRule(provider);
		try {
			Job.getJobManager().beginRule(rule, monitor);
			monitor.setTaskName(getTaskName(provider));
			execute(provider, providerResources, subMonitor);
		} finally {
			Job.getJobManager().endRule(rule);
		}
	}
}
 
Example 12
@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(2, 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 13
Source Project: APICloud-Studio   Source File: IndexPlugin.java    License: GNU General Public License v3.0 6 votes vote down vote up
public void stop(BundleContext context) throws Exception
{
	// grab any running indexing jobs
	IJobManager manager = Job.getJobManager();
	Job[] jobs = manager.find(IndexRequestJob.INDEX_REQUEST_JOB_FAMILY);

	// ...and cancel them
	if (!ArrayUtil.isEmpty(jobs))
	{
		for (Job job : jobs)
		{
			job.cancel();
		}
	}

	fManager = null;
	plugin = null;
	super.stop(context);
}
 
Example 14
Source Project: google-cloud-eclipse   Source File: ConversionTests.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void appEngineWebWithJava8Runtime_Java8_Web31()
    throws CoreException, IOException, InterruptedException, SAXException, AppEngineException {
  IFacetedProject project = projectCreator
      .withFacets(JavaFacet.VERSION_1_8, 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 15
@Override
public void requestClasspathContainerUpdate(final IPath containerPath, final IJavaProject project,
		final IClasspathContainer containerSuggestion) throws CoreException {
	super.requestClasspathContainerUpdate(containerPath, project, containerSuggestion);
	new Job("Classpath container update") { //$NON-NLS-1$
		@Override
		protected IStatus run(IProgressMonitor monitor) {
			try {
				JavaCore.setClasspathContainer(containerPath, new IJavaProject[] { project },
						new IClasspathContainer[] { containerSuggestion }, monitor);
			} catch (CoreException ex) {
				return new Status(IStatus.ERROR, XtendActivator.getInstance().getBundle().getSymbolicName(), 0,
						"Classpath container update failed", ex); //$NON-NLS-1$
			}
			return Status.OK_STATUS;
		}
	}.schedule();
}
 
Example 16
Source Project: CogniCrypt   Source File: ClaferPage.java    License: Eclipse Public License 2.0 6 votes vote down vote up
public boolean checkModel() {

		final Job compileJob = Job.create("Compile Clafer model", (ICoreRunnable) monitor -> {
			// UI updates can only be run in the display thread,
			// so do them via Display.getDefault()
			Display.getDefault().asyncExec(() -> {

				ClaferPage.this.feedbackComposite.setFeedback(" (compiling...)");

				// do the tedious work
				final File cfrFile = new File(Utils.getResourceFromWithin(Constants.CFR_FILE_DIRECTORY_PATH), "temporaryModel" + Constants.CFR_EXTENSION);
				ClaferPage.this.compositeToHoldGranularUIElements.getClaferModel().toFile(cfrFile.getAbsolutePath());
				if (ClaferModel.compile(cfrFile.getAbsolutePath())) {
					ClaferPage.this.feedbackComposite.setFeedback("Compilation successful");
				} else {
					ClaferPage.this.feedbackComposite.setFeedback("Compilation error");
				}
			});
		});

		// start the asynchronous task
		compileJob.schedule();

		return false;
	}
 
Example 17
@Test
public void testCompletion_javadoc() throws Exception {
	IJavaProject javaProject = JavaCore.create(project);
	ICompilationUnit unit = (ICompilationUnit) javaProject.findElement(new Path("org/sample/TestJavadoc.java"));
	unit.becomeWorkingCopy(null);
	String joinOnCompletion = System.getProperty(JDTLanguageServer.JAVA_LSP_JOIN_ON_COMPLETION);
	try {
		System.setProperty(JDTLanguageServer.JAVA_LSP_JOIN_ON_COMPLETION, "true");
		int[] loc = findCompletionLocation(unit, "inner.");
		CompletionParams position = JsonMessageHelper.getParams(createCompletionRequest(unit, loc[0], loc[1]));
		String source = unit.getSource();
		changeDocument(unit, source, 3);
		Job.getJobManager().join(DocumentLifeCycleHandler.DOCUMENT_LIFE_CYCLE_JOBS, new NullProgressMonitor());
		changeDocument(unit, source, 4);
		CompletionList list = server.completion(position).join().getRight();
		CompletionItem resolved = server.resolveCompletionItem(list.getItems().get(0)).join();
		assertEquals("Test ", resolved.getDocumentation().getLeft());
	} finally {
		unit.discardWorkingCopy();
		if (joinOnCompletion == null) {
			System.clearProperty(JDTLanguageServer.JAVA_LSP_JOIN_ON_COMPLETION);
		} else {
			System.setProperty(JDTLanguageServer.JAVA_LSP_JOIN_ON_COMPLETION, joinOnCompletion);
		}
	}
}
 
Example 18
Source Project: sarl   Source File: SARLClasspathContainerInitializer.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void requestClasspathContainerUpdate(
		final IPath containerPath,
		final IJavaProject javaProject,
		final IClasspathContainer containerSuggestion) throws CoreException {
	if (containerSuggestion instanceof SARLClasspathContainer) {
		((SARLClasspathContainer) containerSuggestion).reset();
	}
	super.requestClasspathContainerUpdate(containerPath, javaProject, containerSuggestion);
	final Job job = new Job(Messages.SARLClasspathContainerInitializer_0) {
		@Override
		protected IStatus run(IProgressMonitor monitor) {
			try {
				JavaCore.setClasspathContainer(
						containerPath,
						new IJavaProject[] {javaProject},
						new IClasspathContainer[] {containerSuggestion},
						monitor);
			} catch (CoreException ex) {
				return SARLEclipsePlugin.getDefault().createStatus(IStatus.ERROR, ex);
			}
			return SARLEclipsePlugin.getDefault().createOkStatus();
		}
	};
	job.schedule();
}
 
Example 19
Source Project: dsl-devkit   Source File: ErrorLogListenerTest.java    License: Eclipse Public License 1.0 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 20
Source Project: thym   Source File: HybridProject.java    License: Eclipse Public License 1.0 6 votes vote down vote up
public void prepare(IProgressMonitor monitor, final String...options) throws CoreException{
	ISchedulingRule rule = ResourcesPlugin.getWorkspace().getRuleFactory().modifyRule(getProject());
	try{
		Job.getJobManager().beginRule(rule, monitor);
	
		SubMonitor sm = SubMonitor.convert(monitor);
		sm.setWorkRemaining(100);
		ErrorDetectingCLIResult status = getProjectCLI().prepare(sm.newChild(70),options).convertTo(ErrorDetectingCLIResult.class);
		getProject().refreshLocal(IResource.DEPTH_INFINITE, sm.newChild(30));
		if(status.asStatus().getSeverity() == IStatus.ERROR){
			throw new CoreException(status.asStatus());
		}
	} finally {
		Job.getJobManager().endRule(rule);
	}
}
 
Example 21
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
    List<TmfEventTableColumn> columns = getColumns(event.getApplicationContext());
    ITmfTrace trace = TmfTraceManager.getInstance().getActiveTrace();
    ITmfFilter filter = TmfTraceManager.getInstance().getCurrentTraceContext().getFilter();
    if (trace != null) {
        FileDialog fd = TmfFileDialogFactory.create(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), SWT.SAVE);
        fd.setFilterExtensions(new String[] { "*.csv", "*.*", "*" }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
        fd.setOverwrite(true);
        final String s = fd.open();
        if (s != null) {
            Job j = new ExportToTextJob(trace, filter, columns, s);
            j.setUser(true);
            j.schedule();
        }
    }
    return null;
}
 
Example 22
Source Project: google-cloud-eclipse   Source File: ConversionTests.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void appEngineWebWithJava8Runtime_Java8()
    throws CoreException, IOException, InterruptedException, SAXException, AppEngineException {
  IFacetedProject project =
      projectCreator.withFacets(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 23
Source Project: saros   Source File: NegotiationHandler.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public void handleOutgoingSessionNegotiation(OutgoingSessionNegotiation negotiation) {

  OutgoingInvitationJob outgoingInvitationJob = new OutgoingInvitationJob(negotiation);

  outgoingInvitationJob.setPriority(Job.SHORT);
  outgoingInvitationJob.schedule();
}
 
Example 24
Source Project: google-cloud-eclipse   Source File: GcpProjectQueryJob.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @param projectRepository {@link ProjectRepository#getProjects} must be thread-safe
 * @param dataBindingContext data binding context that binds {@link #projectSelector}
 * @param isLatestQueryJob predicate that lazily determines if this job is the latest query job,
 *     which determines if the job should update {@link ProjectSelector} or die silently. This
 *     predicate is executed in the UI context
 */
GcpProjectQueryJob(Credential credential, ProjectRepository projectRepository,
    ProjectSelector projectSelector, DataBindingContext dataBindingContext,
    Predicate<Job> isLatestQueryJob) {
  super("Google Cloud Platform Projects Query Job");
  this.credential = Preconditions.checkNotNull(credential);
  this.projectRepository = Preconditions.checkNotNull(projectRepository);
  this.projectSelector = Preconditions.checkNotNull(projectSelector);
  this.dataBindingContext = Preconditions.checkNotNull(dataBindingContext);
  this.isLatestQueryJob = Preconditions.checkNotNull(isLatestQueryJob);
  display = projectSelector.getDisplay();
}
 
Example 25
@Override
public IStatus runInUIThread(IProgressMonitor monitor) {
	Job job = new RealJob(JavaUIMessages.JavaPlugin_initializing_ui);
	job.setPriority(Job.SHORT);
	job.schedule();
	return Status.OK_STATUS;
}
 
Example 26
Source Project: sarl   Source File: NewMavenSarlProjectWizard.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean performFinish() {
	if (!super.performFinish()) {
		return false;
	}
	final Job job = new WorkspaceJob("Force the SARL nature") { //$NON-NLS-1$
		@SuppressWarnings({ "deprecation", "synthetic-access" })
		@Override
		public IStatus runInWorkspace(IProgressMonitor monitor) throws CoreException {
			final Model model = NewMavenSarlProjectWizard.this.lastModel;
			if (model != null) {
				final Plugin plugin = Iterables.find(model.getBuild().getPlugins(), it -> PLUGIN_ARTIFACT_ID.equals(it.getArtifactId()));
				plugin.setExtensions(true);
				final IWorkspace workspace = ResourcesPlugin.getWorkspace();
				final IWorkspaceRoot root = workspace.getRoot();
				final IProject project = NewMavenSarlProjectWizard.this.importConfiguration.getProject(root, model);
				// Fixing the "extensions" within the pom file
				final IFile pomFile = project.getFile(IMavenConstants.POM_FILE_NAME);
				pomFile.delete(true, new NullProgressMonitor());
				MavenPlugin.getMavenModelManager().createMavenModel(pomFile, model);
				// Update the project
				final SubMonitor submon = SubMonitor.convert(monitor);
				MavenPlugin.getProjectConfigurationManager().updateProjectConfiguration(project, submon.newChild(1));
				project.refreshLocal(IResource.DEPTH_ONE, submon.newChild(1));
			}
			return Status.OK_STATUS;
		}
	};
	job.setRule(MavenPlugin.getProjectConfigurationManager().getRule());
	job.schedule();
	return true;
}
 
Example 27
/**
 * Fetch the staging locations from GCS in a background task and update the Staging Locations
 * combo.
 */
@VisibleForTesting
void updateStagingLocations(long scheduleDelay) {
  Credential credential = accountSelector.getSelectedCredential();
  String selectedEmail = accountSelector.getSelectedEmail();
  GcpProject project = projectInput.getProject();
  // Retrieving staging locations requires an authenticated user and project.
  // Check if there is an update is in progress; if it matches our user and project,
  // then quick-return, otherwise it is stale and should be cancelled.
  if (fetchStagingLocationsJob != null) {
    if (project != null
        && Objects.equals(project.getId(), fetchStagingLocationsJob.getProjectId())
        && Objects.equals(selectedEmail, fetchStagingLocationsJob.getAccountEmail())
        && fetchStagingLocationsJob.getState() == Job.RUNNING) {
      return;
    }
    fetchStagingLocationsJob.abandon();
  }
  fetchStagingLocationsJob = null;

  if (project != null && credential != null) {
    fetchStagingLocationsJob =
        new FetchStagingLocationsJob(getGcsClient(), selectedEmail, project.getId());
    fetchStagingLocationsJob.onSuccess(
        displayExecutor,
        stagingLocations -> {
          updateStagingLocations(stagingLocations);
          validate(); // reports message back to UI
        });
    fetchStagingLocationsJob.onError(
        displayExecutor,
        exception -> {
          DataflowUiPlugin.logError(
              exception, "Exception while retrieving staging locations"); // $NON-NLS-1$
          validate();
        });
    fetchStagingLocationsJob.schedule(scheduleDelay);
  }
}
 
Example 28
public static void enableDisableProject(CodewindApplication app, boolean enable) {
	Job job = new Job(NLS.bind(Messages.EnableDisableProjectJob, app.name)) {
		@Override
		protected IStatus run(IProgressMonitor monitor) {
			try {
				app.connection.requestProjectOpenClose(app, enable);
				return Status.OK_STATUS;
			} catch (Exception e) {
				Logger.logError("An error occurred updating enablement for: " + app.name + ", with id: " + app.projectID, e); //$NON-NLS-1$ //$NON-NLS-2$
				return new Status(IStatus.ERROR, CodewindUIPlugin.PLUGIN_ID, NLS.bind(Messages.ErrorOnEnableDisableProject, app.name), e);
			}
		}
	};
	job.schedule();
}
 
Example 29
Source Project: tracecompass   Source File: SnapshotHandler.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
    fLock.lock();
    try {
        // Make a copy for thread safety
        final List<TraceSessionComponent> sessions = new ArrayList<>();
        sessions.addAll(fSessions);

        Job job = new Job(Messages.TraceControl_RecordSnapshotJob) {
            @Override
            protected IStatus run(IProgressMonitor monitor) {
                MultiStatus status = new MultiStatus(Activator.PLUGIN_ID, IStatus.OK, null, null);
                for (Iterator<TraceSessionComponent> iterator = sessions.iterator(); iterator.hasNext();) {
                    try {
                        // record snapshot for all selected sessions sequentially
                        TraceSessionComponent session = iterator.next();
                        session.recordSnapshot(monitor);
                        if (monitor.isCanceled()) {
                            status.add(Status.CANCEL_STATUS);
                            break;
                        }
                    } catch (ExecutionException e) {
                        status.add(new Status(IStatus.ERROR, Activator.PLUGIN_ID, Messages.TraceControl_RecordSnapshotFailure, e));
                    }
                }
                return status;
            }
        };
        job.setUser(true);
        job.schedule();
    } finally {
        fLock.unlock();
    }
    return null;
}
 
Example 30
/**
 * Trace closed handler
 *
 * @param signal
 *            Last opened trace was closed
 */
@TmfSignalHandler
public void traceClosed(TmfTraceClosedSignal signal) {
    ITmfTrace trace = fTrace;
    if (trace == signal.getTrace()) {
        // Cancel the filtering job
        Job job = fFilteringJob;
        if (job != null) {
            job.cancel();
        }
    }
    // Check if there is no more opened trace
    if (TmfTraceManager.getInstance().getActiveTrace() == null) {
        if (!getTableViewer().getTable().isDisposed()) {
            getTableViewer().setInput(null);
            getTableViewer().setItemCount(0);
            refresh();
        }

        ISegmentStoreProvider provider = getSegmentProvider();
        if ((provider != null)) {
            SegmentStoreProviderProgressListener listener = fListener;
            if (listener != null) {
                provider.removeListener(listener);
            }
        }
        fTrace = null;
    }
}