List of usage examples for java.util Timer cancel
public void cancel()
From source file:no.feide.moria.directory.backend.JNDIBackend.java
/** * Does a subtree search for an element given a pattern. Only the first * element found is considered, and all references are searched in order * until either a match is found or no more references are left to search. * @param ldap/*from w ww.j a va 2 s. c om*/ * A prepared LDAP context. * @param pattern * The search pattern. Must not include the character '*' or the * substring '\2a' to prevent possible LDAP exploits. * @return The element's relative DN, or <code>null</code> if none was * found. <code>null</code> is also returned if the search pattern * contains an illegal character or substring. * @throws BackendException * If there was a problem accessing the backend. Typical causes * include timeouts. */ private String ldapSearch(final InitialLdapContext ldap, final String pattern) throws BackendException { // Check pattern for illegal content. String[] illegals = { "*", "\\2a" }; for (int i = 0; i < illegals.length; i++) { if (pattern.indexOf(illegals[i]) > -1) return null; } // The context provider URL, for later logging. String url = "unknown backend"; // Start counting the (milli)seconds and prepare for timeouts. long searchStart = System.currentTimeMillis(); JNDISearchInterruptor interruptTask = new JNDISearchInterruptor(ldap, mySessionTicket); NamingEnumeration results; try { // Remember the URL, for later logging. url = (String) ldap.getEnvironment().get(Context.PROVIDER_URL); interruptTask.setURL(url); // Start timeout interruptor and perform the search. Timer interruptTimer = new Timer(); interruptTimer.schedule(interruptTask, (1000 * myTimeout)); results = ldap.search("", pattern, new SearchControls(SearchControls.SUBTREE_SCOPE, 0, 1000 * myTimeout, new String[] {}, false, false)); interruptTimer.cancel(); if (!results.hasMore()) return null; } catch (TimeLimitExceededException e) { // The search timed out. log.logWarn("Search on " + url + " for " + pattern + " timed out after ~" + (System.currentTimeMillis() - searchStart) + "ms", mySessionTicket); return null; } catch (SizeLimitExceededException e) { // The search returned too many results. log.logWarn("Search on " + url + " for " + pattern + " returned too many results", mySessionTicket); return null; } catch (NameNotFoundException e) { // Element not found. Possibly non-existing reference. log.logDebug("Could not find " + pattern + " on " + url, mySessionTicket); // Necessary? return null; } catch (AuthenticationException e) { // Search failed authentication; check non-anonymous search config. try { final String searchUser = (String) ldap.getEnvironment().get(Context.SECURITY_PRINCIPAL); final String errorMessage; if ((searchUser == null) || searchUser.equals("")) errorMessage = "Anonymous search failed authentication on " + url; else errorMessage = "Could not authenticate search user " + searchUser + " on " + url; log.logDebug(errorMessage, mySessionTicket); throw new BackendException(errorMessage, e); } catch (NamingException f) { // Should not happen! log.logCritical("Unable to read LDAP environment", mySessionTicket, f); throw new BackendException("Unable to read LDAP environment", f); } } catch (NamingException e) { // Did we interrupt the search ourselves? if (interruptTask.finished()) { final long elapsed = System.currentTimeMillis() - searchStart; log.logWarn("Search on " + url + " for " + pattern + " timed out after ~" + elapsed + "ms", mySessionTicket); throw new BackendException("Search on " + url + " for " + pattern + " timed out after ~" + elapsed + "ms; connection terminated"); } // All other exceptions. log.logWarn("Search on " + url + " for " + pattern + " failed", mySessionTicket, e); return null; } // We just found at least one element. Did we get an ambigious result? SearchResult entry = null; try { entry = (SearchResult) results.next(); String buffer = new String(); while (results.hasMoreElements()) buffer = buffer + ", " + ((SearchResult) results.next()).getName(); if (!buffer.equals("")) log.logWarn("Search on " + url + " for " + pattern + " gave ambiguous result: [" + entry.getName() + buffer + "]", mySessionTicket); // TODO: Throw BackendException, or a subclass, or just (as now) // pick the first and hope for the best? buffer = null; } catch (NamingException e) { throw new BackendException("Unable to read search results", e); } return entry.getName(); // Relative DN (to the reference). }
From source file:org.hubiquitus.hapi.client.HClient.java
/** * Notify message delegate of an incoming hmessage. If the callback is not set, it will call onMessage. * If the callback is set in the service functions, it will call the callback function instead of onMessage * @param message the received message//from ww w.j a v a2 s. c o m */ private void notifyMessage(final HMessage message, HMessageDelegate messageDelegate) { MyRunnable arun = new MyRunnable(); String apiRef = HUtil.getApiRef(message.getRef()); // 1 we search the delegate with the ref if any if (!this.messagesDelegates.isEmpty() && message.getRef() != null && this.messagesDelegates.containsKey(HUtil.getApiRef(message.getRef()))) { if (this.timeoutHashtable.containsKey(apiRef)) { Timer timeout = timeoutHashtable.get(apiRef); timeoutHashtable.remove(apiRef); if (timeout != null) { timeout.cancel(); } } arun.delegate2Use = this.messagesDelegates.get(HUtil.getApiRef(message.getRef())); messagesDelegates.remove(apiRef); } // 2 - if the ref can not provide a delegate, we try the parameter sent else if (messageDelegate != null) { arun.delegate2Use = messageDelegate; } else { // in other cases we try the default delegate message arun.delegate2Use = this.messageDelegate; } try { if (arun.delegate2Use != null) { // return message asynchronously arun.message = message; new Thread(arun).start(); } } catch (Exception e) { logger.error("message: ", e); } }
From source file:org.pentaho.di.ui.spoon.trans.TransPerfDelegate.java
public void setupContent() { // there is a potential infinite loop below if this method // is called when the transgraph is not running, so we check // early to make sure it won't happen (see PDI-5009) if (!transGraph.isRunning() || transGraph.trans == null || !transGraph.trans.getTransMeta().isCapturingStepPerformanceSnapShots()) { showEmptyGraph();/* ww w . ja v a 2 s . c o m*/ return; // TODO: display help text and rerty button } if (perfComposite.isDisposed()) { return; } // Remove anything on the perf composite, like an empty page message // for (Control control : perfComposite.getChildren()) { if (!control.isDisposed()) { control.dispose(); } } emptyGraph = false; this.title = transGraph.trans.getTransMeta().getName(); this.timeDifference = transGraph.trans.getTransMeta().getStepPerformanceCapturingDelay(); this.stepPerformanceSnapShots = transGraph.trans.getStepPerformanceSnapShots(); // Wait a second for the first data to pour in... // TODO: make this wait more elegant... // while (this.stepPerformanceSnapShots == null || stepPerformanceSnapShots.isEmpty()) { this.stepPerformanceSnapShots = transGraph.trans.getStepPerformanceSnapShots(); try { Thread.sleep(100L); } catch (InterruptedException e) { // Ignore errors } } Set<String> stepsSet = stepPerformanceSnapShots.keySet(); steps = stepsSet.toArray(new String[stepsSet.size()]); Arrays.sort(steps); // Display 2 lists with the data types and the steps on the left side. // Then put a canvas with the graph on the right side // Label dataListLabel = new Label(perfComposite, SWT.NONE); dataListLabel.setText(BaseMessages.getString(PKG, "StepPerformanceSnapShotDialog.Metrics.Label")); spoon.props.setLook(dataListLabel); FormData fdDataListLabel = new FormData(); fdDataListLabel.left = new FormAttachment(0, 0); fdDataListLabel.right = new FormAttachment(spoon.props.getMiddlePct() / 2, Const.MARGIN); fdDataListLabel.top = new FormAttachment(0, Const.MARGIN + 5); dataListLabel.setLayoutData(fdDataListLabel); dataList = new org.eclipse.swt.widgets.List(perfComposite, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL | SWT.LEFT | SWT.BORDER); spoon.props.setLook(dataList); dataList.setItems(dataChoices); dataList.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { // If there are multiple selections here AND there are multiple selections in the steps list, we only take the // first step in the selection... // if (dataList.getSelectionCount() > 1 && stepsList.getSelectionCount() > 1) { stepsList.setSelection(stepsList.getSelectionIndices()[0]); } updateGraph(); } }); FormData fdDataList = new FormData(); fdDataList.left = new FormAttachment(0, 0); fdDataList.right = new FormAttachment(spoon.props.getMiddlePct() / 2, Const.MARGIN); fdDataList.top = new FormAttachment(dataListLabel, Const.MARGIN); fdDataList.bottom = new FormAttachment(40, Const.MARGIN); dataList.setLayoutData(fdDataList); Label stepsListLabel = new Label(perfComposite, SWT.NONE); stepsListLabel.setText(BaseMessages.getString(PKG, "StepPerformanceSnapShotDialog.Steps.Label")); spoon.props.setLook(stepsListLabel); FormData fdStepsListLabel = new FormData(); fdStepsListLabel.left = new FormAttachment(0, 0); fdStepsListLabel.right = new FormAttachment(spoon.props.getMiddlePct() / 2, Const.MARGIN); fdStepsListLabel.top = new FormAttachment(dataList, Const.MARGIN); stepsListLabel.setLayoutData(fdStepsListLabel); stepsList = new org.eclipse.swt.widgets.List(perfComposite, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL | SWT.LEFT | SWT.BORDER); spoon.props.setLook(stepsList); stepsList.setItems(steps); stepsList.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { // If there are multiple selections here AND there are multiple selections in the data list, we only take the // first data item in the selection... // if (dataList.getSelectionCount() > 1 && stepsList.getSelectionCount() > 1) { dataList.setSelection(dataList.getSelectionIndices()[0]); } updateGraph(); } }); FormData fdStepsList = new FormData(); fdStepsList.left = new FormAttachment(0, 0); fdStepsList.right = new FormAttachment(spoon.props.getMiddlePct() / 2, Const.MARGIN); fdStepsList.top = new FormAttachment(stepsListLabel, Const.MARGIN); fdStepsList.bottom = new FormAttachment(100, Const.MARGIN); stepsList.setLayoutData(fdStepsList); canvas = new Canvas(perfComposite, SWT.NONE); spoon.props.setLook(canvas); FormData fdCanvas = new FormData(); fdCanvas.left = new FormAttachment(spoon.props.getMiddlePct() / 2, Const.MARGIN); fdCanvas.right = new FormAttachment(100, 0); fdCanvas.top = new FormAttachment(0, Const.MARGIN); fdCanvas.bottom = new FormAttachment(100, 0); canvas.setLayoutData(fdCanvas); perfComposite.addControlListener(new ControlAdapter() { public void controlResized(ControlEvent event) { updateGraph(); } }); perfComposite.addDisposeListener(new DisposeListener() { public void widgetDisposed(DisposeEvent event) { if (image != null) { image.dispose(); } } }); canvas.addPaintListener(new PaintListener() { public void paintControl(PaintEvent event) { if (image != null && !image.isDisposed()) { event.gc.drawImage(image, 0, 0); } } }); // Refresh automatically every 5 seconds as well. // final Timer timer = new Timer("TransPerfDelegate Timer"); timer.schedule(new TimerTask() { public void run() { updateGraph(); } }, 0, 5000); // When the tab is closed, we remove the update timer // transPerfTab.addDisposeListener(new DisposeListener() { public void widgetDisposed(DisposeEvent arg0) { timer.cancel(); } }); }
From source file:hudson.plugins.blazemeter.PerformanceBuilder.java
@Override public void perform(@Nonnull Run<?, ?> run, @Nonnull FilePath workspace, @Nonnull Launcher launcher, @Nonnull TaskListener listener) throws InterruptedException, IOException { if (!validateTestId(listener)) { run.setResult(Result.FAILURE); return;//from w w w . j ava 2 s . com } BlazemeterCredentialsBAImpl credentials = Utils.findCredentials(credentialsId, CredentialsScope.GLOBAL); boolean isValidCredentials = !StringUtils.isBlank(credentialsId) && validateCredentials(credentials); if (!isValidCredentials) { listener.error(BzmJobNotifier.formatMessage("Can not start build: Invalid credentials=" + credentialsId + "... is deprecated or absent in credentials store.")); run.setResult(Result.NOT_BUILT); return; } String serverUrlConfig = BlazeMeterPerformanceBuilderDescriptor.getDescriptor().getBlazeMeterURL(); String jobName = run.getFullDisplayName(); VirtualChannel channel = launcher.getChannel(); final long reportLinkId = System.currentTimeMillis(); EnvVars envVars = run.getEnvironment(listener); BzmBuild bzmBuild = new BzmBuild(this, credentials.getUsername(), credentials.getPassword().getPlainText(), jobName, run.getId(), StringUtils.isBlank(serverUrlConfig) ? Constants.A_BLAZEMETER_COM : serverUrlConfig, envVars, workspace, listener, ProxyConfiguration.load(), !(channel instanceof LocalChannel), envVars.expand(reportLinkName), reportLinkId); ReportUrlTask reportUrlTask = new ReportUrlTask(run, jobName, channel, reportLinkId); Timer timer = new Timer(true); timer.scheduleAtFixedRate(reportUrlTask, 20 * 1000, 10 * 1000); try { Result result = channel.call(bzmBuild); run.setResult(result); } catch (InterruptedException e) { LOGGER.warning("Build has been aborted"); // start new task for wait Slave InterruptListenerTask interrupt = new InterruptListenerTask(run, jobName, channel); interrupt.start(); interrupt.join(); run.setResult(Result.ABORTED); } catch (Exception e) { listener.getLogger().println(BzmJobNotifier.formatMessage("Failure with exception: " + e.getMessage())); e.printStackTrace(listener.getLogger()); run.setResult(Result.FAILURE); } finally { reportUrlTask.cancel(); timer.cancel(); timer.purge(); } }
From source file:com.googlecode.ehcache.annotations.RefreshingSelfPopulatingCache.java
public RefreshingSelfPopulatingCache(Ehcache cache, CacheEntryFactory cacheEntryFactory, TaskSchedulerAdapter scheduler, TaskExecutor executer, long refreshInterval) { super(cache, cacheEntryFactory); final Timer timer; if (scheduler == null) { timer = new Timer(cache.getName() + " Cache Refresh Timer", true); this.scheduler = new TimerTaskSchedulerAdapter(timer); } else {/*from ww w. ja v a 2s. co m*/ timer = null; this.scheduler = scheduler; } this.executer = executer; this.refreshInterval = refreshInterval; this.scheduleRefreshTask(); //Register a listener with the cache manager to make sure we clear out our timer thread cleanly this.getCacheManager().setCacheManagerEventListener(new CacheManagerEventListener() { public void notifyCacheRemoved(String cacheName) { } public void notifyCacheAdded(String cacheName) { } public void init() throws CacheException { } public Status getStatus() { return null; } public void dispose() throws CacheException { if (timer != null) { timer.cancel(); } } }); }
From source file:org.wso2.emm.system.service.api.OTAServerManager.java
/** * Downloads the property list from remote site, and parse it to property list. * The caller can parse this list and get information. *//* www . ja va2 s. c o m*/ public void getTargetPackagePropertyList(final URL url) { final String operation = Preference.getBoolean(context, context.getResources().getString(R.string.firmware_status_check_in_progress)) ? Constants.Operation.GET_FIRMWARE_UPGRADE_PACKAGE_STATUS : Constants.Operation.UPGRADE_FIRMWARE; if (asyncTask != null) { asyncTask.cancel(true); } asyncTask = new AsyncTask<Void, Void, Void>() { protected Void doInBackground(Void... param) { InputStream reader = null; ByteArrayOutputStream writer = null; BuildPropParser parser = null; final int bufSize = 1024; // First, trying to download the property list file. the build.prop of target image. try { URLConnection urlConnection; /* Use the URL configuration to open a connection to the OTA server */ urlConnection = url.openConnection(); urlConnection.setConnectTimeout(Constants.FIRMWARE_UPGRADE_CONNECTIVITY_TIMEOUT); urlConnection.setReadTimeout(Constants.FIRMWARE_UPGRADE_READ_TIMEOUT); /* Since you get a URLConnection, use it to get the InputStream */ reader = urlConnection.getInputStream(); /* Now that the InputStream is open, get the content length */ final int contentLength = urlConnection.getContentLength(); byte[] buffer = new byte[bufSize]; if (contentLength != -1) { writer = new ByteArrayOutputStream(contentLength); } else { writer = new ByteArrayOutputStream(DEFAULT_STREAM_LENGTH); } int totalBufRead = 0; int bytesRead; Timer timer = new Timer(); Log.d(TAG, "Start download: " + url.toString() + " to buffer"); while ((bytesRead = reader.read(buffer)) > 0) { // Write current segment into byte output stream writer.write(buffer, 0, bytesRead); Log.d(TAG, "wrote " + bytesRead + " into byte output stream"); totalBufRead += bytesRead; buffer = new byte[bufSize]; timer.cancel(); timer = new Timer(); timer.schedule(new Timeout(this), Constants.FIRMWARE_UPGRADE_READ_TIMEOUT); } Log.d(TAG, "Download finished: " + (Integer.toString(totalBufRead)) + " bytes downloaded"); parser = new BuildPropParser(writer, context); timer.cancel(); } catch (SocketTimeoutException e) { String message = "Connection failure (Socket timeout) when retrieving update package size."; Log.e(TAG, message + e); CommonUtils.sendBroadcast(context, operation, Constants.Code.FAILURE, Constants.Status.CONNECTION_FAILED, message); CommonUtils.callAgentApp(context, Constants.Operation.FAILED_FIRMWARE_UPGRADE_NOTIFICATION, 0, null); } catch (IOException e) { String message = "Property list (build.prop) not found in the server."; Log.e(TAG, message + e); CommonUtils.sendBroadcast(context, operation, Constants.Code.FAILURE, Constants.Status.FILE_NOT_FOUND, message); CommonUtils.callAgentApp(context, Constants.Operation.FAILED_FIRMWARE_UPGRADE_NOTIFICATION, 0, null); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { Log.e(TAG, "Failed to close buffer reader." + e); } } if (writer != null) { try { writer.close(); } catch (IOException e) { Log.e(TAG, "Failed to close buffer writer." + e); } } if (parser != null) { if (stateChangeListener != null) { stateChangeListener.onStateOrProgress(OTAStateChangeListener.STATE_IN_CHECKED, OTAStateChangeListener.NO_ERROR, parser, DEFAULT_STATE_INFO_CODE); } } else { reportCheckingError(OTAStateChangeListener.ERROR_CANNOT_FIND_SERVER); } } return null; } }.executeOnExecutor(threadPoolExecutor); }
From source file:org.wso2.iot.system.service.api.OTAServerManager.java
/** * Downloads the property list from remote site, and parse it to property list. * The caller can parse this list and get information. */// ww w . j a va 2 s . c o m public void getTargetPackagePropertyList(final URL url) { final String operation = Preference.getBoolean(context, context.getResources().getString(R.string.firmware_status_check_in_progress)) ? Constants.Operation.GET_FIRMWARE_UPGRADE_PACKAGE_STATUS : Constants.Operation.UPGRADE_FIRMWARE; if (asyncTask != null) { asyncTask.cancel(true); } asyncTask = new AsyncTask<Void, Void, Void>() { protected Void doInBackground(Void... param) { InputStream reader = null; ByteArrayOutputStream writer = null; BuildPropParser parser = null; final int bufSize = 1024; // First, trying to download the property list file. the build.prop of target image. try { URLConnection urlConnection; /* Use the URL configuration to open a connection to the OTA server */ urlConnection = url.openConnection(); urlConnection.setConnectTimeout(Constants.FIRMWARE_UPGRADE_CONNECTIVITY_TIMEOUT); urlConnection.setReadTimeout(Constants.FIRMWARE_UPGRADE_READ_TIMEOUT); /* Since you get a URLConnection, use it to get the InputStream */ reader = urlConnection.getInputStream(); /* Now that the InputStream is open, get the content length */ final int contentLength = urlConnection.getContentLength(); byte[] buffer = new byte[bufSize]; if (contentLength != -1) { writer = new ByteArrayOutputStream(contentLength); } else { writer = new ByteArrayOutputStream(DEFAULT_STREAM_LENGTH); } int totalBufRead = 0; int bytesRead; Timer timer = new Timer(); Log.d(TAG, "Start download: " + url.toString() + " to buffer"); while ((bytesRead = reader.read(buffer)) > 0) { // Write current segment into byte output stream writer.write(buffer, 0, bytesRead); Log.d(TAG, "wrote " + bytesRead + " into byte output stream"); totalBufRead += bytesRead; buffer = new byte[bufSize]; timer.cancel(); timer = new Timer(); timer.schedule(new Timeout(this), Constants.FIRMWARE_UPGRADE_READ_TIMEOUT); } Log.d(TAG, "Download finished: " + (Integer.toString(totalBufRead)) + " bytes downloaded"); parser = new BuildPropParser(writer, context); timer.cancel(); } catch (SocketTimeoutException e) { String message = "Connection failure (Socket timeout) when retrieving update package size."; Log.e(TAG, message + e); CommonUtils.sendBroadcast(context, operation, Constants.Code.FAILURE, Constants.Status.CONNECTION_FAILED, message); CommonUtils.callAgentApp(context, Constants.Operation.FAILED_FIRMWARE_UPGRADE_NOTIFICATION, Preference.getInt(context, context.getResources().getString(R.string.operation_id)), message); } catch (IOException e) { String message = "Property list (build.prop) not found in the server."; Log.e(TAG, message + e); CommonUtils.sendBroadcast(context, operation, Constants.Code.FAILURE, Constants.Status.FILE_NOT_FOUND, message); CommonUtils.callAgentApp(context, Constants.Operation.FAILED_FIRMWARE_UPGRADE_NOTIFICATION, Preference.getInt(context, context.getResources().getString(R.string.operation_id)), message); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { Log.e(TAG, "Failed to close buffer reader." + e); } } if (writer != null) { try { writer.close(); } catch (IOException e) { Log.e(TAG, "Failed to close buffer writer." + e); } } if (parser != null) { if (stateChangeListener != null) { stateChangeListener.onStateOrProgress(OTAStateChangeListener.STATE_IN_CHECKED, OTAStateChangeListener.NO_ERROR, parser, DEFAULT_STATE_INFO_CODE); } } else { reportCheckingError(OTAStateChangeListener.ERROR_CANNOT_FIND_SERVER); } } return null; } }.executeOnExecutor(threadPoolExecutor); }
From source file:org.eclipse.jubula.client.core.ClientTest.java
/** {@inheritDoc} */ public Map<String, String> requestAutConfigMapFromAgent(String autId) { Map<String, String> autConfigMap = null; GetAutConfigMapMessage message = new GetAutConfigMapMessage(autId); GetAutConfigMapResponseCommand response = new GetAutConfigMapResponseCommand(); try {/* ww w . j ava 2 s .c o m*/ AutAgentConnection.getInstance().request(message, response, REQUEST_CONFIG_MAP_TIMEOUT); final AtomicBoolean timeoutFlag = new AtomicBoolean(true); final Timer timerTimeout = new Timer(); timerTimeout.schedule(new TimerTask() { public void run() { timeoutFlag.set(false); timerTimeout.cancel(); } }, REQUEST_CONFIG_MAP_TIMEOUT); while (!response.hasReceivedResponse() && timeoutFlag.get()) { TimeUtil.delay(200); log.info(Messages.WaitingForAutConfigMapFromAgent); } autConfigMap = response.getAutConfigMap(); } catch (NotConnectedException nce) { log.error(nce.getLocalizedMessage(), nce); } catch (CommunicationException ce) { log.error(ce.getLocalizedMessage(), ce); } return autConfigMap; }
From source file:org.eclipse.jubula.client.core.ClientTestImpl.java
/** * creating the job that is building and writing test data to DB. * @param result The test results //from w w w . j a v a2s .com */ private void createReportJob(final TestResult result) { final AtomicBoolean ab = new AtomicBoolean(false); final Job job = new Job(Messages.ClientCollectingInformation) { private String m_jobFamily = this.getName(); public boolean belongsTo(Object family) { return m_jobFamily.equals(family); } protected IStatus run(IProgressMonitor monitor) { try { monitor.beginTask(Messages.ClientWritingReportToDB, IProgressMonitor.UNKNOWN); ITestResultSummaryPO summary = writeTestresultToDB(result); if (m_logPath != null) { monitor.beginTask(Messages.ClientWritingReport, IProgressMonitor.UNKNOWN); writeReportToFileSystem(result); } if (isRunningWithMonitoring()) { monitor.setTaskName(Messages.ClientCalculating); getMonitoringData(); while (result.getMonitoringValues() == null || result.getMonitoringValues().isEmpty()) { TimeUtil.delay(500); if (result.getMonitoringValues() != null) { break; } if (monitor.isCanceled()) { return Status.CANCEL_STATUS; } } monitor.setTaskName(Messages.ClientBuildingReport); buildMonitoringReport(); while (result.getReportData() == null) { TimeUtil.delay(500); if (result.getReportData() == (MonitoringConstants.EMPTY_REPORT)) { break; } if (monitor.isCanceled()) { return Status.CANCEL_STATUS; } } writeMonitoringResults(result); } DataEventDispatcher.getInstance().fireTestresultSummaryChanged(summary, DataState.Added); monitor.done(); return Status.OK_STATUS; } catch (Throwable t) { // this is due that everything that happens in the job // will otherwise not be logged (like memory Exception) log.error(Messages.ClientWritingReportError, t); return Status.CANCEL_STATUS; } } }; job.addJobChangeListener(new JobChangeAdapter() { public void done(IJobChangeEvent event) { ab.set(true); } }); final Timer timerTimeout = new Timer(); timerTimeout.schedule(new TimerTask() { public void run() { job.cancel(); timerTimeout.cancel(); } }, BUILD_REPORT_TIMEOUT); job.setPriority(Job.LONG); job.schedule(); while (!ab.get()) { TimeUtil.delay(200); } }
From source file:org.eclipse.jubula.client.core.ClientTest.java
/** * creating the job that is building and writing test data to DB. * @param result The test results //from ww w . j a v a2s.c o m */ private void createReportJob(final TestResult result) { final AtomicBoolean ab = new AtomicBoolean(false); final Job job = new Job(Messages.ClientCollectingInformation) { private String m_jobFamily = this.getName(); public boolean belongsTo(Object family) { return m_jobFamily.equals(family); } protected IStatus run(IProgressMonitor monitor) { try { monitor.beginTask(Messages.ClientWritingReportToDB, IProgressMonitor.UNKNOWN); ITestResultSummaryPO summary = writeTestresultToDB(result); monitor.beginTask(Messages.ClientWritingReport, IProgressMonitor.UNKNOWN); writeReportToFileSystem(result); if (isRunningWithMonitoring()) { monitor.setTaskName(Messages.ClientCalculating); getMonitoringData(); while (result.getMonitoringValues() == null || result.getMonitoringValues().isEmpty()) { TimeUtil.delay(500); if (result.getMonitoringValues() != null) { break; } if (monitor.isCanceled()) { return Status.CANCEL_STATUS; } } monitor.setTaskName(Messages.ClientBuildingReport); buildMonitoringReport(); while (result.getReportData() == null) { TimeUtil.delay(500); if (result.getReportData() == (MonitoringConstants.EMPTY_REPORT)) { break; } if (monitor.isCanceled()) { return Status.CANCEL_STATUS; } } writeMonitoringResults(result); } DataEventDispatcher.getInstance().fireTestresultSummaryChanged(summary, DataState.Added); monitor.done(); return Status.OK_STATUS; } catch (Throwable t) { // this is due that everything that happens in the job // will otherwise not be logged (like memory Exception) log.error(Messages.ClientWritingReportError, t); return Status.CANCEL_STATUS; } } }; job.addJobChangeListener(new JobChangeAdapter() { public void done(IJobChangeEvent event) { ab.set(true); } }); final Timer timerTimeout = new Timer(); timerTimeout.schedule(new TimerTask() { public void run() { job.cancel(); timerTimeout.cancel(); } }, BUILD_REPORT_TIMEOUT); job.setPriority(Job.LONG); job.schedule(); while (!ab.get()) { TimeUtil.delay(200); } }