List of usage examples for com.google.common.util.concurrent SimpleTimeLimiter SimpleTimeLimiter
public SimpleTimeLimiter()
From source file:google.registry.server.UrlChecker.java
/** Probes {@code url} until it becomes available. */ static void waitUntilAvailable(final URL url, int timeoutMs) { try {/*from www . j a v a 2s .c o m*/ new SimpleTimeLimiter().callWithTimeout(new Callable<Void>() { @Nullable @Override public Void call() throws InterruptedException, IOException { int exponentialBackoffMs = 1; while (true) { if (isAvailable(url)) { return null; } Thread.sleep(exponentialBackoffMs *= 2); } } }, timeoutMs, TimeUnit.MILLISECONDS, true); } catch (Exception e) { throw Throwables.propagate(e); } }
From source file:org.robotninjas.util.callable.DecoratedCallableBuilder.java
DecoratedCallableBuilder() {
this(new SimpleTimeLimiter());
}
From source file:me.defying.chili.timeout.TimeoutInterceptor.java
@Override public Object invoke(final MethodInvocation invocation) throws Throwable { // get annotation, class, method and arguments Timeout annotation = InvocationUtils.getAnnotation(invocation, Timeout.class); // do nothing if (annotation.time() <= 0) { return invocation.proceed(); }/*from w w w .jav a2s. c om*/ TimeLimiter limiter = new SimpleTimeLimiter(); // underlying method invoker Callable<Object> invoker = new TimeoutInvoker(invocation); try { return limiter.callWithTimeout(invoker, annotation.time(), annotation.unit(), true); } catch (UncheckedTimeoutException ex) { throw new TimeoutException(ex); } catch (ChiliException ex) { // when the underlying method invokation throws an exception we need // to unrap it in order to existing code get the real exception throw ex.getCause(); } }
From source file:org.zanata.workflow.ClientWorkFlow.java
@SuppressFBWarnings(value = "GBU_GUAVA_BETA_CLASS_USAGE", justification = "field SimpleTimeLimiter") public List<String> callWithTimeout(final File workingDirectory, String command) { log.info("=== about to call ===\n{}", command); if (!workingDirectory.isDirectory()) { throw new RuntimeException("working directory does not exist: " + workingDirectory); }/*from w ww . j a v a 2 s.c o m*/ final List<String> commands = Lists.newArrayList(Splitter.on(" ").split(command)); SimpleTimeLimiter timeLimiter = new SimpleTimeLimiter(); Callable<List<String>> work = () -> { Process process = ClientWorkFlow.invokeClient(workingDirectory, commands); process.waitFor(); List<String> output = ClientWorkFlow.getOutput(process); logOutputLines(output); return output; }; try { return timeLimiter.callWithTimeout(work, timeoutDuration, TimeUnit.SECONDS, true); } catch (Exception e) { throw new RuntimeException(e); } }
From source file:de.iteratec.iteraplan.presentation.problemreports.DatabaseProblemReportPart.java
static ProblemReportPart generateDatabaseReport(String filename, HttpServletRequest request) { DatabaseProblemReportPart reportPart = new DatabaseProblemReportPart(filename); PrintWriter dbWriter = reportPart.getWriter(); ApplicationContext context = DefaultSpringApplicationContext.getSpringApplicationContext(); Object sessionFactoryObject = context.getBean("sessionFactory"); if (sessionFactoryObject instanceof SessionFactory) { SessionFactory sessionFactory = (SessionFactory) sessionFactoryObject; Session currentSession = sessionFactory.getCurrentSession(); Map<String, ClassMetadata> allClassMetadata = sessionFactory.getAllClassMetadata(); final Set<String> tableNames = Sets.newHashSet(); for (ClassMetadata cm : allClassMetadata.values()) { if (cm instanceof AbstractEntityPersister) { AbstractEntityPersister aep = (AbstractEntityPersister) cm; tableNames.add(aep.getTableName()); }/*from w ww.j av a2 s . c om*/ } ByteArrayOutputStream dbInfoBuffer = new ByteArrayOutputStream(); final PrintWriter dbInfoWriter = new PrintWriter(dbInfoBuffer); Work work = new Work() { @Override public void execute(Connection connection) throws SQLException { try { DatabaseMetaData metaData = connection.getMetaData(); dbInfoWriter.println("Database Name: " + metaData.getDatabaseProductName() + " " + metaData.getDatabaseMajorVersion() + "." + metaData.getDatabaseMinorVersion()); dbInfoWriter.println("Database Product Version: " + metaData.getDatabaseProductVersion()); dbInfoWriter.println("JDBC URL: " + metaData.getURL()); dbInfoWriter.println("JDBC API: " + metaData.getJDBCMajorVersion() + "." + metaData.getJDBCMinorVersion()); dbInfoWriter.println("JDBC-Driver Name: " + metaData.getDriverName() + " " + metaData.getDriverMajorVersion() + "." + metaData.getDriverMinorVersion()); dbInfoWriter.println("JDBC-Driver Version: " + metaData.getDriverVersion()); } catch (Exception e) { e.printStackTrace(); } } }; try { TimeLimiter timeLimiter = new SimpleTimeLimiter(); Session sessionProxy = timeLimiter.newProxy(currentSession, Session.class, TIMEOUT_IN_SECONDS, TimeUnit.SECONDS); sessionProxy.doWork(work); } catch (UncheckedTimeoutException e) { dbInfoWriter.println("Couldn't gather database information from conncetion within " + TIMEOUT_IN_SECONDS + " seconds."); } catch (Exception e) { dbInfoWriter.println("Couldn't gather database information from connection."); } dbInfoWriter.close(); dbWriter.print(dbInfoBuffer); } dbWriter.close(); return reportPart; }
From source file:net.i2cat.netconf.messageQueue.MessageQueue.java
/** * Wait for a new message with the id <code>messageId</code> to arrive in the queue. * * @param messageId a string identifying the message to consume. * @param timeout a long indicating the length of the timeout in milliseconds. If zero or less, no timeout. * @throws Exception an UncheckedTimeoutException if there is no message with <code>messageId</code> after waiting for the specified timeout. * @return/* w w w .j a v a 2 s . c o m*/ */ public RPCElement blockingConsumeById(String messageId, long timeout) throws Exception { final String messageIdFinal = messageId; Callable<RPCElement> consumeCaller = new Callable<RPCElement>() { public RPCElement call() throws Exception { RPCElement element; synchronized (queue) { while ((element = consumeById(messageIdFinal)) == null) { try { log.debug("Waiting (" + messageIdFinal + ")..."); queue.wait(); } catch (InterruptedException e) { // Do nothing. It's probably a timeout. } } } return element; } }; if (timeout <= 0) { return consumeCaller.call(); } SimpleTimeLimiter timeLimiter = new SimpleTimeLimiter(); try { return timeLimiter.callWithTimeout(consumeCaller, timeout, TimeUnit.MILLISECONDS, true); } catch (UncheckedTimeoutException e) { log.debug("BlockingConsumeById(messageId=" + messageId + ") failed due to timeout.", e); throw e; } catch (Exception e) { log.debug("BlockingConsumeById(messageId=" + messageId + ") failed.", e); throw e; } }
From source file:org.apache.falcon.regression.ui.search.AbstractSearchPage.java
protected void waitForAngularToFinish() { final String javaScript = "return (window.angular != null) && " + "(angular.element(document).injector() != null) && " + "(angular.element(document).injector().get('$http').pendingRequests.length === 0)"; boolean isLoaded = false; for (int i = 0; i < PAGELOAD_TIMEOUT_THRESHOLD && !isLoaded; i++) { TimeLimiter timeLimiter = new SimpleTimeLimiter(); final JavascriptExecutor proxyJsExecutor = timeLimiter.newProxy((JavascriptExecutor) driver, JavascriptExecutor.class, 10, TimeUnit.SECONDS); try {//from w ww .ja v a 2 s .co m final Object output = proxyJsExecutor.executeScript(javaScript); isLoaded = Boolean.valueOf(output.toString()); } catch (Exception e) { LOGGER.info( "Checking of pending request failed because of: " + ExceptionUtils.getFullStackTrace(e)); } LOGGER.info(i + 1 + ". waiting on angular to finish."); TimeUtil.sleepSeconds(1); } LOGGER.info("angular is done continuing..."); }
From source file:org.eclipse.jdt.ls.core.internal.contentassist.SignatureHelpRequestor.java
public String computeJavaDoc(CompletionProposal proposal) { try {/*from www. j a va 2 s. c o m*/ IType type = unit.getJavaProject().findType( SignatureUtil.stripSignatureToFQN(String.valueOf(proposal.getDeclarationSignature()))); if (type != null) { String[] parameters = Signature .getParameterTypes(String.valueOf(SignatureUtil.fix83600(proposal.getSignature()))); for (int i = 0; i < parameters.length; i++) { parameters[i] = getLowerBound(parameters[i]); } IMethod method = JavaModelUtil.findMethod(String.valueOf(proposal.getName()), parameters, proposal.isConstructor(), type); if (method != null && method.exists()) { ICompilationUnit unit = type.getCompilationUnit(); if (unit != null) { unit.reconcile(ICompilationUnit.NO_AST, false, null, null); } String javadoc = null; try { javadoc = new SimpleTimeLimiter().callWithTimeout(() -> { Reader reader = JavadocContentAccess.getPlainTextContentReader(method); return reader == null ? null : CharStreams.toString(reader); }, 500, TimeUnit.MILLISECONDS, true); } catch (UncheckedTimeoutException tooSlow) { } catch (Exception e) { JavaLanguageServerPlugin.logException("Unable to read documentation", e); } return javadoc; } } } catch (JavaModelException e) { JavaLanguageServerPlugin.logException("Unable to resolve signaturehelp javadoc", e); } return null; }
From source file:org.bin01.db.verifier.Validator.java
private QueryResult executeQuery(String url, String username, String password, Query query, Duration timeout) { try (Connection connection = DriverManager.getConnection(url, username, password)) { connection.setClientInfo("ApplicationName", "verifier-test:" + queryPair.getName()); connection.setCatalog(query.getCatalog()); connection.setSchema(query.getSchema()); long start = System.nanoTime(); try (Statement statement = connection.createStatement()) { TimeLimiter limiter = new SimpleTimeLimiter(); Stopwatch stopwatch = Stopwatch.createStarted(); Statement limitedStatement = limiter.newProxy(statement, Statement.class, timeout.toMillis(), TimeUnit.MILLISECONDS); try (final ResultSet resultSet = limitedStatement.executeQuery(query.getQuery())) { List<List<Object>> results = limiter.callWithTimeout(getResultSetConverter(resultSet), timeout.toMillis() - stopwatch.elapsed(TimeUnit.MILLISECONDS), TimeUnit.MILLISECONDS, true);//from ww w.j av a 2 s . c o m return new QueryResult(State.SUCCESS, null, nanosSince(start), results); } catch (AssertionError e) { if (e.getMessage().startsWith("unimplemented type:")) { return new QueryResult(State.INVALID, null, null, ImmutableList.<List<Object>>of()); } throw e; } catch (SQLException | VerifierException e) { throw e; } catch (UncheckedTimeoutException e) { return new QueryResult(State.TIMEOUT, null, null, ImmutableList.<List<Object>>of()); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw Throwables.propagate(e); } catch (Exception e) { throw Throwables.propagate(e); } } } catch (SQLException e) { Exception exception = e; if (("Error executing query".equals(e.getMessage()) || "Error fetching results".equals(e.getMessage())) && (e.getCause() instanceof Exception)) { exception = (Exception) e.getCause(); } State state = State.FAILED; return new QueryResult(state, exception, null, null); } catch (VerifierException e) { return new QueryResult(State.TOO_MANY_ROWS, e, null, null); } }
From source file:com.facebook.presto.verifier.QueryRewriter.java
private List<Column> getColumns(Connection connection, CreateTableAsSelect createTableAsSelect) throws SQLException { com.facebook.presto.sql.tree.Query createSelectClause = createTableAsSelect.getQuery(); // Rewrite the query to select zero rows, so that we can get the column names and types QueryBody innerQuery = createSelectClause.getQueryBody(); com.facebook.presto.sql.tree.Query zeroRowsQuery; if (innerQuery instanceof QuerySpecification) { QuerySpecification querySpecification = (QuerySpecification) innerQuery; innerQuery = new QuerySpecification(querySpecification.getSelect(), querySpecification.getFrom(), querySpecification.getWhere(), querySpecification.getGroupBy(), querySpecification.getHaving(), querySpecification.getOrderBy(), Optional.of("0")); zeroRowsQuery = new com.facebook.presto.sql.tree.Query(createSelectClause.getWith(), innerQuery, Optional.empty(), Optional.empty()); } else {//w w w. java2 s . c om zeroRowsQuery = new com.facebook.presto.sql.tree.Query(createSelectClause.getWith(), innerQuery, Optional.empty(), Optional.of("0")); } ImmutableList.Builder<Column> columns = ImmutableList.builder(); try (java.sql.Statement jdbcStatement = connection.createStatement()) { TimeLimiter limiter = new SimpleTimeLimiter(); java.sql.Statement limitedStatement = limiter.newProxy(jdbcStatement, java.sql.Statement.class, timeout.toMillis(), TimeUnit.MILLISECONDS); try (ResultSet resultSet = limitedStatement.executeQuery(formatSql(zeroRowsQuery, Optional.empty()))) { ResultSetMetaData metaData = resultSet.getMetaData(); for (int i = 1; i <= metaData.getColumnCount(); i++) { String name = metaData.getColumnName(i); int type = metaData.getColumnType(i); columns.add(new Column(name, APPROXIMATE_TYPES.contains(type))); } } } return columns.build(); }