Example usage for org.springframework.util StopWatch StopWatch

List of usage examples for org.springframework.util StopWatch StopWatch

Introduction

In this page you can find the example usage for org.springframework.util StopWatch StopWatch.

Prototype

public StopWatch(String id) 

Source Link

Document

Construct a new StopWatch with the given ID.

Usage

From source file:org.springframework.load.AbstractTest.java

/**
 * @see org.springframework.load.Test#reset()
 *///from   w w w  .  java  2  s .c  o m
public void reset() {
    elapsedTimer = new StopWatch("elapsed timer");
    completedTests = 0;
    runningTimer = new StopWatch("running timer");
    pauseTimer = new StopWatch("pause timer");
    testFailedExceptions.clear();
}

From source file:org.springframework.samples.portfolio.web.load.StompWebSocketLoadTestClient.java

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

    // Modify host and port below to match wherever StompWebSocketServer.java is running!!
    // When StompWebSocketServer starts it prints the selected available

    String host = "localhost";
    if (args.length > 0) {
        host = args[0];//from  ww  w .  ja v a  2s . co  m
    }

    int port = 37232;
    if (args.length > 1) {
        port = Integer.valueOf(args[1]);
    }

    String homeUrl = "http://{host}:{port}/home";
    logger.debug("Sending warm-up HTTP request to " + homeUrl);
    HttpStatus status = new RestTemplate().getForEntity(homeUrl, Void.class, host, port).getStatusCode();
    Assert.state(status == HttpStatus.OK);

    final CountDownLatch connectLatch = new CountDownLatch(NUMBER_OF_USERS);
    final CountDownLatch subscribeLatch = new CountDownLatch(NUMBER_OF_USERS);
    final CountDownLatch messageLatch = new CountDownLatch(NUMBER_OF_USERS);
    final CountDownLatch disconnectLatch = new CountDownLatch(NUMBER_OF_USERS);

    final AtomicReference<Throwable> failure = new AtomicReference<>();

    StandardWebSocketClient webSocketClient = new StandardWebSocketClient();

    HttpClient jettyHttpClient = new HttpClient();
    jettyHttpClient.setMaxConnectionsPerDestination(1000);
    jettyHttpClient.setExecutor(new QueuedThreadPool(1000));
    jettyHttpClient.start();

    List<Transport> transports = new ArrayList<>();
    transports.add(new WebSocketTransport(webSocketClient));
    transports.add(new JettyXhrTransport(jettyHttpClient));

    SockJsClient sockJsClient = new SockJsClient(transports);

    try {
        ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
        taskScheduler.afterPropertiesSet();

        String stompUrl = "ws://{host}:{port}/stomp";
        WebSocketStompClient stompClient = new WebSocketStompClient(sockJsClient);
        stompClient.setMessageConverter(new StringMessageConverter());
        stompClient.setTaskScheduler(taskScheduler);
        stompClient.setDefaultHeartbeat(new long[] { 0, 0 });

        logger.debug("Connecting and subscribing " + NUMBER_OF_USERS + " users ");
        StopWatch stopWatch = new StopWatch("STOMP Broker Relay WebSocket Load Tests");
        stopWatch.start();

        List<ConsumerStompSessionHandler> consumers = new ArrayList<>();
        for (int i = 0; i < NUMBER_OF_USERS; i++) {
            consumers.add(new ConsumerStompSessionHandler(BROADCAST_MESSAGE_COUNT, connectLatch, subscribeLatch,
                    messageLatch, disconnectLatch, failure));
            stompClient.connect(stompUrl, consumers.get(i), host, port);
        }

        if (failure.get() != null) {
            throw new AssertionError("Test failed", failure.get());
        }
        if (!connectLatch.await(5000, TimeUnit.MILLISECONDS)) {
            fail("Not all users connected, remaining: " + connectLatch.getCount());
        }
        if (!subscribeLatch.await(5000, TimeUnit.MILLISECONDS)) {
            fail("Not all users subscribed, remaining: " + subscribeLatch.getCount());
        }

        stopWatch.stop();
        logger.debug("Finished: " + stopWatch.getLastTaskTimeMillis() + " millis");

        logger.debug("Broadcasting " + BROADCAST_MESSAGE_COUNT + " messages to " + NUMBER_OF_USERS + " users ");
        stopWatch.start();

        ProducerStompSessionHandler producer = new ProducerStompSessionHandler(BROADCAST_MESSAGE_COUNT,
                failure);
        stompClient.connect(stompUrl, producer, host, port);
        stompClient.setTaskScheduler(taskScheduler);

        if (failure.get() != null) {
            throw new AssertionError("Test failed", failure.get());
        }
        if (!messageLatch.await(60 * 1000, TimeUnit.MILLISECONDS)) {
            for (ConsumerStompSessionHandler consumer : consumers) {
                if (consumer.messageCount.get() < consumer.expectedMessageCount) {
                    logger.debug(consumer);
                }
            }
        }
        if (!messageLatch.await(60 * 1000, TimeUnit.MILLISECONDS)) {
            fail("Not all handlers received every message, remaining: " + messageLatch.getCount());
        }

        producer.session.disconnect();
        if (!disconnectLatch.await(5000, TimeUnit.MILLISECONDS)) {
            fail("Not all disconnects completed, remaining: " + disconnectLatch.getCount());
        }

        stopWatch.stop();
        logger.debug("Finished: " + stopWatch.getLastTaskTimeMillis() + " millis");

        System.out.println("\nPress any key to exit...");
        System.in.read();
    } catch (Throwable t) {
        t.printStackTrace();
    } finally {
        jettyHttpClient.stop();
    }

    logger.debug("Exiting");
    System.exit(0);
}

From source file:org.springframework.xd.dirt.integration.bus.MessageBusSupportBenchmarkTests.java

@Test
public void run() {
    StopWatch watch = new StopWatch("MessageBusSupport");
    watch.start("simple tuple codec");
    runBenchmark(TupleBuilder.tuple().of("foo", "bar", "val", 1234));
    watch.stop();//  w w  w . ja v a 2s.  co  m
    watch.start("string payload");
    runBenchmark(StringUtils.leftPad("hello", 1000, "*"));
    watch.stop();
    System.out.println(watch.prettyPrint());
}

From source file:ubic.gemma.core.tasks.visualization.DifferentialExpressionSearchTaskImpl.java

/**
 * Get information on the conditions to be searched. This is not part of the query for the results themselves, but
 * uses the database to get metadata/summaries about the analyses that will be used. Initializes the searchResult
 * value object. Later, values which are non-missing will be replaced with either 'non-significant' or 'significant'
 * results./* www  .  j ava  2  s  .  c om*/
 *
 * @param searchResult to be initialized
 * @return list of the resultSets that should be queried.
 */
private List<DiffExResultSetSummaryValueObject> addConditionsToSearchResultValueObject(
        DifferentialExpressionGenesConditionsValueObject searchResult) {

    StopWatch watch = new StopWatch("addConditionsToSearchResultValueObject");
    watch.start("Add conditions to search result value object");
    List<DiffExResultSetSummaryValueObject> usedResultSets = new LinkedList<>();

    int i = 0;

    DifferentialExpressionSearchTaskImpl.log.info("Loading " + experimentGroupName + " experiments...");

    // database hit: important that this be fast.
    Map<ExpressionExperimentDetailsValueObject, Collection<DifferentialExpressionAnalysisValueObject>> analyses = differentialExpressionAnalysisService
            .getAnalysesByExperiment(EntityUtils.getIds(experimentGroup));

    experiment: for (ExpressionExperimentDetailsValueObject bas : analyses.keySet()) {

        Collection<DifferentialExpressionAnalysisValueObject> analysesForExperiment = this
                .filterAnalyses(analyses.get(bas));

        if (analysesForExperiment.isEmpty()) {
            continue;
        }

        /*
         * There will often just be one analysis for the experiment. Exception would be when there is subsetting.
         */
        for (DifferentialExpressionAnalysisValueObject analysis : analysesForExperiment) {

            List<DiffExResultSetSummaryValueObject> resultSets = this.filterResultSets(analysis);
            usedResultSets.addAll(resultSets);

            if (resultSets.isEmpty()) {
                DifferentialExpressionSearchTaskImpl.log.info("No resultSets usable for " + bas.getId());
            }

            for (DiffExResultSetSummaryValueObject resultSet : resultSets) {

                // this is taken care of by the filterResultSets
                assert resultSet.getNumberOfDiffExpressedProbes() != null; // sanity check.
                assert resultSet.getExperimentalFactors().size() == 1; // interactions not okay

                ExperimentalFactorValueObject factor = resultSet.getExperimentalFactors().iterator().next();

                Collection<FactorValueValueObject> factorValues = this.filterFactorValues(analysis,
                        factor.getValues(), resultSet.getBaselineGroup().getId());

                if (factorValues.isEmpty()) {
                    /*
                     * This can only happen if there is just a baseline factorvalue. Even for one-sided tests //
                     * that // won't be the case.
                     */
                    DifferentialExpressionSearchTaskImpl.log
                            .warn("Nothing usable for resultSet=" + resultSet.getResultSetId());
                    continue;
                }

                for (FactorValueValueObject factorValue : factorValues) {

                    Condition condition = searchResult.new Condition(bas, analysis, resultSet, factorValue);

                    condition.setExperimentGroupName(experimentGroupName);

                    /*
                     * SANITY CHECKS these fields should be filled in. If not, we are going to skip the results.
                     */
                    if (condition.getNumberDiffExpressedProbes() == -1) {
                        DifferentialExpressionSearchTaskImpl.log
                                .warn(bas + ": Error: No hit list sizes for resultSet with ID="
                                        + resultSet.getResultSetId());
                        continue;
                    }
                    if (condition.getNumberOfProbesOnArray() == null
                            || condition.getNumberDiffExpressedProbes() == null) {
                        DifferentialExpressionSearchTaskImpl.log.error(bas
                                + ": Error: Null counts for # diff ex probe or # probes on array, Skipping");
                        continue experiment;
                    } else if (condition.getNumberOfProbesOnArray() < condition
                            .getNumberDiffExpressedProbes()) {
                        DifferentialExpressionSearchTaskImpl.log.error(
                                bas + ": Error: More diff expressed probes than probes on array. Skipping.");
                        continue experiment;
                    }

                    searchResult.addCondition(condition);

                    i++;
                }
            }
        }

    }

    watch.stop();
    if (watch.getTotalTimeMillis() > 100) {
        // This does not include getting the actual diff ex results.
        DifferentialExpressionSearchTaskImpl.log.info("Get information on conditions/analyses for " + i
                + " factorValues: " + watch.getTotalTimeMillis() + "ms");
    }

    return usedResultSets;
}

From source file:ubic.gemma.core.tasks.visualization.DifferentialExpressionSearchTaskImpl.java

/**
 * Main processing: fetch diff ex results.
 *
 * @param resultSets   to be searched//from w  w w .  jav a2s.  c o  m
 * @param geneIds      to be searched
 * @param searchResult holds the results
 */
private void fetchDifferentialExpressionResults(List<DiffExResultSetSummaryValueObject> resultSets,
        List<Long> geneIds, DifferentialExpressionGenesConditionsValueObject searchResult) {

    StopWatch watch = new StopWatch("Process differential expression search");
    watch.start("Fetch diff ex results");

    // Main query for results; the main time sink.
    Map<Long, Map<Long, DiffExprGeneSearchResult>> resultSetToGeneResults = differentialExpressionResultService
            .findDiffExAnalysisResultIdsInResultSets(resultSets, geneIds);
    watch.stop();

    Collection<DiffExprGeneSearchResult> aggregatedResults = this
            .aggregateAcrossResultSets(resultSetToGeneResults);

    watch.start("Fetch details for contrasts for " + aggregatedResults.size() + " results");
    Map<Long, ContrastsValueObject> detailedResults = this.getDetailsForContrasts(aggregatedResults);

    this.processHits(searchResult, resultSetToGeneResults, resultSets, detailedResults);

    watch.stop();
    DifferentialExpressionSearchTaskImpl.log.info("Diff ex search finished:\n" + watch.prettyPrint());
}

From source file:ubic.gemma.tasks.visualization.DifferentialExpressionSearchTaskImpl.java

/**
 * Get information on the conditions to be searched. This is not part of the query for the results themselves, but
 * uses the database to get metadata/summaries about the analyses that will be used. Initializes the searchResult
 * value object. Later, values which are non-missing will be replaced with either 'non-significant' or 'significant'
 * results./*www. j  av a2 s . co m*/
 * 
 * @param searchResult to be initialized
 * @return lsit of the resultSets that should be queried.
 */
private List<ExpressionAnalysisResultSet> addConditionsToSearchResultValueObject(
        DifferentialExpressionGenesConditionsValueObject searchResult) {

    StopWatch watch = new StopWatch("addConditionsToSearchResultValueObject");
    watch.start("Add conditions to search result value object");
    List<ExpressionAnalysisResultSet> usedResultSets = new LinkedList<ExpressionAnalysisResultSet>();

    int experimentGroupIndex = 0;
    int i = 0;
    for (Collection<ExpressionExperiment> experimentGroup : experimentGroups) {

        log.info("Loading " + experimentGroupNames.get(experimentGroupIndex) + " experiments...");

        // database hit: important that this be fast.
        Map<BioAssaySet, Collection<DifferentialExpressionAnalysis>> analyses = differentialExpressionAnalysisService
                .getAnalyses(experimentGroup);

        experiment: for (BioAssaySet bas : analyses.keySet()) {

            if (!(bas instanceof ExpressionExperiment)) {
                log.warn("Subsets not supported yet (" + bas + "), skipping");
                continue;
            }

            ExpressionExperiment experiment = (ExpressionExperiment) bas;

            Collection<DifferentialExpressionAnalysis> analysesForExperiment = filterAnalyses(
                    analyses.get(experiment));

            if (analysesForExperiment.isEmpty()) {
                continue;
            }

            for (DifferentialExpressionAnalysis analysis : analysesForExperiment) {

                List<ExpressionAnalysisResultSet> resultSets = filterResultSets(analysis.getResultSets());
                usedResultSets.addAll(resultSets);

                if (resultSets.isEmpty()) {
                    log.info("No resultSets usable for " + experiment.getShortName());
                }

                for (ExpressionAnalysisResultSet resultSet : resultSets) {

                    // this is taken care of by the filterResultSets
                    assert resultSet.getHitListSizes() != null;
                    assert resultSet.getExperimentalFactors().size() == 1;

                    ExperimentalFactor factor = resultSet.getExperimentalFactors().iterator().next();
                    Collection<FactorValue> factorValues = filterFactorValues(factor.getFactorValues(),
                            resultSet.getBaselineGroup().getId());

                    for (FactorValue factorValue : factorValues) {

                        Condition condition = searchResult.new Condition(experiment, analysis, resultSet,
                                factorValue);

                        condition.setExperimentGroupName(experimentGroupNames.get(experimentGroupIndex));
                        condition.setExperimentGroupIndex(experimentGroupIndex);

                        /*
                         * SANITY CHECKS these fields should be filled in. If not, we are going to skip the results.
                         */
                        if (condition.getNumberDiffExpressedProbes() == -1) {
                            log.warn(bas + ": Error: No hit list sizes for resultSet with ID="
                                    + resultSet.getId());
                            continue;
                        }
                        if (condition.getNumberOfProbesOnArray() == null
                                || condition.getNumberDiffExpressedProbes() == null) {
                            log.error(bas
                                    + ": Error: Null counts for # diff ex probe or # probes on array, Skipping");
                            continue experiment;
                        } else if (condition.getNumberOfProbesOnArray() < condition
                                .getNumberDiffExpressedProbes()) {
                            log.error(bas
                                    + ": Error: More diff expressed probes than probes on array. Skipping.");
                            continue experiment;
                        }

                        searchResult.addCondition(condition);

                        i++;
                    }
                }
            }
        }
        experimentGroupIndex++;
    }

    watch.stop();
    if (watch.getTotalTimeMillis() > 100) {
        // This does not include getting the actual diff ex results.
        log.info("Get information on conditions/analyses for " + i + " factorValues: "
                + watch.getTotalTimeMillis() + "ms");
    }

    return usedResultSets;
}

From source file:ubic.gemma.tasks.visualization.DifferentialExpressionSearchTaskImpl.java

/**
 * The actual business of fetching the differential expression results.
 * /*w  w w  .  j  av a  2 s.  c o  m*/
 * @param resultSets
 * @param geneIds
 * @param searchResult holds the results
 */
private void fetchDifferentialExpressionResults(
        Map<ExpressionAnalysisResultSet, Collection<Long>> resultSetIdsToArrayDesignsUsed, List<Long> geneIds,
        DifferentialExpressionGenesConditionsValueObject searchResult) {

    StopWatch watch = new StopWatch("Process differential expression search");
    watch.start("Fetch diff ex results");

    // Main query for results; the main time sink.
    Map<Long, Map<Long, DiffExprGeneSearchResult>> resultSetToGeneResults = differentialExpressionResultService
            .findDifferentialExpressionAnalysisResultIdsInResultSet(resultSetIdsToArrayDesignsUsed, geneIds);
    watch.stop();

    Map<Long, ExpressionAnalysisResultSet> resultSetMap = EntityUtils
            .getIdMap(resultSetIdsToArrayDesignsUsed.keySet());
    Collection<DiffExprGeneSearchResult> aggregatedResults = aggregateAcrossResultSets(resultSetToGeneResults);

    watch.start("Fetch details for contrasts for " + aggregatedResults.size() + " results");
    Map<Long, ContrastsValueObject> detailedResults = getDetailsForContrasts(aggregatedResults);

    processHits(searchResult, resultSetToGeneResults, resultSetMap, detailedResults);

    watch.stop();
    log.info("Diff ex search finished:\n" + watch.prettyPrint());
}

From source file:uk.ac.ebi.atlas.experimentimport.analyticsindex.baseline.BaselineAnalyticsIndexerService.java

public int index(BaselineExperiment experiment) {
    String experimentAccession = experiment.getAccession();
    ExperimentType experimentType = experiment.getType();

    String defaultQueryFactorType = experiment.getExperimentalFactors().getDefaultQueryFactorType();
    ExperimentDesign experimentDesign = experiment.getExperimentDesign();

    ImmutableMap<String, String> ensemblSpeciesGroupedByAssayGroupId = SpeciesGrouper
            .buildEnsemblSpeciesGroupedByAssayGroupId(experiment);

    ImmutableSetMultimap<String, String> ontologyTermIdsByAssayAccession = expandOntologyTerms(
            experimentDesign.getAllOntologyTermIdsByAssayAccession());

    ImmutableSetMultimap<String, String> conditionSearchTermsByAssayGroupId = buildConditionSearchTermsByAssayGroupId(
            experiment, ontologyTermIdsByAssayAccession);

    checkArgument(StringUtils.isNotBlank(defaultQueryFactorType));

    LOGGER.info("Start indexing " + experimentAccession);
    StopWatch stopWatch = new StopWatch(getClass().getSimpleName());
    stopWatch.start();/*w w w . j  a  va2s  .c om*/

    //TODO: move this to another class
    ObjectInputStream<BaselineAnalytics> inputStream = (experimentType == ExperimentType.PROTEOMICS_BASELINE)
            ? proteomicsBaselineAnalyticsInputStreamFactory.create(experimentAccession)
            : baselineAnalyticsInputStreamFactory.create(experimentAccession);

    int count = indexRnaSeqBaselineExperimentAnalytics(experimentAccession, experimentType,
            defaultQueryFactorType, conditionSearchTermsByAssayGroupId, ensemblSpeciesGroupedByAssayGroupId,
            inputStream);

    stopWatch.stop();
    LOGGER.info(String.format("Done indexing %s, indexed %,d documents in %s seconds", experimentAccession,
            count, stopWatch.getTotalTimeSeconds()));

    return count;
}

From source file:uk.ac.ebi.atlas.search.baseline.BaselineExperimentAssayGroupSearchService.java

public SortedSet<BaselineExperimentAssayGroup> query(Set<String> geneIds, Optional<String> condition,
        Optional<String> species) {
    LOGGER.info(String.format("<query> geneIds=%s, condition=%s", Joiner.on(", ").join(geneIds), condition));
    StopWatch stopWatch = new StopWatch(getClass().getSimpleName());
    stopWatch.start();/*from  w  w  w  .j  ava  2s. c o  m*/

    String conditionString = condition.isPresent() ? condition.get() : "";
    String speciesString = species.isPresent() ? species.get() : "";

    Optional<ImmutableSet<IndexedAssayGroup>> indexedAssayGroups = fetchAssayGroupsForCondition(
            conditionString);

    SetMultimap<String, String> assayGroupsWithExpressionByExperiment = baselineExperimentAssayGroupsDao
            .fetchExperimentAssayGroupsWithNonSpecificExpression(indexedAssayGroups, Optional.of(geneIds));

    SortedSet<BaselineExperimentAssayGroup> baselineExperimentAssayGroups = searchedForConditionButGotNoResults(
            conditionString, indexedAssayGroups) ? emptySortedSet()
                    : buildResults(assayGroupsWithExpressionByExperiment, !StringUtils.isBlank(conditionString),
                            speciesString);

    stopWatch.stop();
    LOGGER.info(String.format("<query> %s results, took %s seconds", baselineExperimentAssayGroups.size(),
            stopWatch.getTotalTimeSeconds()));

    return baselineExperimentAssayGroups;
}

From source file:uk.ac.ebi.atlas.search.baseline.BaselineExperimentAssayGroupSearchService.java

@Deprecated
public SortedSet<BaselineExperimentAssayGroup> query(String geneQuery, String condition, String specie,
        boolean isExactMatch) {
    LOGGER.info(String.format("<query> geneQuery=%s, condition=%s", geneQuery, condition));
    StopWatch stopWatch = new StopWatch(getClass().getSimpleName());
    stopWatch.start();/*from   w ww.ja  va 2 s  . co  m*/

    Optional<ImmutableSet<IndexedAssayGroup>> indexedAssayGroups = fetchAssayGroupsForCondition(condition);

    String species = StringUtils.isNotBlank(specie) ? specie : "";

    //TODO: move outside into caller, because this is called twice, here and in DiffAnalyticsSearchService
    Optional<Set<String>> geneIds = solrQueryService.expandGeneQueryIntoGeneIds(geneQuery, species,
            isExactMatch);

    SetMultimap<String, String> assayGroupsWithExpressionByExperiment = baselineExperimentAssayGroupsDao
            .fetchExperimentAssayGroupsWithNonSpecificExpression(indexedAssayGroups, geneIds);

    boolean conditionSearch = !isEmpty(indexedAssayGroups);

    SortedSet<BaselineExperimentAssayGroup> baselineExperimentAssayGroups = Sets.newTreeSet();
    if (conditionSearch || StringUtils.isNotEmpty(geneQuery) && StringUtils.isEmpty(condition)) {
        baselineExperimentAssayGroups = buildResults(assayGroupsWithExpressionByExperiment, conditionSearch,
                species);
    }

    stopWatch.stop();
    LOGGER.info(String.format("<query> %s results, took %s seconds", baselineExperimentAssayGroups.size(),
            stopWatch.getTotalTimeSeconds()));

    return baselineExperimentAssayGroups;
}