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:com.persistent.cloudninja.scheduler.TenantBlobSizeProcessor.java

/** 
 * Calculates the blob sizes of private and public container.
 * // ww w  . j av a 2  s.  co  m
 */
@Override
public boolean execute() {
    boolean retVal = true;
    String tenantId = null;
    long blobSize = 0;
    try {
        LOGGER.debug("In Processor");
        TenantBlobSizeQueue queue = (TenantBlobSizeQueue) getWorkQueue();
        tenantId = queue.dequeue(SchedulerSettings.MessageVisibilityTimeout);
        if (tenantId == null) {
            retVal = false;
            LOGGER.debug("Processor : msg is null");
        } else {
            StopWatch watch = new StopWatch();
            watch.start();
            //get the size of blobs in private container.
            blobSize = storageUtility.getContainerSize("tntp-" + tenantId.toLowerCase());
            //get the size of blobs in public container.
            blobSize = blobSize + storageUtility.getContainerSize("tnts-" + tenantId.toLowerCase());
            LOGGER.debug("Processor : msg is " + tenantId);
            MeteringEntity metering = new MeteringEntity();
            metering.setTenantId(tenantId);

            Calendar calendar = Calendar.getInstance();
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S z");
            dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
            String date = dateFormat.format(calendar.getTime());
            metering.setSnapshotTime(dateFormat.parse(date));
            //set the calculated size
            blobSize = blobSize / 1024;
            metering.setBlobStoreUsage(blobSize);
            meteringDao.add(metering);
            LOGGER.info("Processor : blobSize is " + blobSize);
            watch.stop();
            taskCompletionDao.updateTaskCompletionDetails(watch.getTotalTimeSeconds(),
                    "ProcessMeteringBlobSizes", "Measured " + blobSize + " kb for tenant " + tenantId);
        }
    } catch (Exception e) {
        retVal = false;
        LOGGER.error(e.getMessage(), e);
    }
    return retVal;
}

From source file:my.adam.smo.client.Client.java

public BlockingRpcChannel blockingConnect(final InetSocketAddress sa) {
    return new BlockingRpcChannel() {
        private int countDownCallTimesToRelease = 1;
        private RpcChannel rpc = connect(sa);

        @Override//from w  w  w  . j a  v a  2 s . co  m
        public Message callBlockingMethod(Descriptors.MethodDescriptor method, RpcController controller,
                Message request, Message responsePrototype) throws ServiceException {
            StopWatch stopWatch = new StopWatch("callBlockingMethod");
            stopWatch.start();

            final CountDownLatch callbackLatch = new CountDownLatch(countDownCallTimesToRelease);

            final AtomicReference<Message> result = new AtomicReference<Message>();

            RpcCallback<Message> done = new RpcCallback<Message>() {
                @Override
                public void run(Message parameter) {
                    result.set(parameter);
                    callbackLatch.countDown();
                }
            };

            rpc.callMethod(method, controller, request, responsePrototype, done);
            try {
                boolean succeededBeforeTimeout = callbackLatch.await(blocking_method_call_timeout,
                        TimeUnit.SECONDS);
                if (!succeededBeforeTimeout) {
                    throw new ServiceException(
                            "blocking method timeout reached for method:" + method.getFullName());
                }
            } catch (InterruptedException e) {
                getLogger().error("call failed", e);
                stopWatch.stop();
            }

            stopWatch.stop();
            getLogger().trace(stopWatch.shortSummary());

            return result.get();
        }
    };
}

From source file:org.jason.mapmaker.repository.impl.HibernateGenericRepository.java

public void saveList(List<T> objectList) {

    StopWatch stopWatch = new StopWatch();
    stopWatch.start();/*from w w w.  ja v a  2 s  .  com*/
    /*        for (T obj: objectList) {
    try {
        sessionFactory.getCurrentSession().save(obj);
    } catch (DataIntegrityViolationException ex) {
        // okay, so CVE extends RuntimeException, and you aren't supposed to catch RuntimeExceptions. Do
        // I want to roll back an entire save operation just because the USGS screwed up one particular
        // id number???
        System.out.println("Caught DataIntegrityViolationException");
    }
            }*/

    Session session = sessionFactory.openSession();
    Transaction tx = session.beginTransaction();
    int i = 1;
    for (T obj : objectList) {

        session.save(obj);
        //sessionFactory.getCurrentSession().save(obj);
        i++;
        if (i % 100 == 0) {
            session.flush();
            session.clear();
            //sessionFactory.getCurrentSession().flush();
        }
    }

    tx.commit();
    session.close();

    stopWatch.stop();
    log.debug("Persisted " + i + " objects in " + stopWatch.getTotalTimeSeconds() + " seconds");

    //        Session session = sessionFactory.getCurrentSession();
    //        Transaction tx = session.beginTransaction();
    //        int i = 1;
    //        for (T obj : objectList) {
    //
    //            session.save(obj);
    //            //sessionFactory.getCurrentSession().save(obj);
    //            i++;
    //            if (i % 100 == 0) {
    //                session.flush();
    //                session.clear();
    //                //sessionFactory.getCurrentSession().flush();
    //            }
    //        }
    //        if (!tx.wasCommitted()) {
    //            tx.commit();
    //        }
    //sessionFactory.getCurrentSession().getTransaction().commit();
}

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

/**
 * {@inheritDoc}/*from   w w  w .  j ava  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.jeanmile.config.apidoc.SwaggerConfiguration.java

/**
 * Swagger Springfox configuration./*from ww w .  j av a 2s. c o m*/
 */
@Bean
public Docket swaggerSpringfoxDocket(JHipsterProperties jHipsterProperties) {
    log.debug("Starting Swagger");
    StopWatch watch = new StopWatch();
    watch.start();
    ApiInfo apiInfo = new ApiInfo(jHipsterProperties.getSwagger().getTitle(),
            jHipsterProperties.getSwagger().getDescription(), jHipsterProperties.getSwagger().getVersion(),
            jHipsterProperties.getSwagger().getTermsOfServiceUrl(),
            jHipsterProperties.getSwagger().getContact(), jHipsterProperties.getSwagger().getLicense(),
            jHipsterProperties.getSwagger().getLicenseUrl());

    Docket docket = new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo)
            .genericModelSubstitutes(ResponseEntity.class).forCodeGeneration(true)
            .genericModelSubstitutes(ResponseEntity.class)
            .directModelSubstitute(org.joda.time.LocalDate.class, String.class)
            .directModelSubstitute(org.joda.time.LocalDateTime.class, Date.class)
            .directModelSubstitute(org.joda.time.DateTime.class, Date.class)
            .directModelSubstitute(java.time.LocalDate.class, String.class)
            .directModelSubstitute(java.time.ZonedDateTime.class, Date.class)
            .directModelSubstitute(java.time.LocalDateTime.class, Date.class).select()
            .paths(regex(DEFAULT_INCLUDE_PATTERN)).build();
    watch.stop();
    log.debug("Started Swagger in {} ms", watch.getTotalTimeMillis());
    return docket;
}

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

/**
 * Swagger Springfox configuration.// w w  w. j  a  v  a  2  s  .  c o 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();//from   w  w  w  .j  ava 2  s  . c  o  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:edu.isistan.carcha.lsa.LSARunner.java

/**
 * Discover traceability.// w ww. jav a  2s.c  om
 *
 * @param sspaceFile the sspace file
 * @return the traceability document
 * @throws IOException Signals that an I/O exception has occurred.
 */
private TraceabilityDocument discoverTraceability(File sspaceFile) throws IOException {

    TraceabilityDocument ret = new TraceabilityDocument(concerns, designDecision);
    List<TraceabilityLink> links = new ArrayList<TraceabilityLink>();

    StaticSemanticSpace sspace = new StaticSemanticSpace(sspaceFile);

    //build the document vector to compare sentences
    DocumentVectorBuilder builder = new DocumentVectorBuilder(sspace);

    StopWatch sw = new StopWatch();
    sw.start("LSA - Traceability discovery");

    int untracedCount = 0;
    for (Entity req : concerns) {
        //create vector1
        DoubleVector vector1 = builder.buildVector(
                new BufferedReader(new StringReader(req.getFormattedLabel())), new CompactSparseVector());

        boolean hasTrace = false;
        for (Entity arch : designDecision) {
            //create vector2
            DoubleVector vector2 = builder.buildVector(
                    new BufferedReader(new StringReader(arch.getFormattedLabel())), new CompactSparseVector());

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

            //add the edge between the two nodes including the calculated weight
            if (linkWeight > threshold) {
                links.add(new TraceabilityLink(req, arch, linkWeight));
                hasTrace = true;
            }
        }
        if (!hasTrace) {
            untracedCount++;
        }
    }
    sw.stop();
    logger.info(sw.prettyPrint());

    //save the traceability results like: untraced count, links, traced count, etc...
    ret.setLinks(links);
    ret.setUntracedConcernCount(untracedCount);
    ret.setTracedConcernCount(concerns.size() - untracedCount);
    return ret;
}

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

/**
 * Returns a BinaryMeta object or throws ItemNotFoundException if not found.
 * /*from  w  w  w. ja  va2s  . com*/
 * @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:ru.anr.cmdline.base.BootstrapImpl.java

/**
 * {@inheritDoc}/*from  ww w .  j  a  va  2 s  .c  om*/
 */
@Override
@Transactional(propagation = Propagation.REQUIRED)
public ExitShellRequest run() {

    StopWatch sw = new StopWatch("Shell Watch");
    sw.start();

    String[] commandsToExecuteAndThenQuit = commandLine.getShellCommandsToExecute();
    // The shell is used
    JLineShellComponent shell = context.getBean("shell", JLineShellComponent.class);
    ExitShellRequest exitShellRequest;

    if (null == commandsToExecuteAndThenQuit) {
        shell.start();
        shell.promptLoop();
        exitShellRequest = shell.getExitShellRequest();
        if (exitShellRequest == null) {
            // shouldn't really happen, but we'll fallback to this anyway
            exitShellRequest = ExitShellRequest.NORMAL_EXIT;
        }
        shell.waitForComplete();

    } else {
        boolean successful = false;
        exitShellRequest = ExitShellRequest.FATAL_EXIT;

        for (String cmd : commandsToExecuteAndThenQuit) {
            successful = shell.executeCommand(cmd).isSuccess();
            if (!successful) {
                break;
            }
        }

        // if all commands were successful, set the normal exit status
        if (successful) {
            exitShellRequest = ExitShellRequest.NORMAL_EXIT;
        }

    }

    sw.stop();

    if (shell.isDevelopmentMode()) {
        logger.info("Total execution time: {} ms", sw.getLastTaskTimeMillis());
    }
    return exitShellRequest;
}