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.springframework.integration.monitor.DirectChannelMetrics.java

private Object monitorSend(MethodInvocation invocation, MessageChannel channel, Message<?> message)
        throws Throwable {
    if (logger.isTraceEnabled()) {
        logger.trace("Recording send on channel(" + channel + ") : message(" + message + ")");
    }/*from  ww w .j a va2s.c  o m*/
    final StopWatch timer = new StopWatch(channel + ".send:execution");
    try {
        timer.start();

        sendCount.incrementAndGet();
        sendRate.increment();

        Object result = invocation.proceed();

        timer.stop();
        if ((Boolean) result) {
            sendSuccessRatio.success();
            sendDuration.append(timer.getTotalTimeMillis());
        } else {
            sendSuccessRatio.failure();
            sendErrorCount.incrementAndGet();
            sendErrorRate.increment();
        }
        return result;
    } catch (Throwable e) {
        sendSuccessRatio.failure();
        sendErrorCount.incrementAndGet();
        sendErrorRate.increment();
        throw e;
    } finally {
        if (logger.isTraceEnabled()) {
            logger.trace(timer);
        }
    }
}

From source file:org.springframework.integration.monitor.DirectChannelMonitor.java

private Object monitorSend(MethodInvocation invocation, MessageChannel channel, Message<?> message)
        throws Throwable {

    if (logger.isTraceEnabled()) {
        logger.trace("Recording send on channel(" + channel + ") : message(" + message + ")");
    }//from ww  w  . ja va2  s .  c o  m

    final StopWatch timer = new StopWatch(channel + ".send:execution");

    try {
        timer.start();

        sendCount.incrementAndGet();
        sendRate.increment();

        Object result = invocation.proceed();

        timer.stop();
        if ((Boolean) result) {
            sendSuccessRatio.success();
            sendDuration.append(timer.getTotalTimeSeconds());
        } else {
            sendSuccessRatio.failure();
            sendErrorCount.incrementAndGet();
            sendErrorRate.increment();
        }
        return result;

    } catch (Throwable e) {
        sendSuccessRatio.failure();
        sendErrorCount.incrementAndGet();
        sendErrorRate.increment();
        throw e;
    } finally {
        if (logger.isTraceEnabled()) {
            logger.trace(timer);
        }
    }
}

From source file:org.springframework.integration.monitor.SimpleMessageHandlerMetrics.java

private void handleMessage(MethodInvocation invocation, Message<?> message) throws Throwable {
    if (logger.isTraceEnabled()) {
        logger.trace("messageHandler(" + this.handler + ") message(" + message + ") :");
    }/* ww  w. ja va2s  .c o m*/
    String name = this.name;
    if (name == null) {
        name = this.handler.toString();
    }
    StopWatch timer = new StopWatch(name + ".handle:execution");
    try {
        timer.start();
        this.handleCount.incrementAndGet();
        this.activeCount.incrementAndGet();

        invocation.proceed();

        timer.stop();
        this.duration.append(timer.getTotalTimeMillis());
    } catch (Throwable e) {
        this.errorCount.incrementAndGet();
        throw e;
    } finally {
        this.activeCount.decrementAndGet();
    }
}

From source file:org.springframework.integration.monitor.SimpleMessageHandlerMonitor.java

public void handleMessage(Message<?> message)
        throws MessageRejectedException, MessageHandlingException, MessageDeliveryException {
    if (logger.isTraceEnabled()) {
        logger.trace("messageHandler(" + handler + ") message(" + message + ") :");
    }//from w  w  w .j a v  a  2 s .c  o  m

    String name = this.name;
    if (name == null) {
        name = handler.toString();
    }
    StopWatch timer = new StopWatch(name + ".handle:execution");

    try {
        timer.start();
        handleCount.incrementAndGet();

        handler.handleMessage(message);

        timer.stop();
        duration.append(timer.getTotalTimeSeconds());
    } catch (RuntimeException e) {
        errorCount.incrementAndGet();
        throw e;
    } catch (Error e) {
        errorCount.incrementAndGet();
        throw e;
    }
}

From source file:org.springframework.integration.support.management.ExponentialMovingAverageRateTests.java

@Test
@Ignore // tolerance needed is too dependent on hardware
public void testRate() {
    ExponentialMovingAverageRate rate = new ExponentialMovingAverageRate(1, 60, 10);
    int count = 1000000;
    StopWatch watch = new StopWatch();
    watch.start();/*from ww  w. j  a va  2 s .com*/
    for (int i = 0; i < count; i++) {
        rate.increment();
    }
    watch.stop();
    double calculatedRate = count / (double) watch.getTotalTimeMillis() * 1000;
    assertEquals(calculatedRate, rate.getMean(), 4000000);
}

From source file:org.springframework.samples.portfolio.web.load.StompWebSocketLoadTestClient.java

public static void main(String[] args) throws Exception {

    // Modify host and port below to match wherever StompWebSocketServer.java is running!!
    // When StompWebSocketServer starts it prints the selected available

    String host = "localhost";
    if (args.length > 0) {
        host = args[0];/*from   www .jav a2s .  co  m*/
    }

    int port = 37232;
    if (args.length > 1) {
        port = Integer.valueOf(args[1]);
    }

    String homeUrl = "http://{host}:{port}/home";
    logger.debug("Sending warm-up HTTP request to " + homeUrl);
    HttpStatus status = new RestTemplate().getForEntity(homeUrl, Void.class, host, port).getStatusCode();
    Assert.state(status == HttpStatus.OK);

    final CountDownLatch connectLatch = new CountDownLatch(NUMBER_OF_USERS);
    final CountDownLatch subscribeLatch = new CountDownLatch(NUMBER_OF_USERS);
    final CountDownLatch messageLatch = new CountDownLatch(NUMBER_OF_USERS);
    final CountDownLatch disconnectLatch = new CountDownLatch(NUMBER_OF_USERS);

    final AtomicReference<Throwable> failure = new AtomicReference<>();

    StandardWebSocketClient webSocketClient = new StandardWebSocketClient();

    HttpClient jettyHttpClient = new HttpClient();
    jettyHttpClient.setMaxConnectionsPerDestination(1000);
    jettyHttpClient.setExecutor(new QueuedThreadPool(1000));
    jettyHttpClient.start();

    List<Transport> transports = new ArrayList<>();
    transports.add(new WebSocketTransport(webSocketClient));
    transports.add(new JettyXhrTransport(jettyHttpClient));

    SockJsClient sockJsClient = new SockJsClient(transports);

    try {
        ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
        taskScheduler.afterPropertiesSet();

        String stompUrl = "ws://{host}:{port}/stomp";
        WebSocketStompClient stompClient = new WebSocketStompClient(sockJsClient);
        stompClient.setMessageConverter(new StringMessageConverter());
        stompClient.setTaskScheduler(taskScheduler);
        stompClient.setDefaultHeartbeat(new long[] { 0, 0 });

        logger.debug("Connecting and subscribing " + NUMBER_OF_USERS + " users ");
        StopWatch stopWatch = new StopWatch("STOMP Broker Relay WebSocket Load Tests");
        stopWatch.start();

        List<ConsumerStompSessionHandler> consumers = new ArrayList<>();
        for (int i = 0; i < NUMBER_OF_USERS; i++) {
            consumers.add(new ConsumerStompSessionHandler(BROADCAST_MESSAGE_COUNT, connectLatch, subscribeLatch,
                    messageLatch, disconnectLatch, failure));
            stompClient.connect(stompUrl, consumers.get(i), host, port);
        }

        if (failure.get() != null) {
            throw new AssertionError("Test failed", failure.get());
        }
        if (!connectLatch.await(5000, TimeUnit.MILLISECONDS)) {
            fail("Not all users connected, remaining: " + connectLatch.getCount());
        }
        if (!subscribeLatch.await(5000, TimeUnit.MILLISECONDS)) {
            fail("Not all users subscribed, remaining: " + subscribeLatch.getCount());
        }

        stopWatch.stop();
        logger.debug("Finished: " + stopWatch.getLastTaskTimeMillis() + " millis");

        logger.debug("Broadcasting " + BROADCAST_MESSAGE_COUNT + " messages to " + NUMBER_OF_USERS + " users ");
        stopWatch.start();

        ProducerStompSessionHandler producer = new ProducerStompSessionHandler(BROADCAST_MESSAGE_COUNT,
                failure);
        stompClient.connect(stompUrl, producer, host, port);
        stompClient.setTaskScheduler(taskScheduler);

        if (failure.get() != null) {
            throw new AssertionError("Test failed", failure.get());
        }
        if (!messageLatch.await(60 * 1000, TimeUnit.MILLISECONDS)) {
            for (ConsumerStompSessionHandler consumer : consumers) {
                if (consumer.messageCount.get() < consumer.expectedMessageCount) {
                    logger.debug(consumer);
                }
            }
        }
        if (!messageLatch.await(60 * 1000, TimeUnit.MILLISECONDS)) {
            fail("Not all handlers received every message, remaining: " + messageLatch.getCount());
        }

        producer.session.disconnect();
        if (!disconnectLatch.await(5000, TimeUnit.MILLISECONDS)) {
            fail("Not all disconnects completed, remaining: " + disconnectLatch.getCount());
        }

        stopWatch.stop();
        logger.debug("Finished: " + stopWatch.getLastTaskTimeMillis() + " millis");

        System.out.println("\nPress any key to exit...");
        System.in.read();
    } catch (Throwable t) {
        t.printStackTrace();
    } finally {
        jettyHttpClient.stop();
    }

    logger.debug("Exiting");
    System.exit(0);
}

From source file:org.springframework.statemachine.recipes.support.RunnableAction.java

@Override
public final void execute(StateContext<String, String> context) {
    if (!shouldExecute(id, context)) {
        return;/* w ww .j a v  a2s  . com*/
    }
    StopWatch watch = new StopWatch();
    String logId = (id == null ? "" : (" id=" + id));
    log.info("Executing runnable" + logId);
    if (log.isDebugEnabled()) {
        watch.start();
    }
    try {
        onPreExecute(id, context);
        runnable.run();
        onSuccess(id, context);
    } catch (Exception e) {
        onError(id, context, e);
    } finally {
        onPostExecute(id, context);
    }
    if (log.isDebugEnabled()) {
        watch.stop();
        log.debug("Runnable execution took " + watch.getTotalTimeMillis() + " ms" + logId);
    }
}

From source file:org.springframework.xd.dirt.integration.bus.MessageBusSupportBenchmarkTests.java

@Test
public void run() {
    StopWatch watch = new StopWatch("MessageBusSupport");
    watch.start("simple tuple codec");
    runBenchmark(TupleBuilder.tuple().of("foo", "bar", "val", 1234));
    watch.stop();
    watch.start("string payload");
    runBenchmark(StringUtils.leftPad("hello", 1000, "*"));
    watch.stop();// w  ww  .jav a2 s.  c  om
    System.out.println(watch.prettyPrint());
}

From source file:ro.cs.cm.ws.client.om.OMWebServiceClient.java

public GetUserAuthBySecurityTokenResponse getUserAuthBySecurityToken(String securityToken)
        throws XmlMappingException, IOException, WSClientException {
    logger.debug("getUserAuthBySecurityToken START");
    StopWatch sw = new StopWatch();
    sw.start("getUserAuthBySecurityToken");
    GetUserAuthBySecurityTokenResponse getUserAuthBySecurityTokenResponse = null;
    try {//from  w  w  w. j  a  v a2  s .c om
        GetUserAuthBySecurityTokenRequest getUserBySecurityTokenRequest = new GetUserAuthBySecurityTokenRequest();

        getUserBySecurityTokenRequest.setSecurityToken(securityToken);
        getUserBySecurityTokenRequest.setModule(IConstant.MODULE_ID);
        //unmarshall the response to an OrganisationSimple bean
        getUserAuthBySecurityTokenResponse = (GetUserAuthBySecurityTokenResponse) getWebServiceTemplate()
                .marshalSendAndReceive(getUserBySecurityTokenRequest);
        logger.debug(getUserAuthBySecurityTokenResponse.getUserAuth());
    } catch (SoapFaultClientException soapFault) {
        SoapFaultDetail soapFaultDetail = soapFault.getSoapFault().getFaultDetail();
        //if the soap fault detail field is empty, it means another type of exception than EndpointException has been thrown
        if (soapFaultDetail == null) {
            throw new WSClientException(soapFault.getFaultCode().toString(), soapFault.getFaultStringOrReason(),
                    soapFault);
            //soap fault detail field not empty means the Web Service has thrown an EndpointException
        } else {
            SoapFaultDetailElement soapFaultDetailElement = (SoapFaultDetailElement) soapFaultDetail
                    .getDetailEntries().next();
            //unmarshall the soap fault detail element to a WS specific bean named dmeEndpointExceptionBean
            JAXBElement<OMEndpointExceptionBean> endpointException = (JAXBElement<OMEndpointExceptionBean>) getWebServiceTemplate()
                    .getUnmarshaller().unmarshal(soapFaultDetailElement.getSource());
            //throw a new WSClientException with the code and message of the DMEEndpointExceptionBean retrieved previously
            throw new WSClientException(endpointException.getValue().getCode(),
                    endpointException.getValue().getMessage(), soapFault);
        }
    }
    logger.debug("getUserAuthBySecurityToken END");
    sw.stop();
    logger.debug(sw.prettyPrint());
    return getUserAuthBySecurityTokenResponse;
}

From source file:ro.cs.cm.ws.client.om.OMWebServiceClient.java

public List<UserSimple> getUsersSimpleByOrganizationId(int organizationId, boolean isNotDeleted)
        throws XmlMappingException, IOException, WSClientException {
    logger.debug("getUsersSimpleByOrganizationId START");
    StopWatch sw = new StopWatch();
    sw.start("getUsersSimpleByOrganizationId");
    List<UserSimple> users = null;
    try {//  w w  w .jav  a  2s.  co  m
        //create the bean  marshalled into the request
        GetUsersSimpleRequest getUsersSimpleRequest = new GetUsersSimpleRequest();
        getUsersSimpleRequest.setOrganizationId(organizationId);
        getUsersSimpleRequest.setNotDeleted(isNotDeleted);
        //unmarshall the response to an OrganisationSimple bean
        users = ((GetUsersSimpleResponse) getWebServiceTemplate().marshalSendAndReceive(getUsersSimpleRequest))
                .getUsers();
    } catch (SoapFaultClientException soapFault) {
        SoapFaultDetail soapFaultDetail = soapFault.getSoapFault().getFaultDetail();
        //if the soap fault detail field is empty, it means another type of exception than EndpointException has been thrown
        if (soapFaultDetail == null) {
            throw new WSClientException(soapFault.getFaultCode().toString(), soapFault.getFaultStringOrReason(),
                    soapFault);
            //soap fault detail field not empty means the Web Service has thrown an EndpointException
        } else {
            SoapFaultDetailElement soapFaultDetailElement = (SoapFaultDetailElement) soapFaultDetail
                    .getDetailEntries().next();
            //unmarshall the soap fault detail element to a WS specific bean named dmeEndpointExceptionBean
            JAXBElement<OMEndpointExceptionBean> endpointException = (JAXBElement<OMEndpointExceptionBean>) getWebServiceTemplate()
                    .getUnmarshaller().unmarshal(soapFaultDetailElement.getSource());
            //throw a new WSClientException with the code and message of the DMEEndpointExceptionBean retrieved previously
            throw new WSClientException(endpointException.getValue().getCode(),
                    endpointException.getValue().getMessage(), soapFault);
        }
    }
    logger.debug("getUsersSimpleByOrganizationId END");
    sw.stop();
    logger.debug(sw.prettyPrint());
    return users;
}