List of usage examples for org.springframework.util StopWatch start
public void start() throws IllegalStateException
From source file:ru.anr.cmdline.base.BootstrapImpl.java
/** * {@inheritDoc}/*from w w w . java 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; }
From source file:my.adam.smo.client.SocketClient.java
@Inject public SocketClient(@Value("${client_worker_threads:10}") int workerThreads) { bootstrap.setFactory(new NioClientSocketChannelFactory(Executors.newCachedThreadPool(), Executors.newCachedThreadPool(), workerThreads)); bootstrap.setPipelineFactory(new ChannelPipelineFactory() { @Override/* w w w . j a v a2s . c o m*/ public ChannelPipeline getPipeline() throws Exception { StopWatch stopWatch = new StopWatch("getPipeline"); stopWatch.start(); 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.Response.getDefaultInstance()));//UpstreamHandler p.addLast("handler", new SimpleChannelUpstreamHandler() { @Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { StopWatch stopWatch = new StopWatch("messageReceived"); stopWatch.start(); RPCommunication.Response response = (RPCommunication.Response) e.getMessage(); logger.trace("received response:" + response); //encryption if (enableAsymmetricEncryption) { response = getAsymDecryptedResponse(response); logger.trace( "asymmetric encryption enabled, encrypted request: " + response.toString()); } if (enableSymmetricEncryption) { response = getDecryptedResponse(response); logger.trace("symmetric encryption enabled, encrypted request: " + response.toString()); } Message msg = descriptorProtoMap.remove(response.getRequestId()); Message m = msg.getParserForType().parseFrom(response.getResponse()); callbackMap.remove(response.getRequestId()).run(m); super.messageReceived(ctx, e); stopWatch.stop(); logger.trace(stopWatch.shortSummary()); } @Override public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception { if (!standardExceptionHandling(ctx, e)) { super.exceptionCaught(ctx, e); } } }); stopWatch.stop(); logger.trace(stopWatch.shortSummary()); return p; } }); }
From source file:com.persistent.cloudninja.scheduler.PerformanceMonitor.java
@Override public boolean execute() { StopWatch watch = new StopWatch(); try {/* w ww. ja v a2 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: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/*w w w .j a va 2s. c o m*/ 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.jason.mapmaker.repository.impl.HibernateGenericRepository.java
public void saveList(List<T> objectList) { StopWatch stopWatch = new StopWatch(); stopWatch.start(); /* for (T obj: objectList) { try {/*from ww w . j av a 2s. co m*/ 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:org.nebulaframework.util.profiling.ProfilingAspect.java
/** * Advice of Profiling Aspect. Measures and logs the exection * time of advised method./* w w w.j av a 2s . c o m*/ * * @param pjp {ProceedingJoinPoint} * @return Object result * @throws Throwable if exception occurs */ @Around("profilingPointcut()") public Object profile(ProceedingJoinPoint pjp) throws Throwable { StopWatch sw = new StopWatch(); Log localLog = null; try { // Get Log localLog = LogFactory.getLog(pjp.getTarget().getClass()); // Start StopWatch sw.start(); // Proceed Invocation return pjp.proceed(); } finally { // Stop StopWatch sw.stop(); if (localLog == null) { // If local Log not found, use ProfilingAspect's Log localLog = log; } //Log Stats localLog.debug("[Profiling] " + pjp.getTarget().getClass().getName() + "->" + pjp.getSignature().getName() + "() | " + sw.getLastTaskTimeMillis() + " ms"); } }
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// www . jav 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.client.HTTPClient.java
@Inject public HTTPClient(@Value("${client_worker_threads:10}") int workerThreads) { bootstrap.setFactory(new NioClientSocketChannelFactory(Executors.newCachedThreadPool(), Executors.newCachedThreadPool(), workerThreads)); bootstrap.setPipelineFactory(new ChannelPipelineFactory() { @Override/*w w w . j a v a2s. c om*/ public ChannelPipeline getPipeline() throws Exception { StopWatch stopWatch = new StopWatch("getPipeline"); stopWatch.start(); ChannelPipeline p = Channels.pipeline(); if (enableTrafficLogging) { InternalLoggerFactory.setDefaultFactory(new Slf4JLoggerFactory()); p.addLast("logger", new LoggingHandler(InternalLogLevel.DEBUG)); } p.addLast("codec", new HttpClientCodec()); p.addLast("chunkAggregator", new HttpChunkAggregator(MAX_CONTENT_LENGTH)); p.addLast("chunkedWriter", new ChunkedWriteHandler()); p.addLast("decompressor", new HttpContentDecompressor()); p.addLast("handler", new SimpleChannelUpstreamHandler() { @Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { StopWatch stopWatch = new StopWatch("messageReceived"); stopWatch.start(); HttpResponse httpResponse = (HttpResponse) e.getMessage(); ChannelBuffer cb = Base64.decode(httpResponse.getContent(), Base64Dialect.STANDARD); RPCommunication.Response response = RPCommunication.Response .parseFrom(CodedInputStream.newInstance(cb.copy(0, cb.readableBytes()).array())); logger.trace("received response:" + response); //encryption if (enableAsymmetricEncryption) { response = getAsymDecryptedResponse(response); logger.trace( "asymmetric encryption enabled, encrypted request: " + response.toString()); } if (enableSymmetricEncryption) { response = getDecryptedResponse(response); logger.trace("symmetric encryption enabled, encrypted request: " + response.toString()); } Message msg = descriptorProtoMap.remove(response.getRequestId()); Message m = msg.getParserForType().parseFrom(response.getResponse()); callbackMap.remove(response.getRequestId()).run(m); super.messageReceived(ctx, e); stopWatch.stop(); logger.trace(stopWatch.shortSummary()); } @Override public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception { if (!standardExceptionHandling(ctx, e)) { super.exceptionCaught(ctx, e); } } }); stopWatch.stop(); logger.trace(stopWatch.shortSummary()); return p; } }); }
From source file:fr.univrouen.poste.services.GalaxieExcelParser.java
public void process(GalaxieExcel galaxieExcel) throws SQLException { StopWatch chrono = new StopWatch(); chrono.start(); List<List<String>> cells = excelParser .getCells(galaxieExcel.getBigFile().getBinaryFile().getBinaryStream()); Map<String, Long> cellsPosition = new HashMap<String, Long>(); int p = 0;/* ww w . j av a 2 s.c o m*/ List<String> cellsHead = cells.remove(0); for (String cellName : cellsHead) { cellsPosition.put(cellName, new Long(p++)); } galaxieMappingService.checkCellsHead(cellsPosition); Map<List<String>, GalaxieEntry> dbGalaxyEntries = new HashMap<List<String>, GalaxieEntry>(); for (GalaxieEntry galaxieEntry : GalaxieEntry.findAllGalaxieEntrys()) { dbGalaxyEntries.put(getList4Id(galaxieEntry), galaxieEntry); } for (List<String> row : cells) { // create a new galaxyEntry GalaxieEntry galaxieEntry = new GalaxieEntry(); for (String cellName : cellsPosition.keySet()) { int position = cellsPosition.get(cellName).intValue(); if (row.size() > position) { String cellValue = row.get(position); galaxieMappingService.setAttrFromCell(galaxieEntry, cellName, cellValue); } else { logger.debug("can't get " + cellName + " for this row in excel file ..."); } } // Rcupration d'un GalaxieEntry chaque fois trop gourmand, mme avec l'index ... //TypedQuery<GalaxieEntry> query = GalaxieEntry.findGalaxieEntrysByNumEmploiAndNumCandidat(galaxieEntry.getNumEmploi(), galaxieEntry.getNumCandidat(), null, null); GalaxieEntry dbGalaxyEntrie = dbGalaxyEntries.get(getList4Id(galaxieEntry)); if (dbGalaxyEntrie == null) { galaxieEntry.persist(); dbGalaxyEntries.put(getList4Id(galaxieEntry), galaxieEntry); } else { // This GalaxyEntry exists already, we merge it if needed if (!fieldsEquals(dbGalaxyEntrie, galaxieEntry)) { dbGalaxyEntrie.setCivilite(galaxieEntry.getCivilite()); dbGalaxyEntrie.setNom(galaxieEntry.getNom()); dbGalaxyEntrie.setPrenom(galaxieEntry.getPrenom()); if (dbGalaxyEntrie.getEmail().isEmpty()) { if (!galaxieEntry.getEmail().isEmpty()) { dbGalaxyEntrie.setEmail(galaxieEntry.getEmail()); logger.info("Le candidat " + dbGalaxyEntrie.getNumCandidat() + " a maintenant renseign son email : " + galaxieEntry.getEmail()); } } // si email diffrent et si le candidat n'a pas activ son compte - on rinitialise le compte == on le supprime et on le rcr avec cette nvelle adresse mail else if (!dbGalaxyEntrie.getEmail().equals(galaxieEntry.getEmail())) { try { User user = User.findUsersByEmailAddress(dbGalaxyEntrie.getEmail()).getSingleResult(); if (user.getActivationDate() == null && !user.isCandidatActif()) { logger.info("Le candidat " + dbGalaxyEntrie.getNumCandidat() + " a chang d'email alors qu'il n'avait pas encore activ son compte - on relance la procdure de cration de son compte/candidature."); // cas o le candidat postule plusieurs postes pris en compte ainsi List<GalaxieEntry> userGalaxieEntries = GalaxieEntry .findGalaxieEntrysByCandidat(user).getResultList(); for (GalaxieEntry userGalaxieEntry : userGalaxieEntries) { dbGalaxyEntries.remove(getList4Id(userGalaxieEntry)); } user.remove(); galaxieEntry.persist(); dbGalaxyEntries.put(getList4Id(galaxieEntry), galaxieEntry); continue; } dbGalaxyEntrie.setEmail(galaxieEntry.getEmail()); } catch (Exception e) { logger.warn("Pb avec le candidat " + dbGalaxyEntrie.getNumCandidat() + " qui a chang d'email ...", e); } } dbGalaxyEntrie.setLocalisation(galaxieEntry.getLocalisation()); dbGalaxyEntrie.setProfil(galaxieEntry.getProfil()); dbGalaxyEntrie.setEtatDossier(galaxieEntry.getEtatDossier()); dbGalaxyEntrie.merge(); } } } chrono.stop(); logger.info("Le traitement du fichier Excel Galaxie a t effectu en " + chrono.getTotalTimeMillis() / 1000.0 + " sec."); }
From source file:com.persistent.cloudninja.scheduler.TenantWebBandWidthUsageProcessor.java
@Override public boolean execute() { StopWatch watch = new StopWatch(); LOGGER.info("Start of TenantWebBandWidthUsageProcessor:execute"); boolean returnFlag = true; TenantWebBandWidthUsageQueue queue = (TenantWebBandWidthUsageQueue) getWorkQueue(); try {/* w w w .j a v a2 s. co m*/ watch.start(); List<WebLogMeteringBatch> list = queue.dequeue(); LOGGER.debug("Queue List Size :" + list.size()); for (int i = 0; i < list.size(); i++) { tenantWebBandWidthUsageProcessUtility.getTenantWebBandWidthUsage(list.get(i)); } watch.stop(); taskCompletionDao.updateTaskCompletionDetails(watch.getTotalTimeSeconds(), "ProcessMeteringWebAppBandwidth", "Processed a batch of " + list.size() + " Tomcat Logs"); } catch (StorageException e) { returnFlag = false; LOGGER.error(e.getMessage(), e); } catch (ParseException e) { returnFlag = false; LOGGER.error(e.getMessage(), e); } LOGGER.debug("ReturnFlag :" + returnFlag); LOGGER.info("End of TenantWebBandWidthUsageProcessor:execute"); return returnFlag; }