List of usage examples for com.google.common.base Stopwatch Stopwatch
Stopwatch()
From source file:com.google.walkaround.util.server.RetryHelper.java
public <R> R run(Body<R> b) throws PermanentFailure { Stopwatch stopwatch = new Stopwatch().start(); for (int retries = 0; true; retries++) { try {//from w ww .j a v a 2s . c om return runBodyOnce(b); } catch (RetryableFailure e) { long elapsedMillis = stopwatch.elapsedMillis(); log.log(Level.WARNING, "Problem on retry " + retries + ", millis elapsed so far: " + elapsedMillis, e); long delayMillis = retryStrategy.delayMillisBeforeRetry(retries, elapsedMillis, e); if (delayMillis < 0) { log.warning("Negative delay: " + delayMillis); delayMillis = 100; } log.info("Sleeping for " + delayMillis + " millis"); try { Thread.sleep(delayMillis); } catch (InterruptedException e2) { Thread.currentThread().interrupt(); throw new PermanentFailure("Interrupted while waiting to retry; " + retries + " tries total, " + stopwatch.elapsedMillis() + " millis elapsed", e2); } } } }
From source file:co.cask.cdap.test.MetricsManager.java
/** * waitFor a metric value count for the metric identified by metricName and context. * @param tags - context identified by tags map * @param metricName/*from ww w. j av a 2 s.co m*/ * @param count - expected metric total count value * @param timeout * @param timeoutUnit * @throws TimeoutException * @throws InterruptedException */ public void waitForTotalMetricCount(Map<String, String> tags, String metricName, long count, long timeout, TimeUnit timeoutUnit) throws TimeoutException, InterruptedException { long value = getTotalMetric(tags, metricName); // Min sleep time is 10ms, max sleep time is 1 seconds long sleepMillis = Math.max(10, Math.min(timeoutUnit.toMillis(timeout) / 10, TimeUnit.SECONDS.toMillis(1))); Stopwatch stopwatch = new Stopwatch().start(); while (value < count && stopwatch.elapsedTime(timeoutUnit) < timeout) { TimeUnit.MILLISECONDS.sleep(sleepMillis); value = getTotalMetric(tags, metricName); } if (value < count) { throw new TimeoutException("Time limit reached: Expected '" + count + "' but got '" + value + "'"); } }
From source file:co.cask.cdap.data2.util.hbase.DefaultHBaseDDLExecutor.java
@Override public void createTableIfNotExists(TableDescriptor descriptor, @Nullable byte[][] splitKeys) throws IOException { HTableDescriptor htd = getHTableDescriptor(descriptor); if (admin.tableExists(htd.getName())) { return;/*w ww .j av a 2 s . c o m*/ } boolean tableExistsFailure = false; try { LOG.debug("Attempting to create table '{}' if it does not exist", Bytes.toString(htd.getName())); admin.createTable(htd, splitKeys); } catch (TableExistsException e) { // table may exist because someone else is creating it at the same // time. But it may not be available yet, and opening it might fail. LOG.debug("Table '{}' already exists.", Bytes.toString(htd.getName()), e); tableExistsFailure = true; } // Wait for table to materialize try { Stopwatch stopwatch = new Stopwatch(); stopwatch.start(); long sleepTime = TimeUnit.MILLISECONDS.toNanos(5000L) / 10; sleepTime = sleepTime <= 0 ? 1 : sleepTime; do { if (admin.tableExists(htd.getName())) { if (tableExistsFailure) { LOG.info("Table '{}' exists now. Assuming that another process concurrently created it.", Bytes.toString(htd.getName())); } else { LOG.info("Table '{}' created.", Bytes.toString(htd.getName())); } return; } else { TimeUnit.NANOSECONDS.sleep(sleepTime); } } while (stopwatch.elapsedTime(TimeUnit.MILLISECONDS) < 5000L); } catch (InterruptedException e) { LOG.warn("Sleeping thread interrupted."); } LOG.error("Table '{}' does not exist after waiting {} ms. Giving up.", Bytes.toString(htd.getName()), MAX_CREATE_TABLE_WAIT); }
From source file:fr.ippon.wip.transformers.CSSTransformer.java
/** * Transform the given CSS code: add the prefix defined in portlet config * before each selectors, rewrite URL thanks to the CSS regex defined in * config, remove absolute positionning and add custom CSS. * /*from w ww . j a v a 2 s.com*/ * @param input * the string corresponding to the CSS code * @return a string corresponding to the transformed CSS code * @throws TransformerException */ public String transform(String input) throws SAXException, IOException, TransformerException { super.transform(input); Stopwatch stopwatch = new Stopwatch().start(); if (wipConfig.isEnableCssRewriting()) { // Getting prefix final String wip = "\n." + wipConfig.getPortletDivId() + " "; // removing comments input = input.replaceAll("\\/\\*[^*]*\\*+([^/*][^*]*\\*+)*\\/", ""); // Removing all double white spaced characters input = input.replaceAll("\\r|\\n", ""); input = input.replaceAll(System.getProperty("line.separator"), ""); input = " " + input; // Parsing the file to add the wip prefix before selectors if (wipConfig.isAddPrefix()) { StringBuilder aux = new StringBuilder(); String imported = ""; String selector; int index = 0; int blocStart = input.indexOf("{", 0); int blocEnd = input.indexOf("}", 0); if (blocStart > -1) { do { selector = input.substring(index + 1, blocStart).trim(); if (selector.startsWith("@import") || selector.startsWith("@CHARSET")) { // Get import and save it int i = input.indexOf(";", index); imported += input.substring(index + 1, i + 1); index = i; } else { if (selector.startsWith("@media")) { // this code should transform css code inside // @media, but it make the browser freezing... // Pattern pattern = Pattern.compile("\\s*\\{"); // Matcher matcher = // pattern.matcher(input).region(index + 1, // input.length()); // matcher.find(); // int startMediaCss = matcher.end(); // // pattern = Pattern.compile("\\}\\s*\\}"); // matcher = // pattern.matcher(input).region(startMediaCss, // input.length()); // matcher.find(); // int endMediaCss = matcher.start() + 1; // blocEnd = matcher.end(); // // String transformedMediaCss = // transform(input.substring(startMediaCss, // endMediaCss)); // String result = "\n" + selector + "{" + // transformedMediaCss + "}"; // aux.append(result); // Copy the entire bloc without modification blocEnd = input.indexOf("}}", index) + 1; if (blocEnd < 1) blocEnd = input.indexOf("} }", index) + 1; aux.append("\n" + selector); aux.append(input.substring(blocStart, blocEnd + 1)); } else { if (selector.contains(",")) selector = selector.replaceAll(",", "," + wip); aux.append("\n" + wip + selector); aux.append(input.substring(blocStart, blocEnd + 1)); } // Next step index = blocEnd; blocStart = input.indexOf("{", index); blocEnd = input.indexOf("}", blocStart); } } while (blocStart > -1); input = imported + aux.toString(); } } // Rewriting URLs String regex = wipConfig.getCssRegex(); input = rewrite(regex, input, response); // Removing position: absolute; if (!wipConfig.isAbsolutePositioning()) input = input.replaceAll("absolute", "relative"); } timeProcess.set(stopwatch.elapsedMillis()); return input; }
From source file:com.springer.omelet.mail.Email.java
/*** * Return List of Message filter by Subject,From_ADD,To_ADDR * //from w w w .j a v a2s .co m * @param emailFilter * @param filterText * :text present in Subject of email * @return */ public List<Message> getMessages(EMAIL_FILTER emailFilter, String filterText) { Stopwatch sw = new Stopwatch(); sw.start(); List<Message> returnMessage = new ArrayList<Message>(); int loopCount; try { folder.open(Folder.READ_ONLY); Message[] msgs = folder.getMessages(); int inboMessageCount = folder.getMessageCount(); LOGGER.info("Message count is:" + inboMessageCount); if (inboMessageCount < maxcountEMailCheck) { loopCount = 0; } else { loopCount = inboMessageCount - maxcountEMailCheck; } for (int i = inboMessageCount - 1; i >= loopCount; i--) { switch (emailFilter) { case SUBJECT: if (msgs[i].getSubject().toString().equalsIgnoreCase(filterText)) { returnMessage.add(msgs[i]); } break; case FROM_ADD: // Assumption is from address is only one if (msgs[i].getFrom()[0].toString().contains(filterText)) { returnMessage.add(msgs[i]); } break; case TO_ADDR: for (Address addr : msgs[i].getRecipients(RecipientType.TO)) { LOGGER.info("Sno:" + i + "To Email Add is" + addr.toString()); if (addr.toString().contains(filterText)) { returnMessage.add(msgs[i]); } } break; default: break; } } // CLose the folder folder.close(true); } catch (MessagingException e) { LOGGER.error(e); } sw.stop(); LOGGER.info("Time Taken by getMessage is" + sw.elapsedTime(TimeUnit.SECONDS)); return returnMessage; }
From source file:org.apache.hadoop.hbase.ScanPerformanceEvaluation.java
public void testScan() throws IOException { Stopwatch tableOpenTimer = new Stopwatch(); Stopwatch scanOpenTimer = new Stopwatch(); Stopwatch scanTimer = new Stopwatch(); tableOpenTimer.start();/*from ww w.j av a 2 s . c om*/ HTable table = new HTable(getConf(), TableName.valueOf(tablename)); tableOpenTimer.stop(); Scan scan = getScan(); scanOpenTimer.start(); ResultScanner scanner = table.getScanner(scan); scanOpenTimer.stop(); long numRows = 0; long numCells = 0; scanTimer.start(); while (true) { Result result = scanner.next(); if (result == null) { break; } numRows++; numCells += result.rawCells().length; } scanTimer.stop(); scanner.close(); table.close(); ScanMetrics metrics = ProtobufUtil.toScanMetrics(scan.getAttribute(Scan.SCAN_ATTRIBUTES_METRICS_DATA)); long totalBytes = metrics.countOfBytesInResults.get(); double throughput = (double) totalBytes / scanTimer.elapsedTime(TimeUnit.SECONDS); double throughputRows = (double) numRows / scanTimer.elapsedTime(TimeUnit.SECONDS); double throughputCells = (double) numCells / scanTimer.elapsedTime(TimeUnit.SECONDS); System.out.println("HBase scan: "); System.out.println("total time to open table: " + tableOpenTimer.elapsedMillis() + " ms"); System.out.println("total time to open scanner: " + scanOpenTimer.elapsedMillis() + " ms"); System.out.println("total time to scan: " + scanTimer.elapsedMillis() + " ms"); System.out.println("Scan metrics:\n" + metrics.getMetricsMap()); System.out.println( "total bytes: " + totalBytes + " bytes (" + StringUtils.humanReadableInt(totalBytes) + ")"); System.out.println("throughput : " + StringUtils.humanReadableInt((long) throughput) + "B/s"); System.out.println("total rows : " + numRows); System.out.println("throughput : " + StringUtils.humanReadableInt((long) throughputRows) + " rows/s"); System.out.println("total cells : " + numCells); System.out.println("throughput : " + StringUtils.humanReadableInt((long) throughputCells) + " cells/s"); }
From source file:com.twitter.hraven.rest.RestJSONResource.java
@GET @Path("job/{cluster}/{jobId}") @Produces(MediaType.APPLICATION_JSON)/*from ww w . j av a 2 s . com*/ public JobDetails getJobById(@PathParam("cluster") String cluster, @PathParam("jobId") String jobId, @QueryParam("include") List<String> includeFields) throws IOException { LOG.info("Fetching JobDetails for jobId=" + jobId); Stopwatch timer = new Stopwatch().start(); Predicate<String> includeFilter = null; if (includeFields != null && !includeFields.isEmpty()) { includeFilter = new SerializationContext.FieldNameFilter(includeFields); } serializationContext.set(new SerializationContext(SerializationContext.DetailLevel.EVERYTHING, null, null, includeFilter, null)); JobDetails jobDetails = getJobHistoryService().getJobByJobID(cluster, jobId); timer.stop(); if (jobDetails != null) { LOG.info("For job/{cluster}/{jobId} with input query:" + " job/" + cluster + SLASH + jobId + "&" + StringUtil.buildParam("include", includeFields) + " fetched jobDetails for " + jobDetails.getJobName() + " in " + timer); } else { LOG.info("For job/{cluster}/{jobId} with input query:" + " job/" + cluster + SLASH + jobId + "&" + StringUtil.buildParam("include", includeFields) + " No jobDetails found, but spent " + timer); } // export latency metrics HravenResponseMetrics.JOB_API_LATENCY_VALUE.set(timer.elapsed(TimeUnit.MILLISECONDS)); return jobDetails; }
From source file:yaphyre.raytracer.RayTracer.java
/** * The real rendering loop. This takes the given camera and renders the scene from its view. Notice: This method does * no rendering on its own, but calls the {@link #renderWindow(yaphyre.core.Camera, Sampler, RenderWindow, * Transformation)} method which renders a part of the image designated by the given {@link RenderWindow}.<br/> This * method is responsible for preparing the rendering and managing the multi-threaded execution of the rendering * process.// w ww . j av a 2s. c o m * * @param camera The {@link Camera} to render the scene for. */ private void render(Camera camera) { this.camera = camera; int imageWidth = this.camera.getFilm().getXResolution(); int imageHeight = this.camera.getFilm().getYResolution(); LOGGER.info("{}", scene); if (sampler == null) { LOGGER.warn("No sampler set -> initializing default sampler: {}", SinglePointSampler.class.getSimpleName()); sampler = new SinglePointSampler(); } // TODO move this transformation into the camera Transformation rasterToCamera = Transformation.rasterToUnitSquare(imageWidth, imageHeight); Stopwatch overallTime = new Stopwatch(); long cpuTime; if (useSingleTreadedRendering) { cpuTime = renderSingleThreaded(imageWidth, imageHeight, rasterToCamera, overallTime); } else { cpuTime = renderMultiThreaded(imageWidth, imageHeight, rasterToCamera, overallTime); } printRenderStatistics(overallTime.elapsedMillis(), cpuTime); }
From source file:co.cask.cdap.examples.wordcount.RetrieveCountsHandler.java
/** * Returns the counts for all words in the input. The request body is expected to contain * a comma-separated list of words./*from w ww . j a v a 2 s . co m*/ */ @Path("counts") @POST public void getCounts(HttpServiceRequest request, HttpServiceResponder responder) { String wordString = Charsets.UTF_8.decode(request.getContent()).toString(); String[] words = wordString.split(","); Map<String, Long> wordCounts = Maps.newHashMap(); Stopwatch timer = new Stopwatch().start(); for (int i = 0; i < words.length; i++) { byte[] countBytes = wordCountsTable.read(Bytes.toBytes(words[i])); long count = countBytes != null ? Bytes.toLong(countBytes) : 0; wordCounts.put(words[i], count); } timer.stop(); Map<String, Object> responseBody = Maps.newHashMap(); responseBody.put("counts", wordCounts); responseBody.put("elapsed", timer.toString()); responder.sendJson(responseBody); }
From source file:org.n52.lod.csw.CSWLoDEnabler.java
/** * executes the program: 1.) retrieves the record descriptions from the CSW * 2.) transforms the descriptions to RDF 3.) inserts the produced RDF into * the triplestore/*from w w w.ja va 2 s . c o m*/ * * @param startPos * * @throws IOException */ public void runStartingFrom(int startPos) throws IOException { log.info("STARTING CSW to LOD.."); if (!(addToServer || saveToFile)) { log.warn("Neither triple store nor file output are activated."); return; } final Stopwatch overallTimer = new Stopwatch(); overallTimer.start(); final Stopwatch retrievingTimer = new Stopwatch(); final Stopwatch mappingTimer = new Stopwatch(); final Stopwatch otherTimer = new Stopwatch(); otherTimer.start(); XmlToRdfMapper mapper = new GluesMapper(config); TripleSink serverSink = null; if (addToServer) { try { serverSink = new VirtuosoServer(config, mapper); } catch (RuntimeException e) { log.error("Could not connect to graph", e); } } TripleSink fileSink = null; if (saveToFile) { fileSink = new FileTripleSink(mapper); } long recordsInTotal = FALLBACK_RECORDS_TOTAL; try { recordsInTotal = csw.getNumberOfRecords(); log.debug("Retrieved number of records from server: {}", recordsInTotal); } catch (IllegalStateException | HttpClientException | XmlException e) { log.error("Could not retrieve number of records from catalog {}, falling back to {}", csw, FALLBACK_RECORDS_TOTAL, e); } report.startIndex = startPos; report.recordNumber = recordsInTotal; otherTimer.stop(); // main loop while (startPos < recordsInTotal) { retrievingTimer.start(); Map<String, GetRecordByIdResponseDocument> records = retrieveRecords(startPos, NUMBER_OF_RECORDS_PER_ITERATION, recordsInTotal); retrievingTimer.stop(); mappingTimer.start(); if (addToServer && serverSink != null) serverSink.addRecords(records, report); if (saveToFile && fileSink != null) fileSink.addRecords(records, report); mappingTimer.stop(); startPos = startPos + NUMBER_OF_RECORDS_PER_ITERATION; log.debug("Finished intermediate run at {}", overallTimer.toString()); } // end of main loop otherTimer.start(); if (fileSink != null) try { fileSink.close(); } catch (Exception e) { log.error("Could not close file sink {}", fileSink, e); } if (serverSink != null) try { serverSink.close(); } catch (Exception e) { log.error("Could not close server sink {}", serverSink, e); } if (!report.issues.isEmpty()) log.error(report.extendedToString()); overallTimer.stop(); otherTimer.stop(); log.info("DONE with CSW to LOD.. duration = {} (retrieving: {}, mapping = {}, other = {})", overallTimer, retrievingTimer, mappingTimer, otherTimer); log.info("Results: {}", report); log.info("Sinks: server = {}, file = {}", addToServer, saveToFile); log.info("Server: {} | File: {}", serverSink, fileSink); }