List of usage examples for java.util.concurrent TimeoutException getMessage
public String getMessage()
From source file:cli.Manager.java
public void receiveMessages(int timeoutSeconds, boolean returnOnTimeout, ReceiveMessageHandler handler) throws IOException { final TextSecureMessageReceiver messageReceiver = new TextSecureMessageReceiver(URL, TRUST_STORE, username, password, signalingKey, USER_AGENT); TextSecureMessagePipe messagePipe = null; try {/*from w w w. j ava 2s .c o m*/ messagePipe = messageReceiver.createMessagePipe(); while (true) { TextSecureEnvelope envelope; try { envelope = messagePipe.read(timeoutSeconds, TimeUnit.SECONDS); handler.handleMessage(envelope); } catch (TimeoutException e) { if (returnOnTimeout) return; } catch (InvalidVersionException e) { System.err.println("Ignoring error: " + e.getMessage()); } save(); } } finally { if (messagePipe != null) messagePipe.shutdown(); } }
From source file:fitnesse.FitNesseExpediter.java
private Response makeResponse(final Request request) throws Exception { Response response;// w w w .j a v a2s .c o m try { executorService.submit(new Callable<Request>() { @Override public Request call() throws Exception { request.parse(); return request; } }).get(requestParsingTimeLimit, TimeUnit.MILLISECONDS); if (request.hasBeenParsed()) { if (context.contextRoot.equals(request.getRequestUri() + "/")) { response = new SimpleResponse(); response.redirect(context.contextRoot, ""); } else { response = createGoodResponse(request); } } else { response = reportError(request, 400, "The request could not be parsed."); } } catch (SocketException se) { throw se; } catch (TimeoutException e) { String message = "The client request has been unproductive for too long. It has timed out and will no longer be processed."; LOG.log(Level.FINE, message, e); response = reportError(request, 408, message); } catch (HttpException e) { LOG.log(Level.FINE, "An error occured while fulfilling user request", e); response = reportError(request, 400, e.getMessage()); } catch (Exception e) { LOG.log(Level.WARNING, "An error occured while fulfilling user request", e); response = reportError(request, e); } // Add those as default headers? response.addHeader("Server", "FitNesse-" + context.version); response.addHeader("Connection", "close"); return response; }
From source file:com.google.acre.appengine.script.AppEngineAsyncUrlfetch.java
public void wait_on_result(long time, TimeUnit tunit) { int i = 0;//from w ww .ja va 2 s . c o m long endtime = System.currentTimeMillis() + tunit.toMillis(time); Context ctx = Context.getCurrentContext(); while (_requests.size() > 0) { long pass_start_time = System.currentTimeMillis(); if (i > _requests.size() - 1) i = 0; if (time != -1 && endtime <= System.currentTimeMillis()) { for (AsyncRequest r : _requests) { r.request.cancel(true); } throw new JSURLTimeoutError("Time limit exceeded").newJSException(_scope); } AsyncRequest asyncreq = _requests.get(i); Future<HTTPResponse> futr = asyncreq.request; Function callback = asyncreq.callback; if (futr.isCancelled()) { JSURLError jse = new JSURLError("Request cancelled"); callback.call(ctx, _scope, null, new Object[] { asyncreq.url.toString(), jse.toJSError(_scope) }); _requests.remove(i); continue; } try { HTTPResponse res = futr.get(10, TimeUnit.MILLISECONDS); callback.call(ctx, _scope, null, new Object[] { asyncreq.url.toString(), callback_result(asyncreq, res) }); _requests.remove(i); continue; } catch (TimeoutException e) { // This is timeout on the futr.get() call, not a request timeout } catch (CancellationException e) { // pass, handled by isCancelled } catch (ExecutionException e) { JSURLError jse = new JSURLError(e.getMessage()); callback.call(ctx, _scope, null, new Object[] { asyncreq.url.toString(), jse.toJSError(_scope) }); _requests.remove(i); continue; } catch (InterruptedException e) { JSURLError jse = new JSURLError(e.getMessage()); callback.call(ctx, _scope, null, new Object[] { asyncreq.url.toString(), jse.toJSError(_scope) }); _requests.remove(i); continue; } _costCollector.collect("auub", System.currentTimeMillis() - pass_start_time); i++; } }
From source file:com.dotmarketing.business.MemcachedCacheAdministratorImpl.java
@Override public void flushAll() { Logger.info(this.getClass(), "Full Cache Flush"); try {/*from w w w . ja v a2 s. co m*/ _oldCache.flushAll(); getClient().flushAll(); } catch (TimeoutException e) { Logger.error(this.getClass(), "Flush all failed: " + e.getMessage(), e); } catch (InterruptedException e) { Logger.error(this.getClass(), "Flush all failed: " + e.getMessage(), e); } catch (MemcachedException e) { Logger.error(this.getClass(), "Flush all failed: " + e.getMessage(), e); } }
From source file:com.clustercontrol.repository.session.RepositoryRunManagementBean.java
/** * Quartz???<BR>/* w w w.j ava 2 s . c o m*/ * <P> * Quartz??????<BR> * <BR> * ?????????<BR> * @throws HinemosUnknown * @throws JobInfoNotFound * * @see com.clustercontrol.jobmanagement.factory.OperationJob#runJob() */ public void run() { if (duplicateExec.tryAcquire()) { try { if (countCheck()) { long start = HinemosTime.currentTimeMillis(); RepositoryControllerBean controller = new RepositoryControllerBean(); //? try { List<String> facilityIdList = controller.getNodeFacilityIdList(); List<Future<Boolean>> futureList = new ArrayList<Future<Boolean>>(); //???? for (String facilityId : facilityIdList) { futureList.add(_executorService.submit(new DeviceSearchTask(facilityId))); } //? for (Future<Boolean> future : futureList) { try { future.get(60 * 1000, TimeUnit.MILLISECONDS); } catch (TimeoutException e) { // SNMP????????????????? m_log.warn("run() : " + e.getClass().getName(), e); } catch (InterruptedException e) { m_log.warn("run() : " + e.getClass().getName(), e); } catch (ExecutionException e) { m_log.warn("run() : " + e.getClass().getName(), e); } } } catch (HinemosUnknown e) { m_log.warn("run() : " + e.getClass().getSimpleName() + ", " + e.getMessage(), e); } m_log.info("auto device search : time=" + (HinemosTime.currentTimeMillis() - start) + "ms"); } } finally { duplicateExec.release(); } } else { m_log.warn("runningCheck is busy !!"); } }
From source file:org.glowroot.central.SyntheticMonitorService.java
private void runSyntheticMonitor(AgentRollup agentRollup, SyntheticMonitorConfig syntheticMonitorConfig, List<AlertConfig> alertConfigs, Callable<FutureWithStartTick> callable) throws Exception { SyntheticMonitorUniqueKey uniqueKey = ImmutableSyntheticMonitorUniqueKey.of(agentRollup.id(), syntheticMonitorConfig.getId()); if (!activeSyntheticMonitors.add(uniqueKey)) { return;/*from w ww . j a v a 2s . c o m*/ } FutureWithStartTick future = callable.call(); // important that uniqueKey is always removed on completion even on unexpected errors future.whenComplete((v, t) -> activeSyntheticMonitors.remove(uniqueKey)); OnRunComplete onRunComplete = new OnRunComplete(agentRollup, syntheticMonitorConfig); if (alertConfigs.isEmpty()) { future.thenAccept(onRunComplete); return; } int maxAlertThresholdMillis = 0; for (AlertConfig alertConfig : alertConfigs) { maxAlertThresholdMillis = Math.max(maxAlertThresholdMillis, alertConfig.getCondition().getSyntheticMonitorCondition().getThresholdMillis()); } long captureTime; long durationNanos; boolean success; String errorMessage; try { // wait an extra second to make sure no edge case where TimeoutException occurs with // stopwatch.elapsed(MILLISECONDS) < maxAlertThresholdMillis SyntheticRunResult result = future.get(maxAlertThresholdMillis + 1000L, MILLISECONDS); captureTime = result.captureTime(); durationNanos = result.durationNanos(); Throwable throwable = result.throwable(); if (throwable == null) { success = true; errorMessage = null; } else { success = false; errorMessage = getBestMessageForSyntheticFailure(throwable); } } catch (TimeoutException e) { logger.debug(e.getMessage(), e); captureTime = clock.currentTimeMillis(); durationNanos = 0; // durationNanos is only used below when success is true success = false; errorMessage = null; } if (!isCurrentlyDisabled(agentRollup.id())) { if (success) { for (AlertConfig alertConfig : alertConfigs) { AlertCondition alertCondition = alertConfig.getCondition(); SyntheticMonitorCondition condition = alertCondition.getSyntheticMonitorCondition(); boolean currentlyTriggered = durationNanos >= MILLISECONDS .toNanos(condition.getThresholdMillis()); sendAlertIfStatusChanged(agentRollup, syntheticMonitorConfig, alertConfig, condition, captureTime, currentlyTriggered, null); } } else { sendAlertOnErrorIfStatusChanged(agentRollup, syntheticMonitorConfig, alertConfigs, errorMessage, captureTime); } } // need to run at end to ensure new synthetic response doesn't get stored before consecutive // count is checked in sendAlertOnErrorIfStatusChanged() future.thenAccept(onRunComplete); }
From source file:org.cloudifysource.esc.shell.installer.CloudGridAgentBootstrapper.java
private void installOnMachines(final long endTime, final AgentlessInstaller installer, final int numOfManagementMachines, final InstallationDetails[] installations) throws InterruptedException, TimeoutException, InstallerException { final ExecutorService executors = Executors.newFixedThreadPool(numOfManagementMachines); final BootstrapLogsFilters bootstrapLogs = new BootstrapLogsFilters(verbose); try {/*w w w.j a va2 s . c om*/ bootstrapLogs.applyLogFilters(); final List<Future<Exception>> futures = new ArrayList<Future<Exception>>(); for (final InstallationDetails detail : installations) { final Future<Exception> future = executors.submit(new Callable<Exception>() { @Override public Exception call() { try { installer.installOnMachineWithIP(detail, CalcUtils.millisUntil(endTime), TimeUnit.MILLISECONDS); } catch (final TimeoutException e) { logger.log(Level.INFO, "Failed accessing management VM " + detail.getPublicIp() + " Reason: " + e.getMessage(), e); return e; } catch (final InterruptedException e) { logger.log(Level.INFO, "Failed accessing management VM " + detail.getPublicIp() + " Reason: " + e.getMessage(), e); return e; } catch (final InstallerException e) { logger.log(Level.INFO, "Failed accessing management VM " + detail.getPublicIp() + " Reason: " + e.getMessage(), e); return e; } return null; } }); futures.add(future); } for (final Future<Exception> future : futures) { try { final Exception e = future.get(CalcUtils.millisUntil(endTime), TimeUnit.MILLISECONDS); if (e != null) { if (e instanceof TimeoutException) { throw (TimeoutException) e; } if (e instanceof InterruptedException) { throw (InterruptedException) e; } if (e instanceof InstallerException) { throw (InstallerException) e; } throw new InstallerException("Failed creating machines.", e); } } catch (final ExecutionException e) { throw new InstallerException("Failed creating machines.", e); } } } finally { executors.shutdown(); bootstrapLogs.restoreLogFilters(); } }
From source file:com.palantir.atlasdb.keyvalue.cassandra.CQLKeyValueService.java
@Override public void compactInternally(String tableName) { Preconditions.checkArgument(!Strings.isNullOrEmpty(tableName), "tableName:[%s] should not be null or empty", tableName);//www . jav a2s . c o m CassandraKeyValueServiceConfig config = configManager.getConfig(); if (!compactionManager.isPresent()) { log.error( "No compaction client was configured, but compact was called. If you actually want to clear deleted data immediately " + "from Cassandra, lower your gc_grace_seconds setting and run `nodetool compact {} {}`.", config.keyspace(), tableName); return; } long compactionTimeoutSeconds = config.jmx().get().compactionTimeoutSeconds(); try { alterTableForCompaction(tableName, 0, 0.0f); CQLKeyValueServices.waitForSchemaVersionsToCoalesce("setting up tables for compaction", this); compactionManager.get().performTombstoneCompaction(compactionTimeoutSeconds, config.keyspace(), tableName); } catch (TimeoutException e) { log.error("Compaction could not finish in {} seconds. {}", compactionTimeoutSeconds, e.getMessage()); log.error(compactionManager.get().getCompactionStatus()); } catch (InterruptedException e) { log.error("Compaction for {}.{} was interrupted.", config.keyspace(), tableName); } finally { alterTableForCompaction(tableName, CassandraConstants.GC_GRACE_SECONDS, CassandraConstants.TOMBSTONE_THRESHOLD_RATIO); CQLKeyValueServices.waitForSchemaVersionsToCoalesce("setting up tables post-compaction", this); } }
From source file:org.apache.flink.test.recovery.AbstractProcessFailureRecoveryTest.java
protected void waitUntilNumTaskManagersAreRegistered(ActorRef jobManager, int numExpected, long maxDelay) throws Exception { final long deadline = System.currentTimeMillis() + maxDelay; while (true) { long remaining = deadline - System.currentTimeMillis(); if (remaining <= 0) { fail("The TaskManagers did not register within the expected time (" + maxDelay + "msecs)"); }/*from w w w.j av a 2 s .c o m*/ FiniteDuration timeout = new FiniteDuration(remaining, TimeUnit.MILLISECONDS); try { Future<?> result = Patterns.ask(jobManager, JobManagerMessages.getRequestNumberRegisteredTaskManager(), new Timeout(timeout)); Integer numTMs = (Integer) Await.result(result, timeout); if (numTMs == numExpected) { break; } } catch (TimeoutException e) { // ignore and retry } catch (ClassCastException e) { fail("Wrong response: " + e.getMessage()); } } }
From source file:org.apache.flink.test.recovery.AbstractTaskManagerProcessFailureRecoveryTest.java
protected void waitUntilNumTaskManagersAreRegistered(ActorRef jobManager, int numExpected, long maxDelayMillis) throws Exception { final long pollInterval = 10_000_000; // 10 ms = 10,000,000 nanos final long deadline = System.nanoTime() + maxDelayMillis * 1_000_000; long time;/*from w w w .j ava 2 s. c o m*/ while ((time = System.nanoTime()) < deadline) { FiniteDuration timeout = new FiniteDuration(pollInterval, TimeUnit.NANOSECONDS); try { Future<?> result = Patterns.ask(jobManager, JobManagerMessages.getRequestNumberRegisteredTaskManager(), new Timeout(timeout)); int numTMs = (Integer) Await.result(result, timeout); if (numTMs == numExpected) { return; } } catch (TimeoutException e) { // ignore and retry } catch (ClassCastException e) { fail("Wrong response: " + e.getMessage()); } long timePassed = System.nanoTime() - time; long remainingMillis = (pollInterval - timePassed) / 1_000_000; if (remainingMillis > 0) { Thread.sleep(remainingMillis); } } fail("The TaskManagers did not register within the expected time (" + maxDelayMillis + "msecs)"); }