Example usage for org.springframework.util StopWatch getTotalTimeMillis

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

Introduction

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

Prototype

public long getTotalTimeMillis() 

Source Link

Document

Get the total time in milliseconds for all tasks.

Usage

From source file:com.hd123.oauth2.config.SwaggerConfiguration.java

/**
 * Swagger Springfox configuration.// w w  w  . jav  a  2 s.  co m
 */
@Bean
@Role(ROLE_SUPPORT)
@Profile(UN_PRODUCTION)
@Description("Heading OAuth2 API Documentation")
public Docket swaggerSpringfoxDocket() {
    final boolean debugAble = logger.isDebugEnabled();
    if (debugAble) {
        logger.debug("Starting Swagger");
    }
    final StopWatch watch = new StopWatch();
    watch.start();
    final ApiInfo apiInfo = apiInfo();
    final Docket docket = new Docket(SWAGGER_2).apiInfo(apiInfo).enable(!profileUtil.isProd())
            .enableUrlTemplating(false).forCodeGeneration(true).genericModelSubstitutes(ResponseEntity.class)
            .ignoredParameterTypes(Pageable.class)
            .directModelSubstitute(java.time.LocalDate.class, String.class)
            .directModelSubstitute(java.time.ZonedDateTime.class, Date.class)
            .directModelSubstitute(java.time.LocalDateTime.class, Date.class).useDefaultResponseMessages(false)
            .alternateTypeRules(newRule(
                    typeResolver.resolve(DeferredResult.class,
                            typeResolver.resolve(ResponseEntity.class, WildcardType.class)),
                    typeResolver.resolve(WildcardType.class)))
            .globalResponseMessage(GET,
                    newArrayList(new ResponseMessageBuilder().code(500).message("Internal Server Error")
                            .responseModel(new ModelRef("Error")).build()))
            .select().apis(any()).paths(regex(appProperties.getSwagger().getApiPattern())).build();
    watch.stop();

    if (debugAble) {
        logger.debug("Started Swagger in {} ms", watch.getTotalTimeMillis());
    }

    return docket;
}

From source file:no.arkivlab.hioa.nikita.webapp.spring.SwaggerConfig.java

@Bean
public Docket swaggerDocket() { // @formatter:off

    logger.debug("Starting Swagger");
    StopWatch watch = new StopWatch();
    watch.start();//w w w  . j a  va 2 s.co m
    Contact contact = new Contact(webappProperties.getSwagger().getContactName(),
            webappProperties.getSwagger().getContactUrl(), webappProperties.getSwagger().getContactEmail());

    ApiInfo apiInfo = new ApiInfo(webappProperties.getSwagger().getTitle(),
            webappProperties.getSwagger().getDescription(), webappProperties.getSwagger().getVersion(),
            webappProperties.getSwagger().getTermsOfServiceUrl(), contact,
            webappProperties.getSwagger().getLicense(), webappProperties.getSwagger().getLicenseUrl());

    Docket docket = new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo).forCodeGeneration(true)
            .genericModelSubstitutes(ResponseEntity.class).ignoredParameterTypes(Pageable.class)
            .ignoredParameterTypes(java.sql.Date.class)
            .directModelSubstitute(java.time.LocalDate.class, java.sql.Date.class)
            .directModelSubstitute(java.time.ZonedDateTime.class, Date.class)
            .directModelSubstitute(java.time.LocalDateTime.class, Date.class).select()
            .apis(RequestHandlerSelectors.any()).paths(PathSelectors.any()).build()
            .pathMapping(Constants.HATEOAS_API_PATH).genericModelSubstitutes(ResponseEntity.class);

    watch.stop();
    logger.debug("Started Swagger in {} ms", watch.getTotalTimeMillis());
    return docket;
    // @formatter:on
}

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

/**
 * Returns a BinaryMeta object or throws ItemNotFoundException if not found.
 * // www .  j a v a  2s.  c o m
 * @param pubId
 * @param url
 * @return
 * @throws ItemNotFoundException
 * @throws StorageException 
 */
private BinaryVariant getBinaryVariantByUrl(int pubId, String url)
        throws ItemNotFoundException, StorageException {

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

    BinaryVariantDAO binaryVariantDAO = HomeUtils.getInstance().getBinaryVariantDao(pubId);

    BinaryVariant binaryVariant = null;
    try {
        binaryVariant = binaryVariantDAO.findByURL(pubId, url);
        if (binaryVariant == null) {
            if (logger.isDebugEnabled()) {
                logger.debug("Cannot find BinaryVariant in Tridion.");
            }
            throw new ItemNotFoundException("No binary found with url :" + url);
        }
        if (logger.isDebugEnabled()) {
            logger.debug("Returning BinaryMeta " + binaryVariant);
        }
    } catch (StorageException e) {
        logger.error("StorageException caught throw runtime exception");
        throw new RuntimeException(e);
    } finally {
        if (logger.isDebugEnabled()) {
            stopWatch.stop();
            logger.debug("Exit getBinaryMetaByUrl (" + stopWatch.getTotalTimeMillis() + " ms)");
        }
    }

    return binaryVariant;
}

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

private Page getSimplePage(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");
    }//www.j a  v  a  2 s .  c o m

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

    PageMeta pageMeta = null;
    Page page = null;
    try {
        TCMURI tcmUri = new TCMURI(uri);

        pageMeta = brokerPageProvider.getPageMetaById(tcmUri.getPublicationId(), tcmUri.getItemId());

        page = (Page) getPageFromMeta(pageMeta);

        try {
            // run all filters regardless if they are allowed to be cached
            // or not
            doFilters(page, context, BaseFilter.RunPhase.Both);
        } catch (FilterException e) {
            logger.error("Error in filter. ", e);
            throw new RuntimeException(e);
        }

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

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

    return page;
}

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

private SimpleBinary getBinaryFromUri(String uri, RequestContext context) throws ItemNotFoundException,
        NotAuthorizedException, ParseException, StorageException, NotAuthenticatedException {

    StopWatch stopWatch = null;
    if (logger.isDebugEnabled()) {
        logger.debug("Enter getBinaryFromUri with uri: " + uri);
        stopWatch = new StopWatch("getBinaryFromUri");
        stopWatch.start();//from w w w.j  a  va  2  s.co m
    }

    SimpleBinaryImpl simpleBinary;
    // retrieve the SimpleComponent for this mm component
    ComponentFactory compFactory = new SimpleComponentFactory();
    // make sure there are no filters set, we need only the simple component
    // factory logic itself!
    compFactory.setFilters(new LinkedList<Filter>());
    Component mmComp = compFactory.getComponent(uri, context);

    simpleBinary = new SimpleBinaryImpl();
    simpleBinary.setNativeMetadata(mmComp.getNativeMetadata());
    simpleBinary.setFactory(this);
    simpleBinary.setId(TridionUtils.createUri(mmComp.getNativeMetadata()).toString());
    simpleBinary.setTitle(mmComp.getNativeMetadata().getTitle());

    try {
        doFilters(simpleBinary, context, null);
    } catch (FilterException e) {
        logger.warn("Error in filter. ", e);
        throw new RuntimeException(e);
    } finally {
        if (logger.isDebugEnabled()) {
            stopWatch.stop();
            logger.debug("Exit getBinaryFromUri (" + stopWatch.getTotalTimeMillis() + " ms)");
        }
    }

    return simpleBinary;
}

From source file:io.tronbot.graphql.actuator.config.apidoc.SwaggerConfiguration.java

/**
 * Swagger Springfox configuration./*from  w  w  w  .  j av a2  s . c o  m*/
 *
 * @param jHipsterProperties the properties of the application
 * @return the Swagger Springfox configuration
 */
@Bean
public Docket swaggerSpringfoxDocket(JHipsterProperties jHipsterProperties) {
    log.debug("Starting Swagger");
    StopWatch watch = new StopWatch();
    watch.start();
    Contact contact = new Contact(jHipsterProperties.getSwagger().getContactName(),
            jHipsterProperties.getSwagger().getContactUrl(), jHipsterProperties.getSwagger().getContactEmail());

    ApiInfo apiInfo = new ApiInfo(jHipsterProperties.getSwagger().getTitle(),
            jHipsterProperties.getSwagger().getDescription(), jHipsterProperties.getSwagger().getVersion(),
            jHipsterProperties.getSwagger().getTermsOfServiceUrl(), contact,
            jHipsterProperties.getSwagger().getLicense(), jHipsterProperties.getSwagger().getLicenseUrl());

    List<Parameter> globalOperationParameters = new ArrayList<>();
    globalOperationParameters.add(new ParameterBuilder().parameterType("header").description("JWT Token")
            .modelRef(new ModelRef("string")).name(JWTConfigurer.AUTHORIZATION_HEADER)
            .defaultValue(JWTConfigurer.AUTHORIZATION_TOKEN_SCHEMA + authenticationService.authJWT())
            .required(false).build());

    Docket docket = new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo).forCodeGeneration(true)
            .genericModelSubstitutes(ResponseEntity.class).ignoredParameterTypes(java.sql.Date.class)
            .directModelSubstitute(java.time.LocalDate.class, java.sql.Date.class)
            .directModelSubstitute(java.time.ZonedDateTime.class, Date.class)
            .directModelSubstitute(java.time.LocalDateTime.class, Date.class)
            .globalOperationParameters(globalOperationParameters).select().paths(regex(DEFAULT_INCLUDE_PATTERN))
            .build();

    watch.stop();
    log.debug("Started Swagger in {} ms", watch.getTotalTimeMillis());
    return docket;
}

From source file:com.api.foobar.config.apidoc.SwaggerConfiguration.java

/**
 * Swagger Springfox configuration./*from   w w w  . ja  va2 s.co m*/
 *
 * @param swaggerProperties the properties of the application
 * @return the Swagger Springfox configuration
 */
@Bean
public Docket swaggerSpringfoxDocket(SwaggerProperties swaggerProperties) {
    log.debug("Starting Swagger");
    StopWatch watch = new StopWatch();
    watch.start();
    Contact contact = getContact(swaggerProperties);

    ApiInfo apiInfo = getApiInfo(swaggerProperties, contact);

    Docket docket = new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo).forCodeGeneration(true)
            //                .genericModelSubstitutes(ResponseEntity.class)
            //                .ignoredParameterTypes(Pageable.class)
            //                .ignoredParameterTypes(java.sql.Date.class)
            //                .directModelSubstitute(java.time.LocalDate.class, java.sql.Date.class)
            //                .directModelSubstitute(java.time.ZonedDateTime.class, Date.class)
            //                .directModelSubstitute(java.time.LocalDateTime.class, Date.class)
            .select().apis(RequestHandlerSelectors.any()).paths(apiPaths()).build().pathMapping("/")
            .directModelSubstitute(DateTime.class, String.class).genericModelSubstitutes(ResponseEntity.class)
            .alternateTypeRules(newRule(
                    typeResolver.resolve(DeferredResult.class,
                            typeResolver.resolve(ResponseEntity.class, WildcardType.class)),
                    typeResolver.resolve(WildcardType.class)))
            .globalOperationParameters(globalOperationParameters()).useDefaultResponseMessages(true) //Flag to indicate if default http response codes need to be used or not
            .securitySchemes(newArrayList(apiKey())).securityContexts(newArrayList(securityContext()))
            .enableUrlTemplating(false); //if true, use 'from style query' for generated paths

    watch.stop();
    log.debug("Started Swagger in {} ms", watch.getTotalTimeMillis());
    return docket;
}

From source file:org.dd4t.core.filters.impl.DefaultLinkResolverFilter.java

protected void resolveXhtmlField(XhtmlField xhtmlField) {

    StopWatch stopWatch = null;
    if (logger.isDebugEnabled()) {
        stopWatch = new StopWatch();
        stopWatch.start();//from ww  w .  j  ava  2 s . c o  m
    }

    List<Object> xhtmlValues = xhtmlField.getValues();
    List<String> newValues = new ArrayList<String>();

    if (useXslt) {
        // find all component links and try to resolve them
        for (Object xhtmlValue : xhtmlValues) {
            String result = xslTransformer.transformSourceFromFilesource(
                    "<ddtmproot>" + (String) xhtmlValue + "</ddtmproot>", "/resolveXhtmlWithLinks.xslt",
                    params);
            newValues.add(XSLTPattern.matcher(result).replaceAll(""));
        }
    } else {
        // find all component links and try to resolve them
        for (Object xhtmlValue : xhtmlValues) {

            Matcher m = RegExpPattern.matcher((String) xhtmlValue);

            StringBuffer sb = new StringBuffer();
            String resolvedLink = null;
            while (m.find()) {
                resolvedLink = getLinkResolver().resolve(m.group(1));
                // if not possible to resolve the link do nothing
                if (resolvedLink != null) {
                    m.appendReplacement(sb, "href=\"" + resolvedLink + "\"");
                }
            }
            m.appendTail(sb);
            newValues.add(sb.toString());
        }

    }

    xhtmlField.setTextValues(newValues);

    if (logger.isDebugEnabled()) {
        stopWatch.stop();
        logger.debug("Parsed rich text field '" + xhtmlField.getName() + "' in "
                + stopWatch.getTotalTimeMillis() + " ms.");
    }
}

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

/**
 * This is just a intermediate method to avoid naming conflicts with the
 * simpleFactory./*from  ww  w  .  j av  a2 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.surevine.alfresco.audit.SpringAuditFilterBean.java

/**
 * {@inheritDoc}//from www. j  a  va 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);
}