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

The following examples show how to use org.eclipse.core.runtime.jobs.JobChangeAdapter. 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: XViewerWorkbenchJob.java    From nebula with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Add a job change listeners that handles a done event if the result was IStatus.OK.
 */
private void addDefaultJobChangeListener() {
   addJobChangeListener(new JobChangeAdapter() {
      /**
       * (non-Javadoc)
       * @see org.eclipse.core.runtime.jobs.JobChangeAdapter#done(org.eclipse.core.runtime.jobs.IJobChangeEvent)
       */
      @Override
      public void done(IJobChangeEvent event) {

         //Abort if it is not running
         if (!XViewerDisplay.isStandaloneXViewer() && !XViewerDisplay.isWorkbenchRunning()) {
            return;
         }

         if (event.getResult().getCode() == IStatus.OK) {
            performDone(event);
         }
      }
   });
}
 
Example #2
Source File: DeployDiagramHandler.java    From bonita-studio with GNU General Public License v2.0 6 votes vote down vote up
private void runInJob(DiagramFileStore diagramFileStore, DeployProcessOperation deployOperation) {
    Job deployJob = new Job(String.format(Messages.deployingProcessesFrom, diagramFileStore.getName())) {

        @Override
        protected IStatus run(IProgressMonitor monitor) {
            return deployOperation.run(monitor);
        }
    };
    deployJob.addJobChangeListener(new JobChangeAdapter() {

        @Override
        public void done(IJobChangeEvent event) {
            Display.getDefault().syncExec(() -> displayDeployResult(event.getResult()));
        }
    });
    deployJob.setUser(true);
    deployJob.schedule();
}
 
Example #3
Source File: PyProjectPythonDetails.java    From Pydev with Eclipse Public License 1.0 6 votes vote down vote up
private JobChangeAdapter createOnJobComplete() {
    JobChangeAdapter onJobComplete = new JobChangeAdapter() {
        @Override
        public void done(IJobChangeEvent event) {
            //Update the display when the configuration has ended.
            Display.getDefault().asyncExec(new Runnable() {
                @Override
                public void run() {
                    //Only update if the page is still there.
                    //If something is disposed, it has been closed.
                    if (!interpreterNoteText.isDisposed()) {
                        updateInterpretersAndDefaultInCombo();
                    }
                }
            });
        };
    };
    return onJobComplete;
}
 
Example #4
Source File: ConfigurationEditorInput.java    From neoscada with Eclipse Public License 1.0 6 votes vote down vote up
@SuppressWarnings ( "unchecked" )
public void performSave ( final IProgressMonitor monitor )
{
    // provide a copy so that it can be accessed outside the realm
    final UpdateJob updateJob = update ( new HashMap<String, String> ( this.dataMap ), null );

    updateJob.setProgressGroup ( monitor, 2 );

    updateJob.addJobChangeListener ( new JobChangeAdapter () {
        @Override
        public void done ( final IJobChangeEvent event )
        {
            performLoad ( monitor );
        }
    } );

    updateJob.schedule ();
}
 
Example #5
Source File: AbstractJhlClientAdapter.java    From APICloud-Studio with GNU General Public License v3.0 6 votes vote down vote up
public void upgradeProject(final File path) {

	UpgradeJob job = new UpgradeJob("upgrade", path);

	job.setUser(true);
	job.schedule();
	job.getState();
	job.addJobChangeListener(new JobChangeAdapter() {
		public void done(IJobChangeEvent event) {
			if (event.getResult().isOK())
				Display.getDefault().asyncExec(new Runnable() {
					public void run() {
						MessageDialog.openInformation(null,
								"upgrade is over", "SVN升级完毕,请重新操作!");
					}
				});
		}
	});
}
 
Example #6
Source File: SVNTeamProviderType.java    From APICloud-Studio with GNU General Public License v3.0 6 votes vote down vote up
public synchronized static AutoShareJob getAutoShareJob() {
    if (autoShareJob == null) {
        autoShareJob = new AutoShareJob();
        autoShareJob.addJobChangeListener(new JobChangeAdapter() {
            public void done(IJobChangeEvent event) {
                // Reschedule the job if it has unprocessed projects
                if (!autoShareJob.isQueueEmpty()) {
                    autoShareJob.schedule();
                }
            }
        });
        autoShareJob.setSystem(true);
        autoShareJob.setPriority(Job.SHORT);
        // Must run with the workspace rule to ensure that projects added while we're running
        // can be shared
        autoShareJob.setRule(ResourcesPlugin.getWorkspace().getRoot());
    }
    return autoShareJob;
}
 
Example #7
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 #8
Source File: CompositeArtifactsDowloadJobChangeListener.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 6 votes vote down vote up
private JobChangeAdapter getSiteDownloadJobChangeListener(
    final File tempFile, final UpdateSiteToken token) {

  return new JobChangeAdapter() {
    @Override
    public void done(IJobChangeEvent event) {
      IStatus result = event.getResult();
      if (result != null && result.isOK()) {
        Element rootElement = getRootElement(tempFile);
        if (rootElement != null) {
          List<UpdateInfo> updates =
              updateCheckersMap.get(token).checkForUpdates(rootElement);
          assert (updates != null);
          if (!updates.isEmpty()) {
            updateList.addAll(updates);
          }
        }
      }
      // Signal the parent on completion of the download.
      siteXmlDownloadJobsCountDownLatch.countDown();
    }
  };
}
 
Example #9
Source File: PreloadingRepositoryHandler.java    From elexis-3-core with Eclipse Public License 1.0 5 votes vote down vote up
void doExecuteAndLoad(){
	if (preloadRepositories()) {
		// cancel any load that is already running
		Job.getJobManager().cancel(LoadMetadataRepositoryJob.LOAD_FAMILY);
		final LoadMetadataRepositoryJob loadJob =
			new LoadMetadataRepositoryJob(getProvisioningUI());
		setLoadJobProperties(loadJob);
		if (waitForPreload()) {
			loadJob.addJobChangeListener(new JobChangeAdapter() {
				public void done(IJobChangeEvent event){
					if (PlatformUI.isWorkbenchRunning())
						if (event.getResult().isOK()) {
							PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
								public void run(){
									doExecute(loadJob);
								}
							});
						}
				}
			});
			loadJob.setUser(true);
			loadJob.schedule();
			
		} else {
			loadJob.setSystem(true);
			loadJob.setUser(false);
			loadJob.schedule();
			doExecute(null);
		}
	} else {
		doExecute(null);
	}
}
 
Example #10
Source File: AutoConfigMaker.java    From Pydev with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Attempts to automatically find and apply an interpreter of the interpreter type specified
 * in the constructor, in cases when no interpreters of that type are yet configured.
 * @param onConfigComplete An optional JobChangeAdapter to be associated with the configure operation.
 */
public boolean autoConfigSingleApply(JobChangeAdapter onConfigComplete) {
    if (interpreterManager.getInterpreterInfos().length != 0) {
        return false;
    }
    ObtainInterpreterInfoOperation operation = autoConfigSearch();
    //autoConfigSearch displays an error dialog if an interpreter couldn't be found, so don't display errors for null cases here.
    if (operation == null) {
        return false;
    }
    return applyOperation(onConfigComplete, operation, interpreterManager, charWriter, true);
}
 
Example #11
Source File: WizardNewHybridProjectCreationPage.java    From thym with Eclipse Public License 1.0 5 votes vote down vote up
private void checkCordovaIsAvailable() {
	cordovaIsAvailableJob = new CordovaIsAvailableJob();
	cordovaIsAvailableJob.setUser(true);
	cordovaIsAvailableJob.schedule();
	cordovaIsAvailableJob.addJobChangeListener(new JobChangeAdapter() {
		
		@Override
		public void done(IJobChangeEvent event) {
			if(!getControl().isDisposed()){
				final Display display = getControl().getDisplay();
				final int severity = event.getJob().getResult().getSeverity();
				display.syncExec(new Runnable() {
					@Override
					public void run() {
						if(severity == Status.OK){
							if(cordovaIsAvailableJob.getCordovaVersion() != null){
								updateCordovaLabel(cordovaIsAvailableJob.getCordovaVersion(), null, null, true);
							} else {
								updateCordovaLabel(ErrorDetectingCLIResult.CORDOVA_NOT_FOUND, 
										JFaceResources.getImage(DLG_IMG_MESSAGE_ERROR), 
										getControl().getDisplay().getSystemColor(SWT.COLOR_RED), false);
							}
						} else {
							updateCordovaLabel("Unable to determine if cordova is available", 
									JFaceResources.getImage(DLG_IMG_MESSAGE_WARNING), null, true);
						}
					}
					
					private void updateCordovaLabel(String text, Image image, Color foreground , boolean found){
						cordovaLabel.setText(text);
						cordovaLabel.setImage(image);
						cordovaLabel.setForeground(foreground);
						cordovaFound = found;
						setPageComplete(validatePage());
					}
				});
			}
		}
	});
}
 
Example #12
Source File: WidgetModel.java    From thym with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void modelDirtyStateChanged(IStructuredModel model, boolean isDirty) {
	if (!isDirty) {
		synchronized (this) {
			final HybridProject project = getProject();

			final IDOMModel domModel = (IDOMModel) model;

			Job updatePlugins = new Job(
					"Synchronize project " + project.getProject().getName() + " with config.xml") {

				@Override
				protected IStatus run(IProgressMonitor monitor) {
					if (project.getProject().exists()) {
						reloadEditableWidget();
						Widget newWidget = load(domModel.getDocument());
						syncEngines(project, newWidget, monitor);
						syncPlugins(project, newWidget, monitor);
					}
					return Status.OK_STATUS;
				}
			};

			updatePlugins.addJobChangeListener(new JobChangeAdapter() {

				@Override
				public void done(IJobChangeEvent event) {
					lastWidget.reload(domModel.getDocument().getDocumentElement());
					reloadEditableWidget();
					readonlyWidget = null;
					readonlyTimestamp = -1;
				}
			});
			ISchedulingRule rule = ResourcesPlugin.getWorkspace().getRuleFactory().modifyRule(project.getProject());
			updatePlugins.setRule(rule);
			updatePlugins.schedule();
		}
	}
}
 
Example #13
Source File: CheckLoaderDialog.java    From APICloud-Studio with GNU General Public License v3.0 5 votes vote down vote up
public void downloadBaseloader(final Shell shell, int id) {
	try {
		DownLoadJob downloadjob = new DownLoadJob(Messages.DOWNLOADOFFICIALLOADER, id);
		downloadjob.setUser(true);
		downloadjob.schedule();

		downloadjob.addJobChangeListener(new JobChangeAdapter() {
			public void done(IJobChangeEvent event) {
				if (event.getResult().isOK())
					Display.getDefault().syncExec(new Runnable() {
						public void run() {
							MessageDialog.openInformation(null, Messages.DOWNLOADSUCCESS,
									Messages.LOADERDOWNLOADSUCC);
						}
					});
				else
					Display.getDefault().syncExec(new Runnable() {
						public void run() {
							MessageDialog.openError(null, Messages.DOWNLOADEXCEPTION, Messages.DOWNLOADERROR);
						}
					});
				close();
			}
		});

		ResourcesPlugin.getWorkspace().build(
				IncrementalProjectBuilder.CLEAN_BUILD, null);
		ResourcesPlugin.getWorkspace().getRoot()
				.refreshLocal(IResource.DEPTH_INFINITE, null);
	com.apicloud.loader.platforms.android.ADBActivator.setHasBaseLoader(true);
	com.apicloud.loader.platforms.android.ADBActivator.setHasAppLoader(true);
	} catch (Exception e) {
		e.printStackTrace();
	}
}
 
Example #14
Source File: ADBService.java    From APICloud-Studio with GNU General Public License v3.0 5 votes vote down vote up
public void syncLog() throws ADBException {
	if (!logListenning) {
		ScriptingConsole.getInstance().clear();
		ScriptLogger.logError("开启日志监听...");
		logListenning = true;
		Job startADBJob = new Job("Start ADB log") {
			protected IStatus run(IProgressMonitor monitor) {
				if (isStarted) {
					try {
						ADBCmdProcessor.callProcess(new ADBCommand(
								ADBCommand.CMD_TYPE_LOGCAT));
						logListenning = true;
					} catch (ADBException e) {
						e.printStackTrace();
						logListenning = false;
						//throw adbEx;
					}
				}
				return Status.OK_STATUS;
			}
		};
		
		startADBJob.setSystem(true);
		startADBJob.schedule(500L);
		startADBJob.addJobChangeListener(new JobChangeAdapter() {
			public void done(IJobChangeEvent event) {
				if (event.getResult().isOK()) {
					ScriptLogger.logError("\u65AD\u5F00\u8FDE\u63A5...");
					logListenning = false;
				}
			}
		});

	}
}
 
Example #15
Source File: TriStateFilteredCheckboxTree.java    From tracecompass with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected WorkbenchJob doCreateRefreshJob() {
    WorkbenchJob job = super.doCreateRefreshJob();
    job.addJobChangeListener(new JobChangeAdapter() {
        @Override
        public void done(IJobChangeEvent event) {
            if (getCheckboxTreeViewer().getTree().isDisposed()) {
                return;
            }
            maintainAllCheckIntegrity();
        }
    });
    return job;
}
 
Example #16
Source File: AbstractStatsView.java    From eclipse-cs with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Causes the view to re-sync its contents with the workspace. Note that changes will be scheduled
 * in a background job, and may not take effect immediately.
 */
protected final void refresh() {

  @SuppressWarnings("cast")
  final IWorkbenchSiteProgressService service = (IWorkbenchSiteProgressService) getSite()
          .getAdapter(IWorkbenchSiteProgressService.class);

  // rebuild statistics data
  CreateStatsJob job = new CreateStatsJob(getFilter(), getViewId());
  job.setPriority(Job.DECORATE);
  job.setRule(ResourcesPlugin.getWorkspace().getRoot());
  job.addJobChangeListener(new JobChangeAdapter() {
    @Override
    public void done(IJobChangeEvent event) {
      mStats = ((CreateStatsJob) event.getJob()).getStats();
      Job uiJob = new WorkbenchJob(Messages.AbstractStatsView_msgRefreshStats) {

        @Override
        public IStatus runInUIThread(IProgressMonitor monitor) {
          handleStatsRebuilt();
          return Status.OK_STATUS;
        }
      };
      uiJob.setPriority(Job.DECORATE);
      uiJob.setSystem(true);
      uiJob.schedule();
    }
  });
  service.schedule(job, 0, true);
}
 
Example #17
Source File: FactoryEditor.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
public void refresh ()
{
    final LoadFactoryJob job = this.factoryInput.createLoadJob ();
    job.addJobChangeListener ( new JobChangeAdapter () {
        @Override
        public void done ( final IJobChangeEvent event )
        {
            FactoryEditor.this.handleSetResult ( job.getFactory (), FactoryEditor.this.factoryInput.getConnectionUri () );
        }
    } );
    job.schedule ();
}
 
Example #18
Source File: FactoryEditor.java    From neoscada with Eclipse Public License 1.0 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 #19
Source File: DeployConsolePageParticipant.java    From google-cloud-eclipse with Apache License 2.0 5 votes vote down vote up
private void addJobChangeListener() {
  DeployJob job = console.getJob();
  if (job != null) {
    job.addJobChangeListener(new JobChangeAdapter() {
      @Override
      public void done(IJobChangeEvent event) {
        update();
      }
    });
  }
}
 
Example #20
Source File: DeployCommandHandler.java    From google-cloud-eclipse with Apache License 2.0 5 votes vote down vote up
private void launchDeployJob(IProject project, Credential credential)
    throws IOException, CoreException {
  sendAnalyticsPing(AnalyticsEvents.APP_ENGINE_DEPLOY);

  IPath workDirectory = createWorkDirectory();
  DeployPreferences deployPreferences = getDeployPreferences(project);

  DeployConsole messageConsole =
      MessageConsoleUtilities.createConsole(getConsoleName(deployPreferences.getProjectId()),
                                            new DeployConsole.Factory());
  IConsoleManager consoleManager = ConsolePlugin.getDefault().getConsoleManager();
  consoleManager.showConsoleView(messageConsole);
  ConsoleColorProvider colorProvider = new ConsoleColorProvider();
  MessageConsoleStream outputStream = messageConsole.newMessageStream();
  MessageConsoleStream errorStream = messageConsole.newMessageStream();
  outputStream.setActivateOnWrite(true);
  errorStream.setActivateOnWrite(true);
  outputStream.setColor(colorProvider.getColor(IDebugUIConstants.ID_STANDARD_OUTPUT_STREAM));
  errorStream.setColor(colorProvider.getColor(IDebugUIConstants.ID_STANDARD_ERROR_STREAM));

  StagingDelegate stagingDelegate = getStagingDelegate(project);

  DeployJob deploy = new DeployJob(deployPreferences, credential, workDirectory,
      outputStream, errorStream, stagingDelegate);
  messageConsole.setJob(deploy);
  deploy.addJobChangeListener(new JobChangeAdapter() {

    @Override
    public void done(IJobChangeEvent event) {
      if (event.getResult().isOK()) {
        sendAnalyticsPing(AnalyticsEvents.APP_ENGINE_DEPLOY_SUCCESS);
      }
      launchCleanupJob();
    }
  });
  deploy.schedule();
}
 
Example #21
Source File: DeployConsole.java    From google-cloud-eclipse with Apache License 2.0 5 votes vote down vote up
public void setJob(DeployJob newJob) {
  DeployJob oldJob = job;
  job = newJob;
  firePropertyChange(this, PROPERTY_JOB, oldJob, newJob);
  job.addJobChangeListener(new JobChangeAdapter() {
    @Override
    public void done(IJobChangeEvent event) {
      PlatformUI.getWorkbench().getDisplay().asyncExec(() -> {
        setName(Messages.getString("job.terminated.template", getName()));
      });
    }
  });
}
 
Example #22
Source File: ConfigurationEditorInput.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
public void performLoad ( final IProgressMonitor monitor )
{
    final LoadJob job = load ();
    job.addJobChangeListener ( new JobChangeAdapter () {
        @Override
        public void done ( final IJobChangeEvent event )
        {
            handleSetResult ( job.getConfiguration () );
        }
    } );
    job.setProgressGroup ( monitor, 2 );
    job.schedule ();
}
 
Example #23
Source File: ClearMarkersAction.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Clear the FindBugs markers on each project in the given selection,
 * displaying a progress monitor.
 */
@Override
protected void work(final IWorkbenchPart part, IResource resource, final List<WorkItem> resources) {
    FindBugsJob clearMarkersJob = new ClearMarkersJob(resource, resources);
    clearMarkersJob.addJobChangeListener(new JobChangeAdapter() {
        @Override
        public void done(IJobChangeEvent event) {
            refreshViewer(part, resources);
        }
    });
    clearMarkersJob.scheduleInteractive();
}
 
Example #24
Source File: PreloadingRepositoryHandler.java    From translationstudio8 with GNU General Public License v2.0 4 votes vote down vote up
void doExecuteAndLoad() {
	if (preloadRepositories()) {
		// cancel any load that is already running
		final IStatus[] checkStatus = new IStatus[1];
		Job.getJobManager().cancel(LoadMetadataRepositoryJob.LOAD_FAMILY);
		final LoadMetadataRepositoryJob loadJob = new LoadMetadataRepositoryJob(getProvisioningUI()) {
			public IStatus runModal(IProgressMonitor monitor) {
				SubMonitor sub = SubMonitor.convert(monitor, getProgressTaskName(), 1000);
				IStatus status = super.runModal(sub.newChild(500));
				if (status.getSeverity() == IStatus.CANCEL)
					return status;
				if (status.getSeverity() != IStatus.OK) {
					// 记录检查错误
					checkStatus[0] = status;
					return Status.OK_STATUS;
				}
				try {
					doPostLoadBackgroundWork(sub.newChild(500));
				} catch (OperationCanceledException e) {
					return Status.CANCEL_STATUS;
				}
				return status;
			}
		};
		setLoadJobProperties(loadJob);
		loadJob.setName(P2UpdateUtil.CHECK_UPDATE_JOB_NAME);
		if (waitForPreload()) {
			loadJob.addJobChangeListener(new JobChangeAdapter() {
				public void done(IJobChangeEvent event) {
					if (PlatformUI.isWorkbenchRunning())
						if (event.getResult().isOK()) {
							PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
								public void run() {
									if (checkStatus[0] != null) {
										// 提示连接异常
										P2UpdateUtil.openConnectErrorInfoDialog(getShell(),
												P2UpdateUtil.INFO_TYPE_CHECK);
										return;
									}
									doExecute(loadJob);
								}
							});
						}
				}
			});
			loadJob.setUser(true);
			loadJob.schedule();

		} else {
			loadJob.setSystem(true);
			loadJob.setUser(false);
			loadJob.schedule();
			doExecute(null);
		}
	} else {
		doExecute(null);
	}
}
 
Example #25
Source File: FactoryEditor.java    From neoscada with Eclipse Public License 1.0 4 votes vote down vote up
public void handleDelete ()
{
    final ISelection sel = this.viewer.getSelection ();
    if ( sel == null || sel.isEmpty () || ! ( sel instanceof IStructuredSelection ) )
    {
        return;
    }

    final IStructuredSelection selection = (IStructuredSelection)sel;

    final Collection<String> items = new LinkedList<String> ();

    final Iterator<?> i = selection.iterator ();
    while ( i.hasNext () )
    {
        final ConfigurationDescriptor info = (ConfigurationDescriptor)i.next ();
        items.add ( info.getConfigurationInformation ().getId () );
    }

    if ( items.isEmpty () )
    {
        return;
    }

    if ( !MessageDialog.openConfirm ( this.viewer.getControl ().getShell (), "Delete configurations", String.format ( "Delete %s configuration entries", items.size () ) ) )
    {
        return;
    }

    final org.eclipse.core.runtime.jobs.Job job = this.factoryInput.createDeleteJob ( items );
    job.addJobChangeListener ( new JobChangeAdapter () {

        @Override
        public void done ( final IJobChangeEvent event )
        {
            refresh ();
        }

    } );
    job.schedule ();
}
 
Example #26
Source File: AutomaticUpdate.java    From tmxeditor8 with GNU General Public License v2.0 4 votes vote down vote up
public void checkForUpdates() throws OperationCanceledException {
	// 检查 propfile
	String profileId = getProvisioningUI().getProfileId();
	IProvisioningAgent agent = getProvisioningUI().getSession().getProvisioningAgent();
	IProfile profile = null;
	if (agent != null) {
		IProfileRegistry registry = (IProfileRegistry) agent.getService(IProfileRegistry.SERVICE_NAME);
		if (registry != null) {
			profile = registry.getProfile(profileId);
		}
	}
	if (profile == null) {
		// Inform the user nicely
		P2UpdateUtil.openConnectErrorInfoDialog(getShell(), P2UpdateUtil.INFO_TYPE_AUTO_CHECK);
		return;
	}

	// 开始检查前先确定是否有repository
	RepositoryTracker repoMan = getProvisioningUI().getRepositoryTracker();
	if (repoMan.getKnownRepositories(getProvisioningUI().getSession()).length == 0) {
		P2UpdateUtil.openConnectErrorInfoDialog(getShell(), P2UpdateUtil.INFO_TYPE_AUTO_CHECK);
		return;
	}

	final IStatus[] checkStatus = new IStatus[1];
	Job.getJobManager().cancel(LoadMetadataRepositoryJob.LOAD_FAMILY);
	final LoadMetadataRepositoryJob loadJob = new LoadMetadataRepositoryJob(getProvisioningUI()) {
		public IStatus runModal(IProgressMonitor monitor) {
			SubMonitor sub = SubMonitor.convert(monitor, P2UpdateUtil.CHECK_UPDATE_TASK_NAME, 1000);
			// load repository
			IStatus status = super.runModal(sub.newChild(500));
			if (status.getSeverity() == IStatus.CANCEL) {
				return status;
			}
			if (status.getSeverity() != Status.OK) {
				// load repository error
				checkStatus[0] = status;
			}
			operation = getProvisioningUI().getUpdateOperation(null, null);
			// check for updates
			IStatus resolveStatus = operation.resolveModal(sub.newChild(500));
			if (resolveStatus.getSeverity() == IStatus.CANCEL) {
				return Status.CANCEL_STATUS;
			}
			return Status.OK_STATUS;
		}
	};
	loadJob.setName(P2UpdateUtil.ATUO_CHECK_UPDATE_JOB_NAME);
	loadJob.setProperty(LoadMetadataRepositoryJob.ACCUMULATE_LOAD_ERRORS, Boolean.toString(true));
	loadJob.addJobChangeListener(new JobChangeAdapter() {
		public void done(IJobChangeEvent event) {
			if (PlatformUI.isWorkbenchRunning())
				if (event.getResult().isOK()) {
					PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
						public void run() {
							if (checkStatus[0] != null) {
								// 提示连接异常
								P2UpdateUtil.openConnectErrorInfoDialog(getShell(),
										P2UpdateUtil.INFO_TYPE_AUTO_CHECK);
								return;
							}
							doUpdate();
						}
					});
				}
		}
	});
	loadJob.setUser(true);
	loadJob.schedule();
}
 
Example #27
Source File: PreloadingRepositoryHandler.java    From tmxeditor8 with GNU General Public License v2.0 4 votes vote down vote up
void doExecuteAndLoad() {
	if (preloadRepositories()) {
		// cancel any load that is already running
		final IStatus[] checkStatus = new IStatus[1];
		Job.getJobManager().cancel(LoadMetadataRepositoryJob.LOAD_FAMILY);
		final LoadMetadataRepositoryJob loadJob = new LoadMetadataRepositoryJob(getProvisioningUI()) {
			public IStatus runModal(IProgressMonitor monitor) {
				SubMonitor sub = SubMonitor.convert(monitor, getProgressTaskName(), 1000);
				IStatus status = super.runModal(sub.newChild(500));
				if (status.getSeverity() == IStatus.CANCEL)
					return status;
				if (status.getSeverity() != IStatus.OK) {
					// 记录检查错误
					checkStatus[0] = status;
					return Status.OK_STATUS;
				}
				try {
					doPostLoadBackgroundWork(sub.newChild(500));
				} catch (OperationCanceledException e) {
					return Status.CANCEL_STATUS;
				}
				return status;
			}
		};
		setLoadJobProperties(loadJob);
		loadJob.setName(P2UpdateUtil.CHECK_UPDATE_JOB_NAME);
		if (waitForPreload()) {
			loadJob.addJobChangeListener(new JobChangeAdapter() {
				public void done(IJobChangeEvent event) {
					if (PlatformUI.isWorkbenchRunning())
						if (event.getResult().isOK()) {
							PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
								public void run() {
									if (checkStatus[0] != null) {
										// 提示连接异常
										P2UpdateUtil.openConnectErrorInfoDialog(getShell(),
												P2UpdateUtil.INFO_TYPE_CHECK);
										return;
									}
									doExecute(loadJob);
								}
							});
						}
				}
			});
			loadJob.setUser(true);
			loadJob.schedule();

		} else {
			loadJob.setSystem(true);
			loadJob.setUser(false);
			loadJob.schedule();
			doExecute(null);
		}
	} else {
		doExecute(null);
	}
}
 
Example #28
Source File: TaskJobHandler.java    From orion.server with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Schedules {@link TaskJob} and handles response. If job lasts more than {@link this#WAIT_TIME}
 * handler starts a task and returns 202 (Accepted) response with task details. If job finishes sooner the
 * response if immediately returned filled with {@link TaskJob#getResult()}, if result is OK, than only
 * {@link ServerStatus#getJsonData()} is returned, if result is OK and it is not an instance of {@link ServerStatus}
 * than {@link TaskJob#getFinalResult()} is returned as a response content.
 * 
 * @param request
 * @param response
 * @param job Job that should be handled as a task.
 * @param statusHandler status handler to handle error statuses.
 * @return <code>true</code> if job was handled properly.
 * @throws IOException
 * @throws ServletException
 * @throws URISyntaxException
 * @throws JSONException
 */
public static boolean handleTaskJob(HttpServletRequest request, HttpServletResponse response, TaskJob job, ServletResourceHandler<IStatus> statusHandler, IURIUnqualificationStrategy strategy) throws IOException, ServletException, URISyntaxException, JSONException {
	final Object jobIsDone = new Object();
	final JobChangeAdapter jobListener = new JobChangeAdapter() {
		public void done(IJobChangeEvent event) {
			synchronized (jobIsDone) {
				jobIsDone.notify();
			}
		}
	};
	job.addJobChangeListener(jobListener);

	job.schedule();

	try {
		synchronized (jobIsDone) {
			if (job.getState() != Job.NONE) {
				jobIsDone.wait(WAIT_TIME);
			}
		}
	} catch (InterruptedException e) {
	}
	job.removeJobChangeListener(jobListener);

	if (job.getState() == Job.NONE || job.getRealResult() != null) {
		if (job.getRealResult() == null) {
			logger.error("Job RealResult is null result=" + job.getResult(), job.getResult() != null ? job.getResult().getException() : null);
		}
		return writeResult(request, response, job, statusHandler, strategy);
	} else {
		TaskInfo task = job.startTask();
		task.setUnqualificationStrategy(strategy);
		JSONObject result = task.toJSON();
		URI taskLocation = createTaskLocation(ServletResourceHandler.getURI(request), task.getId(), task.isKeep());
		result.put(ProtocolConstants.KEY_LOCATION, taskLocation);
		if (!task.isRunning()) {
			job.removeTask(); // Task is not used, we may remove it
			return writeResult(request, response, job, statusHandler, strategy);
		}
		response.setHeader(ProtocolConstants.HEADER_LOCATION, ServletResourceHandler.resovleOrionURI(request, taskLocation).toString());
		OrionServlet.writeJSONResponse(request, response, result, strategy);
		response.setStatus(HttpServletResponse.SC_ACCEPTED);
		return true;
	}
}
 
Example #29
Source File: UpdateManager.java    From developer-studio with Apache License 2.0 4 votes vote down vote up
/**
 * Install selected features in to developer studio. Note: call
 * {@link #setSelectedFeaturesToInstall(List) setSelectedFeaturesToInstall}
 * first.
 * 
 * @param monitor
 */
public void installSelectedFeatures(IProgressMonitor monitor) {
	SubMonitor progress = SubMonitor.convert(monitor, Messages.UpdateManager_32, 2);

	URI[] repos = new URI[] { getDevStudioReleaseSite() };
	session = new ProvisioningSession(p2Agent);
	installOperation = new InstallOperation(session, selectedFeatures);
	installOperation.getProvisioningContext().setArtifactRepositories(repos);
	installOperation.getProvisioningContext().setMetadataRepositories(repos);
	IStatus status = installOperation.resolveModal(progress.newChild(1));
	if (status.getSeverity() == IStatus.CANCEL || progress.isCanceled()) {
		throw new OperationCanceledException();
	} else if (status.getSeverity() == IStatus.ERROR) {
		String message = status.getChildren()[0].getMessage();
		log.error(Messages.UpdateManager_33 + message);
		UpdateMetaFileReaderJob.promptUserError(message, Messages.UpdateManager_33);
	} else {
		ProvisioningJob provisioningJob = installOperation.getProvisioningJob(progress.newChild(1));
		if (provisioningJob != null) {
			provisioningJob.addJobChangeListener(new JobChangeAdapter() {
				@Override
				public void done(IJobChangeEvent arg0) {
					Display.getDefault().syncExec(new Runnable() {
						@Override
						public void run() {
							boolean restart = MessageDialog.openQuestion(Display.getDefault().getActiveShell(),
									Messages.UpdateManager_34,
									Messages.UpdateManager_35 + Messages.UpdateManager_36);
							if (restart) {
								PlatformUI.getWorkbench().restart();
							}
						}
					});
				}
			});
			provisioningJob.schedule();
			Display.getDefault().syncExec(new Runnable() {
				@Override
				public void run() {
					try {
						PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage()
								.showView(IProgressConstants.PROGRESS_VIEW_ID);
					} catch (PartInitException e) {
						log.error(e);
					}
				}
			});
		} else {
			log.error(Messages.UpdateManager_37);
		}
	}
}
 
Example #30
Source File: UpdateManager.java    From developer-studio with Apache License 2.0 4 votes vote down vote up
/**
 * Install selected updates in to developer studio. Note: call
 * {@link #setSelectedUpdates(List) setSelectedUpdates} first.
 * 
 * @param monitor
 */
public void installSelectedUpdates(IProgressMonitor monitor) {
	SubMonitor progress = SubMonitor.convert(monitor, Messages.UpdateManager_26, 2);
	URI[] repos = new URI[] { getDevStudioUpdateSite() };
	session = new ProvisioningSession(p2Agent);
	updateOperation = new UpdateOperation(session);
	updateOperation.getProvisioningContext().setArtifactRepositories(repos);
	updateOperation.getProvisioningContext().setMetadataRepositories(repos);

	updateOperation.setSelectedUpdates(selectedUpdates);
	IStatus status = updateOperation.resolveModal(progress.newChild(1));
	if (status.getSeverity() == IStatus.CANCEL) {
		throw new OperationCanceledException();
	} else if (status.getSeverity() == IStatus.ERROR) {
		String message = status.getChildren()[0].getMessage();
		UpdateMetaFileReaderJob.promptUserError(message, Messages.UpdateManager_27);
		log.error(Messages.UpdateManager_27 + message);
	} else {
		final ProvisioningJob provisioningJob = updateOperation.getProvisioningJob(progress.newChild(1));
		if (provisioningJob != null) {
			provisioningJob.addJobChangeListener(new JobChangeAdapter() {
				@Override
				public void done(IJobChangeEvent arg0) {
					Display.getDefault().syncExec(new Runnable() {
						@Override
						public void run() {
							boolean restart = MessageDialog.openQuestion(Display.getDefault().getActiveShell(),
									Messages.UpdateManager_28,
									Messages.UpdateManager_29 + Messages.UpdateManager_30);
							if (restart) {
								PlatformUI.getWorkbench().restart();
							}
						}
					});
				}
			});
			provisioningJob.schedule();
			Display.getDefault().syncExec(new Runnable() {
				@Override
				public void run() {
					try {
						PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage()
								.showView(IProgressConstants.PROGRESS_VIEW_ID);
					} catch (PartInitException e) {
						log.error(e);
					}
				}
			});
		} else {
			log.error(Messages.UpdateManager_31);
		}
	}
}