List of usage examples for org.springframework.util StopWatch StopWatch
public StopWatch(String id)
From source file:com.emc.smartcomm.UregApplication.java
/** * @param register A SmartRegister instance *//*ww w . j av a 2 s . c o m*/ public void uregApplication(SmartRegister register) { logger.info("Processing UREG Tranasctional Flow:"); GrsiRequest greq = PopulateData.setGrsiRequest(); GrsiResponse grsiResponse = PopulateData.setGrsiResponse(); BabProtocolRequest breq = PopulateData.setBabRequest(); BabProtocolResponse bres = PopulateData.setBabResponse(); ValidateRegRequest vreg = PopulateData.setValidateRegRequest(); ValidateRegResponse vres = PopulateData.setValidateRegResponse(); greq.setSvcFlag(register.getChannel()); String msg = register.toString(); String path = "/appl/LogTransaction.txt"; Timestamp txStartTime = PrepareLog.getCurrentTimeStamp(); StopWatch sw = new StopWatch("UREG Transaction"); sw.start("UREG Transaction"); logger.debug("UREG Transaction Initiated:{}", txStartTime); StopWatch sw0 = new StopWatch("UREG REQUEST"); sw0.start("UREG REQUEST"); uregTemplate.convertAndSend(msg); sw0.stop(); logger.debug(sw0.prettyPrint()); logger.debug(sw0.shortSummary()); StopWatch sw1 = new StopWatch("GRSI Request"); sw1.start("GRSI Request"); grsiTemplate.convertAndSend(greq); sw1.stop(); logger.debug(sw1.prettyPrint()); logger.debug(sw1.shortSummary()); if ("PVS".equals(grsiResponse.getsx12())) // || "BAB".equals(grsiResponse.getsx13())) { StopWatch sw2 = new StopWatch("Validate Request:"); sw2.start("Validate Request:"); String validateRegText = vreg.toString(); validateRegTemplate.convertAndSend(validateRegText); sw2.stop(); logger.debug(sw2.prettyPrint()); logger.debug(sw2.shortSummary()); } if ("PPC".equals(grsiResponse.getsx03())) { StopWatch sw3 = new StopWatch("BAB Request"); sw3.start("BAB Request:"); babTemplate.convertAndSend("bab.Request", breq.toString()); sw3.stop(); logger.debug(sw3.prettyPrint()); logger.debug(sw3.shortSummary()); } grsiResponse.setsx03("NSN"); if ("NSN".equals(grsiResponse.getsx03())) { InputStream is = getClass().getResourceAsStream("/mock/SOAPProtocolRecharge.txt"); String message = FileReader.readFile(is); StopWatch sw4 = new StopWatch("SOAP Recharge Request: "); sw4.start("SOAP Recharge Request:"); soapRechargeTemplate.convertAndSend(message); sw4.stop(); logger.debug(sw4.prettyPrint()); logger.debug(sw4.shortSummary()); } Timestamp txEndTime = PrepareLog.getCurrentTimeStamp(); logger.debug("Persisting Transaction log in gemxd and oracle"); LogTransaction logTransaction = PrepareLog.prepareLog(greq, grsiResponse, breq, bres, vreg, vres); logTransaction.setTxnStartTime(txStartTime); logTransaction.setTxnEndTime(txEndTime); StopWatch sw5 = new StopWatch("Transaction Persistence: "); sw5.start("Transaction Persistence:"); logTransactionService.logTransaction(logTransaction); sw5.stop(); logger.debug(sw5.prettyPrint()); logger.debug(sw5.shortSummary()); ExternalFileWriter.writeToFile(path, PopulateData.populateLog()); sw.stop(); logger.debug(sw.prettyPrint()); logger.debug(sw.shortSummary()); logger.debug("UREG Transaction is Completed:{}", txEndTime); logger.info("UREG Transaction TimeSpan:{}", (txEndTime.getTime() - txStartTime.getTime())); }
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 ww w.j a v a 2 s. c o 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:fr.acxio.tools.agia.alfresco.configuration.SimpleNodeFactoryTest.java
@Test public void testGetNodes() throws Exception { FolderDefinition aDefaultNodeDefinition = NodeFactoryUtils.createFolderDefinition("test", null, null, null); // FieldSet aData = new DefaultFieldSet(new String[]{"A", "B", "C"}, new String[]{"A", "B", "C"}); StopWatch aStopWatch = new StopWatch("testGetNodes"); aStopWatch.start("Create a node list"); SimpleNodeFactory aNodeFactory = new SimpleNodeFactory(); aNodeFactory.setNamespaceContext(namespaceContext); aNodeFactory.setNodeDefinition(aDefaultNodeDefinition); NodeList aNodeList = aNodeFactory.getNodes(evaluationContext); aStopWatch.stop();//from w w w.ja va2 s. c o m assertNotNull(aNodeList); assertEquals(1, aNodeList.size()); assertTrue(aNodeList.get(0) instanceof Folder); Folder aFolder = (Folder) aNodeList.get(0); assertEquals("test", aFolder.getName()); assertNotNull(aFolder.getAspects()); assertEquals(0, aFolder.getAspects().size()); assertNotNull(aFolder.getAssociations()); assertEquals(0, aFolder.getAssociations().size()); assertNotNull(aFolder.getFolders()); assertEquals(0, aFolder.getFolders().size()); assertNotNull(aFolder.getDocuments()); assertEquals(0, aFolder.getDocuments().size()); assertNull(aFolder.getParent()); assertEquals("/cm:test", aFolder.getPath()); assertNotNull(aFolder.getType()); assertEquals("{http://www.alfresco.org/model/content/1.0}folder", aFolder.getType().toString()); System.out.println(aStopWatch.prettyPrint()); }
From source file:rk.java.compute.cep.ComputeService.java
public ComputeService(BlockingQueue<IPriceTick> queue, final int numberOfTickSources, IPriceEventSink eventbus) {/*from w w w. j av a 2 s . c o m*/ this.feedQueue = queue; this.numberOfTickSources = numberOfTickSources; this.eventbus = eventbus; this.handlerCache = new ConcurrentHashMap<String, Compute>(); this.stopWatch = new StopWatch("Dispatcher Task"); executorService = Executors.newCachedThreadPool(); ecs = new ExecutorCompletionService<StopWatch>(executorService); dispatchTaskFuture = ecs.submit(new Callable<StopWatch>() { @Override public StopWatch call() throws Exception { stopWatch.start(); run(); stopWatch.stop(); return stopWatch; } }); }
From source file:my.adam.smo.server.SocketServer.java
@Inject public SocketServer(@Value("${server_worker_threads:10}") int workerCount) { bootstrap.setFactory(new NioServerSocketChannelFactory(Executors.newCachedThreadPool(), Executors.newCachedThreadPool(), workerCount)); ChannelPipelineFactory pipelineFactory = new ChannelPipelineFactory() { @Override// w w w .j av a 2s . c o m public ChannelPipeline getPipeline() throws Exception { ChannelPipeline p = Channels.pipeline(); if (enableTrafficLogging) { InternalLoggerFactory.setDefaultFactory(new Slf4JLoggerFactory()); p.addLast("logger", new LoggingHandler(InternalLogLevel.DEBUG)); } p.addLast("frameEncoder", new LengthFieldPrepender(4));//DownstreamHandler p.addLast("protobufEncoder", new ProtobufEncoder());//DownstreamHandler p.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(MAX_FRAME_BYTES_LENGTH, 0, 4, 0, 4));//UpstreamHandler p.addLast("protobufDecoder", new ProtobufDecoder(RPCommunication.Request.getDefaultInstance()));//UpstreamHandler p.addLast("handler", new SimpleChannelUpstreamHandler() { @Override public void messageReceived(ChannelHandlerContext ctx, final MessageEvent e) throws Exception { StopWatch stopWatch = new StopWatch("messageReceived"); stopWatch.start(); RPCommunication.Request request = (RPCommunication.Request) e.getMessage(); logger.trace("received request:" + request.toString()); if (enableAsymmetricEncryption) { request = getAsymDecryptedRequest(request); logger.trace("asymmetric encryption enabled, decrypted request: " + request.toString()); } if (enableSymmetricEncryption) { request = getDecryptedRequest(request); logger.trace("symmetric encryption enabled, decrypted request: " + request.toString()); } final RPCommunication.Request protoRequest = request; RpcController dummyController = new DummyRpcController(); Service service = serviceMap.get(request.getServiceName()); logger.trace("got service: " + service + " for name " + request.getServiceName()); Descriptors.MethodDescriptor methodToCall = service.getDescriptorForType() .findMethodByName(request.getMethodName()); logger.trace("got method: " + methodToCall + " for name " + request.getMethodName()); Message methodArguments = service.getRequestPrototype(methodToCall).newBuilderForType() .mergeFrom(request.getMethodArgument()).build(); logger.trace("get method arguments from request " + methodArguments.toString()); RpcCallback<Message> callback = new RpcCallback<Message>() { @Override public void run(Message parameter) { RPCommunication.Response response = RPCommunication.Response.newBuilder() .setResponse(parameter.toByteString()) .setRequestId(protoRequest.getRequestId()).build(); //encryption if (enableSymmetricEncryption) { response = getEncryptedResponse(response); logger.trace("symmetric encryption enabled, encrypted response: " + response.toString()); } if (enableAsymmetricEncryption) { response = getAsymEncryptedResponse(response); logger.trace("asymmetric encryption enabled, encrypted response: " + response.toString()); } e.getChannel().write(response); logger.trace("finishing call, response sent"); } }; logger.trace("calling " + methodToCall.getFullName()); service.callMethod(methodToCall, dummyController, methodArguments, callback); stopWatch.stop(); logger.trace(stopWatch.shortSummary()); } @Override public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception { if (!standardExceptionHandling(ctx, e)) { super.exceptionCaught(ctx, e); } } }); return p; } }; bootstrap.setPipelineFactory(pipelineFactory); }
From source file:my.adam.smo.server.HTTPServer.java
@Inject public HTTPServer(@Value("${server_worker_threads:10}") int workerCount) { bootstrap.setFactory(new NioServerSocketChannelFactory(Executors.newCachedThreadPool(), Executors.newCachedThreadPool(), workerCount)); ChannelPipelineFactory pipelineFactory = new ChannelPipelineFactory() { @Override/*from w ww . jav a 2 s. com*/ public ChannelPipeline getPipeline() throws Exception { ChannelPipeline p = Channels.pipeline(); if (enableTrafficLogging) { InternalLoggerFactory.setDefaultFactory(new Slf4JLoggerFactory()); p.addLast("logger", new LoggingHandler(InternalLogLevel.DEBUG)); } p.addLast("codec", new HttpServerCodec()); p.addLast("chunkAggregator", new HttpChunkAggregator(MAX_CONTENT_LENGTH)); p.addLast("chunkedWriter", new ChunkedWriteHandler()); p.addLast("compressor", new HttpContentCompressor()); p.addLast("handler", new SimpleChannelUpstreamHandler() { @Override public void messageReceived(ChannelHandlerContext ctx, final MessageEvent e) throws Exception { StopWatch stopWatch = new StopWatch("messageReceived"); stopWatch.start(); final DefaultHttpRequest httpRequest = (DefaultHttpRequest) e.getMessage(); ChannelBuffer cb = Base64.decode(httpRequest.getContent(), Base64Dialect.STANDARD); RPCommunication.Request request = RPCommunication.Request .parseFrom(cb.copy(0, cb.readableBytes()).array()); logger.trace("received request:" + request.toString()); if (enableAsymmetricEncryption) { request = getAsymDecryptedRequest(request); logger.trace("asymmetric encryption enabled, decrypted request: " + request.toString()); } if (enableSymmetricEncryption) { request = getDecryptedRequest(request); logger.trace("symmetric encryption enabled, decrypted request: " + request.toString()); } final RPCommunication.Request protoRequest = request; RpcController dummyController = new DummyRpcController(); Service service = serviceMap.get(request.getServiceName()); logger.trace("got service: " + service + " for name " + request.getServiceName()); Descriptors.MethodDescriptor methodToCall = service.getDescriptorForType() .findMethodByName(request.getMethodName()); logger.trace("got method: " + methodToCall + " for name " + request.getMethodName()); Message methodArguments = service.getRequestPrototype(methodToCall).newBuilderForType() .mergeFrom(request.getMethodArgument()).build(); logger.trace("get method arguments from request " + methodArguments.toString()); RpcCallback<Message> callback = new RpcCallback<Message>() { @Override public void run(Message parameter) { HttpResponse httpResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); ByteArrayOutputStream paramOutputStream = new ByteArrayOutputStream(); CodedOutputStream paramCodedOutputStream = CodedOutputStream .newInstance(paramOutputStream); try { parameter.writeTo(paramCodedOutputStream); paramCodedOutputStream.flush(); } catch (IOException e1) { logger.error("failed to write to output stream"); } RPCommunication.Response response = RPCommunication.Response.newBuilder() .setResponse(ByteString.copyFrom(paramOutputStream.toByteArray())) .setRequestId(protoRequest.getRequestId()).build(); if (enableSymmetricEncryption) { response = getEncryptedResponse(response); logger.trace("symmetric encryption enabled, encrypted response: " + response.toString()); } if (enableAsymmetricEncryption) { response = getAsymEncryptedResponse(response); logger.trace("asymmetric encryption enabled, encrypted response: " + response.toString()); } ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); CodedOutputStream codedOutputStream = CodedOutputStream.newInstance(outputStream); try { response.writeTo(codedOutputStream); codedOutputStream.flush(); } catch (IOException e1) { logger.error("unable to write to output stream", e1); } byte[] arr = outputStream.toByteArray(); ChannelBuffer resp = Base64.encode(ChannelBuffers.copiedBuffer(arr), Base64Dialect.STANDARD); httpResponse.setContent(resp); httpResponse.addHeader(HttpHeaders.Names.CONTENT_LENGTH, resp.readableBytes()); httpResponse.addHeader(HttpHeaders.Names.CONTENT_TYPE, HttpHeaders.Values.APPLICATION_X_WWW_FORM_URLENCODED); e.getChannel().write(httpResponse); logger.trace("finishing call, httpResponse sent"); } }; logger.trace("calling " + methodToCall.getFullName()); service.callMethod(methodToCall, dummyController, methodArguments, callback); stopWatch.stop(); logger.trace(stopWatch.shortSummary()); } @Override public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception { if (!standardExceptionHandling(ctx, e)) { super.exceptionCaught(ctx, e); } } }); return p; } }; bootstrap.setPipelineFactory(pipelineFactory); }
From source file:org.sharetask.utility.log.PerformanceInterceptor.java
@SuppressWarnings("PMD.AvoidCatchingThrowable") @Override/*w ww . j a v a 2 s . co m*/ protected Object invokeUnderTrace(final MethodInvocation invocation, final Log logger) throws Throwable { final String name = invocation.getMethod().getDeclaringClass().getName() + "." + invocation.getMethod().getName(); final StopWatch stopWatch = new StopWatch(name); Object returnValue = null; try { stopWatch.start(name); returnValue = invocation.proceed(); return returnValue; } catch (final Throwable ex) { if (stopWatch.isRunning()) { stopWatch.stop(); } throw ex; } finally { if (stopWatch.isRunning()) { stopWatch.stop(); } writeToLog(logger, replacePlaceholders(exitMessage, invocation, returnValue, null, stopWatch.getTotalTimeMillis())); } }
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"); }/* ww w . j a va 2 s .com*/ 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.SimpleComponentFactory.java
/** * Get the component by the component uri and component template uri * /*from w w w . jav a 2 s . com*/ * @return the component * @throws ItemNotFoundException * if no item found * @throws NotAuthorizedException * if the user is not authorized to get the item * @throws NotAuthenticatedException */ @Override public Component getComponent(String componentUri, String componentTemplateUri, RequestContext context) throws ItemNotFoundException, NotAuthorizedException, NotAuthenticatedException { if (context == null && securityFilterPresent()) { throw new RuntimeException("use of getComponent is not allowed when a SecurityFilter is set"); } StopWatch stopWatch = null; if (logger.isDebugEnabled()) { logger.debug("Enter getComponent url: " + componentUri + " and componentTemplateUri: " + componentTemplateUri); stopWatch = new StopWatch("getComponent"); stopWatch.start(); } Component component = null; try { TCMURI tcmUri = new TCMURI(componentUri); ComponentMeta componentMeta = componentProvider.getComponentMeta(tcmUri.getItemId(), tcmUri.getPublicationId()); component = new SimpleComponentImpl(); component.setId(TridionUtils.createUri(componentMeta).toString()); component.setTitle(componentMeta.getTitle()); component.setNativeMetadata(componentMeta); PublicationImpl pub = new PublicationImpl(); pub.setId(String.valueOf(componentMeta.getPublicationId())); component.setPublication(pub); Schema schema = new SchemaImpl(); schema.setId(String.valueOf(componentMeta.getSchemaId())); component.setSchema(schema); if (componentTemplateUri != null) { TCMURI ctUri = new TCMURI(componentTemplateUri); component.setSource(componentProvider.getComponentXMLByTemplate(tcmUri.getItemId(), ctUri.getItemId(), tcmUri.getItemId())); } else { component.setSource(componentProvider.getComponentXML(tcmUri.getItemId(), tcmUri.getItemId())); } try { doFilters(component, context, BaseFilter.RunPhase.Both); } catch (FilterException e) { logger.error("Error in filter. ", e); throw new RuntimeException(e); } } catch (ParseException e) { logger.error("Not able to parse uri: " + componentUri, e); throw new RuntimeException(e); } catch (StorageException e) { logger.error("Not possible to get uri: " + componentUri, 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.SimplePageFactory.java
private Page findSimplePageByUrl(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"); }/*w w w . j a v a2s . c om*/ StopWatch stopWatch = null; if (logger.isDebugEnabled()) { logger.debug("Enter findSimplePageByUrl url: " + url + " and publicationId: " + publicationId); stopWatch = new StopWatch("findSimplePageByUrl"); stopWatch.start(); } PageMeta pageMeta = null; Page page = null; try { pageMeta = brokerPageProvider.getPageMetaByURL(url, publicationId); if (logger.isDebugEnabled()) { stopWatch.stop(); logger.debug("Got pageMeta in " + stopWatch.getTotalTimeMillis() + " ms"); stopWatch.start(); } page = (Page) getPageFromMeta(pageMeta); if (logger.isDebugEnabled()) { stopWatch.stop(); logger.debug("Got Page in " + stopWatch.getTotalTimeMillis() + " ms"); stopWatch.start(); } 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); } if (logger.isDebugEnabled()) { stopWatch.stop(); logger.debug("Ran filters in " + stopWatch.getTotalTimeMillis() + " ms"); stopWatch.start(); } } catch (StorageException e) { logger.error("Storage exception when searching for page: " + url, e); throw new RuntimeException(e); } if (logger.isDebugEnabled()) { stopWatch.stop(); logger.debug("Exit findSimplePageByUrl (" + stopWatch.getTotalTimeMillis() + " ms)"); } return page; }