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

The following examples show how to use org.eclipse.core.runtime.jobs.Job. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: XtendContainerInitializer.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
@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 #2
Source File: BindProjectWizard.java    From codewind-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
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 #3
Source File: ErrorLogListenerTest.java    From dsl-devkit with 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 #4
Source File: HybridProject.java    From thym with 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 #5
Source File: SARLClasspathContainerInitializer.java    From sarl with 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 #6
Source File: ConversionTests.java    From google-cloud-eclipse with 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 #7
Source File: CodewindEclipseApplication.java    From codewind-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@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 #8
Source File: ExportToTextCommandHandler.java    From tracecompass with Eclipse Public License 2.0 6 votes vote down vote up
@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 #9
Source File: BaseTest.java    From codewind-eclipse with 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 #10
Source File: CloudSdkModifyJobTest.java    From google-cloud-eclipse with Apache License 2.0 6 votes vote down vote up
@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 #11
Source File: CompletionHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@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 #12
Source File: DFSFolder.java    From hadoop-gpu with 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 #13
Source File: OpenThemePreferencesHandler.java    From APICloud-Studio with GNU General Public License v3.0 6 votes vote down vote up
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 #14
Source File: SyncApplicationDialog.java    From APICloud-Studio with GNU General Public License v3.0 6 votes vote down vote up
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 #15
Source File: RepositoryProviderOperation.java    From APICloud-Studio with GNU General Public License v3.0 6 votes vote down vote up
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 #16
Source File: DocumentLifeCycleHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 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(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 #17
Source File: IndexPlugin.java    From APICloud-Studio with 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 #18
Source File: ConversionTests.java    From google-cloud-eclipse with 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 #19
Source File: ClaferPage.java    From CogniCrypt with 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 #20
Source File: SVNHistoryPage.java    From APICloud-Studio with GNU General Public License v3.0 6 votes vote down vote up
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 #21
Source File: FilteredTypesSelectionDialog.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
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 #22
Source File: MavenBuildSupportTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 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 #23
Source File: InstallNewSoftwareHandler.java    From elexis-3-core with Eclipse Public License 1.0 5 votes vote down vote up
protected void setLoadJobProperties(Job loadJob){
	super.setLoadJobProperties(loadJob);
	// If we are doing a background load, we do not wish to authenticate, as the
	// user is unaware that loading was needed
	if (!waitForPreload()) {
		loadJob.setProperty(LoadMetadataRepositoryJob.SUPPRESS_AUTHENTICATION_JOB_MARKER,
			Boolean.toString(true));
		loadJob.setProperty(LoadMetadataRepositoryJob.SUPPRESS_REPOSITORY_EVENTS,
			Boolean.toString(true));
	}
}
 
Example #24
Source File: EnableSarlMavenNatureAction.java    From sarl with Apache License 2.0 5 votes vote down vote up
/** Create the configuration job for a Maven project.
 *
 * @param project the project to configure.
 * @return the job.
 */
@SuppressWarnings("static-method")
protected Job createJobForMavenProject(IProject project) {
	return new Job(Messages.EnableSarlMavenNatureAction_0) {

		@Override
		protected IStatus run(IProgressMonitor monitor) {
			final SubMonitor mon = SubMonitor.convert(monitor, 3);
			try {
				// The project should be a Maven project.
				final IPath descriptionFilename = project.getFile(new Path(IProjectDescription.DESCRIPTION_FILE_NAME)).getLocation();
				final File projectDescriptionFile = descriptionFilename.toFile();
				final IPath classpathFilename = project.getFile(new Path(FILENAME_CLASSPATH)).getLocation();
				final File classpathFile = classpathFilename.toFile();
				// Project was open by the super class. Close it because Maven fails when a project already exists.
				project.close(mon.newChild(1));
				// Delete the Eclipse project and classpath definitions because Maven fails when a project already exists.
				project.delete(false, true, mon.newChild(1));
				if (projectDescriptionFile.exists()) {
					projectDescriptionFile.delete();
				}
				if (classpathFile.exists()) {
					classpathFile.delete();
				}
				// Import
				MavenImportUtils.importMavenProject(
						project.getWorkspace().getRoot(),
						project.getName(),
						true,
						mon.newChild(1));
			} catch (CoreException exception) {
				SARLMavenEclipsePlugin.getDefault().log(exception);
			}
			return Status.OK_STATUS;
		}
	};
}
 
Example #25
Source File: BundleManager.java    From APICloud-Studio with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Load the bundle in the specified directory
 * 
 * @param bundleDirectory
 *            The directory containing a bundle and its children
 * @param wait
 *            Allows us to be synchronous when executing this
 */
public void loadBundle(File bundleDirectory, boolean wait)
{
	BundleLoadJob job = new BundleLoadJob(bundleDirectory);

	// If we're running and not testing, schedule in parallel but limit how many run in parallel based on processor
	// count
	if (!EclipseUtil.isTesting() && Platform.isRunning())
	{
		job.setRule(new SerialPerObjectRule(counter++));

		if (counter >= maxBundlesToLoadInParallel())
		{
			counter = 0;
		}

		job.setPriority(Job.SHORT);
		job.schedule();
		if (wait)
		{
			try
			{
				job.join();
			}
			catch (InterruptedException e)
			{
				// ignore error
			}
		}
	}
	else
	{
		// We're already running inline, so don't need to ever "wait"
		job.run(new NullProgressMonitor());
	}
}
 
Example #26
Source File: AbstractOpenConsoleCommand.java    From bonita-studio with GNU General Public License v2.0 5 votes vote down vote up
private void executeJob() {
    if (runSynchronously) {
        doOpen(Repository.NULL_PROGRESS_MONITOR);
    } else {
        Job job = new Job(Messages.initializingUserXP) {

            @Override
            public IStatus run(IProgressMonitor monitor) {
                return doOpen(monitor);
            }
        };
        job.setUser(true);
        job.schedule();
    }
}
 
Example #27
Source File: ProjectSelectorSelectionChangedListener.java    From google-cloud-eclipse with Apache License 2.0 5 votes vote down vote up
@Override
public void selectionChanged(SelectionChangedEvent event) {
  projectSelector.clearStatusLink();
  latestQueryJob = null;

  IStructuredSelection selection = (IStructuredSelection) event.getSelection();
  if (selection.isEmpty()) {
    return;
  }

  GcpProject project = (GcpProject) selection.getFirstElement();
  String email = accountSelector.getSelectedEmail();
  String createAppLink = MessageFormat.format(CREATE_APP_LINK,
      project.getId(), UrlEscapers.urlFormParameterEscaper().escape(email));

  boolean queryCached = project.hasAppEngineInfo();
  if (queryCached) {
    if (project.getAppEngine() == AppEngine.NO_APPENGINE_APPLICATION) {
      projectSelector.setStatusLink(
          Messages.getString("projectselector.missing.appengine.application.link", createAppLink),
          createAppLink /* tooltip */);
    }
  } else {  // The project has never been queried.
    Credential credential = accountSelector.getSelectedCredential();
    Predicate<Job> isLatestQueryJob = job -> job == latestQueryJob;
    latestQueryJob = new AppEngineApplicationQueryJob(project, credential, projectRepository,
        projectSelector, createAppLink, isLatestQueryJob);
    latestQueryJob.schedule();
  }
}
 
Example #28
Source File: RunMobileDialog.java    From APICloud-Studio with GNU General Public License v3.0 5 votes vote down vote up
protected void buttonPressed(int buttonId) {
	if (buttonId == 0) {
		StructuredSelection ss = (StructuredSelection)this.list.getSelection();
		IProject project = (IProject)ss.getFirstElement();
		Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
		if(validate(getID(project),project)){
			
		
		final SyncApplicationDialog sad = new SyncApplicationDialog(shell, aMobiles,iMobiles, project);
		final CountDownLatch threadSignal = new CountDownLatch(aMobiles.size()+iMobiles.size());
		sad.open();
		sad.run(threadSignal);
		Job job = new WorkspaceJob("")
		{
			@Override
			public IStatus runInWorkspace(IProgressMonitor monitor)
					throws CoreException {
				try {
					threadSignal.await();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				sad.finish();
				return Status.OK_STATUS;
			}
		};
		job.schedule();
		close();
	}else if (buttonId == 1) {
		close();
	}else{
		close();
	}
	} else{
		close();
	}
}
 
Example #29
Source File: ParseStatusContributionItem.java    From tlaplus with MIT License 5 votes vote down vote up
public void updateStatus() {
	if (statusLabel == null || statusLabel.isDisposed()) {
		return;
	}

	final Job j = new ToolboxJob("Calculating specification size...") {
		/* (non-Javadoc)
		 * @see org.eclipse.core.runtime.jobs.Job#run(org.eclipse.core.runtime.IProgressMonitor)
		 */
		protected IStatus run(IProgressMonitor monitor) {
			final Spec spec = Activator.getSpecManager().getSpecLoaded();

			UIHelper.runUIAsync(new Runnable() {
				/* (non-Javadoc)
				 * @see java.lang.Runnable#run()
				 */
				public void run() {
					if (spec == null && !composite.isDisposed()) {
						composite.setVisible(false);
					} else if(!statusLabel.isDisposed() && !composite.isDisposed()) {
						statusLabel.setText(AdapterFactory.getStatusAsString(spec));
						statusLabel.setBackground(statusLabel.getDisplay().getSystemColor(AdapterFactory.getStatusAsSWTBGColor(spec)));
						statusLabel.setForeground(statusLabel.getDisplay().getSystemColor(AdapterFactory.getStatusAsSWTFGColor(spec)));
						statusLabel.redraw();
						composite.setVisible(true);
					}
				}
			});
			return Status.OK_STATUS;
		}
	};
	j.schedule();
}
 
Example #30
Source File: AppEngineApplicationQueryJob.java    From google-cloud-eclipse with Apache License 2.0 5 votes vote down vote up
/**
 * @param projectRepository {@link ProjectRepository#getAppEngineApplication} must be thread-safe
 * @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.
 */
public AppEngineApplicationQueryJob(GcpProject project, Credential credential,
    ProjectRepository projectRepository, ProjectSelector projectSelector, String createAppLink,
    Predicate<Job> isLatestQueryJob) {
  super("Checking GCP project has App Engine Application...");
  this.project = project;
  this.credential = credential;
  this.projectRepository = projectRepository;
  this.projectSelector = projectSelector;
  this.createAppLink = createAppLink;
  isLatestAppQueryJob = isLatestQueryJob;
  display = projectSelector.getDisplay();
}