Example usage for org.springframework.util StopWatch start

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

Introduction

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

Prototype

public void start() throws IllegalStateException 

Source Link

Document

Start an unnamed task.

Usage

From source file:org.dd4t.core.factories.impl.GenericPageFactory.java

private GenericPage getGenericPage(String uri, RequestContext context)
        throws ItemNotFoundException, NotAuthorizedException, NotAuthenticatedException {

    if (context == null && securityFilterPresent()) {
        throw new RuntimeException("use of getPage is not allowed when a SecurityFilter is set");
    }//  w w  w  .  j  a  v a 2 s.  c om

    StopWatch stopWatch = null;
    if (logger.isDebugEnabled()) {
        logger.debug("Enter getGenericPage with uri: " + uri);
        stopWatch = new StopWatch("getGenericPage");
        stopWatch.start();
    }

    GenericPage page = (GenericPage) getCacheProvider().loadFromLocalCache(uri);
    if (page == null) {
        try {
            TCMURI tcmUri = new TCMURI(uri);
            PageMeta pageMeta = getPageProvider().getPageMetaById(tcmUri.getItemId(),
                    tcmUri.getPublicationId());

            if (pageMeta == null)
                throw new ItemNotFoundException("Unable to find page by id " + tcmUri);

            page = getPageFromMeta(pageMeta);

            try {
                // run only the filters where the result is allowed to be
                // cached.
                doFilters(page, context, BaseFilter.RunPhase.BeforeCaching);
            } catch (FilterException e) {
                logger.error("Error in filter. ", e);
                throw new RuntimeException(e);
            }

            getCacheProvider().storeInItemCache(uri, page, tcmUri.getPublicationId(), tcmUri.getItemId());

        } catch (IOException e) {
            logger.error("IOException when processing page: " + uri, e);
            throw new RuntimeException(e);
        } catch (ParseException e) {
            logger.error("ParseException when searching for page: " + uri, e);
            throw new RuntimeException(e);
        } catch (StorageException e) {
            logger.error("StorageException when searching for page: " + uri, e);
            throw new RuntimeException(e);
        }
    }

    try {
        // run only the filters where the result is not allowed to be
        // cached.
        doFilters(page, context, BaseFilter.RunPhase.AfterCaching);
    } catch (FilterException e) {
        logger.error("Error in filter. ", e);
        throw new RuntimeException(e);
    } finally {
        if (logger.isDebugEnabled()) {
            stopWatch.stop();
            logger.debug("Exit getGenericPage (" + stopWatch.getTotalTimeMillis() + " ms)");
        }
    }

    return page;
}

From source file:org.dd4t.core.factories.impl.GenericComponentFactory.java

/**
 * Get the component by the component uri and template uri.
 * //www .j av a2  s  . c  o m
 * @return the component
 * @throws ItemNotFoundException
 *             if no item found NotAuthorizedException if the user is not
 *             authorized to get the component
 * @throws NotAuthenticatedException 
 */
public DynamicComponent getComponent(String componentUri, String componentTemplateUri, RequestContext context)
        throws ItemNotFoundException, NotAuthorizedException, NotAuthenticatedException {

    if (context == null && securityFilterPresent()) {
        throw new RuntimeException(
                "use of getComponent without a context is not allowed when a SecurityFilter is set");
    }

    if (!componentUri.endsWith("-16")) {
        componentUri += "-16";
    }

    StopWatch stopWatch = null;
    if (logger.isDebugEnabled()) {
        logger.debug("Enter getComponent with uri: " + componentUri);
        stopWatch = new StopWatch("getComponent");
        stopWatch.start();
    }

    DynamicComponent component = (DynamicComponent) getCacheProvider().loadFromLocalCache(componentUri);
    if (component == null) {
        TCMURI tcmUri;
        ComponentMeta componentMeta;
        com.tridion.dcp.ComponentPresentation dcp;

        try {

            tcmUri = new TCMURI(componentUri);

            componentMeta = getComponentProvider().getComponentMeta(tcmUri.getItemId(),
                    tcmUri.getPublicationId());

            if (componentMeta == null) {
                throw new ItemNotFoundException("Unable to find item with id " + componentUri
                        + " in the broker. Is the item published?");
            }

            if (componentTemplateUri != null) {
                TCMURI ctUri = new TCMURI(componentTemplateUri);

                dcp = getComponentProvider().getDynamicComponentPresentation(tcmUri.getItemId(),
                        ctUri.getItemId(), tcmUri.getPublicationId());
            } else {
                dcp = getComponentProvider().getDynamicComponentPresentation(tcmUri.getItemId(), 0,
                        tcmUri.getPublicationId());
            }
        } catch (ParseException e1) {
            logger.error("No item found with uri: " + componentUri + "; could not parse the URI: " + e1);
            throw new ItemNotFoundException(
                    "No item found with uri: " + componentUri + "; could not parse the URI: " + e1);
        } catch (StorageException e2) {
            logger.error("No item found with uri: " + componentUri + "; broker is down.");
            throw new ItemNotFoundException("No item found with uri: " + componentUri + "; broker is down.");
        }

        if (dcp.getContent() == null) {
            logger.error(
                    "Source is null for item: " + componentUri + " and templateUri: " + componentTemplateUri);
            throw new ItemNotFoundException(
                    "No item found with uri: " + componentUri + " and templateUri: " + componentTemplateUri);
        }

        try {
            component = getDCPFromSource(dcp);

            component.setNativeMetadata(componentMeta);

            // Rogier Oudshoorn, 7/2/2012
            // object size is roughly half the xml string size; 

            ((BasePublishedItem) component).setSourceSize(dcp.getContent().length());

            try {
                doFilters(component, context, BaseFilter.RunPhase.BeforeCaching);
            } catch (FilterException e) {
                logger.error("Error in filter. ", e);
                throw new RuntimeException(e);
            }

            getCacheProvider().storeInItemCache(componentUri, component,
                    component.getNativeMetadata().getPublicationId(),
                    component.getNativeMetadata().getItemId());
        } catch (Exception e) {
            logger.error("error when deserializing component", e);
            throw new RuntimeException(e);
        }
    }

    try {
        doFilters(component, context, BaseFilter.RunPhase.AfterCaching);
    } catch (FilterException e) {
        logger.error("Error in filter. ", e);
        throw new RuntimeException(e);
    }

    if (logger.isDebugEnabled()) {
        stopWatch.stop();
        logger.debug("Exit getComponent (" + stopWatch.getTotalTimeMillis() + " ms)");
    }

    return component;
}

From source file:org.dd4t.core.factories.impl.GenericPageFactory.java

/**
 * This is just a intermediate method to avoid naming conflicts with the
 * simpleFactory.//w ww.  j av a  2  s.  c om
 * @throws NotAuthenticatedException 
 */
private GenericPage findGenericPageByUrl(String url, int publicationId, RequestContext context)
        throws ItemNotFoundException, NotAuthorizedException, NotAuthenticatedException {

    if (context == null && securityFilterPresent()) {
        throw new RuntimeException("use of findPageByUrl is not allowed when a SecurityFilter is set");
    }

    StopWatch stopWatch = null;
    StopWatch subWatch = null;
    if (logger.isDebugEnabled()) {
        logger.debug("Enter findGenericPageByUrl with url:" + url + " and publicationId: " + publicationId);
        stopWatch = new StopWatch("findGenericPageByUrl");
        stopWatch.start();

        subWatch = new StopWatch("subTasks");
        subWatch.start();
    }

    String cacheKey = publicationId + "-" + url;
    GenericPage page = (GenericPage) getCacheProvider().loadFromLocalCache(cacheKey);
    if (page == null) {
        try {
            PageMeta pageMeta = getPageProvider().getPageMetaByURL(url, publicationId);

            page = getPageFromMeta(pageMeta);

            try {
                // run only the filters where the result is allowed to be
                // cached.
                doFilters(page, context, BaseFilter.RunPhase.BeforeCaching);
            } catch (FilterException e) {
                logger.warn("Error in filter. ", e);
                throw new RuntimeException(e);
            }

            getCacheProvider().storeInItemCache(cacheKey, page, pageMeta.getPublicationId(),
                    pageMeta.getItemId());

        } catch (IOException e) {
            logger.error("IOException when processing page: " + url, e);
            throw new RuntimeException(e);
        } catch (StorageException e) {
            logger.error("StorageException when searching for page: " + url, e);
            throw new RuntimeException(e);
        }
    }

    if (logger.isDebugEnabled()) {
        subWatch.stop();
        logger.debug("Page retrieved in " + subWatch.getTotalTimeMillis() + " ms)");
        subWatch = new StopWatch("again");
        subWatch.start();
    }

    try {
        // run only the filters where the result is not allowed to be
        // cached.
        doFilters(page, context, BaseFilter.RunPhase.AfterCaching);
    } catch (FilterException e) {
        logger.error("Error in filter. ", e);
        throw new RuntimeException(e);
    } finally {
        if (logger.isDebugEnabled()) {
            subWatch.stop();
            logger.debug("Ran filters in " + subWatch.getTotalTimeMillis() + " ms)");
            stopWatch.stop();
            logger.debug(
                    "Exit findGenericPageByUrl for " + url + " (" + stopWatch.getTotalTimeMillis() + " ms)");
        }
    }

    return page;
}

From source file:com.persistent.cloudninja.scheduler.TenantStorageBWProcessor.java

/** 
 * Calculates storage bandwidth of tenant.
 *//* w  w  w .j  av a 2 s  . c om*/
@Override
public boolean execute() {
    StopWatch watch = new StopWatch();
    boolean retVal = true;
    List<StorageBandwidthBatchEntity> batchesToProcess = null;
    try {
        LOGGER.debug("In TenantStorageBWProcessor");
        TenantStorageBWQueue queue = (TenantStorageBWQueue) getWorkQueue();
        batchesToProcess = queue.dequeue();
        if (batchesToProcess == null) {
            retVal = false;
        } else {
            watch.start();
            processBatches(batchesToProcess);
            watch.stop();
            taskCompletionDao.updateTaskCompletionDetails(watch.getTotalTimeSeconds(),
                    "GenerateStorageBandwidth", "Batch Size = " + batchesToProcess.size());
        }
    } catch (Exception e) {
        retVal = false;
        LOGGER.error(e.getMessage(), e);
    }
    return retVal;
}

From source file:org.openmrs.module.diabetesmanagement.web.controller.SimulationFormController.java

/**
 * The onSubmit method receives the form/command object that was modified by the input form and
 * saves it to the database.//from ww w  . j  a  v a2  s  .c  o  m
 * 
 * @see org.springframework.web.servlet.mvc.SimpleFormController#onSubmit(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse, java.lang.Object,
 *      org.springframework.validation.BindException)
 * @param request Current servlet request.
 * @param response Current servlet response.
 * @param command Form object with request parameters bound onto it.
 * @param errors Holder without errors.
 * @return The prepared model and view, or null.
 * @throws Exception In case of errors.
 */
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command,
        BindException errors) throws Exception {
    Context.addProxyPrivilege(OpenmrsConstants.PRIV_VIEW_USERS);
    Context.addProxyPrivilege(OpenmrsConstants.PRIV_VIEW_PATIENTS);
    try {
        if (Context.isAuthenticated()) {
            StopWatch stopwatch = new StopWatch();
            ObjectOutputStream out = null;
            File f = null;
            File root = OpenmrsUtil.getDirectoryInApplicationDataDirectory("diabetesmanagement/simulation");
            String sessionId = request.getSession().getId() + "_";

            // Benchmarking the simulation model run
            Simulation sim = (Simulation) command;
            stopwatch.start();
            sim.runSimulation();
            stopwatch.stop();
            sim.setExecutionTime(stopwatch.getTotalTimeSeconds());

            // Serializing current results, if available
            if (sim.getResultsAvailableCurrent()) {
                // Current plasma glucose
                f = new File(root.getAbsolutePath(), sessionId + FILENAME_PLASMA_GLUCOSE_CURRENT);
                f.delete();
                out = new ObjectOutputStream(new FileOutputStream(f));
                out.writeObject(sim.getResultGlucoseCurrent());
                out.close();
                // Current plasma insulin
                f = new File(root.getAbsolutePath(), sessionId + FILENAME_PLASMA_INSULIN_CURRENT);
                f.delete();
                out = new ObjectOutputStream(new FileOutputStream(f));
                out.writeObject(sim.getResultInsulinCurrent());
                out.close();
                // Current meals
                if (sim.getMealsCurrent() != null) {
                    f = new File(root.getAbsolutePath(), sessionId + FILENAME_MEALS_CURRENT);
                    f.delete();
                    out = new ObjectOutputStream(new FileOutputStream(f));
                    out.writeObject(sim.getMealsCurrent());
                    out.close();
                }
                // Current insulin injections (1)
                if (sim.getInsulinInjections1() != null) {
                    f = new File(root.getAbsolutePath(), sessionId + FILENAME_INJECTIONS_1);
                    f.delete();
                    out = new ObjectOutputStream(new FileOutputStream(f));
                    out.writeObject(sim.getInsulinInjections1());
                    out.close();
                }
                // Current insulin injections (2)
                if (sim.getInsulinInjections2() != null) {
                    f = new File(root.getAbsolutePath(), sessionId + FILENAME_INJECTIONS_2);
                    f.delete();
                    out = new ObjectOutputStream(new FileOutputStream(f));
                    out.writeObject(sim.getInsulinInjections2());
                    out.close();
                }
            }

            // Serializing previous results, if available
            if (sim.getResultsAvailablePrevious()) {
                // Previous plasma glucose
                f = new File(root.getAbsolutePath(), sessionId + FILENAME_PLASMA_GLUCOSE_PREVIOUS);
                f.delete();
                out = new ObjectOutputStream(new FileOutputStream(f));
                out.writeObject(sim.getResultGlucosePrevious());
                out.close();
                // Previous plasma insulin
                f = new File(root.getAbsolutePath(), sessionId + FILENAME_PLASMA_INSULIN_PREVIOUS);
                f.delete();
                out = new ObjectOutputStream(new FileOutputStream(f));
                out.writeObject(sim.getResultInsulinPrevious());
                out.close();
                // Previous meals
                if (sim.getMealsPrevious() != null) {
                    f = new File(root.getAbsolutePath(), sessionId + FILENAME_MEALS_PREVIOUS);
                    f.delete();
                    out = new ObjectOutputStream(new FileOutputStream(f));
                    out.writeObject(sim.getMealsCurrent());
                    out.close();
                }
            }
        }
    } finally {
        Context.removeProxyPrivilege(OpenmrsConstants.PRIV_VIEW_USERS);
        Context.removeProxyPrivilege(OpenmrsConstants.PRIV_VIEW_PATIENTS);
    }

    return showForm(request, response, errors);
}

From source file:com.surevine.alfresco.audit.SpringAuditFilterBean.java

/**
 * {@inheritDoc}// www .  j av  a 2 s. c o m
 */
public void doFilter(final ServletRequest request, final ServletResponse response,
        final FilterChain filterChain) throws IOException, ServletException {

    HttpServletRequest httpServletRequest = null;
    BufferedHttpServletResponse httpServletResponse = null;

    if (request instanceof HttpServletRequest && response instanceof HttpServletResponse) {
        httpServletRequest = (HttpServletRequest) request;
    } else {
        throw new ServletException(
                new IllegalArgumentException("Invalid request or response parameter provided."));
    }

    String method = httpServletRequest.getMethod();

    // Only override current HttpServletRequest with custom implementation if post data
    // will be read.
    if (MULTI_READ_HTTP_METHODS.contains(method)) {
        httpServletRequest = new MultiReadHttpServletRequest(httpServletRequest);
    }

    // Now iterate over each of the installed listeners searching to see if, firstly the http methods match
    // and secondly that an event is fired.
    for (AuditEventListener listener : listeners) {

        if (listener.getMethod().equals(method) && listener.isEventFired(httpServletRequest)) {

            // Need to allow the output to be read twice from the response
            httpServletResponse = new BufferedHttpServletResponse((HttpServletResponse) response);

            List<Auditable> itemsToAudit = null;
            String username = null;
            try {

                HttpSession sess = httpServletRequest.getSession();
                SessionUser user = (SessionUser) sess.getAttribute(AuthenticationHelper.AUTHENTICATION_USER);
                if (user != null) {
                    username = user.getUserName();
                }

                // Used to track total processing time for the request being audited
                StopWatch timer = new StopWatch();

                // There are certain listener types where we have to construct the audit items prior to passing to
                // the filter
                // chain.
                if (listener instanceof GetAuditEventListener
                        || listener instanceof MultiDocumentDeleteAuditEventListener
                        || listener instanceof SafeMoveDocumentAuditEventListener
                        || listener instanceof UnlockDocumentAuditEventListener
                        || listener instanceof UndeleteAuditEventListener
                        || listener instanceof ImmediateArchiveAuditEventListener) {
                    itemsToAudit = listener.populateAuditItems(httpServletRequest, httpServletResponse);

                    // Continue with the filter chain
                    timer.start();
                    filterChain.doFilter(httpServletRequest, httpServletResponse);
                    timer.stop();

                    // Calling finish on the response will release the output stream back to the client.
                    httpServletResponse.finish();

                } else {
                    // Populate the audit item after the filter chain has been run
                    timer.start();
                    filterChain.doFilter(httpServletRequest, httpServletResponse);
                    timer.stop();

                    // Calling finish on the response will release the output stream back to the client.
                    httpServletResponse.finish();

                    itemsToAudit = listener.populateAuditItems(httpServletRequest, httpServletResponse);

                }

                for (Auditable audit : itemsToAudit) {
                    listener.decideSuccess(httpServletResponse, audit);
                    audit.setUser(username);
                    audit.setTimeSpent(timer.getTotalTimeMillis());
                    repository.audit(audit);
                }

            } catch (JSONException e) {
                logger.error("JSONException caught during audit, " + e.getMessage());
                throw new ServletException(e);
            } catch (AlfrescoRuntimeException alfrescoRuntime) {
                logger.error("AlfrescoRuntimeException caught during audit, " + alfrescoRuntime.getMessage());
                throw new ServletException(alfrescoRuntime);
            } catch (DataIntegrityViolationException e) {
                logger.error("Data Integrity Exception caught during audit, " + e.getMessage());
                throw new ServletException(
                        "A Data Integreity Violation occured.  Please see the logs for more information");

            } catch (Exception e) {

                logger.error("Exception caught during audit " + e.getMessage());
                throw new ServletException(e);
            }

            return;
        }
    }

    // If we fall out here there was no auditable event so simply complete the filter chain.
    // And we won't have tinkered with the response object so just add the servletresponse
    // as the parameter.
    filterChain.doFilter(httpServletRequest, response);
}

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

@Override
@Deprecated// w  w w .j a  v  a  2s  . 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.jxt.web.service.FilteredMapServiceImpl.java

/**
 * filtered application map/*from   w w  w .java  2 s .  co m*/
 */
@Override
public ApplicationMap selectApplicationMap(List<TransactionId> transactionIdList, Range originalRange,
        Range scanRange, Filter filter) {
    if (transactionIdList == null) {
        throw new NullPointerException("transactionIdList must not be null");
    }
    if (filter == null) {
        throw new NullPointerException("filter must not be null");
    }

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

    final List<List<SpanBo>> filterList = selectFilteredSpan(transactionIdList, filter);

    DotExtractor dotExtractor = createDotExtractor(scanRange, filterList);
    ApplicationMap map = createMap(originalRange, scanRange, filterList);

    ApplicationMapWithScatterScanResult applicationMapWithScatterScanResult = new ApplicationMapWithScatterScanResult(
            map, dotExtractor.getApplicationScatterScanResult());

    watch.stop();
    logger.debug("Select filtered application map elapsed. {}ms", watch.getTotalTimeMillis());

    return applicationMapWithScatterScanResult;
}

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

@Override
public ApplicationMap selectApplicationMapWithScatterData(List<TransactionId> transactionIdList,
        Range originalRange, Range scanRange, int xGroupUnit, int yGroupUnit, Filter filter) {
    if (transactionIdList == null) {
        throw new NullPointerException("transactionIdList must not be null");
    }/*from  w w w .j a v a  2s.c  o m*/
    if (filter == null) {
        throw new NullPointerException("filter must not be null");
    }

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

    final List<List<SpanBo>> filterList = selectFilteredSpan(transactionIdList, filter);

    DotExtractor dotExtractor = createDotExtractor(scanRange, filterList);
    ApplicationMap map = createMap(originalRange, scanRange, filterList);

    ApplicationMapWithScatterData applicationMapWithScatterData = new ApplicationMapWithScatterData(map,
            dotExtractor.getApplicationScatterData(originalRange.getFrom(), originalRange.getTo(), xGroupUnit,
                    yGroupUnit));

    watch.stop();
    logger.debug("Select filtered application map elapsed. {}ms", watch.getTotalTimeMillis());

    return applicationMapWithScatterData;
}