Example usage for org.springframework.util StopWatch stop

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

Introduction

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

Prototype

public void stop() throws IllegalStateException 

Source Link

Document

Stop the current task.

Usage

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");
    }// ww  w .ja 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();// www.  j a v  a2s.c  o  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:com.persistent.cloudninja.scheduler.TenantWebBandWidthUsageGenerator.java

@Override
public boolean execute() {
    StopWatch watch = new StopWatch();
    LOGGER.info("Start of TenantWebBandWidthUsageGenerator:execute");
    // Generate Queue
    TenantWebBandWidthUsageQueue queue = (TenantWebBandWidthUsageQueue) getWorkQueue();
    boolean returnFlag = true;
    int batchSize = SchedulerSettings.WEB_BANDWIDTH_USAGE_BATCH_SIZE;
    int numBatchesPrepared = 0;
    int webLogMeteringBatchListSize = 0;

    try {/* ww w. j  a  va  2  s.  co  m*/
        watch.start();
        List<WebLogMeteringBatch> webLogMeteringBatchList = tenantWebBandWidthUsageGeneratorUtility
                .retrieveTomcatLogs();
        webLogMeteringBatchListSize = webLogMeteringBatchList.size();
        for (int i = 0; i < webLogMeteringBatchListSize; i = i + batchSize) {

            List<WebLogMeteringBatch> batchToProcess = new ArrayList<WebLogMeteringBatch>();
            for (int j = 0; j < batchSize
                    && ((numBatchesPrepared * batchSize) + j) < webLogMeteringBatchList.size(); j++) {

                batchToProcess.add(webLogMeteringBatchList.get(j + i));
            }
            // Enqueue
            queue.enqueue(batchToProcess);
            numBatchesPrepared++;
        }

        LOGGER.debug("TenantWebBandWidthUsageGenerator:execute ---> Number of batched processed"
                + numBatchesPrepared);
        LOGGER.info("End of TenantWebBandWidthUsageGenerator:execute");
        watch.stop();
        taskCompletionDao.updateTaskCompletionDetails(watch.getTotalTimeSeconds(),
                "GenerateMeterWebAppBandwidthWork",
                "Measure " + webLogMeteringBatchListSize + " logs in " + numBatchesPrepared + " batches.");
    } catch (StorageException stgException) {
        LOGGER.error(stgException.getMessage(), stgException);
    } catch (Exception e) {
        LOGGER.error(e.getMessage(), e);
    }
    return returnFlag;
}

From source file:com.quartzdesk.executor.core.job.AbstractJob.java

/**
 * The method invoked by the Quartz scheduler.
 *
 * @param context a {@link JobExecutionContext} instance.
 * @throws JobExecutionException if an error occurs while executing the job.
 *//*from  w w w  .  ja va  2 s  . c  o m*/
@Override
public final void execute(JobExecutionContext context) throws JobExecutionException {
    String jobFullName = context.getJobDetail().getKey().toString();

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

    ClassLoader origContextClassLoader = Thread.currentThread().getContextClassLoader();

    try {
        if (log.isInfoEnabled())
            log.info("Started scheduled job: {}", jobFullName);

        if (log.isDebugEnabled()) {
            StringBuilder jobDataMapDump = new StringBuilder();

            // map that contains merged job data from the job detail data map and trigger data map
            JobDataMap jobDataMap = context.getMergedJobDataMap();
            for (Iterator<String> keys = jobDataMap.keySet().iterator(); keys.hasNext();) {
                String key = keys.next();
                String value = CommonUtils.safeToString(jobDataMap.get(key));

                jobDataMapDump.append(key).append('=').append(value);

                if (keys.hasNext())
                    jobDataMapDump.append(CommonConst.NL);
            }

            log.debug("Job data map dump:{}{}", CommonConst.NL, jobDataMapDump.toString());
        }

        // Set the context class loader to be the class loader of the job class.
        // This is a workaround/fix for the WebSpere Application Server where
        // WebSphere work manager threads are typically used to execute jobs.
        Thread.currentThread().setContextClassLoader(getClass().getClassLoader());

        executeJob(context);

        sw.stop();

        if (log.isInfoEnabled())
            log.info("Finished scheduled job: {}. Time taken: {}s.", jobFullName, sw.getTotalTimeSeconds());
    } catch (JobExecutionException e) {
        if (log.isErrorEnabled())
            log.error("Error executing scheduled job: " + jobFullName, e);
        throw e;
    } finally {
        // restore the original thread context class loader
        Thread.currentThread().setContextClassLoader(origContextClassLoader);
    }
}

From source file:com.quartzdesk.test.quartz.v2.AbstractJob.java

/**
 * The method invoked by the Spring scheduler. This method simply delegates the
 * execution to the {@link #executeJob(JobExecutionContext)} method.
 *
 * @param context a {@link JobExecutionContext} instance.
 * @throws JobExecutionException if an error occurs while executing the
 * job.//from  w w  w.j  ava2 s . c om
 */
@Override
public final void execute(JobExecutionContext context) throws JobExecutionException {
    String jobFullName = context.getJobDetail().getKey().toString();
    String triggerFullName = context.getTrigger().getKey().toString();

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

    ClassLoader origContextClassLoader = Thread.currentThread().getContextClassLoader();

    try {
        if (log.isInfoEnabled())
            log.info("Started scheduled job: {}, fired by trigger: {}", jobFullName, triggerFullName);

        if (log.isDebugEnabled()) {
            StringBuilder jobDataMapDump = new StringBuilder();

            // map that contains merged job data from the job detail data map and trigger data map
            JobDataMap jobDataMap = context.getMergedJobDataMap();
            for (Iterator<String> keys = jobDataMap.keySet().iterator(); keys.hasNext();) {
                String key = keys.next();
                String value = CommonUtils.safeToString(jobDataMap.get(key));

                jobDataMapDump.append(key).append('=').append(value);

                if (keys.hasNext())
                    jobDataMapDump.append(CommonConst.NL);
            }

            log.debug("Job data map dump:{}{}", CommonConst.NL, jobDataMapDump.toString());
        }

        // Set the context class loader to be the class loader of the job class.
        // This is a workaround/fix for a problem with setting the thread's context
        // class loader through Quartz properties when WebSphere work manager threads
        // are used.
        Thread.currentThread().setContextClassLoader(getClass().getClassLoader());

        executeJob(context);

        sw.stop();

        if (log.isInfoEnabled())
            log.info("Finished scheduled job: {}. Time taken: {}s.", jobFullName, sw.getTotalTimeSeconds());
    } catch (JobExecutionException e) {
        if (log.isErrorEnabled())
            log.error("Error executing scheduled job: " + jobFullName, e);
        throw e;
    } finally {
        // restore the original thread context class loader
        Thread.currentThread().setContextClassLoader(origContextClassLoader);
    }
}

From source file:com.quartzdesk.test.quartz.v1.AbstractJob.java

/**
 * The method invoked by the Spring scheduler. This method simply delegates the
 * execution to the {@link #executeJob(JobExecutionContext)} method.
 *
 * @param context a {@link JobExecutionContext} instance.
 * @throws JobExecutionException if an error occurs while executing the
 * job./*w  w  w.j  a  v a2s.c  o  m*/
 */
@SuppressWarnings("unchecked")
@Override
public final void execute(JobExecutionContext context) throws JobExecutionException {
    String jobFullName = context.getJobDetail().getFullName();
    String triggerFullName = context.getTrigger().getFullName();

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

    ClassLoader origContextClassLoader = Thread.currentThread().getContextClassLoader();

    try {
        if (log.isInfoEnabled())
            log.info("Started scheduled job: {}, fired by trigger: {}", jobFullName, triggerFullName);

        if (log.isDebugEnabled()) {
            StringBuilder jobDataMapDump = new StringBuilder();

            // map that contains merged job data from the job detail data map and trigger data map
            JobDataMap jobDataMap = context.getMergedJobDataMap();
            for (Iterator<String> keys = (Iterator<String>) jobDataMap.keySet().iterator(); keys.hasNext();) {
                String key = keys.next();
                String value = CommonUtils.safeToString(jobDataMap.get(key));

                jobDataMapDump.append(key).append('=').append(value);

                if (keys.hasNext())
                    jobDataMapDump.append(CommonConst.NL);
            }

            log.debug("Job data map dump:{}{}", CommonConst.NL, jobDataMapDump.toString());
        }

        // Set the context class loader to be the class loader of the job class.
        // This is a workaround/fix for a problem with setting the thread's context
        // class loader through Quartz properties when WebSphere work manager threads
        // are used.
        Thread.currentThread().setContextClassLoader(getClass().getClassLoader());

        executeJob(context);

        sw.stop();

        if (log.isInfoEnabled())
            log.info("Finished scheduled job: {}. Time taken: {}s.", jobFullName, sw.getTotalTimeSeconds());
    } catch (JobExecutionException e) {
        if (log.isErrorEnabled())
            log.error("Error executing scheduled job: " + jobFullName, e);
        throw e;
    } finally {
        // restore the original thread context class loader
        Thread.currentThread().setContextClassLoader(origContextClassLoader);
    }
}

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

/**
 * Swagger Springfox configuration./*  ww  w . j a  va 2 s .c om*/
 *
 * @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:edu.isistan.carcha.lsa.TraceabilityComparator.java

/**
 * Run./*from  w  ww.  j  av a2 s  .co m*/
 *
 * @param builder the Vector builder to construct vector using the sspace
 * @param reqConcerns the requirement concerns
 * @param archConcerns the architectural concerns
 */
@SuppressWarnings("unused")
private void run(DocumentVectorBuilder builder, List<String> reqConcerns, List<String> archConcerns) {
    StopWatch sw = new StopWatch();
    sw.start("Start the traceability comparation");
    init();
    int i = 0;
    int count = reqConcerns.size();
    this.untracedCount = 0;
    for (String lineForVector1 : reqConcerns) {
        Entity req = Entity.buildFromString(lineForVector1, NodeType.CC);
        addNode(req);
        //create vector 1
        DoubleVector vector1 = new CompactSparseVector();
        vector1 = builder.buildVector(new BufferedReader(new StringReader(req.getFormattedLabel())), vector1);
        boolean hasTrace = false;
        for (String lineForVector2 : archConcerns) {
            Entity arch = Entity.buildFromString(lineForVector2, NodeType.DD);
            addNode(arch);
            //create vector 2
            DoubleVector vector2 = new CompactSparseVector();
            vector2 = builder.buildVector(new BufferedReader(new StringReader(arch.getFormattedLabel())),
                    vector2);

            //Math round is WAY faster than DoubleFormat
            Double linkWeight = ((double) Math.round(Similarity.cosineSimilarity(vector1, vector2) * 1000)
                    / 1000);

            //add the edge between the two nodes including the calculated weight
            if (linkWeight > threshold) {
                addEdge(req, arch, linkWeight);
                hasTrace = true;
            }
        }
        if (!hasTrace) {
            this.untracedCount++;
        }
    }
    sw.stop();
    logger.info(sw.shortSummary());
    String filename = saveGraph();
}

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

/**
 * Swagger Springfox configuration./*w w  w.j ava 2s .com*/
 *
 * @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  w  w  w.j  a va 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.");
    }
}