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:com.citytechinc.cq.clientlibs.core.listeners.components.impl.DependentComponentEventListener.java

@Override
public void onEvent(EventIterator events) {

    Stopwatch stopwatch = Stopwatch.createStarted();

    List<DependentComponentEvent> dependentComponentEventList = Lists.newArrayList();

    Set<DependentComponent> dependentComponents = dependentComponentManager.getComponents();

    while (events.hasNext()) {
        Event currentEvent = events.nextEvent();

        try {//w w w . java2 s .  c om
            Optional<DependentComponentEvent> eventOptional = dependentComponentEventFactory.make(currentEvent,
                    dependentComponentManager.getComponentsByPath(), session);

            if (eventOptional.isPresent()) {
                dependentComponentEventList.add(eventOptional.get());
            }
        } catch (PathNotFoundException e) {
            LOG.debug("Path Not Found Exception encountered while processing event", e);
        } catch (RepositoryException e) {
            LOG.error("Repository Exception encountered while processing event", e);
        }

    }

    if (dependentComponentEventList.size() > 0) {
        try {
            clientLibraryCacheManager.clearCache();
        } catch (ClientLibraryCachingException e) {
            LOG.error("Exception encountered attempting to clear the cache", e);
        }
        dependentComponentManager.requestRefresh();
    }

    stopwatch.stop();
    LOG.debug("Client Library event handling completed in " + stopwatch.elapsed(TimeUnit.MILLISECONDS)
            + "ms. Resulted in " + dependentComponentEventList.size() + " events");

}

From source file:fr.ymanvieu.trading.admin.AdminService.java

@Transactional(rollbackFor = Exception.class)
public SymbolInfo add(String code, String provider) throws IOException, SymbolException, ProviderException {
    Stopwatch sw = Stopwatch.createStarted();

    boolean hasHistory = false;

    PairEntity pair = pairService.getForCode(code);

    if (pair != null) {
        throw SymbolException.ALREADY_EXISTS(pair.getSymbol());
    }/*from  w  w  w .  j  a  v a2  s.c o m*/

    LookupDetails details = lookupService.getDetails(code, provider);

    String source = details.getSource();
    String currency = details.getCurrency();
    String name = details.getName();

    // FIXME SEKAMD=X (armenian diram) O_o -> Advanced Micro...

    SymbolEntity targetSymbol = symbolService.getForCode(currency);

    if (targetSymbol == null) {
        // TODO refactor
        CurrencyInfo ci = symbolService.getCurrencyInfo(currency);
        String countryFlag = ci.getCountryFlag();
        String currencyName = ci.getName();

        currencyName = (countryFlag != null && currencyName != null) ? currencyName : name;

        symbolService.addSymbol(currency, currencyName, countryFlag, null);
    }

    SymbolEntity sourceSymbol = symbolService.getForCode(source);
    String sourceName = null;

    if (sourceSymbol == null) {
        // TODO refactor
        String countryFlag = CurrencyUtils.countryFlagForCurrency(source);
        String currencyName = CurrencyUtils.nameForCurrency(source);

        sourceName = (countryFlag != null && currencyName != null) ? currencyName : name;

        symbolService.addSymbol(source, sourceName, countryFlag, currency);
    }

    pair = pairService.create(code, name, source, currency, provider);

    Quote latestQuote = stock.getLatestRate(code);

    if (latestQuote == null) {
        throw SymbolException.UNAVAILABLE(code);
    }

    // TODO immutability ! copy data
    latestQuote.setCode(source);
    latestQuote.setCurrency(currency);

    List<Quote> historicalQuotes = new ArrayList<>();

    try {
        historicalQuotes.addAll(stock.getHistoricalRates(code));

        for (Quote q : historicalQuotes) {
            q.setCode(source);
            q.setCurrency(currency);
        }

        hasHistory = true;
    } catch (RuntimeException e) {
        log.warn("No history for code: {}", code);
    }

    historicalQuotes.add(latestQuote);

    rateService.addHistoricalRates(historicalQuotes);
    rateService.addLatestRate(latestQuote);

    log.info("{} created in: {}", pair.getSymbol(), sw);

    return new SymbolInfo(pair.getSymbol(), pair.getName(), hasHistory, latestQuote);
}

From source file:org.lenskit.cli.commands.TrainModel.java

@Override
public void execute(Namespace opts) throws IOException, RecommenderBuildException {
    Context ctx = new Context(opts);
    LenskitConfiguration dataConfig = ctx.input.getConfiguration();
    LenskitRecommenderEngineBuilder builder = LenskitRecommenderEngine.newBuilder();
    for (LenskitConfiguration config : ctx.environment.loadConfigurations(ctx.getConfigFiles())) {
        builder.addConfiguration(config);
    }/* w w w .j  a  va  2s  . co m*/
    builder.addConfiguration(dataConfig, ModelDisposition.EXCLUDED);

    Stopwatch timer = Stopwatch.createStarted();
    LenskitRecommenderEngine engine = builder.build();
    timer.stop();
    logger.info("built model in {}", timer);
    File output = ctx.getOutputFile();
    CompressionMode comp = CompressionMode.autodetect(output);

    logger.info("writing model to {}", output);
    try (OutputStream raw = new FileOutputStream(output); OutputStream stream = comp.wrapOutput(raw)) {
        engine.write(stream);
    }
}

From source file:com.facebook.buck.distributed.build_client.BuildSlaveLogsMaterializer.java

/** Fetches and materializes all logs directories. */
public void fetchAndMaterializeAllLogs(StampedeId stampedeId, List<BuildSlaveRunId> toMaterialize,
        long maxTimeoutForLogsToBeAvailableMillis) throws TimeoutException {
    Stopwatch stopwatch = Stopwatch.createStarted();
    while (stopwatch.elapsed(TimeUnit.MILLISECONDS) <= maxTimeoutForLogsToBeAvailableMillis) {
        toMaterialize = fetchAndMaterializeAvailableLogs(stampedeId, toMaterialize);
        if (toMaterialize.isEmpty()) {
            return;
        }//from   w  ww . j  a v  a  2  s .co  m

        // Back off not to hammer the servers.
        try {
            Thread.sleep(POLLING_CADENCE_MILLIS);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    throw new TimeoutException(String.format(
            "Failed to fetch the logs for BuildSlaveRunIds=[%s] and StampedeId=[%s] " + "within [%d millis].",
            Joiner.on(", ").join(toMaterialize.stream().map(x -> x.getId()).collect(Collectors.toList())),
            stampedeId.getId(), maxTimeoutForLogsToBeAvailableMillis));
}

From source file:org.balloon_project.overflight.task.endpointSource.CKANLoader.java

/**
 * Loads all Linked Open Data endpoints from Datahub.io which offer a SPARQL endpoint
 * @return List of Linked Open Data SPARQL endpoints
 *///from  w  ww .  j av a 2s.co  m
public List<Endpoint> loadEndpoints() throws IOException {
    logger.info("CKAN endpoint loading started");
    Stopwatch timer = Stopwatch.createStarted();

    List<Endpoint> result = new LinkedList<>();
    result.addAll(queryCKAN(DATAHUB_QUERY_LODCLOUD));
    result.addAll(queryCKAN(DATAHUB_QUERY_LOD));

    logger.info(result.size() + " CKAN endpoints loaded. (Duration: " + timer.stop().elapsed(TimeUnit.SECONDS)
            + "s)");

    return result;
}

From source file:org.apache.brooklyn.test.performance.PerformanceTestUtils.java

public static Future<?> sampleProcessCpuTime(final Duration period, final String loggingContext,
        final List<Double> cpuFractions) {
    final ExecutorService executor = Executors.newSingleThreadExecutor(new ThreadFactory() {
        @Override/*from   w  w  w. j  a  v  a 2s .c o m*/
        public Thread newThread(Runnable r) {
            Thread thread = new Thread(r, "brooklyn-sampleProcessCpuTime-" + loggingContext);
            thread.setDaemon(true); // let the JVM exit
            return thread;
        }
    });
    Future<?> future = executor.submit(new Runnable() {
        @Override
        public void run() {
            try {
                long prevCpuTime = getProcessCpuTime();
                if (prevCpuTime == -1) {
                    LOG.warn("ProcessCPuTime not available; cannot sample; aborting");
                    return;
                }
                while (true) {
                    Stopwatch stopwatch = Stopwatch.createStarted();
                    Thread.sleep(period.toMilliseconds());
                    long currentCpuTime = getProcessCpuTime();

                    long elapsedTime = stopwatch.elapsed(TimeUnit.MILLISECONDS);
                    double fractionCpu = (elapsedTime > 0)
                            ? ((double) currentCpuTime - prevCpuTime)
                                    / TimeUnit.MILLISECONDS.toNanos(elapsedTime)
                            : -1;
                    prevCpuTime = currentCpuTime;

                    LOG.info("CPU fraction over last {} was {} ({})", new Object[] {
                            Time.makeTimeStringRounded(elapsedTime), fractionCpu, loggingContext });

                    if (cpuFractions != null) {
                        cpuFractions.add(fractionCpu);
                    }
                }
            } catch (InterruptedException e) {
                return; // graceful termination
            } finally {
                executor.shutdownNow();
            }
        }
    });
    return future;
}

From source file:com.b2international.snowowl.snomed.reasoner.server.classification.ReasonerTaxonomyWalker.java

/**
 * /*from   w  w  w .j a va2 s. c  o m*/
 */
public void walk() {
    LOGGER.info(">>> Taxonomy extraction");

    final Stopwatch stopwatch = Stopwatch.createStarted();
    final Deque<Node<OWLClass>> nodesToProcess = new LinkedList<Node<OWLClass>>();
    nodesToProcess.add(reasoner.getTopClassNode());

    // Breadth-first walk through the class hierarchy
    while (!nodesToProcess.isEmpty()) {

        final Node<OWLClass> currentNode = nodesToProcess.removeFirst();
        final NodeSet<OWLClass> nextNodeSet = walk(currentNode);

        if (!EMPTY_NODE_SET.equals(nextNodeSet)) {

            nodesToProcess.addAll(nextNodeSet.getNodes());

        }

    }

    processedConceptIds.clear();
    processedConceptIds = null;

    LOGGER.info(MessageFormat.format("<<< Taxonomy extraction [{0}]", stopwatch.stop().toString()));
}

From source file:org.obiba.opal.shell.commands.ImportCommand.java

@Override
public int execute() {
    int errorCode;

    Stopwatch stopwatch = Stopwatch.createStarted();

    List<FileObject> filesToImport = getFilesToImport();
    errorCode = executeImports(filesToImport);

    if (!options.isSource() & !options.isTables() & filesToImport.isEmpty()) {
        // Should this be considered success or an error? Will treat as an error for now.
        getShell().printf("No file, source or tables provided. Import canceled.\n");
        errorCode = CRITICAL_ERROR;/*from   w w  w. jav a2 s. co m*/
    } else if (errorCode != SUCCESS) {
        getShell().printf("Import failed.\n");
        log.info("Import failed in {}", stopwatch.stop());
    } else {
        getShell().printf("Import done.\n");
        log.info("Import succeed in {}", stopwatch.stop());
    }
    return errorCode;
}

From source file:ec.jwsacruncher.App.java

private static void process(FileWorkspace ws, WorkspaceItem item, SaProcessing processing,
        EstimationPolicyType policy, int bundleSize) throws IOException {
    Stopwatch stopwatch = Stopwatch.createStarted();

    System.out.println("Refreshing data");
    processing.refresh(policy, false);//from   www . jav a  2 s. c o  m
    SaBatchInformation info = new SaBatchInformation(processing.size() > bundleSize ? bundleSize : 0);
    info.setName(item.getId());
    info.setItems(processing);
    SaBatchProcessor processor = new SaBatchProcessor(info, new ConsoleFeedback());
    processor.process();

    System.out.println("Saving new processing...");
    FileRepository.storeSaProcessing(ws, item, processing);

    System.out.println("Processing time: " + stopwatch.elapsed(TimeUnit.SECONDS) + "s");
}

From source file:brooklyn.util.net.Networking.java

public static boolean isPortAvailable(InetAddress localAddress, int port) {
    if (port < MIN_PORT_NUMBER || port > MAX_PORT_NUMBER) {
        throw new IllegalArgumentException("Invalid start port: " + port);
    }//w w  w . j  a  va 2s.c  o  m

    // For some operations it's not valid to pass ANY_NIC (0.0.0.0).
    // We substitute for the loopback address in those cases.
    InetAddress localAddressNotAny = (localAddress == null || ANY_NIC.equals(localAddress)) ? LOOPBACK
            : localAddress;

    Stopwatch watch = Stopwatch.createStarted();
    try {
        //despite http://stackoverflow.com/questions/434718/sockets-discover-port-availability-using-java
        //(recommending the following) it isn't 100% reliable (e.g. nginx will happily coexist with ss+ds)
        //so we also do the above check
        ServerSocket ss = null;
        DatagramSocket ds = null;
        try {
            // Check TCP port
            ss = new ServerSocket();
            ss.setSoTimeout(250);
            ss.setReuseAddress(true);
            ss.bind(new InetSocketAddress(localAddress, port));

            // Check UDP port
            ds = new DatagramSocket(null);
            ds.setSoTimeout(250);
            ds.setReuseAddress(true);
            ds.bind(new InetSocketAddress(localAddress, port));
        } catch (IOException e) {
            return false;
        } finally {
            if (ds != null) {
                ds.close();
            }

            if (ss != null) {
                try {
                    ss.close();
                } catch (IOException e) {
                    /* should not be thrown */
                }
            }
        }

        if (localAddress == null || ANY_NIC.equals(localAddress)) {
            // sometimes 0.0.0.0 can be bound to even if 127.0.0.1 has the port as in use;
            // check all interfaces if 0.0.0.0 was requested
            Enumeration<NetworkInterface> nis = null;
            try {
                nis = NetworkInterface.getNetworkInterfaces();
            } catch (SocketException e) {
                throw Exceptions.propagate(e);
            }
            while (nis.hasMoreElements()) {
                NetworkInterface ni = nis.nextElement();
                Enumeration<InetAddress> as = ni.getInetAddresses();
                while (as.hasMoreElements()) {
                    InetAddress a = as.nextElement();
                    if (!isPortAvailable(a, port))
                        return false;
                }
            }
        }

        return true;
    } finally {
        // Until timeout was added, was taking 1min5secs for /fe80:0:0:0:1cc5:1ff:fe81:a61d%8 : 8081
        if (log.isTraceEnabled())
            log.trace("Took {} to determine if port {} : {} was available", new Object[] {
                    Time.makeTimeString(watch.elapsed(TimeUnit.MILLISECONDS), true), localAddress, port });
    }
}