List of usage examples for org.apache.commons.lang.time StopWatch getTime
public long getTime()
Get the time on the stopwatch.
This is either the time between the start and the moment this method is called, or the amount of time between start and stop.
From source file:com.redhat.rhn.manager.errata.test.ErrataManagerTest.java
public void xxxxLookupErrataByAdvisoryType() throws IOException { String bugfix = "Bug Fix Advisory"; String pea = "Product Enhancement Advisory"; String security = "Security Advisory"; StopWatch st = new StopWatch(); st.start();/*w ww . java2 s . c om*/ List erratas = ErrataManager.lookupErrataByType(bugfix); outputErrataList(erratas); System.out.println("Got bugfixes: " + erratas.size() + " time: " + st); assertTrue(erratas.size() > 0); erratas = ErrataManager.lookupErrataByType(pea); outputErrataList(erratas); System.out.println("Got pea enhancments: " + erratas.size() + " time: " + st); assertTrue(erratas.size() > 0); erratas = ErrataManager.lookupErrataByType(security); outputErrataList(erratas); assertTrue(erratas.size() > 0); System.out.println("Got security advisories: " + erratas.size() + " time: " + st); st.stop(); System.out.println("TIME: " + st.getTime()); }
From source file:com.yahoo.flowetl.core.Plumber.java
/** * Translates a set of roots into a runnable object. * //from w ww.j av a2 s .c o m * @param roots * * @return the pipe runner * * @throws PipeException */ public PipeRunner translate(final Set<Pipe> roots) throws PipeException { if (roots == null || roots.isEmpty()) { throw new IllegalArgumentException("No valid pipes provided"); } // first translate to a graph final DefaultDirectedGraph<Pipe, PipeEdge> runGraph = new DefaultDirectedGraph<Pipe, PipeEdge>( new EdgeFactory<Pipe, PipeEdge>() { @Override public PipeEdge createEdge(Pipe src, Pipe tgt) { StringBuilder tmp = new StringBuilder(); tmp.append("{" + src.getName() + "}"); tmp.append("->"); tmp.append("{" + tgt.getName() + "}"); return new PipeEdge(tmp.toString()); } }); // find all reachable pipes from the given roots final Set<Pipe> reachableInputs = new HashSet<Pipe>(); Set<Pipe> reachablePipesTmp = new HashSet<Pipe>(); for (Pipe p : roots) { discoverReachable(p, reachablePipesTmp); reachableInputs.addAll(reachablePipesTmp); reachableInputs.add(p); reachablePipesTmp.clear(); } // add as vertexes.. for (Pipe p : reachableInputs) { runGraph.addVertex(p); } // connect together for (Pipe v : reachableInputs) { List<Pipe> outs = v.getOutputs(); if (outs != null) { int max = v.maxOutputs(); int cur = outs.size(); if (max != -1 && (max < cur)) { throw new PipeException( "Pipe " + v + " is only allowed " + max + " outputs but it has " + cur + " outputs"); } for (Pipe t : outs) { if (t == null) { continue; } PipeEdge edgeName = runGraph.addEdge(v, t); if (logger.isEnabled(Level.INFO)) { logger.log(Level.INFO, "Connected " + v + " to " + t + " with edge " + edgeName); } } } } // do cycle detection CycleDetector<Pipe, PipeEdge> cycleDetect = new CycleDetector<Pipe, PipeEdge>(runGraph); Set<Pipe> cycleNodes = cycleDetect.findCycles(); if (cycleNodes != null && cycleNodes.isEmpty() == false) { StringBuilder msg = new StringBuilder("The following pipes are causing cycles ["); msg.append(StringUtils.join(cycleNodes, ",")); msg.append("]"); throw new PipeException(msg.toString()); } // check connected components ConnectivityInspector<Pipe, PipeEdge> cInspector = new ConnectivityInspector<Pipe, PipeEdge>(runGraph); if (cInspector.isGraphConnected() == false) { throw new PipeException( "The pipes provided have occurences which do not actually connect to other pipes"); } // display if (logger.isEnabled(Level.DEBUG)) { StringWriter w = new StringWriter(); DOTExporter<Pipe, PipeEdge> d = new DOTExporter<Pipe, PipeEdge>(new VertexNameProvider<Pipe>() { @Override public String getVertexName(Pipe p) { return p.getName(); } }, new VertexNameProvider<Pipe>() { @Override public String getVertexName(Pipe p) { return p.getName(); } }, new EdgeNameProvider<PipeEdge>() { @Override public String getEdgeName(PipeEdge e) { return String.valueOf(e); } }); d.export(w, runGraph); try { w.close(); } catch (IOException e1) { // should be ok to ignore this... } logger.log(Level.DEBUG, w.toString()); } // all verified, yippe PipeRunner out = new PipeRunner() { @Override public void run() { // use topological order to figure out // how to run this graph in a way // that will ensure the inputs are satisfied // before a vertex is ran... GraphIterator<Pipe, PipeEdge> it = makeTraversalIterator(runGraph); // get the ordering first // which doesn't involve activating any of the pipes // just seeing what the iteration order will be... final List<Pipe> order = IterUtils.toList(it, ArrayList.class); // now make the real run iterator it = makeTraversalIterator(runGraph); it.addTraversalListener(new TraversalListenerAdapter<Pipe, PipeEdge>() { @Override public void vertexTraversed(VertexTraversalEvent<Pipe> v) { if (logger.isEnabled(Level.INFO)) { logger.log(Level.INFO, "Vertex " + v.getVertex() + " was visited"); } } }); StopWatch overallTimer = new StopWatch(); overallTimer.start(); notifyStart(order); // keep track of which ones we exec'ed // maybe for use later?? final List<Pipe> curExecd = new ArrayList<Pipe>(order.size()); // iterate StopWatch perRunTimer = new StopWatch(); List<Pipe> pipeOutputs = null; PipeResult pipeRes = null; while (it.hasNext()) { Pipe toRun = it.next(); perRunTimer.reset(); perRunTimer.start(); notifyStartGenerate(toRun); { pipeRes = toRun.generateOutput(); } perRunTimer.stop(); curExecd.add(toRun); pipeOutputs = toRun.getOutputs(); if (pipeOutputs != null) { for (Pipe tmp : pipeOutputs) { if (tmp == null) { continue; } tmp.attachInput(pipeRes); } } notifyFinishGenerate(toRun, pipeRes, perRunTimer.getTime()); // now clear it toRun.clearInputs(); } overallTimer.stop(); notifyComplete(overallTimer.getTime()); } }; return out; }
From source file:net.nan21.dnet.core.web.controller.data.AbstractDsRpcController.java
/** * Default handler for remote procedure call on a filter. * // w w w .ja v a 2 s . c o m * @param resourceName * @param dataformat * @param dataString * @param paramString * @return * @throws Exception */ @RequestMapping(method = RequestMethod.POST, params = { Constants.REQUEST_PARAM_ACTION + "=" + Constants.DS_ACTION_RPC, Constants.DS_ACTION_RPC + "Type=filter" }) @ResponseBody public String rpcFilter(@PathVariable String resourceName, @PathVariable String dataFormat, @RequestParam(value = Constants.REQUEST_PARAM_SERVICE_NAME_PARAM, required = true) String rpcName, @RequestParam(value = Constants.REQUEST_PARAM_DATA, required = false, defaultValue = "{}") String dataString, @RequestParam(value = Constants.REQUEST_PARAM_PARAMS, required = false, defaultValue = "{}") String paramString, HttpServletRequest request, HttpServletResponse response) throws Exception { try { StopWatch stopWatch = new StopWatch(); stopWatch.start(); if (logger.isInfoEnabled()) { logger.info("Processing request: {}.{} -> action = {}-filter / {}", new String[] { resourceName, dataFormat, Constants.DS_ACTION_RPC, rpcName }); } if (logger.isDebugEnabled()) { logger.debug(" --> request-data: {} ", new String[] { dataString }); logger.debug(" --> request-params: {} ", new String[] { paramString }); } this.prepareRequest(request, response); this.authorizeDsAction(resourceName, Constants.DS_ACTION_RPC, rpcName); IDsService<M, F, P> service = this.findDsService(resourceName); IDsMarshaller<M, F, P> marshaller = service.createMarshaller(dataFormat); F filter = marshaller.readFilterFromString(dataString); P params = marshaller.readParamsFromString(paramString); service.rpcFilter(rpcName, filter, params); IActionResultRpcFilter result = this.packRpcFilterResult(filter, params); stopWatch.stop(); result.setExecutionTime(stopWatch.getTime()); return marshaller.writeResultToString(result); } finally { this.finishRequest(); } }
From source file:com.qualogy.qafe.gwt.server.RPCServiceImpl.java
public GEventItemDataObject executeEventItem(EventItemDataGVO eventItem) throws GWTServiceException, GWTApplicationStoreException { StopWatch stopWatch = new StopWatch(); logger.info("Event started[thread id=" + Thread.currentThread().getId() + "]"); stopWatch.start();//from ww w . java2 s . com try { EventItemProcessor eventItemProcessor = new EventItemProcessorImpl(); Map<String, Object> outputValues = eventItemProcessor.execute(eventItem); GEventItemDataObject gEventItemDataObject = new GEventItemDataObject(); gEventItemDataObject.setOutputValues(outputValues); stopWatch.stop(); return gEventItemDataObject; } catch (Exception e) { GWTServiceException gWTServiceException = handleException(e); //gWTServiceException.setGDataObject(ExceptionProcessor.handle(eventData, e)); stopWatch.stop(); if (gWTServiceException.getGDataObject() != null) { gWTServiceException.getGDataObject().setTime(Long.valueOf(stopWatch.getTime())); } logger.info("Event ends[thread id=" + Thread.currentThread().getId() + "]"); throw gWTServiceException; } }
From source file:eagle.storage.jdbc.entity.impl.JdbcEntityUpdaterImpl.java
@Override public int update(List<E> entities) throws Exception { ConnectionManager cm = ConnectionManagerFactory.getInstance(); TorqueStatementPeerImpl<E> peer = cm.getStatementExecutor(this.jdbcEntityDefinition.getJdbcTableName()); Connection connection = cm.getConnection(); connection.setAutoCommit(false);/*w ww .j a va 2 s.c om*/ StopWatch stopWatch = new StopWatch(); stopWatch.start(); int num = 0; try { for (E entity : entities) { String primaryKey = entity.getEncodedRowkey(); PrimaryKeyCriteriaBuilder pkBuilder = new PrimaryKeyCriteriaBuilder(Arrays.asList(primaryKey), this.jdbcEntityDefinition.getJdbcTableName()); Criteria selectCriteria = pkBuilder.build(); if (LOG.isDebugEnabled()) LOG.debug("Updating by query: " + SqlBuilder.buildQuery(selectCriteria).getDisplayString()); ColumnValues columnValues = JdbcEntitySerDeserHelper.buildColumnValues(entity, this.jdbcEntityDefinition); num += peer.delegate().doUpdate(selectCriteria, columnValues, connection); } if (LOG.isDebugEnabled()) LOG.debug("Committing updates"); connection.commit(); } catch (Exception ex) { LOG.error("Failed to update, rolling back", ex); connection.rollback(); throw ex; } finally { stopWatch.stop(); if (LOG.isDebugEnabled()) LOG.debug("Closing connection"); connection.close(); } LOG.info(String.format("Updated %s records in %s ms", num, stopWatch.getTime())); return num; }
From source file:au.id.hazelwood.xmltvguidebuilder.runner.App.java
public void run(File configFile, File outFile) throws InvalidConfigException, JAXBException, IOException { LOGGER.info("Running XMLTV Guide Builder"); StopWatch watch = new StopWatch(); watch.start();/* w w w. j av a 2s.c om*/ LOGGER.info("Reading config file '{}'", configFile.getCanonicalPath()); Config config = configFactory.create(configFile); DateTime today = new DateTime().withTimeAtStartOfDay(); DateTime from = today.plusDays(config.getOffset()); DateTime to = from.plusDays(config.getDays()); LOGGER.info("Getting listing from foxtel grabber between {} and {}", toISODateTime(from), toISODateTime(to)); ChannelListings channelListings = grabber.getListing(config, from, to, config.getChannelConfigs()); LOGGER.info("Verifying listings for all channels between {} and {}", new Object[] { toISODateTime(from), toISODateTime(to) }); DateTime subsetTo = from.plusDays(7).isBefore(to) ? from.plusDays(7) : to; listingVerifier.verifyListing(channelListings, from, to, subsetTo); LOGGER.info("Backup old output files"); backupOldOutputFiles(outFile); LOGGER.info("Writing result to {}", outFile.getCanonicalPath()); Writer writer = new BufferedWriter(new FileWriterWithEncoding(outFile, "UTF-8")); bindingService.marshal(xmltvMapper.toXmltv(channelListings), writer); IOUtils.closeQuietly(writer); watch.stop(); LOGGER.info("XMLTV Guide Builder successful in {}", formatDurationWords(watch.getTime())); }
From source file:eagle.service.generic.GenericEntityServiceResource.java
/** * @param value rowkey value//from w ww . j a v a 2 s. com * @param serviceName entity service name * @return GenericServiceAPIResponseEntity */ @GET @Path(ROWKEY_PATH) @Produces(MediaType.APPLICATION_JSON) public GenericServiceAPIResponseEntity search(@QueryParam("value") String value, @QueryParam("serviceName") String serviceName) { GenericServiceAPIResponseEntity response = new GenericServiceAPIResponseEntity(); Map<String, Object> meta = new HashMap<>(); DataStorage dataStorage; StopWatch stopWatch = null; try { if (serviceName == null) throw new IllegalArgumentException("serviceName is null"); RowkeyQueryStatement queryStatement = new RowkeyQueryStatement(value, serviceName); stopWatch = new StopWatch(); stopWatch.start(); dataStorage = DataStorageManager.getDataStorageByEagleConfig(); if (dataStorage == null) { LOG.error("Data storage is null"); throw new IllegalDataStorageException("data storage is null"); } QueryResult<?> result = queryStatement.execute(dataStorage); if (result.isSuccess()) { meta.put(FIRST_TIMESTAMP, result.getFirstTimestamp()); meta.put(LAST_TIMESTAMP, result.getLastTimestamp()); meta.put(TOTAL_RESULTS, result.getSize()); meta.put(ELAPSEDMS, stopWatch.getTime()); response.setObj(result.getData()); response.setType(result.getEntityType()); response.setSuccess(true); response.setMeta(meta); return response; } } catch (Exception e) { response.setException(e); LOG.error(e.getMessage(), e); } finally { if (stopWatch != null) stopWatch.stop(); } return response; }
From source file:net.nan21.dnet.core.web.controller.data.AbstractDsWriteController.java
/** * Default handler for delete action.// ww w . j a va 2 s .c om * * @param resourceName * @param dataformat * @param idsString * @param paramString * @return * @throws Exception */ @RequestMapping(method = RequestMethod.POST, params = Constants.REQUEST_PARAM_ACTION + "=" + Constants.DS_ACTION_DELETE) @ResponseBody public String delete(@PathVariable String resourceName, @PathVariable String dataFormat, @RequestParam(value = Constants.REQUEST_PARAM_DATA, required = false, defaultValue = "{}") String dataString, @RequestParam(value = Constants.REQUEST_PARAM_PARAMS, required = false, defaultValue = "{}") String paramString, HttpServletRequest request, HttpServletResponse response) throws Exception { try { StopWatch stopWatch = new StopWatch(); stopWatch.start(); if (logger.isInfoEnabled()) { logger.info("Processing request: {}.{} -> action = {} ", new String[] { resourceName, dataFormat, Constants.DS_ACTION_DELETE }); } this.prepareRequest(request, response); this.authorizeDsAction(resourceName, Constants.DS_ACTION_DELETE, null); if (!dataString.startsWith("[")) { dataString = "[" + dataString + "]"; } IDsService<M, F, P> service = this.findDsService(resourceName); IDsMarshaller<M, F, P> marshaller = service.createMarshaller(IDsMarshaller.JSON); List<M> list = marshaller.readListFromString(dataString); // P params = marshaller.readParamsFromString(paramString); List<Object> ids = new ArrayList<Object>(); for (M ds : list) { ids.add(((IModelWithId) ds).getId()); } service.deleteByIds(ids); IActionResultDelete result = this.packResultDelete(); stopWatch.stop(); result.setExecutionTime(stopWatch.getTime()); String out = null; if (dataFormat.equals(IDsMarshaller.XML)) { IDsMarshaller<M, F, P> resultMarshaller = service.createMarshaller(dataFormat); out = resultMarshaller.writeResultToString(result); response.setContentType("text/xml; charset=UTF-8"); } else { out = marshaller.writeResultToString(result); response.setContentType("text/plain; charset=UTF-8"); } return out; } catch (Exception e) { this.handleException(e, response); return null; } finally { this.finishRequest(); } }
From source file:eagle.service.generic.GenericEntityServiceResource.java
/** * @param serviceName entity service name * @return GenericServiceAPIResponseEntity *//*from ww w .j av a 2 s .co m*/ @POST @Path(ROWKEY_PATH) @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public GenericServiceAPIResponseEntity search(InputStream inputStream, @QueryParam("serviceName") String serviceName) { GenericServiceAPIResponseEntity response = new GenericServiceAPIResponseEntity(); Map<String, Object> meta = new HashMap<>(); DataStorage dataStorage; StopWatch stopWatch = null; try { if (serviceName == null) throw new IllegalArgumentException("serviceName is null"); final List<String> values = unmarshalAsStringlist(inputStream); final RowkeyQueryStatement queryStatement = new RowkeyQueryStatement(values, serviceName); stopWatch = new StopWatch(); stopWatch.start(); dataStorage = DataStorageManager.getDataStorageByEagleConfig(); if (dataStorage == null) { LOG.error("Data storage is null"); throw new IllegalDataStorageException("Data storage is null"); } QueryResult<?> result = queryStatement.execute(dataStorage); if (result.isSuccess()) { meta.put(FIRST_TIMESTAMP, result.getFirstTimestamp()); meta.put(LAST_TIMESTAMP, result.getLastTimestamp()); meta.put(TOTAL_RESULTS, result.getSize()); meta.put(ELAPSEDMS, stopWatch.getTime()); response.setObj(result.getData()); response.setType(result.getEntityType()); response.setSuccess(true); response.setMeta(meta); return response; } } catch (Exception e) { response.setException(e); LOG.error(e.getMessage(), e); } finally { if (stopWatch != null) stopWatch.stop(); } return response; }
From source file:net.di2e.ecdr.libs.result.relevance.RelevanceNormalizer.java
/** * Normalize the relevance score for the results in the query response based on the contextual query criteria * * @param results//from w w w. ja v a 2 s.c o m * @param originalQuery * @return */ public List<Result> normalize(List<Result> results, Query originalQuery) { SortBy sortBy = originalQuery.getSortBy(); // We want to do relevance sort if no sort order was specfied or if Relevance sort was specified if (sortBy == null || sortBy.getPropertyName() == null || sortBy.getPropertyName().getPropertyName() == null || Result.RELEVANCE.equals(sortBy.getPropertyName().getPropertyName())) { Map<String, String> filterParameters = getFilterParameters(originalQuery); if (canNormalizeQuery(filterParameters)) { LOGGER.debug( "Query contained search phrase and will be sorted by relevance, performing re-indexing to normalize relevance."); Directory directory = null; DirectoryReader iReader = null; Map<String, Result> docMap = new HashMap<>(); List<Result> updatedResults = new ArrayList<>(); StopWatch stopWatch = new StopWatch(); stopWatch.start(); try { Analyzer analyzer = new StandardAnalyzer(); // create memory-stored index directory = new RAMDirectory(); IndexWriterConfig config = new IndexWriterConfig(Version.LATEST, analyzer); IndexWriter iWriter = new IndexWriter(directory, config); // loop through all of the results and add them to the index for (Result curResult : results) { Document doc = new Document(); String text = TextParser.parseTextFrom(curResult.getMetacard().getMetadata()); String uuid = UUID.randomUUID().toString(); doc.add(new Field(METADATA_FIELD, text, TextField.TYPE_STORED)); doc.add(new Field(ID_FIELD, uuid, TextField.TYPE_STORED)); iWriter.addDocument(doc); docMap.put(uuid, curResult); } IOUtils.closeQuietly(iWriter); LOGGER.debug("{} Document indexing finished in {} seconds.", RELEVANCE_TIMER, (double) stopWatch.getTime() / 1000.0); // Now search the index: iReader = DirectoryReader.open(directory); IndexSearcher iSearcher = new IndexSearcher(iReader); // Parse a simple query that searches for "text": QueryParser parser = new QueryParser(METADATA_FIELD, analyzer); org.apache.lucene.search.Query query = getQuery(parser, filterParameters); ScoreDoc[] hits = iSearcher.search(query, null, docMap.size()).scoreDocs; LOGGER.debug("Got back {} results", hits.length); // loop through the indexed search results and update the scores in the original query results for (ScoreDoc curHit : hits) { Document doc = iSearcher.doc(curHit.doc); String uuid = doc.getField(ID_FIELD).stringValue(); Result result = docMap.get(uuid); docMap.remove(uuid); updatedResults.add(updateResult(result, curHit.score)); LOGGER.debug("Relevance for result {} was changed FROM {} TO {}", result.getMetacard().getId(), result.getRelevanceScore(), curHit.score); } // check if there are any results left that did not match the keyword query for (Map.Entry<String, Result> curEntry : docMap.entrySet()) { // add result in with 0 relevance score updatedResults.add(updateResult(curEntry.getValue(), 0)); } // create new query response return updatedResults; } catch (ParseException | IOException | RuntimeException e) { LOGGER.warn( "Received an exception while trying to perform re-indexing, sending original queryResponse on.", e); return results; } finally { IOUtils.closeQuietly(iReader); IOUtils.closeQuietly(directory); stopWatch.stop(); LOGGER.debug("{} Total relevance process took {} seconds.", RELEVANCE_TIMER, (double) stopWatch.getTime() / 1000.0); } } else { LOGGER.debug( "Query is not sorted based on relevance with contextual criteria. Skipping relevance normalization."); } } else { LOGGER.debug( "Query is not sorted based on relevance with contextual criteria. Skipping relevance normalization."); } return results; }