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:nl.knaw.huygens.timbuctoo.tools.importer.JsonImporter.java

public static void main(String[] args) throws Exception {
    Stopwatch stopWatch = Stopwatch.createStarted();

    String vreId = (args.length > 0) ? args[0] : DEFAULT_VRE_ID;
    LOG.info("VRE: {}", vreId);

    String directoryName = (args.length > 1) ? args[1] : IMPORT_DIRECTORY_NAME + vreId + "/";
    LOG.info("Import directory: {}", directoryName);

    Injector injector = ToolsInjectionModule.createInjector();
    Repository repository = injector.getInstance(Repository.class);
    IndexManager indexManager = injector.getInstance(IndexManager.class);

    try {//  ww w . j  a  v  a2s.c o m
        File directory = new File(directoryName);
        File file = new File(directory, CONTROL_FILE_NAME);
        JsonImporter importer = new JsonImporter(repository, indexManager, vreId, directory);
        importer.handleFile(file, 2, false);
    } finally {
        indexManager.close();
        repository.close();
        LOG.info("Time used: {}", stopWatch);
    }
}

From source file:com.google.devtools.build.android.LibraryRClassGeneratorAction.java

public static void main(String[] args) throws Exception {
    final Stopwatch timer = Stopwatch.createStarted();
    OptionsParser optionsParser = OptionsParser.newOptionsParser(Options.class, AaptConfigOptions.class);
    optionsParser.parseAndExitUponError(args);
    AaptConfigOptions aaptConfigOptions = optionsParser.getOptions(AaptConfigOptions.class);
    Options options = optionsParser.getOptions(Options.class);
    logger.fine(String.format("Option parsing finished at %sms", timer.elapsed(TimeUnit.MILLISECONDS)));
    try (ScopedTemporaryDirectory scopedTmp = new ScopedTemporaryDirectory("android_resource_generated")) {
        AndroidResourceClassWriter resourceClassWriter = AndroidResourceClassWriter.createWith(
                aaptConfigOptions.androidJar, scopedTmp.getPath(), Strings.nullToEmpty(options.packageForR));
        resourceClassWriter.setIncludeClassFile(true);
        resourceClassWriter.setIncludeJavaFile(false);
        final AndroidResourceProcessor resourceProcessor = new AndroidResourceProcessor(stdLogger);
        logger.fine(String.format("Setup finished at %sms", timer.elapsed(TimeUnit.MILLISECONDS)));

        final ParsedAndroidData data = resourceProcessor.deserializeSymbolsToData(options.symbols);
        logger.fine(String.format("Deserialization finished at %sms", timer.elapsed(TimeUnit.MILLISECONDS)));

        data.writeResourcesTo(resourceClassWriter);
        resourceClassWriter.flush();/*from w ww .  j  a  va  2  s  .  c om*/
        logger.fine(String.format("R writing finished at %sms", timer.elapsed(TimeUnit.MILLISECONDS)));

        resourceProcessor.createClassJar(scopedTmp.getPath(), options.classJarOutput);
        logger.fine(String.format("Creating class jar finished at %sms", timer.elapsed(TimeUnit.MILLISECONDS)));
    } catch (IOException | MergingException | DeserializationException e) {
        logger.log(Level.SEVERE, "Errors during R generation.", e);
        throw e;
    }
}

From source file:com.google.devtools.build.android.AndroidResourceParsingAction.java

public static void main(String[] args) throws Exception {
    OptionsParser optionsParser = OptionsParser.newOptionsParser(Options.class);
    optionsParser.parseAndExitUponError(args);
    Options options = optionsParser.getOptions(Options.class);

    Preconditions.checkNotNull(options.primaryData);
    Preconditions.checkNotNull(options.output);

    final Stopwatch timer = Stopwatch.createStarted();
    ParsedAndroidData parsedPrimary = ParsedAndroidData.from(options.primaryData);
    logger.fine(String.format("Walked XML tree at %dms", timer.elapsed(TimeUnit.MILLISECONDS)));
    UnwrittenMergedAndroidData unwrittenData = UnwrittenMergedAndroidData.of(null, parsedPrimary,
            ParsedAndroidData.from(ImmutableList.<DependencyAndroidData>of()));
    AndroidDataSerializer serializer = AndroidDataSerializer.create();
    unwrittenData.serializeTo(serializer);
    serializer.flushTo(options.output);//  w w  w  .  j ava 2  s  . c o  m
    logger.fine(String.format("Finished parse + serialize in %dms", timer.elapsed(TimeUnit.MILLISECONDS)));
}

From source file:nl.knaw.huygens.timbuctoo.tools.conversion.MongoTinkerPopConverter.java

public static void main(String[] args) throws Exception {
    Stopwatch stopwatch = Stopwatch.createStarted();
    Injector injector = ToolsInjectionModule.createInjectorWithoutSolr();
    Graph graph = injector.getInstance(Graph.class);
    ElementConverterFactory converterFactory = injector.getInstance(ElementConverterFactory.class);
    IdGenerator idGenerator = injector.getInstance(IdGenerator.class);
    TinkerPopConversionStorage graphStorage = injector.getInstance(TinkerPopConversionStorage.class);

    MongoConversionStorage mongoStorage = injector.getInstance(MongoConversionStorage.class);
    TypeRegistry registry = injector.getInstance(TypeRegistry.class);

    MongoTinkerPopConverter converter = new MongoTinkerPopConverter(graphStorage, graph, idGenerator,
            converterFactory, registry, mongoStorage);

    try {//from  w  w w .  ja v a 2s.  c o m
        converter.convertSystemEntities();
        converter.convertDomainEntities();
    } finally {
        graph.shutdown();
        mongoStorage.close();
    }

    LOG.info("Done in {}", stopwatch.stop());
}

From source file:com.google.devtools.build.android.AndroidResourceValidatorAction.java

public static void main(String[] args) throws Exception {
    final Stopwatch timer = Stopwatch.createStarted();
    OptionsParser optionsParser = OptionsParser.newOptionsParser(Options.class, AaptConfigOptions.class);
    optionsParser.parseAndExitUponError(args);
    AaptConfigOptions aaptConfigOptions = optionsParser.getOptions(AaptConfigOptions.class);
    Options options = optionsParser.getOptions(Options.class);

    final AndroidResourceProcessor resourceProcessor = new AndroidResourceProcessor(stdLogger);
    VariantType packageType = VariantType.LIBRARY;

    Preconditions.checkNotNull(options.rOutput);
    Preconditions.checkNotNull(options.srcJarOutput);
    try (ScopedTemporaryDirectory scopedTmp = new ScopedTemporaryDirectory("resource_validator_tmp")) {
        Path tmp = scopedTmp.getPath();
        Path expandedOut = tmp.resolve("tmp-expanded");
        Path resources = expandedOut.resolve("res");
        Path assets = expandedOut.resolve("assets");
        Path generatedSources = tmp.resolve("generated_resources");
        Path dummyManifest = tmp.resolve("manifest-aapt-dummy/AndroidManifest.xml");

        unpackZip(options.mergedResources, expandedOut);
        logger.fine(String.format("unpacked zip at %sms", timer.elapsed(TimeUnit.MILLISECONDS)));

        // We need to make the manifest aapt safe (w.r.t., placeholders). For now, just stub it out.
        resourceProcessor.writeDummyManifestForAapt(dummyManifest, options.packageForR);

        resourceProcessor.runAapt(aaptConfigOptions.aapt, aaptConfigOptions.androidJar,
                aaptConfigOptions.buildToolsVersion, packageType, aaptConfigOptions.debug, options.packageForR,
                new FlagAaptOptions(aaptConfigOptions), aaptConfigOptions.resourceConfigs,
                ImmutableList.<String>of(), dummyManifest, resources, assets, generatedSources,
                null, /* packageOut */
                null, /* proguardOut */
                null, /* mainDexProguardOut */
                null /* publicResourcesOut */);
        logger.fine(String.format("aapt finished at %sms", timer.elapsed(TimeUnit.MILLISECONDS)));

        resourceProcessor.copyRToOutput(generatedSources, options.rOutput, VariantType.LIBRARY == packageType);

        resourceProcessor.createSrcJar(generatedSources, options.srcJarOutput,
                VariantType.LIBRARY == packageType);
    } catch (Exception e) {
        logger.log(java.util.logging.Level.SEVERE, "Unexpected", e);
        throw e;/*w  ww. ja  v  a 2  s  .  c  om*/
    } finally {
        resourceProcessor.shutdown();
    }
    logger.fine(String.format("Resources merged in %sms", timer.elapsed(TimeUnit.MILLISECONDS)));
}

From source file:org.krm1312.test.ClientApp.java

public static void main(String[] args) throws Exception {

    TcpClientFactory<Message<byte[]>, Message<byte[]>> tcpClientFactory = spec -> spec
            .codec(new Reactor2StompCodec()).connect("127.0.0.1", 61613);

    TcpClient<Message<byte[]>, Message<byte[]>> tcpClient = NetStreams.tcpClient(NettyTcpClient.class,
            tcpClientFactory);/*from   w  w  w  .ja v  a2 s.c  o  m*/

    AtomicReference<ChannelStream<Message<byte[]>, Message<byte[]>>> reference = new AtomicReference<>();
    CountDownLatch latch = new CountDownLatch(1);

    tcpClient.start(channelStream -> {

        reference.set(channelStream);

        channelStream.consume(message -> {
            StompHeaderAccessor inAccessor = MessageHeaderAccessor.getAccessor(message,
                    StompHeaderAccessor.class);
            if (StompCommand.CONNECTED.equals(inAccessor.getCommand())) {
                latch.countDown();
            }
        });

        StompHeaderAccessor accessor = StompHeaderAccessor.create(StompCommand.CONNECT);
        accessor.setAcceptVersion("1.1,1.2");
        accessor.setLogin("guest");
        accessor.setPasscode("guest");
        Message<byte[]> connectMessage = MessageBuilder.createMessage(new byte[0],
                accessor.getMessageHeaders());
        channelStream.writeWith(Streams.just(connectMessage)).subscribe(Promises.prepare());

        return Promises.prepare();
    });

    latch.await(5000, TimeUnit.MILLISECONDS);
    ChannelStream<Message<byte[]>, Message<byte[]>> channelStream = reference.get();

    int cnt = 1000;
    Stopwatch sw = Stopwatch.createStarted();
    for (int i = 0; i < cnt; i++) {
        logger.debug("Sending message: " + i);
        StompHeaderAccessor outAccessor = StompHeaderAccessor.create(StompCommand.SEND);
        outAccessor.setDestination("/topic/foo");
        Message<byte[]> outMessage = MessageBuilder.createMessage(new byte[0], outAccessor.getMessageHeaders());
        Promise<Void> promise = Promises.prepare();
        channelStream.writeWith(Streams.just(outMessage)).subscribe(promise);
        promise.await();
    }
    logger.info("Sent {} in {}", cnt, sw);

    System.in.read();

}

From source file:nl.knaw.huygens.timbuctoo.tools.importer.neww.CobwwwebNoImporter.java

public static void main(String[] args) throws Exception {
    Stopwatch stopWatch = Stopwatch.createStarted();

    CobwwwebNoImporter importer = null;/*w ww .j a v  a 2s  .c  o  m*/
    try {
        Injector injector = ToolsInjectionModule.createInjector();
        Repository repository = injector.getInstance(Repository.class);
        IndexManager indexManager = injector.getInstance(IndexManager.class);

        importer = new CobwwwebNoImporter(repository, indexManager);
        importer.importAll();
    } finally {
        if (importer != null) {
            importer.close();
        }
        LOG.info("Time used: {}", stopWatch);
    }
}

From source file:org.opendaylight.netconf.test.tool.Main.java

public static void main(final String[] args) {
    final TesttoolParameters params = TesttoolParameters.parseArgs(args, TesttoolParameters.getParser());
    params.validate();//from  w w  w. j  av a2s. co m
    final ch.qos.logback.classic.Logger root = (ch.qos.logback.classic.Logger) LoggerFactory
            .getLogger(Logger.ROOT_LOGGER_NAME);
    root.setLevel(params.debug ? Level.DEBUG : Level.INFO);

    final NetconfDeviceSimulator netconfDeviceSimulator = new NetconfDeviceSimulator(params.threadPoolSize);
    try {
        LOG.debug("Trying to start netconf test-tool with parameters {}", params);
        final List<Integer> openDevices = netconfDeviceSimulator.start(params);
        if (openDevices.size() == 0) {
            LOG.error("Failed to start any simulated devices, exiting...");
            System.exit(1);
        }
        if (params.controllerDestination != null) {
            final ArrayList<ArrayList<Execution.DestToPayload>> allThreadsPayloads = params
                    .getThreadsPayloads(openDevices);
            final ArrayList<Execution> executions = new ArrayList<>();
            for (ArrayList<Execution.DestToPayload> payloads : allThreadsPayloads) {
                executions.add(new Execution(params, payloads));
            }
            final ExecutorService executorService = Executors.newFixedThreadPool(params.threadAmount);
            final Stopwatch time = Stopwatch.createStarted();
            List<Future<Void>> futures = executorService.invokeAll(executions, params.timeOut,
                    TimeUnit.SECONDS);
            int threadNum = 0;
            for (Future<Void> future : futures) {
                threadNum++;
                if (future.isCancelled()) {
                    LOG.info("{}. thread timed out.", threadNum);
                } else {
                    try {
                        future.get();
                    } catch (final ExecutionException e) {
                        LOG.info("{}. thread failed.", threadNum, e);
                    }
                }
            }
            time.stop();
            LOG.info("Time spent with configuration of devices: {}.", time);
        }

        if (params.distroFolder != null) {
            final ConfigGenerator configGenerator = new ConfigGenerator(params.distroFolder, openDevices);
            final List<File> generated = configGenerator.generate(params.ssh, params.generateConfigBatchSize,
                    params.generateConfigsTimeout, params.generateConfigsAddress, params.devicesPerPort);
            configGenerator.updateFeatureFile(generated);
            configGenerator.changeLoadOrder();
        }
    } catch (final Exception e) {
        LOG.error("Unhandled exception", e);
        netconfDeviceSimulator.close();
        System.exit(1);
    }

    // Block main thread
    synchronized (netconfDeviceSimulator) {
        try {
            netconfDeviceSimulator.wait();
        } catch (final InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}

From source file:com.github.ibole.infrastructure.security.jwt.auth0.Auth0Utils.java

public static void main(String[] args) throws Exception {

    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("EC");
    keyPairGenerator.initialize(256);//  w w  w .  ja v a  2  s .co  m
    KeyPair keyPair = keyPairGenerator.generateKeyPair();
    ECPublicKey ecPublicKey = (ECPublicKey) keyPair.getPublic();
    ECPrivateKey ecPrivateKey = (ECPrivateKey) keyPair.getPrivate();

    JwtObject jwt = new JwtObject();
    jwt.setAudience("audience");
    jwt.setClientId("clientId");
    jwt.setIssuer("issuer");
    jwt.setLoginId("loginId");
    jwt.setSubject("subject");
    jwt.setTtlSeconds(5);
    jwt.getRoles().add("admin");

    final Stopwatch stopwatch = Stopwatch.createStarted();

    String token = createJwtWithECKey(jwt, ecPublicKey, ecPrivateKey);

    TokenValidationCallback<DecodedJWT> callback = new BaseTokenValidationCallback<DecodedJWT>();
    validateToken(token, jwt.getClientId(), ecPublicKey, ecPrivateKey, callback);

    //Thread.currentThread().sleep(9000);

    JwtObject newjwt = claimsOfTokenWithoutValidation(token, ecPublicKey, ecPrivateKey);

    String elapsedString = Long.toString(stopwatch.elapsed(TimeUnit.MILLISECONDS));

    System.out.println("Spent: " + elapsedString);
    System.out.println(callback.getTokenStatus());
    System.out.println(token);

}

From source file:nl.knaw.huygens.timbuctoo.tools.importer.ckcc.CKCCImporter.java

public static void main(String[] args) throws Exception {
    Stopwatch stopWatch = Stopwatch.createStarted();

    // Handle commandline arguments
    String directory = (args.length > 0) ? args[0] : "../../timbuctoo-testdata/src/main/resources/ckcc/";

    CKCCImporter importer = null;//from   w w w.  j av a 2 s  .  c  o  m
    try {
        Injector injector = ToolsInjectionModule.createInjector();
        Repository repository = injector.getInstance(Repository.class);
        IndexManager indexManager = injector.getInstance(IndexManager.class);

        importer = new CKCCImporter(repository, indexManager, directory);
        importer.importAll(false);
    } finally {
        if (importer != null) {
            importer.close();
        }
        LOG.info("Time used: {}", stopWatch);
    }
}