Example usage for org.springframework.util StopWatch getLastTaskTimeMillis

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

Introduction

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

Prototype

public long getLastTaskTimeMillis() throws IllegalStateException 

Source Link

Document

Get the time taken by the last task in milliseconds.

Usage

From source file:com.jxt.web.service.FilteredMapServiceImpl.java

@Override
@Deprecated/*from w w  w. java 2 s  .  co m*/
public LoadFactor linkStatistics(Range range, List<TransactionId> traceIdSet, Application sourceApplication,
        Application destinationApplication, Filter filter) {
    if (sourceApplication == null) {
        throw new NullPointerException("sourceApplication must not be null");
    }
    if (destinationApplication == null) {
        throw new NullPointerException("destApplicationName must not be null");
    }
    if (filter == null) {
        throw new NullPointerException("filter must not be null");
    }

    StopWatch watch = new StopWatch();
    watch.start();

    List<List<SpanBo>> originalList = this.traceDao.selectAllSpans(traceIdSet);
    List<SpanBo> filteredTransactionList = filterList(originalList, filter);

    LoadFactor statistics = new LoadFactor(range);

    // TODO need to handle these separately by node type (like fromToFilter)

    // scan transaction list
    for (SpanBo span : filteredTransactionList) {
        if (sourceApplication.equals(span.getApplicationId(),
                registry.findServiceType(span.getApplicationServiceType()))) {
            List<SpanEventBo> spanEventBoList = span.getSpanEventBoList();
            if (spanEventBoList == null) {
                continue;
            }

            // find dest elapsed time
            for (SpanEventBo spanEventBo : spanEventBoList) {
                if (destinationApplication.equals(spanEventBo.getDestinationId(),
                        registry.findServiceType(spanEventBo.getServiceType()))) {
                    // find exception
                    boolean hasException = spanEventBo.hasException();
                    // add sample
                    // TODO : need timeslot value instead of the actual value
                    statistics.addSample(span.getStartTime() + spanEventBo.getStartElapsed(),
                            spanEventBo.getEndElapsed(), 1, hasException);
                    break;
                }
            }
        }
    }

    watch.stop();
    logger.info("Fetch link statistics elapsed. {}ms", watch.getLastTaskTimeMillis());

    return statistics;
}

From source file:com.mmnaseri.dragonfly.runtime.analysis.ApplicationDesignAdvisor.java

@Override
public List<DesignIssue> analyze() {
    final List<DesignIssue> issues = new CopyOnWriteArrayList<DesignIssue>();
    final StopWatch stopWatch = new StopWatch();
    stopWatch.start();/*from w  ww  . j  a  v a2s .  com*/
    log.info("Starting design advisor on " + applicationContext.getDisplayName());
    final TaskManager taskManager = new ThreadPoolTaskManager(Runtime.getRuntime().availableProcessors(), true);
    final Thread analyzerThread = new Thread(taskManager);
    final SessionPreparator sessionPreparator = applicationContext.getBean(SessionPreparator.class);
    with(getAnalyzers(sessionPreparator)).each(new Processor<ApplicationDesignAnalyzer>() {
        @Override
        public void process(ApplicationDesignAnalyzer applicationDesignAnalyzer) {
            taskManager.schedule(new AnalyzerTask(applicationDesignAnalyzer, issues));
        }
    });
    try {
        analyzerThread.start();
        analyzerThread.join();
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }
    stopWatch.stop();
    log.info("Finished analysis of " + applicationContext.getDisplayName() + " in "
            + stopWatch.getLastTaskTimeMillis() + "ms");
    return issues;
}

From source file:com.navercorp.pinpoint.web.controller.ScatterChartController.java

/**
 * @param applicationName/*w ww .j a  v  a  2s.c  om*/
 * @param from
 * @param to
 * @param limit           max number of data return. if the requested data exceed this limit, we need additional calls to
 *                        fetch the rest of the data
 * @return
 */
@RequestMapping(value = "/getScatterData", method = RequestMethod.GET)
public ModelAndView getScatterData(@RequestParam("application") String applicationName,
        @RequestParam("from") long from, @RequestParam("to") long to,
        @RequestParam("xGroupUnit") int xGroupUnit, @RequestParam("yGroupUnit") int yGroupUnit,
        @RequestParam("limit") int limit,
        @RequestParam(value = "backwardDirection", required = false, defaultValue = "true") boolean backwardDirection,
        @RequestParam(value = "filter", required = false) String filterText,
        @RequestParam(value = "_callback", required = false) String jsonpCallback,
        @RequestParam(value = "v", required = false, defaultValue = "1") int version) {
    if (xGroupUnit <= 0) {
        throw new IllegalArgumentException("xGroupUnit(" + xGroupUnit + ") must be positive number");
    }
    if (yGroupUnit < 0) {
        throw new IllegalArgumentException("yGroupUnit(" + yGroupUnit + ") may not be negative number");
    }

    limit = LimitUtils.checkRange(limit);

    StopWatch watch = new StopWatch();
    watch.start("getScatterData");

    // TODO range check verification exception occurs. "from" is bigger than "to"
    final Range range = Range.createUncheckedRange(from, to);
    logger.debug(
            "fetch scatter data. RANGE={}, X-Group-Unit:{}, Y-Group-Unit:{}, LIMIT={}, BACKWARD_DIRECTION:{}, FILTER:{}",
            range, xGroupUnit, yGroupUnit, limit, backwardDirection, filterText);

    ModelAndView mv = null;
    if (StringUtils.isEmpty(filterText)) {
        mv = selectScatterData(applicationName, range, xGroupUnit, Math.max(yGroupUnit, 1), limit,
                backwardDirection, version);
    } else {
        mv = selectFilterScatterData(applicationName, range, xGroupUnit, Math.max(yGroupUnit, 1), limit,
                backwardDirection, filterText, version);
    }

    if (jsonpCallback == null) {
        mv.setViewName("jsonView");
    } else {
        mv.setViewName("jsonpView");
    }

    watch.stop();

    logger.info("Fetch scatterData time : {}ms", watch.getLastTaskTimeMillis());

    return mv;
}

From source file:io.mandrel.worker.Loop.java

protected void updateMetrics(StopWatch watch, Blob blob) {
    spiderAccumulator.incNbPages();/*w  ww  .  j a v  a2s . c om*/
    globalAccumulator.incNbPages();

    spiderAccumulator.incPageForStatus(blob.getMetadata().getFetchMetadata().getStatusCode());
    globalAccumulator.incPageForStatus(blob.getMetadata().getFetchMetadata().getStatusCode());

    spiderAccumulator.incPageForHost(blob.getMetadata().getUri().getHost());
    globalAccumulator.incPageForHost(blob.getMetadata().getUri().getHost());

    spiderAccumulator.incTotalTimeToFetch(watch.getLastTaskTimeMillis());

    if (blob.getMetadata().getSize() != null) {
        spiderAccumulator.incTotalSize(blob.getMetadata().getSize());
        globalAccumulator.incTotalSize(blob.getMetadata().getSize());
    }
}

From source file:no.abmu.lise.service.hibernate3.LiseImportServiceH3Impl.java

private void processSheetOne(Session session, LiseImportExcelParser excelParser) {

    List<Entity> entityStorList = new ArrayList<Entity>();
    Consortium currentConsortium = null;
    Product currentProduct = null;// w  w  w.  ja v  a  2  s  . c o  m
    String currentProductName = null;
    int productSaved = 0;
    int productCustomerRelationSaved = 0;
    int productCustomerRelationNotSaved = 0;

    int linkToCustomerContactPerson = 0;
    int linkToSupplierContactPerson = 0;

    int missingLinkToCustomerContactPerson = 0;
    int missingLinkToSupplierContactPerson = 0;

    int numberOfCustomerProductComment = 0;

    excelParser.setSheetName("Sheet1");
    excelParser.load();
    Date creationTime = new Date();
    StopWatch stopWatch = new StopWatch();
    stopWatch.start("processSheetOne");
    logger.debug("Starting building the Domain model:");
    for (; excelParser.hasNext(); excelParser.next()) {

        Consortium consortiumInLine = createConsortium(excelParser);
        Assert.assertNotNull("consortiumInLine", consortiumInLine);
        if (!consortiumInLine.equals(currentConsortium)) {
            // New current consortium
            currentConsortium = consortiumInLine;
            String logMessage = "Row " + excelParser.getCurrentRowNumber() + " in " + excelParser.getSheetName()
                    + " new consortium ==> " + currentConsortium.getConsortiumName();
            logger.info(logMessage);

            // Get supplier
            Map<String, String> supplierExcelColumnMap = excelParser.getConsortiumSupplierOrgUnitColumns();
            OrganisationUnit supplier = getOrganisationUnit(session, excelParser, supplierExcelColumnMap);
            if (supplier != null) {
                currentConsortium.setSupplier(supplier);
            } else {
                String warningMessage = "Row " + excelParser.getCurrentRowNumber() + " in "
                        + excelParser.getSheetName() + " did not find supplier ==> "
                        + excelParser.getSupplierName();
                logger.warn(warningMessage);
            }

            // Get supplier contact person
            String supContactPersonName = excelParser.getConsortiumSupplierContactPerson();
            ExtendedContactPerson supplierContactPerson = findContactPerson(session, supContactPersonName);

            if (supplierContactPerson != null) {
                currentConsortium.setSupplierContactPerson(supplierContactPerson);
                linkToSupplierContactPerson++;
            } else {
                String warningMessage = "Row " + excelParser.getCurrentRowNumber() + " in "
                        + excelParser.getSheetName() + " no supplier contact person ==> "
                        + supContactPersonName;
                logger.warn(warningMessage);
                missingLinkToSupplierContactPerson++;
            }

            // Get abmu administrator contact person
            String abmuContactPersonName = excelParser.getConsortiumAbmuContactPerson();
            ExtendedContactPerson abmuContactPerson = findContactPerson(session, abmuContactPersonName);
            if (abmuContactPerson != null) {
                currentConsortium.setAbmuContactPerson(abmuContactPerson);
            } else {
                String warningMessage = "Row " + excelParser.getCurrentRowNumber() + " in "
                        + excelParser.getSheetName() + " no ABMU contact person ==> " + abmuContactPersonName;
                logger.warn(warningMessage);
            }

            entityStorList.add(currentConsortium);
        }

        Product productInLine = createProduct(excelParser);
        Assert.assertNotNull("productInLine", productInLine);
        Assert.assertNotNull("productInLine.getProductName()", productInLine.getProductName());
        if (!productInLine.getProductName().equals(currentProductName)) {
            // New current product
            currentProduct = productInLine;
            currentProductName = currentProduct.getProductName();
            String logMessage = "Row " + excelParser.getCurrentRowNumber() + " in " + excelParser.getSheetName()
                    + " new product ==> " + currentProduct.getProductName();
            logger.info(logMessage);

            currentConsortium.addProduct(currentProduct);
            productSaved++;
        }

        // Get customer
        Map<String, String> customerExcelColumnMap = excelParser.getRelationCustomerProductOrgUnitColumns();
        OrganisationUnit customer = getOrganisationUnit(session, excelParser, customerExcelColumnMap);
        if (customer != null) {

            ProductCustomerRelation productCustomerRelation = new ProductCustomerRelation(currentProduct,
                    customer);

            // Get customer contact person
            String contactPersonName = excelParser.getRcpContactPerson();
            ExtendedContactPerson customerContactPerson = findContactPerson(session, contactPersonName);

            if (customerContactPerson != null) {
                productCustomerRelation.setCustomerContactPerson(customerContactPerson);
                linkToCustomerContactPerson++;
            } else {
                String warningMessage = "Row " + excelParser.getCurrentRowNumber() + " in "
                        + excelParser.getSheetName() + "] no customer contact person ==> " + contactPersonName;
                logger.warn(warningMessage);
                missingLinkToCustomerContactPerson++;
            }

            currentProduct.addProductCustomerRelations(productCustomerRelation);
            productCustomerRelationSaved++;

            LiseComment customerProductComment = getCustomerProductComment(excelParser);
            if (customerProductComment != null) {
                customerProductComment.setCreated(creationTime);
                customerProductComment.setLastUpdated(creationTime);
                productCustomerRelation.addLiseComment(customerProductComment);
                numberOfCustomerProductComment++;

            }

        } else {
            String warnMessage = "Row " + excelParser.getCurrentRowNumber() + " in "
                    + excelParser.getSheetName() + " no customer with name (" + excelParser.getSupplierName()
                    + ").";
            logger.warn(warnMessage);
            productCustomerRelationNotSaved++;
        }
    }

    creationTime = new Date();
    //
    // Save 
    //
    Hibernate3Util.saveEntities(session, entityStorList);
    stopWatch.stop();
    logger.info("   =============================================================================  ");
    logger.info("Saved [" + entityStorList.size() + "] consortium.");
    logger.info("Saved [" + productSaved + "] products.");
    logger.info("Saved [" + productCustomerRelationSaved + "] productCustomerRelations.");
    logger.info("Saved [" + linkToSupplierContactPerson + "] link to supplier contactPerson.");
    logger.info("Saved [" + linkToCustomerContactPerson + "] link to customer contactPerson.");
    logger.info("Saved [" + numberOfCustomerProductComment + "] customer product comments.");
    logger.info("Missing [" + productCustomerRelationNotSaved + "] productCustomerRelations.");
    logger.info("Missing [" + missingLinkToSupplierContactPerson + "] link to supplier contactPerson.");
    logger.info("Missing [" + missingLinkToCustomerContactPerson + "] link to customer contactPerson.");
    logger.info("TransactionTime [" + stopWatch.getLastTaskTimeMillis() + "] in ms.");
    logger.info("   =============================================================================  ");
}

From source file:no.abmu.lise.service.hibernate3.LiseImportServiceH3Impl.java

private void precessSheetTwo(Session session, LiseImportExcelParser excelParser) {

    List<Entity> entityStorList = new ArrayList<Entity>();

    int noConsortium = 0;
    int noInvoiceNumber = 0;
    excelParser.setSheetName("Sheet2");
    excelParser.load();/*w  ww  .j a va  2 s .co  m*/
    Date creationTime = new Date();

    StopWatch stopWatch = new StopWatch();
    stopWatch.start("precessSheetTwo");
    logger.debug("Starting building the Domain model:");
    for (; excelParser.hasNext(); excelParser.next()) {

        Consortium consortiumFromDb = findConsortiumInDb(excelParser);
        if (consortiumFromDb != null) {
            Consortium consortiumInSession = (Consortium) session.get(Consortium.class,
                    consortiumFromDb.getId());
            String logMessage = "Row " + excelParser.getCurrentRowNumber() + " in " + excelParser.getSheetName()
                    + " prosessing consortium ==> " + consortiumInSession.getConsortiumName();
            logger.info(logMessage);

            PaymentToSupplier paymentToSupplier = createPaymentToSupplier(excelParser);
            if (paymentToSupplier.getLiseComment() != null) {
                paymentToSupplier.getLiseComment().setCreated(creationTime);
                paymentToSupplier.getLiseComment().setLastUpdated(creationTime);
            }

            if (StringUtil.isEmpty(paymentToSupplier.getInvoiceNumber())) {
                noInvoiceNumber++;
                String errorMessage = "Row " + excelParser.getCurrentRowNumber()
                        + " no invoice number for consortium " + consortiumInSession.getConsortiumName();
                logger.error(errorMessage);
                paymentToSupplier.setInvoiceNumber("DUMMY");
            }
            consortiumInSession.addPaymentToSupplier(paymentToSupplier);
            entityStorList.add(consortiumInSession);
        } else {
            noConsortium++;
        }
    }
    creationTime = new Date();
    //
    // Save 
    //
    Hibernate3Util.saveEntities(session, entityStorList);
    stopWatch.stop();
    logger.info("   =============================================================================  ");
    logger.info("Saving [" + entityStorList.size() + "] consortium with payment to supplier infomation.");
    logger.info("Payment to supplier with wissing [" + noInvoiceNumber + "] invoice number.");
    logger.info("Missing [" + noConsortium + "] consortium with payment to supplier infomation.");
    logger.info("TransactionTime [" + stopWatch.getLastTaskTimeMillis() + "] in ms.");
    logger.info("   =============================================================================  ");
}

From source file:no.abmu.lise.service.hibernate3.LiseImportServiceH3Impl.java

private void processSheetThree(Session session, LiseImportExcelParser excelParser) {

    List<Entity> entityStorList = new ArrayList<Entity>();

    int noProductCustomerRelation = 0;
    excelParser.setSheetName("Sheet3");
    excelParser.load();// w w  w .  j  a  v a  2  s . c  o m
    Date creationTime = new Date();
    StopWatch stopWatch = new StopWatch();
    stopWatch.start("processSheetThree");
    for (; excelParser.hasNext(); excelParser.next()) {

        ProductCustomerRelation productCustomerFromDb = findProductCustomerRelInDb(excelParser);
        if (productCustomerFromDb != null) {
            ProductCustomerRelation productCustomerRelInSession = (ProductCustomerRelation) session
                    .get(ProductCustomerRelation.class, productCustomerFromDb.getId());

            InvoiceToCustomer invoiceToCustomer = createInvoiceToCustomer(excelParser);

            // Make sure we have currency on all invoices to customer
            if (invoiceToCustomer.getCurrency() == null) {
                Product product = productCustomerRelInSession.getProduct();
                Consortium consortium = product.getConsortium();
                invoiceToCustomer.setCurrency(consortium.getCurrency());
            }

            // Setting up percentage currency buffer
            if (invoiceToCustomer.getCurrency().equals(Currency.getInstance("NOK"))) {
                invoiceToCustomer.setPercentageCurrencyBuffer(BigDecimal.valueOf(0));
            } else {
                invoiceToCustomer.setPercentageCurrencyBuffer(BigDecimal.valueOf(1.75));
            }

            // Be sure there are original amount
            if (invoiceToCustomer.getOriginalAmount() == null) {
                invoiceToCustomer.setOriginalAmount(BigDecimal.valueOf(0));
            }

            if (invoiceToCustomer.getLiseComment() != null) {
                invoiceToCustomer.getLiseComment().setCreated(creationTime);
                invoiceToCustomer.getLiseComment().setLastUpdated(creationTime);
            }

            productCustomerRelInSession.addInvoicesToCustomer(invoiceToCustomer);
            entityStorList.add(productCustomerRelInSession);
        } else {
            noProductCustomerRelation++;
        }
    }

    creationTime = new Date();
    //
    // Save 
    //
    Hibernate3Util.saveEntities(session, entityStorList);
    stopWatch.stop();
    logger.info("   =============================================================================  ");
    logger.info("Saving [" + entityStorList.size() + "] product customer relations with invoice information.");
    logger.info(
            "Missing [" + noProductCustomerRelation + "] product customer relations with invoice information.");
    logger.info("TransactionTime [" + stopWatch.getLastTaskTimeMillis() + "] in ms.");
    logger.info("   =============================================================================  ");
}

From source file:org.alfresco.repo.search.impl.solr.DbOrIndexSwitchingQueryLanguage.java

public ResultSet executeQuery(SearchParameters searchParameters, ADMLuceneSearcherImpl admLuceneSearcher) {
    QueryConsistency consistency = searchParameters.getQueryConsistency();
    if (consistency == QueryConsistency.DEFAULT) {
        consistency = queryConsistency;/* ww  w .java  2 s  .c om*/
    }

    switch (consistency) {
    case EVENTUAL:
        if (indexQueryLanguage != null) {
            if (logger.isDebugEnabled()) {
                logger.debug("Using SOLR query: " + dbQueryLanguage.getName() + " for " + searchParameters);
            }
            StopWatch stopWatch = new StopWatch("index only");
            stopWatch.start();
            ResultSet results = indexQueryLanguage.executeQuery(searchParameters, admLuceneSearcher);
            stopWatch.stop();
            if (logger.isDebugEnabled()) {
                logger.debug("SOLR returned " + results.length() + " results in "
                        + stopWatch.getLastTaskTimeMillis() + "ms");
            }
            return results;
        } else {
            throw new QueryModelException("No query language available");
        }
    case TRANSACTIONAL:
        if (dbQueryLanguage != null) {
            if (logger.isDebugEnabled()) {
                logger.debug("Trying db query for " + dbQueryLanguage.getName() + " for " + searchParameters);
            }
            StopWatch stopWatch = new StopWatch("database only");
            stopWatch.start();
            ResultSet results = dbQueryLanguage.executeQuery(flattenDBQuery(searchParameters),
                    admLuceneSearcher);
            stopWatch.stop();
            if (logger.isDebugEnabled()) {
                logger.debug("DB returned " + results.length() + " results in "
                        + stopWatch.getLastTaskTimeMillis() + "ms");
            }
            return results;
        } else {
            throw new QueryModelException("No query language available");
        }
    case HYBRID:
        if (!hybridEnabled) {
            throw new DisabledFeatureException("Hybrid query is disabled.");
        }
        return executeHybridQuery(searchParameters, admLuceneSearcher);
    case DEFAULT:
    case TRANSACTIONAL_IF_POSSIBLE:
    default:
        StopWatch stopWatch = new StopWatch("DB if possible");
        if (dbQueryLanguage != null) {
            try {
                if (logger.isDebugEnabled()) {
                    logger.debug(
                            "Trying db query for " + dbQueryLanguage.getName() + " for " + searchParameters);
                }
                stopWatch.start();
                ResultSet results = dbQueryLanguage.executeQuery(flattenDBQuery(searchParameters),
                        admLuceneSearcher);
                stopWatch.stop();
                if (logger.isDebugEnabled()) {
                    logger.debug("DB returned " + results.length() + " results in "
                            + stopWatch.getLastTaskTimeMillis() + "ms");
                }
                return results;
            } catch (QueryModelException qme) {
                if (stopWatch.isRunning()) {
                    stopWatch.stop();
                }
                // MNT-10323: Logging configuration on JBoss leads to clogging of the log with a lot of these errors because of INFO level when WQS module is installed
                if (logger.isDebugEnabled()) {
                    logger.debug(
                            "DB query failed for " + dbQueryLanguage.getName() + " for " + searchParameters,
                            qme);
                }

                if (indexQueryLanguage != null) {
                    if (logger.isDebugEnabled()) {
                        logger.debug(
                                "Using SOLR query: " + dbQueryLanguage.getName() + " for " + searchParameters);
                    }
                    stopWatch.start();
                    ResultSet results = indexQueryLanguage.executeQuery(searchParameters, admLuceneSearcher);
                    stopWatch.stop();
                    if (logger.isDebugEnabled()) {
                        logger.debug("SOLR returned " + results.length() + " results in "
                                + stopWatch.getLastTaskTimeMillis() + "ms");
                    }
                    return results;
                }
            }
        } else {
            if (indexQueryLanguage != null) {
                if (logger.isDebugEnabled()) {
                    logger.debug("(No DB QL) Using SOLR query: " + "dbQueryLanguage==null" + " for "
                            + searchParameters);
                }
                stopWatch.start();
                ResultSet results = indexQueryLanguage.executeQuery(searchParameters, admLuceneSearcher);
                stopWatch.stop();
                if (logger.isDebugEnabled()) {
                    logger.debug("SOLR returned " + results.length() + " results in "
                            + stopWatch.getLastTaskTimeMillis() + "ms");
                }
                return results;
            }
        }
        throw new QueryModelException("No query language available");
    }

}

From source file:org.alfresco.repo.search.impl.solr.DbOrIndexSwitchingQueryLanguage.java

private ResultSet executeHybridQuery(SearchParameters searchParameters,
        ADMLuceneSearcherImpl admLuceneSearcher) {
    if (indexQueryLanguage == null || dbQueryLanguage == null) {
        throw new QueryModelException("Both index and DB query language required for hybrid search [index="
                + indexQueryLanguage + ", DB=" + dbQueryLanguage + "]");
    }//from ww w.ja  v  a 2  s. c om

    StopWatch stopWatch = new StopWatch("hybrid search");
    if (logger.isDebugEnabled()) {
        logger.debug(
                "Hybrid search, using SOLR query: " + dbQueryLanguage.getName() + " for " + searchParameters);
    }
    stopWatch.start("index query");
    ResultSet indexResults = indexQueryLanguage.executeQuery(searchParameters, admLuceneSearcher);
    stopWatch.stop();
    if (logger.isDebugEnabled()) {
        logger.debug("SOLR query returned " + indexResults.length() + " results in "
                + stopWatch.getLastTaskTimeMillis() + "ms");
    }
    // TODO: if the results are up-to-date, then nothing more to do - return the results.

    if (!(indexResults instanceof SolrJSONResultSet)) {
        if (logger.isWarnEnabled()) {
            logger.warn("Hybrid search can only use database when SOLR is also in use. "
                    + "Skipping DB search, returning results from index.");
        }
        return indexResults;
    }

    long lastTxId = ((SolrJSONResultSet) indexResults).getLastIndexedTxId();
    searchParameters.setSinceTxId(lastTxId);
    if (logger.isDebugEnabled()) {
        logger.debug(
                "Hybrid search, using DB query: " + dbQueryLanguage.getName() + " for " + searchParameters);
    }
    stopWatch.start("database query");
    ResultSet dbResults = dbQueryLanguage.executeQuery(searchParameters, admLuceneSearcher);
    stopWatch.stop();
    if (logger.isDebugEnabled()) {
        logger.debug("DB query returned " + dbResults.length() + " results in "
                + stopWatch.getLastTaskTimeMillis() + "ms");
    }
    // Merge result sets
    List<ChildAssociationRef> childAssocs = new ArrayList<>();
    NodeParameters nodeParameters = new NodeParameters();
    nodeParameters.setFromTxnId(lastTxId + 1);
    // TODO: setToTxnId(null) when SolrDAO behaviour is fixed.
    nodeParameters.setToTxnId(Long.MAX_VALUE);
    stopWatch.start("get changed nodes");
    List<Node> changedNodeList = solrDao.getNodes(nodeParameters, null);
    stopWatch.stop();
    if (logger.isDebugEnabled()) {
        logger.debug("Nodes changed since last indexed transaction (ID " + lastTxId + ") = "
                + changedNodeList.size() + " (took " + stopWatch.getLastTaskTimeMillis() + "ms)");
    }
    stopWatch.start("merge result sets");
    Set<NodeRef> nodeRefs = new HashSet<>(changedNodeList.size());
    for (Node n : changedNodeList) {
        nodeRefs.add(n.getNodeRef());
    }
    // Only use the SOLR results for nodes that haven't changed since indexing.
    for (ChildAssociationRef car : indexResults.getChildAssocRefs()) {
        if (!nodeRefs.contains(car.getChildRef())) {
            childAssocs.add(car);
        }
    }
    // Merge in all the database results.
    childAssocs.addAll(dbResults.getChildAssocRefs());

    ResultSet results = new ChildAssocRefResultSet(nodeService, childAssocs);
    stopWatch.stop(); // merge result sets
    if (logger.isDebugEnabled()) {
        String stats = String.format("SOLR=%d, DB=%d, total=%d", indexResults.length(), dbResults.length(),
                results.length());
        logger.debug("Hybrid search returning combined results with counts: " + stats);
        logger.debug(stopWatch.prettyPrint());
    }
    return results;
}

From source file:org.springframework.batch.admin.jmx.StepExecutionServiceLevelMonitor.java

public void invoke(ProceedingJoinPoint joinPoint, final StepExecution stepExecution, Step step)
        throws Throwable {

    final AtomicBoolean finished = new AtomicBoolean(false);
    final StopWatch timer = new StopWatch(stepExecution.getStepName() + ":execution");

    try {/*from w  ww  .  j a  v a  2s.co  m*/

        if (timeout > 0) {

            if (notificationPublisher != null) {
                Notification notification = new Notification("INFO", this, sequence++,
                        "Starting:" + stepExecution);
                notificationPublisher.sendNotification(notification);
            }

            timer.start("StepExecution.Id:" + stepExecution.getId());
            final long threshold = (long) (timeout * (1 - warningMargin));
            Date warningTime = new Date(System.currentTimeMillis() + threshold);
            logger.debug("Scheduling warning after (ms) " + threshold);
            taskScheduler.schedule(new Runnable() {

                public void run() {
                    if (!finished.get()) {
                        logger.debug("Sending warning (step not complete after " + threshold + " ms): "
                                + stepExecution);
                        if (notificationPublisher != null) {
                            Notification notification = new Notification("WARN",
                                    StepExecutionServiceLevelMonitor.this, sequence++,
                                    "Warning:" + stepExecution);
                            notificationPublisher.sendNotification(notification);
                        }
                    } else {
                        logger.debug("No warning necessary for " + stepExecution);
                    }
                }

            }, warningTime);
        }

        joinPoint.proceed();

    } finally {

        finished.set(true);

        if (timeout > 0) {
            timer.stop();
            Executors.newSingleThreadScheduledExecutor().shutdown();
            if (timer.getLastTaskTimeMillis() > timeout) {
                overruns++;
                logger.debug("Notifying overrun " + stepExecution);
                if (notificationPublisher != null) {
                    Notification notification = new Notification("ERROR", this, sequence++,
                            "Overrun:" + stepExecution);
                    notificationPublisher.sendNotification(notification);
                }
            }
        }

    }

}