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

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

Introduction

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

Prototype

@CheckReturnValue
public static Stopwatch createStarted() 

Source Link

Document

Creates (and starts) a new stopwatch using System#nanoTime as its time source.

Usage

From source file:qa.qcri.nadeef.core.util.sql.SQLDialectBase.java

/**
 * Loads CSV file when bulk load is not used.
 * @param dbConfig {@link qa.qcri.nadeef.tools.DBConfig}
 * @param tableName table name./*w  w w  .  jav a2 s.c  om*/
 * @param file CSV file.
 * @param skipHeader skip header.
 * @return line of rows loaded.
 */
public int fallbackLoad(DBConfig dbConfig, String tableName, File file, boolean skipHeader) {
    Tracer tracer = Tracer.getTracer(SQLDialectBase.class);
    Stopwatch stopwatch = Stopwatch.createStarted();

    try (Connection conn = DBConnectionPool.createConnection(dbConfig, false);
            Statement stat = conn.createStatement();
            BufferedReader reader = new BufferedReader(new FileReader(file))) {
        ResultSet rs = stat.executeQuery(this.selectAll(tableName));
        ResultSetMetaData metaData = rs.getMetaData();
        String line;
        int lineCount = 0;
        int size = 0;
        // Batch load the data
        while ((line = reader.readLine()) != null) {
            lineCount++;
            if (Strings.isNullOrEmpty(line))
                continue;
            if (skipHeader && lineCount == 1)
                continue;
            size += line.toCharArray().length;
            String[] tokens = line.split(",");
            String[] newTokens = new String[tokens.length];
            for (int i = 0; i < tokens.length; i++) {
                newTokens[i] = CommonTools.unescapeString(tokens[i], CommonTools.DOUBLE_QUOTE);
            }

            String sql = this.importFromCSV(metaData, tableName, newTokens);
            stat.addBatch(sql);

            if (lineCount % 10240 == 0) {
                stat.executeBatch();
            }
        }

        stat.executeBatch();
        conn.commit();

        tracer.info("Dumped " + size + " bytes in " + stopwatch.elapsed(TimeUnit.MILLISECONDS) + " ms.");
        stopwatch.stop();
        return lineCount;
    } catch (Exception ex) {
        tracer.err("Cannot load file " + file.getName(), ex);
    }
    return 0;
}

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

/**
 * Loads CSV file when bulk load is not used.
 * @param dbConfig {@link qa.qcri.nadeef.tools.DBConfig}
 * @param tableName table name./*from   w  w w.  j a  v  a  2s.  c  o  m*/
 * @param file CSV file.
 * @param skipHeader skip header.
 * @return line of rows loaded.
 */
public int fallbackLoad(DBConfig dbConfig, String tableName, File file, boolean skipHeader) {
    Logger tracer = Logger.getLogger(SQLDialectBase.class);
    Stopwatch stopwatch = Stopwatch.createStarted();

    try (Connection conn = DBConnectionPool.createConnection(dbConfig, false);
            Statement stat = conn.createStatement();
            BufferedReader reader = new BufferedReader(new FileReader(file))) {
        ResultSet rs = stat.executeQuery(this.selectAll(tableName));
        ResultSetMetaData metaData = rs.getMetaData();
        String line;
        int lineCount = 0;
        int size = 0;
        // Batch load the data
        while ((line = reader.readLine()) != null) {
            lineCount++;
            if (Strings.isNullOrEmpty(line))
                continue;
            if (skipHeader && lineCount == 1)
                continue;
            size += line.toCharArray().length;
            String[] tokens = line.split(",");
            String[] newTokens = new String[tokens.length];
            for (int i = 0; i < tokens.length; i++) {
                newTokens[i] = CommonTools.unescapeString(tokens[i], CommonTools.DOUBLE_QUOTE);
            }

            String sql = this.importFromCSV(metaData, tableName, newTokens);
            stat.addBatch(sql);

            if (lineCount % 10240 == 0) {
                stat.executeBatch();
            }
        }

        stat.executeBatch();
        conn.commit();

        tracer.info("Dumped " + size + " bytes in " + stopwatch.elapsed(TimeUnit.MILLISECONDS) + " ms.");
        stopwatch.stop();
        return lineCount;
    } catch (Exception ex) {
        tracer.error("Cannot load file " + file.getName(), ex);
    }
    return 0;
}

From source file:co.mitro.core.servlets.ListMySecretsAndGroupKeys.java

public static ListMySecretsAndGroupKeysResponse executeWithoutAuditLog(MitroRequestContext context)
        throws SQLException, MitroServletException, DoEmailVerificationException {
    ListMySecretsAndGroupKeysResponse out = new RPC.ListMySecretsAndGroupKeysResponse();
    Stopwatch stopwatch = Stopwatch.createStarted();
    out.myUserId = context.requestor.getName();
    @SuppressWarnings("deprecation")
    AuthenticatedDB userDb = AuthenticatedDB.deprecatedNew(context.manager, context.requestor);

    out.groups = Maps.newHashMap();//from   ww  w  . java2  s. co  m
    out.organizations = Maps.newHashMap();
    Set<String> users = Sets.newHashSet();
    Set<Integer> groupIds = getGroupsUsersAndOrgsFromRawStatement(context, context.requestor.getId(), null,
            out.groups, out.organizations, users, null);
    for (GroupInfo gi : out.organizations.values()) {
        if (gi.isTopLevelOrg) {
            if (userDb.isOrganizationAdmin(gi.groupId)) {
                gi.isRequestorAnOrgAdmin = true;
            } else {
                gi.encryptedPrivateKey = null;
                gi.isRequestorAnOrgAdmin = false;
            }
        }
    }

    out.autocompleteUsers = Lists.newArrayList(users);
    out.secretToPath = Maps.newHashMap();
    getSecretInfo(context, AdminAccess.IGNORE_ACCESS_VIA_TOPLEVEL_GROUPS, out.secretToPath, groupIds, null,
            IncludeAuditLogInfo.NO_AUDIT_LOG_INFO);

    logger.info("{} elapsed: {} ms:", out.myUserId, stopwatch.elapsed(TimeUnit.MILLISECONDS));
    return out;
}

From source file:com.minestellar.moon.MinestellarMoon.java

@EventHandler
public void preInit(FMLPreInitializationEvent event) {
    Stopwatch stopwatch = Stopwatch.createStarted();

    new ConfigManagerMoon(new File(event.getModConfigurationDirectory(), "Minestellar/moon.cfg"));

    MoonBlocks.init();/*w  w  w .j  ava 2 s  . c om*/
    MoonItems.init();

    DimensionMoon.init();

    MinestellarMoon.proxy.preInit(event);

    log.info("PreInitialization Completed in " + stopwatch.elapsed(TimeUnit.MILLISECONDS) + " ms.");
}

From source file:ec.nbdemetra.spreadsheet.SpreadSheetBasicFileHandler.java

@Override
public Object asyncLoad(File file, BasicFileViewer.ProgressCallback progress) throws Exception {
    ArrayBook.Builder result = ArrayBook.builder();
    Stopwatch sw = Stopwatch.createStarted();
    Book.Factory factory = factories.firstMatch(filePredicate(file)).get();
    try (Book book = factory.load(file)) {
        for (int s = 0; s < book.getSheetCount(); s++) {
            result.sheet(book.getSheet(s));
            progress.setProgress(0, book.getSheetCount(), s);
        }/*from  ww w  .  j  av a 2s  .  c o m*/
    }
    return new Model(factory.getName(), file, result.build(), sw.stop().elapsed(TimeUnit.MILLISECONDS));
}

From source file:co.rsk.bitcoinj.params.AbstractBitcoinNetParams.java

@Override
public void checkDifficultyTransitions(final StoredBlock storedPrev, final BtcBlock nextBlock,
        final BtcBlockStore blockStore) throws VerificationException, BlockStoreException {
    BtcBlock prev = storedPrev.getHeader();

    // Is this supposed to be a difficulty transition point?
    if (!isDifficultyTransitionPoint(storedPrev)) {

        // No ... so check the difficulty didn't actually change.
        if (nextBlock.getDifficultyTarget() != prev.getDifficultyTarget())
            throw new VerificationException("Unexpected change in difficulty at height "
                    + storedPrev.getHeight() + ": " + Long.toHexString(nextBlock.getDifficultyTarget()) + " vs "
                    + Long.toHexString(prev.getDifficultyTarget()));
        return;//w  w w.j  a v  a 2  s . co m
    }

    // We need to find a block far back in the chain. It's OK that this is expensive because it only occurs every
    // two weeks after the initial block chain download.
    final Stopwatch watch = Stopwatch.createStarted();
    StoredBlock cursor = blockStore.get(prev.getHash());
    for (int i = 0; i < this.getInterval() - 1; i++) {
        if (cursor == null) {
            // This should never happen. If it does, it means we are following an incorrect or busted chain.
            throw new VerificationException(
                    "Difficulty transition point but we did not find a way back to the genesis block.");
        }
        cursor = blockStore.get(cursor.getHeader().getPrevBlockHash());
    }
    watch.stop();
    if (watch.elapsed(TimeUnit.MILLISECONDS) > 50)
        log.info("Difficulty transition traversal took {}", watch);

    BtcBlock blockIntervalAgo = cursor.getHeader();
    int timespan = (int) (prev.getTimeSeconds() - blockIntervalAgo.getTimeSeconds());
    // Limit the adjustment step.
    final int targetTimespan = this.getTargetTimespan();
    if (timespan < targetTimespan / 4)
        timespan = targetTimespan / 4;
    if (timespan > targetTimespan * 4)
        timespan = targetTimespan * 4;

    BigInteger newTarget = Utils.decodeCompactBits(prev.getDifficultyTarget());
    newTarget = newTarget.multiply(BigInteger.valueOf(timespan));
    newTarget = newTarget.divide(BigInteger.valueOf(targetTimespan));

    if (newTarget.compareTo(this.getMaxTarget()) > 0) {
        log.info("Difficulty hit proof of work limit: {}", newTarget.toString(16));
        newTarget = this.getMaxTarget();
    }

    int accuracyBytes = (int) (nextBlock.getDifficultyTarget() >>> 24) - 3;
    long receivedTargetCompact = nextBlock.getDifficultyTarget();

    // The calculated difficulty is to a higher precision than received, so reduce here.
    BigInteger mask = BigInteger.valueOf(0xFFFFFFL).shiftLeft(accuracyBytes * 8);
    newTarget = newTarget.and(mask);
    long newTargetCompact = Utils.encodeCompactBits(newTarget);

    if (newTargetCompact != receivedTargetCompact)
        throw new VerificationException("Network provided difficulty bits do not match what was calculated: "
                + Long.toHexString(newTargetCompact) + " vs " + Long.toHexString(receivedTargetCompact));
}

From source file:com.github.ibole.microservice.security.auth.jwt.jose4j.EcJose4jTokenAuthenticator.java

/**
 * Create Access Token.//w  w w. j a  v  a 2  s.  c  o m
 * 
 */
@Override
public String createAccessToken(JwtObject claimObj) throws TokenHandlingException {
    Preconditions.checkArgument(claimObj != null, "Parameter claimObj cannot be null");
    final Stopwatch stopwatch = Stopwatch.createStarted();
    String token = null;
    try {
        if (!Constants.ANONYMOUS_ID.equalsIgnoreCase(claimObj.getLoginId())
                && !getCacheService().has(getRefreshTokenKey(claimObj.getLoginId()))) {
            throw new RefreshTokenNotFoundException("Refresh token not found.");
        }
        token = JoseUtils.createJwtWithECKey(claimObj, (EllipticCurveJsonWebKey) ecJsonWebKey);
        getCacheService().set(getRefreshTokenKey(claimObj.getLoginId()), Constants.ACCESS_TOKEN, token);
    } catch (JoseException ex) {
        logger.error("Error happened when generating the jwt token.", ex);
        throw new TokenHandlingException(ex);
    }
    String elapsedString = Long.toString(stopwatch.elapsed(TimeUnit.MILLISECONDS));
    logger.debug("Create access token elapsed time: {} ms", elapsedString);
    return token;
}

From source file:org.grouplens.lenskit.cli.Predict.java

@Override
public void execute() throws IOException, RecommenderBuildException {
    LenskitRecommenderEngine engine = loadEngine();

    long user = options.getLong("user");
    List<Long> items = options.get("items");

    LenskitRecommender rec = engine.createRecommender();
    RatingPredictor pred = rec.getRatingPredictor();
    if (pred == null) {
        logger.error("recommender has no rating predictor");
        throw new UnsupportedOperationException("no rating predictor");
    }/*  ww w.  j ava 2 s.c  o  m*/

    logger.info("predicting {} items", items.size());
    Symbol pchan = getPrintChannel();
    Stopwatch timer = Stopwatch.createStarted();
    SparseVector preds = pred.predict(user, items);
    Long2ObjectMap channel = null;
    if (pchan != null) {
        for (TypedSymbol sym : preds.getChannelSymbols()) {
            if (sym.getRawSymbol().equals(pchan)) {
                channel = preds.getChannel(sym);
            }
        }
    }
    for (VectorEntry e : preds.fast()) {
        System.out.format("  %d: %.3f", e.getKey(), e.getValue());
        if (channel != null) {
            System.out.format(" (%s)", channel.get(e.getKey()));
        }
        System.out.println();
    }
    timer.stop();
    logger.info("predicted for {} items in {}", items.size(), timer);
}

From source file:org.graylog2.shared.initializers.PeriodicalsService.java

@Override
protected void shutDown() throws Exception {
    for (Periodical periodical : periodicals.getAllStoppedOnGracefulShutdown()) {
        LOG.info("Shutting down periodical [{}].", periodical.getClass().getCanonicalName());
        Stopwatch s = Stopwatch.createStarted();

        // Cancel future executions.
        Map<Periodical, ScheduledFuture> futures = periodicals.getFutures();
        if (futures.containsKey(periodical)) {
            futures.get(periodical).cancel(false);

            s.stop();//w w w  .j av  a2 s.  co  m
            LOG.info("Shutdown of periodical [{}] complete, took <{}ms>.",
                    periodical.getClass().getCanonicalName(), s.elapsed(TimeUnit.MILLISECONDS));
        } else {
            LOG.error("Could not find periodical [{}] in futures list. Not stopping execution.",
                    periodical.getClass().getCanonicalName());
        }
    }
}

From source file:org.glowroot.container.trace.TraceService.java

public @Nullable Trace getActiveTrace(int timeout, TimeUnit unit) throws Exception {
    Stopwatch stopwatch = Stopwatch.createStarted();
    Trace trace = null;//from   w w w  .j av a 2s .  c  o  m
    // try at least once (e.g. in case timeoutMillis == 0)
    boolean first = true;
    while (first || stopwatch.elapsed(unit) < timeout) {
        trace = getActiveTrace();
        if (trace != null) {
            break;
        }
        Thread.sleep(20);
        first = false;
    }
    return trace;
}