List of usage examples for org.springframework.util StopWatch stop
public void stop() throws IllegalStateException
From source file:com.auditbucket.engine.service.MediationFacade.java
public Integer createHeaders(final Company company, final Fortress fortress, final List<MetaInputBean> inputBeans) throws DatagioException { fortress.setCompany(company);/* w w w . j a v a2 s .c om*/ Long id = DateTime.now().getMillis(); StopWatch watch = new StopWatch(); watch.start(); logger.info("Starting Batch [{}] - size [{}]", id, inputBeans.size()); boolean newMode = true; if (newMode) { // Tune to balance against concurrency and batch transaction insert efficiency. List<List<MetaInputBean>> splitList = Lists.partition(inputBeans, 20); for (List<MetaInputBean> metaInputBeans : splitList) { class DLCommand implements Command { Iterable<MetaInputBean> headers = null; DLCommand(List<MetaInputBean> processList) { this.headers = new CopyOnWriteArrayList<>(processList); } @Override public Command execute() throws DatagioException { //fortressService.registerFortress(company, new FortressInputBean(headers.iterator().next().getFortress()), true); Iterable<TrackResultBean> resultBeans = trackService.createHeaders(headers, company, fortress); processLogs(company, resultBeans); return this; } } DeadlockRetry.execute(new DLCommand(metaInputBeans), "creating headers", 20); } } else { logger.info("Processing in slow Transaction mode"); for (MetaInputBean inputBean : inputBeans) { createHeader(company, fortress, inputBean); } } watch.stop(); logger.info("Completed Batch [{}] - secs= {}, RPS={}", id, f.format(watch.getTotalTimeSeconds()), f.format(inputBeans.size() / watch.getTotalTimeSeconds())); return inputBeans.size(); }
From source file:com.persistent.cloudninja.scheduler.PerformanceMonitor.java
@Override public boolean execute() { StopWatch watch = new StopWatch(); try {// w ww .j av a 2 s. co m LOGGER.debug("PerformanceMonitor : Execute"); watch.start(); Date lastReadTime = kpiValueTempDao.getMaxTimestamp(); Date lastBatchTime = null; Calendar calendar = Calendar.getInstance(); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S z"); dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); String date = null; if (lastReadTime == null) { date = dateFormat.format(calendar.getTime()); lastReadTime = dateFormat.parse(date); } calendar = Calendar.getInstance(); date = dateFormat.format(calendar.getTime()); Date currentUTCTime = dateFormat.parse(date); List<KpiValueTempEntity> listKpiValueTempEntities = null; while (lastReadTime.getTime() <= currentUTCTime.getTime()) { LOGGER.debug("PerformanceMonitor : Process performance counters"); calendar.setTime(lastReadTime); calendar.add(Calendar.MINUTE, 30); date = dateFormat.format(calendar.getTime()); lastBatchTime = dateFormat.parse(date); WADPerformanceCountersEntity[] arrPerfCounter = storageUtility .getPerfCounterEntities(lastReadTime.getTime(), lastBatchTime.getTime()); listKpiValueTempEntities = convertAzureEntityToDBEntity(arrPerfCounter); kpiValueTempDao.addAll(listKpiValueTempEntities); kpiValueTempDao.executeProcessKpiValues(); LOGGER.debug("PerformanceMonitor : Process complete"); lastReadTime = lastBatchTime; } watch.stop(); taskCompletionDao.updateTaskCompletionDetails(watch.getTotalTimeSeconds(), "ProcessPerformanceCounters", ""); LOGGER.debug("PerformanceMonitor : Finish"); } catch (ParseException e) { LOGGER.error(e.getMessage(), e); } return true; }
From source file:org.dd4t.core.factories.impl.GenericPageFactory.java
/** * This is just a intermediate method to avoid naming conflicts with the * simpleFactory./* w ww . j a va 2s. co m*/ * @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:net.sf.juffrou.reflect.spring.BeanWrapperTests.java
@Test public void testLargeMatchingPrimitiveArray() { if (LogFactory.getLog(BeanWrapperTests.class).isTraceEnabled()) { // Skip this test: Trace logging blows the time limit. return;/*from w w w. j ava2 s.co m*/ } PrimitiveArrayBean tb = new PrimitiveArrayBean(); BeanWrapper bw = new JuffrouSpringBeanWrapper(tb); int[] input = new int[1024]; StopWatch sw = new StopWatch(); sw.start("array1"); for (int i = 0; i < 1000; i++) { bw.setPropertyValue("array", input); } sw.stop(); assertEquals(1024, tb.getArray().length); assertEquals(0, tb.getArray()[0]); long time1 = sw.getLastTaskTimeMillis(); assertTrue("Took too long", sw.getLastTaskTimeMillis() < 100); bw.registerCustomEditor(String.class, new StringTrimmerEditor(false)); sw.start("array2"); for (int i = 0; i < 1000; i++) { bw.setPropertyValue("array", input); } sw.stop(); assertTrue("Took too long", sw.getLastTaskTimeMillis() < 125); bw.registerCustomEditor(int.class, "array.somePath", new CustomNumberEditor(Integer.class, false)); sw.start("array3"); for (int i = 0; i < 1000; i++) { bw.setPropertyValue("array", input); } sw.stop(); assertTrue("Took too long", sw.getLastTaskTimeMillis() < 100); bw.registerCustomEditor(int.class, "array[0].somePath", new CustomNumberEditor(Integer.class, false)); sw.start("array3"); for (int i = 0; i < 1000; i++) { bw.setPropertyValue("array", input); } sw.stop(); assertTrue("Took too long", sw.getLastTaskTimeMillis() < 100); bw.registerCustomEditor(int.class, new CustomNumberEditor(Integer.class, false)); sw.start("array4"); for (int i = 0; i < 100; i++) { bw.setPropertyValue("array", input); } sw.stop(); assertEquals(1024, tb.getArray().length); assertEquals(0, tb.getArray()[0]); assertTrue("Took too long", sw.getLastTaskTimeMillis() > time1); }
From source file:my.adam.smo.client.SocketClient.java
@Override public RpcChannel connect(final InetSocketAddress sa) { RpcChannel rpcChannel = new RpcChannel() { private Channel c = bootstrap.connect(sa).awaitUninterruptibly().getChannel(); @Override/*w ww.ja v a 2 s . com*/ public void callMethod(Descriptors.MethodDescriptor method, RpcController controller, Message request, Message responsePrototype, RpcCallback<Message> done) { StopWatch stopWatch = new StopWatch("callMethod"); stopWatch.start(); long id = seqNum.addAndGet(1); logger.trace("calling method: " + method.getFullName()); //infinit reconnection loop while (reconnect && !c.isOpen()) { logger.debug("channel closed " + sa); logger.debug("trying to reconnect"); c.disconnect().awaitUninterruptibly(); c.unbind().awaitUninterruptibly(); c = bootstrap.connect(sa).awaitUninterruptibly().getChannel(); try { Thread.sleep(reconnect_delay * 1000); } catch (InterruptedException e) { logger.error("error while sleeping", e); } } RPCommunication.Request protoRequest = RPCommunication.Request.newBuilder() .setServiceName(method.getService().getFullName()).setMethodName(method.getName()) .setMethodArgument(request.toByteString()).setRequestId(id).build(); logger.trace("request built: " + request.toString()); if (enableSymmetricEncryption) { protoRequest = getEncryptedRequest(protoRequest); logger.trace("symmetric encryption enabled, encrypted request: " + protoRequest.toString()); } if (enableAsymmetricEncryption) { protoRequest = getAsymEncryptedRequest(protoRequest); logger.trace("asymmetric encryption enabled, encrypted request: " + protoRequest.toString()); } callbackMap.put(id, done); descriptorProtoMap.put(id, responsePrototype); c.write(protoRequest); logger.trace("request sent: " + protoRequest.toString()); stopWatch.stop(); logger.trace(stopWatch.shortSummary()); } }; logger.trace("connected to address: " + sa.toString()); return rpcChannel; }
From source file:com.persistent.cloudninja.scheduler.TenantDBBandwidthProcessor.java
@Override public boolean execute() { boolean retVal = true; int tenantDBBWsCount = 0; try {/*from w w w.j a v a2 s . c o m*/ LOGGER.debug("In Processor"); TenantDBBandwidthQueue queue = (TenantDBBandwidthQueue) getWorkQueue(); String message = queue.dequeue(SchedulerSettings.MessageVisibilityTimeout); if (message == null) { retVal = false; LOGGER.debug("Processor : msg is null"); } else { StopWatch watch = new StopWatch(); watch.start(); LOGGER.debug("Processor : msg is " + message); List<DBBandwidthUsageEntity> listDbBandwidthUsageEntities = partitionStatsAndBWUsageDao .getBandwidthUsage(); tenantDBBWsCount = listDbBandwidthUsageEntities.size(); Map<String, MeteringEntity> map = new HashMap<String, MeteringEntity>(); MeteringEntity meteringEntity = null; String dbName = null; String tenantId = null; for (DBBandwidthUsageEntity dbBandwidthUsageEntity : listDbBandwidthUsageEntities) { dbName = dbBandwidthUsageEntity.getDatabaseName(); if (dbName.startsWith("tnt_")) { tenantId = dbName.substring(4); if (map.containsKey(tenantId)) { meteringEntity = map.get(tenantId); setDatabaseBandwidth(dbBandwidthUsageEntity, meteringEntity); } else { meteringEntity = new MeteringEntity(); meteringEntity.setTenantId(tenantId); setDatabaseBandwidth(dbBandwidthUsageEntity, meteringEntity); map.put(tenantId, meteringEntity); } } } 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()); for (Iterator<MeteringEntity> iterator = map.values().iterator(); iterator.hasNext();) { meteringEntity = (MeteringEntity) iterator.next(); meteringEntity.setSnapshotTime(dateFormat.parse(date)); meteringDao.add(meteringEntity); } LOGGER.info("Processor : DB bandwidth calculated."); watch.stop(); taskCompletionDao.updateTaskCompletionDetails(watch.getTotalTimeSeconds(), "ProcessMeteringTenantDBBandwidthUse", "Measured the database bandwith use for " + tenantDBBWsCount + " tenants."); } } catch (StorageException e) { retVal = false; LOGGER.error(e.getMessage(), e); } catch (ParseException e) { retVal = false; LOGGER.error(e.getMessage(), e); } return retVal; }
From source file:my.adam.smo.client.HTTPClient.java
@Override public RpcChannel connect(final InetSocketAddress sa) { RpcChannel rpcChannel = new RpcChannel() { private Channel c = bootstrap.connect(sa).awaitUninterruptibly().getChannel(); @Override//from w w w . ja v a 2 s. c om public void callMethod(Descriptors.MethodDescriptor method, RpcController controller, Message request, Message responsePrototype, RpcCallback<Message> done) { StopWatch stopWatch = new StopWatch("callMethod"); stopWatch.start(); long id = seqNum.addAndGet(1); logger.trace("calling method: " + method.getFullName()); HttpRequest httpRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "http://" + sa.getHostName() + ":" + sa.getPort()); httpRequest.setHeader(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE); httpRequest.setHeader(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP); httpRequest.setHeader(HttpHeaders.Names.CONTENT_TYPE, HttpHeaders.Values.APPLICATION_X_WWW_FORM_URLENCODED); RPCommunication.Request protoRequest = RPCommunication.Request.newBuilder() .setServiceName(method.getService().getFullName()).setMethodName(method.getName()) .setMethodArgument(request.toByteString()).setRequestId(id).build(); logger.trace("request built: " + request.toString()); if (enableSymmetricEncryption) { protoRequest = getEncryptedRequest(protoRequest); logger.trace("symmetric encryption enabled, encrypted request: " + protoRequest.toString()); } if (enableAsymmetricEncryption) { protoRequest = getAsymEncryptedRequest(protoRequest); logger.trace("asymmetric encryption enabled, encrypted request: " + protoRequest.toString()); } byte[] arr = protoRequest.toByteArray(); ChannelBuffer s = Base64.encode(ChannelBuffers.copiedBuffer(arr), Base64Dialect.STANDARD); httpRequest.setContent(s); httpRequest.addHeader(HttpHeaders.Names.CONTENT_LENGTH, s.readableBytes()); httpRequest.setChunked(false); callbackMap.put(id, done); descriptorProtoMap.put(id, responsePrototype); c.write(httpRequest); logger.trace("request sent: " + protoRequest.toString()); stopWatch.stop(); logger.trace(stopWatch.shortSummary()); } }; logger.trace("connected to address: " + sa.toString()); return rpcChannel; }
From source file:org.dd4t.core.factories.impl.SimpleComponentFactory.java
/** * Get the component by the component uri and component template uri * /* w w w . ja v a2s .c om*/ * @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:sample.contact.ClientApplication.java
public void invokeContactService(Authentication authentication, int nrOfCalls) { StopWatch stopWatch = new StopWatch(nrOfCalls + " ContactService call(s)"); Map<String, ContactService> contactServices = this.beanFactory.getBeansOfType(ContactService.class, true, true);// www. j a v a2 s.c o m SecurityContextHolder.getContext().setAuthentication(authentication); for (String beanName : contactServices.keySet()) { Object object = this.beanFactory.getBean("&" + beanName); try { System.out.println("Trying to find setUsername(String) method on: " + object.getClass().getName()); Method method = object.getClass().getMethod("setUsername", new Class[] { String.class }); System.out.println("Found; Trying to setUsername(String) to " + authentication.getPrincipal()); method.invoke(object, authentication.getPrincipal()); } catch (NoSuchMethodException ignored) { System.out.println("This client proxy factory does not have a setUsername(String) method"); } catch (IllegalAccessException ignored) { ignored.printStackTrace(); } catch (InvocationTargetException ignored) { ignored.printStackTrace(); } try { System.out.println("Trying to find setPassword(String) method on: " + object.getClass().getName()); Method method = object.getClass().getMethod("setPassword", new Class[] { String.class }); method.invoke(object, authentication.getCredentials()); System.out.println("Found; Trying to setPassword(String) to " + authentication.getCredentials()); } catch (NoSuchMethodException ignored) { System.out.println("This client proxy factory does not have a setPassword(String) method"); } catch (IllegalAccessException ignored) { } catch (InvocationTargetException ignored) { } ContactService remoteContactService = contactServices.get(beanName); System.out.println("Calling ContactService '" + beanName + "'"); stopWatch.start(beanName); List<Contact> contacts = null; for (int i = 0; i < nrOfCalls; i++) { contacts = remoteContactService.getAll(); } stopWatch.stop(); if (contacts.size() != 0) { for (Contact contact : contacts) { System.out.println("Contact: " + contact); } } else { System.out.println("No contacts found which this user has permission to"); } System.out.println(); System.out.println(stopWatch.prettyPrint()); } SecurityContextHolder.clearContext(); }