Example usage for com.google.common.base Stopwatch elapsed

List of usage examples for com.google.common.base Stopwatch elapsed

Introduction

In this page you can find the example usage for com.google.common.base Stopwatch elapsed.

Prototype

@CheckReturnValue
public long elapsed(TimeUnit desiredUnit) 

Source Link

Document

Returns the current elapsed time shown on this stopwatch, expressed in the desired time unit, with any fraction rounded down.

Usage

From source file:com.example.postgres.PostgresSqlServlet.java

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {

    final String createTableSql = "CREATE TABLE IF NOT EXISTS visits ( visit_id SERIAL NOT NULL, "
            + "user_ip VARCHAR(46) NOT NULL, ts timestamp NOT NULL, " + "PRIMARY KEY (visit_id) );";
    final String createVisitSql = "INSERT INTO visits (user_ip, ts) VALUES (?, ?);";
    final String selectSql = "SELECT user_ip, ts FROM visits ORDER BY ts DESC " + "LIMIT 10;";

    String path = req.getRequestURI();
    if (path.startsWith("/favicon.ico")) {
        return; // ignore the request for favicon.ico
    }//from ww  w. ja v  a2 s .co m

    PrintWriter out = resp.getWriter();
    resp.setContentType("text/plain");

    // store only the first two octets of a users ip address
    String userIp = req.getRemoteAddr();
    InetAddress address = InetAddress.getByName(userIp);
    if (address instanceof Inet6Address) {
        // nest indexOf calls to find the second occurrence of a character in a string
        // an alternative is to use Apache Commons Lang: StringUtils.ordinalIndexOf()
        userIp = userIp.substring(0, userIp.indexOf(":", userIp.indexOf(":") + 1)) + ":*:*:*:*:*:*";
    } else if (address instanceof Inet4Address) {
        userIp = userIp.substring(0, userIp.indexOf(".", userIp.indexOf(".") + 1)) + ".*.*";
    }

    Stopwatch stopwatch = Stopwatch.createStarted();
    try (PreparedStatement statementCreateVisit = conn.prepareStatement(createVisitSql)) {
        conn.createStatement().executeUpdate(createTableSql);
        statementCreateVisit.setString(1, userIp);
        statementCreateVisit.setTimestamp(2, new Timestamp(new Date().getTime()));
        statementCreateVisit.executeUpdate();

        try (ResultSet rs = conn.prepareStatement(selectSql).executeQuery()) {
            stopwatch.stop();
            out.print("Last 10 visits:\n");
            while (rs.next()) {
                String savedIp = rs.getString("user_ip");
                String timeStamp = rs.getString("ts");
                out.println("Time: " + timeStamp + " Addr: " + savedIp);
            }
            out.println("Elapsed: " + stopwatch.elapsed(TimeUnit.MILLISECONDS));
        }
    } catch (SQLException e) {
        throw new ServletException("SQL error", e);
    }
}

From source file:com.thinkbiganalytics.feedmgr.nifi.CreateFeedBuilder.java

private long eventTime(Stopwatch eventTime) {
    eventTime.stop();//from   w  w  w.j a  v a2  s.  co  m
    long elapsedTime = eventTime.elapsed(TimeUnit.MILLISECONDS);
    eventTime.reset();
    return elapsedTime;
}

From source file:org.apache.drill.exec.server.Drillbit.java

public void run() throws Exception {
    final Stopwatch w = new Stopwatch().start();
    logger.debug("Startup begun.");
    coord.start(10000);//from w  w w .  ja v a 2s . c  o  m
    storeProvider.start();
    final DrillbitEndpoint md = engine.start();
    manager.start(md, engine.getController(), engine.getDataConnectionCreator(), coord, storeProvider);
    final DrillbitContext drillbitContext = manager.getContext();
    drillbitContext.getStorage().init();
    drillbitContext.getOptionManager().init();
    javaPropertiesToSystemOptions();
    registrationHandle = coord.register(md);
    startJetty();

    Runtime.getRuntime().addShutdownHook(new ShutdownThread(this, new StackTrace()));
    logger.info("Startup completed ({} ms).", w.elapsed(TimeUnit.MILLISECONDS));
}

From source file:com.palantir.atlasdb.keyvalue.impl.ProfilingKeyValueService.java

@Override
public void multiPut(Map<String, ? extends Map<Cell, byte[]>> valuesByTable, long timestamp) {
    if (log.isTraceEnabled()) {
        Stopwatch stopwatch = Stopwatch.createStarted();
        delegate.multiPut(valuesByTable, timestamp);
        int totalCells = 0;
        long totalBytes = 0;
        for (Map<Cell, byte[]> values : valuesByTable.values()) {
            totalCells += values.size();
            totalBytes += byteSize(values);
        }/*from  w  ww  . j  a v  a 2  s.  c o  m*/
        log.trace("Call to KVS.multiPut on {} tables putting {} total cells of {} total bytes took {} ms.",
                valuesByTable.keySet().size(), totalCells, totalBytes,
                stopwatch.elapsed(TimeUnit.MILLISECONDS));
    } else {
        delegate.multiPut(valuesByTable, timestamp);
    }
}

From source file:org.apache.brooklyn.rest.filter.LoggingFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;

    String rid = RequestTaggingFilter.getTag();
    boolean isInteresting = !UNINTERESTING_METHODS.contains(httpRequest.getMethod().toUpperCase());
    boolean shouldLog = (isInteresting && LOG.isDebugEnabled()) || LOG.isTraceEnabled();
    boolean requestErrored = false;
    if (shouldLog) {
        String message = "Request {} starting: {} {} from {}";
        Object[] args = new Object[] { rid, httpRequest.getMethod(), httpRequest.getRequestURI(),
                httpRequest.getRemoteAddr() };
        if (isInteresting) {
            LOG.debug(message, args);/*from   w  w  w .  ja va  2s .  c o  m*/
        } else {
            LOG.trace(message, args);
        }
    }

    Stopwatch timer = Stopwatch.createStarted();
    try {
        chain.doFilter(request, response);
    } catch (Throwable e) {
        requestErrored = true;
        isInteresting = true;
        LOG.warn("Request " + rid + " (" + httpRequest.getMethod() + " " + httpRequest.getRequestURI()
                + " from " + httpRequest.getRemoteAddr() + ") failed: " + e, e);
        // Propagate for handling by other filter
        throw Exceptions.propagate(e);
    } finally {
        timer.stop();
        // This logging must not happen before chain.doFilter, or FormMapProvider will not work as expected.
        // Getting the parameter map consumes the request body and only resource methods using @FormParam
        // will work as expected.
        isInteresting |= (timer.elapsed(TimeUnit.SECONDS) - REQUEST_DURATION_LOG_POINT.toSeconds()) > 0;
        if (shouldLog) {
            boolean includeHeaders = requestErrored || httpResponse.getStatus() / 100 == 5
                    || LOG.isTraceEnabled();
            String message = getRequestCompletedMessage(includeHeaders, Duration.of(timer), rid, httpRequest,
                    httpResponse);
            if (requestErrored || isInteresting) {
                LOG.debug(message);
            } else {
                LOG.trace(message);
            }
        }
    }
}

From source file:org.apache.drill.exec.store.hive.HiveMetadataProvider.java

/**
 * Return {@link InputSplitWrapper}s for given {@link HiveReadEntry}. First splits are looked up in cache, if not
 * found go through {@link InputFormat#getSplits(JobConf, int)} to find the splits.
 *
 * @param hiveReadEntry Subset of the {@link HiveReadEntry} used when creating this object.
 *
 * @return//from ww w . j  a v a 2  s.com
 */
public List<InputSplitWrapper> getInputSplits(final HiveReadEntry hiveReadEntry) {
    final Stopwatch timeGetSplits = Stopwatch.createStarted();
    try {
        if (!isPartitionedTable) {
            return getTableInputSplits();
        }

        final List<InputSplitWrapper> splits = Lists.newArrayList();
        for (Partition p : hiveReadEntry.getPartitions()) {
            splits.addAll(getPartitionInputSplits(p));
        }
        return splits;
    } catch (final Exception e) {
        logger.error("Failed to get InputSplits", e);
        throw new DrillRuntimeException("Failed to get InputSplits", e);
    } finally {
        logger.debug("Took {} s to get InputSplits from {}.{}",
                timeGetSplits.elapsed(TimeUnit.NANOSECONDS) / 1000, hiveReadEntry.getTable().getDbName(),
                hiveReadEntry.getTable().getTableName());
    }
}

From source file:org.apache.distributedlog.service.stream.StreamImpl.java

/**
 * Process the pending request after acquired stream.
 *
 * @param success whether the acquisition succeed or not
 * @param oldWriter the old writer to abort
 * @param oldPendingOps the old pending ops to execute
 * @param stopwatch stopwatch to measure the time spent on acquisition
 * @param acquirePromise the promise to complete the acquire operation
 *///from  w w  w  . ja v a2 s. com
void processPendingRequestsAfterAcquire(boolean success, AsyncLogWriter oldWriter,
        Queue<StreamOp> oldPendingOps, Stopwatch stopwatch, Promise<Boolean> acquirePromise) {
    if (success) {
        streamAcquireStat.registerSuccessfulEvent(stopwatch.elapsed(TimeUnit.MICROSECONDS));
    } else {
        streamAcquireStat.registerFailedEvent(stopwatch.elapsed(TimeUnit.MICROSECONDS));
    }
    for (StreamOp op : oldPendingOps) {
        executeOp(op, success);
        pendingOpsCounter.dec();
    }
    Abortables.asyncAbort(oldWriter, true);
    FutureUtils.setValue(acquirePromise, success);
}

From source file:com.mycelium.wapi.api.WapiClient.java

/**
 * Attempt to connect and send to a URL in our list of URLS, if it fails try
 * the next until we have cycled through all URLs. timeout.
 *//*from   w w w  .j av  a  2  s  . c om*/
private Response getConnectionAndSendRequestWithTimeout(Object request, String function, int timeout) {
    int originalConnectionIndex = _serverEndpoints.getCurrentEndpointIndex();
    while (true) {
        // currently active server-endpoint
        HttpEndpoint serverEndpoint = _serverEndpoints.getCurrentEndpoint();
        try {
            OkHttpClient client = serverEndpoint.getClient();
            _logger.logInfo("Connecting to " + serverEndpoint.getBaseUrl() + " ("
                    + _serverEndpoints.getCurrentEndpointIndex() + ")");

            client.setConnectTimeout(timeout, TimeUnit.MILLISECONDS);
            client.setReadTimeout(timeout, TimeUnit.MILLISECONDS);
            client.setWriteTimeout(timeout, TimeUnit.MILLISECONDS);

            Stopwatch callDuration = Stopwatch.createStarted();
            // build request
            final String toSend = getPostBody(request);
            Request rq = new Request.Builder().addHeader(MYCELIUM_VERSION_HEADER, versionCode)
                    .post(RequestBody.create(MediaType.parse("application/json"), toSend))
                    .url(serverEndpoint.getUri(WapiConst.WAPI_BASE_PATH, function).toString()).build();

            // execute request
            Response response = client.newCall(rq).execute();
            callDuration.stop();
            _logger.logInfo(String.format(Locale.ENGLISH, "Wapi %s finished (%dms)", function,
                    callDuration.elapsed(TimeUnit.MILLISECONDS)));

            // Check for status code 2XX
            if (response.isSuccessful()) {
                if (serverEndpoint instanceof FeedbackEndpoint) {
                    ((FeedbackEndpoint) serverEndpoint).onSuccess();
                }
                return response;
            } else {
                // If the status code is not 200 we cycle to the next server
                logError(String.format(Locale.ENGLISH, "Http call to %s failed with %d %s", function,
                        response.code(), response.message()));
                // throw...
            }
        } catch (IOException e) {
            logError("IOException when sending request " + function, e);
            if (serverEndpoint instanceof FeedbackEndpoint) {
                _logger.logInfo("Resetting tor");
                ((FeedbackEndpoint) serverEndpoint).onError();
            }
        }
        // Try the next server
        _serverEndpoints.switchToNextEndpoint();
        if (_serverEndpoints.getCurrentEndpointIndex() == originalConnectionIndex) {
            // We have tried all URLs
            return null;
        }

    }
}

From source file:com.example.cloudsql.CloudSqlServlet.java

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
    final String createTableSql = "CREATE TABLE IF NOT EXISTS visits ( visit_id INT NOT NULL "
            + "AUTO_INCREMENT, user_ip VARCHAR(46) NOT NULL, timestamp DATETIME NOT NULL, "
            + "PRIMARY KEY (visit_id) )";
    final String createVisitSql = "INSERT INTO visits (user_ip, timestamp) VALUES (?, ?)";
    final String selectSql = "SELECT user_ip, timestamp FROM visits ORDER BY timestamp DESC " + "LIMIT 10";

    String path = req.getRequestURI();
    if (path.startsWith("/favicon.ico")) {
        return; // ignore the request for favicon.ico
    }/*  w w  w.j  ava  2  s .c o m*/

    PrintWriter out = resp.getWriter();
    resp.setContentType("text/plain");

    // store only the first two octets of a users ip address
    String userIp = req.getRemoteAddr();
    InetAddress address = InetAddress.getByName(userIp);
    if (address instanceof Inet6Address) {
        // nest indexOf calls to find the second occurrence of a character in a string
        // an alternative is to use Apache Commons Lang: StringUtils.ordinalIndexOf()
        userIp = userIp.substring(0, userIp.indexOf(":", userIp.indexOf(":") + 1)) + ":*:*:*:*:*:*";
    } else if (address instanceof Inet4Address) {
        userIp = userIp.substring(0, userIp.indexOf(".", userIp.indexOf(".") + 1)) + ".*.*";
    }

    Stopwatch stopwatch = Stopwatch.createStarted();
    try (PreparedStatement statementCreateVisit = conn.prepareStatement(createVisitSql)) {
        conn.createStatement().executeUpdate(createTableSql);
        statementCreateVisit.setString(1, userIp);
        statementCreateVisit.setTimestamp(2, new Timestamp(new Date().getTime()));
        statementCreateVisit.executeUpdate();

        try (ResultSet rs = conn.prepareStatement(selectSql).executeQuery()) {
            stopwatch.stop();
            out.print("Last 10 visits:\n");
            while (rs.next()) {
                String savedIp = rs.getString("user_ip");
                String timeStamp = rs.getString("timestamp");
                out.print("Time: " + timeStamp + " Addr: " + savedIp + "\n");
            }
            out.println("Elapsed: " + stopwatch.elapsed(TimeUnit.MILLISECONDS));
        }
    } catch (SQLException e) {
        throw new ServletException("SQL error", e);
    }
}

From source file:qa.qcri.nadeef.core.utils.sql.PostgresSQLDialect.java

/**
 * {@inheritDoc}//from   w w w. j  a  v a  2s  .c o m
 */
@Override
public int bulkLoad(DBConfig dbConfig, String tableName, Path file, boolean skipHeader) {
    Logger tracer = Logger.getLogger(PostgresSQLDialect.class);
    tracer.info("Bulk load CSV file " + file.toString());
    try (Connection conn = DBConnectionPool.createConnection(dbConfig, true);
            FileReader reader = new FileReader(file.toFile())) {
        Stopwatch watch = Stopwatch.createStarted();
        Schema schema = DBMetaDataTool.getSchema(dbConfig, tableName);
        StringBuilder builder = new StringBuilder();
        for (Column column : schema.getColumns()) {
            if (column.getColumnName().equalsIgnoreCase("TID"))
                continue;
            builder.append(column.getColumnName()).append(",");
        }
        builder.deleteCharAt(builder.length() - 1);

        CopyManager copyManager = new CopyManager((BaseConnection) conn);
        String sql = String.format("COPY %s (%s) FROM STDIN WITH (FORMAT 'csv', DELIMITER ',', HEADER %s)",
                tableName, builder.toString(), skipHeader ? "true" : "false");
        tracer.info(sql);
        copyManager.copyIn(sql, reader);
        watch.stop();
        tracer.info("Bulk load finished in " + watch.elapsed(TimeUnit.MILLISECONDS) + " ms");
    } catch (Exception ex) {
        tracer.error("Loading csv file " + file.getFileName() + " failed.", ex);
        return 1;
    }
    return 0;
}