Example usage for com.google.common.util.concurrent TimeLimiter newProxy

List of usage examples for com.google.common.util.concurrent TimeLimiter newProxy

Introduction

In this page you can find the example usage for com.google.common.util.concurrent TimeLimiter newProxy.

Prototype

<T> T newProxy(T target, Class<T> interfaceType, long timeoutDuration, TimeUnit timeoutUnit);

Source Link

Document

Returns an instance of interfaceType that delegates all method calls to the target object, enforcing the specified time limit on each call.

Usage

From source file:com.facebook.presto.raptor.backup.TimeoutBackupStore.java

private static <T> T timeLimited(T target, Class<T> clazz, Duration timeout, ExecutorService executor) {
    TimeLimiter limiter = new SimpleTimeLimiter(executor);
    return limiter.newProxy(target, clazz, timeout.toMillis(), MILLISECONDS);
}

From source file:io.prestosql.plugin.raptor.legacy.backup.TimeoutBackupStore.java

private static <T> T timeLimited(T target, Class<T> clazz, Duration timeout, ExecutorService executor,
        int maxThreads) {
    executor = new ExecutorServiceAdapter(new BoundedExecutor(executor, maxThreads));
    TimeLimiter limiter = SimpleTimeLimiter.create(executor);
    return limiter.newProxy(target, clazz, timeout.toMillis(), MILLISECONDS);
}

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 w w  .  j  a  v  a  2  s. c  o m
        }

        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: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 ww  w .  j av  a 2s .  c  o  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: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 ww .j  a v  a  2  s.  c  o  m
        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();
}

From source file:io.prestosql.verifier.QueryRewriter.java

private List<Column> getColumns(Connection connection, CreateTableAsSelect createTableAsSelect)
        throws SQLException {
    io.prestosql.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();
    io.prestosql.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 io.prestosql.sql.tree.Query(createSelectClause.getWith(), innerQuery,
                Optional.empty(), Optional.empty());
    } else {//  w  ww  . ja  va2  s  .co  m
        zeroRowsQuery = new io.prestosql.sql.tree.Query(createSelectClause.getWith(), innerQuery,
                Optional.empty(), Optional.of("0"));
    }

    ImmutableList.Builder<Column> columns = ImmutableList.builder();
    try (java.sql.Statement jdbcStatement = connection.createStatement()) {
        ExecutorService executor = newSingleThreadExecutor();
        TimeLimiter limiter = SimpleTimeLimiter.create(executor);
        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)));
            }
        } catch (UncheckedTimeoutException e) {
            throw new SQLException("SQL statement execution timed out", e);
        } finally {
            executor.shutdownNow();
        }
    }

    return columns.build();
}

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);/*w  w w  .j a va 2 s  . c om*/
                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.Validator.java

private QueryResult executeQuery(String url, String username, String password, Query query, String sql,
        Duration timeout, Map<String, String> sessionProperties) {
    try (Connection connection = DriverManager.getConnection(url, username, password)) {
        trySetConnectionProperties(query, connection);
        for (Map.Entry<String, String> entry : sessionProperties.entrySet()) {
            connection.unwrap(PrestoConnection.class).setSessionProperty(entry.getKey(), entry.getValue());
        }/*from   w  w  w .j ava 2 s  .c  om*/
        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);
            if (explainOnly) {
                sql = "EXPLAIN " + sql;
            }
            try (final ResultSet resultSet = limitedStatement.executeQuery(sql)) {
                List<List<Object>> results = limiter.callWithTimeout(getResultSetConverter(resultSet),
                        timeout.toMillis() - stopwatch.elapsed(TimeUnit.MILLISECONDS), TimeUnit.MILLISECONDS,
                        true);
                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 = isPrestoQueryInvalid(e) ? State.INVALID : 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:io.prestosql.verifier.Validator.java

private QueryResult executeQuery(String url, String username, String password, Query query, String sql,
        Duration timeout, Map<String, String> sessionProperties) {
    ExecutorService executor = newSingleThreadExecutor();
    TimeLimiter limiter = SimpleTimeLimiter.create(executor);

    String queryId = null;//from   w w  w.jav a2s.  c  o  m
    try (Connection connection = DriverManager.getConnection(url, username, password)) {
        trySetConnectionProperties(query, connection);
        for (Map.Entry<String, String> entry : sessionProperties.entrySet()) {
            connection.unwrap(PrestoConnection.class).setSessionProperty(entry.getKey(), entry.getValue());
        }

        try (Statement statement = connection.createStatement()) {
            Stopwatch stopwatch = Stopwatch.createStarted();
            Statement limitedStatement = limiter.newProxy(statement, Statement.class, timeout.toMillis(),
                    MILLISECONDS);
            if (explainOnly) {
                sql = "EXPLAIN " + sql;
            }

            long start = System.nanoTime();
            PrestoStatement prestoStatement = limitedStatement.unwrap(PrestoStatement.class);
            ProgressMonitor progressMonitor = new ProgressMonitor();
            prestoStatement.setProgressMonitor(progressMonitor);
            boolean isSelectQuery = limitedStatement.execute(sql);

            List<List<Object>> results;
            if (isSelectQuery) {
                ResultSetConverter converter = limiter.newProxy(this::convertJdbcResultSet,
                        ResultSetConverter.class, timeout.toMillis() - stopwatch.elapsed(MILLISECONDS),
                        MILLISECONDS);
                results = converter.convert(limitedStatement.getResultSet());
            } else {
                results = ImmutableList.of(ImmutableList.of(limitedStatement.getLargeUpdateCount()));
            }

            prestoStatement.clearProgressMonitor();
            QueryStats queryStats = progressMonitor.getFinalQueryStats();
            if (queryStats == null) {
                throw new VerifierException("Cannot fetch query stats");
            }
            Duration queryCpuTime = new Duration(queryStats.getCpuTimeMillis(), MILLISECONDS);
            queryId = queryStats.getQueryId();
            return new QueryResult(State.SUCCESS, null, nanosSince(start), queryCpuTime, queryId, results);
        }
    } 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 = isPrestoQueryInvalid(e) ? State.INVALID : State.FAILED;
        return new QueryResult(state, exception, null, null, queryId, ImmutableList.of());
    } catch (VerifierException e) {
        return new QueryResult(State.TOO_MANY_ROWS, e, null, null, queryId, ImmutableList.of());
    } catch (UncheckedTimeoutException e) {
        return new QueryResult(State.TIMEOUT, e, null, null, queryId, ImmutableList.of());
    } finally {
        executor.shutdownNow();
    }
}