List of usage examples for com.google.common.base Stopwatch stop
public Stopwatch stop()
From source file:de.schildbach.wallet.data.DynamicFeeLiveData.java
private static void fetchDynamicFees(final HttpUrl url, final File tempFile, final File targetFile, final String userAgent) { final Stopwatch watch = Stopwatch.createStarted(); final Request.Builder request = new Request.Builder(); request.url(url);/*from w w w . j a v a 2s . c o m*/ request.header("User-Agent", userAgent); if (targetFile.exists()) request.header("If-Modified-Since", HttpDate.format(new Date(targetFile.lastModified()))); final OkHttpClient.Builder httpClientBuilder = Constants.HTTP_CLIENT.newBuilder(); httpClientBuilder.connectTimeout(5, TimeUnit.SECONDS); httpClientBuilder.writeTimeout(5, TimeUnit.SECONDS); httpClientBuilder.readTimeout(5, TimeUnit.SECONDS); final OkHttpClient httpClient = httpClientBuilder.build(); final Call call = httpClient.newCall(request.build()); try { final Response response = call.execute(); final int status = response.code(); if (status == HttpURLConnection.HTTP_NOT_MODIFIED) { log.info("Dynamic fees not modified at {}, took {}", url, watch); } else if (status == HttpURLConnection.HTTP_OK) { final ResponseBody body = response.body(); final FileOutputStream os = new FileOutputStream(tempFile); Io.copy(body.byteStream(), os); os.close(); final Date lastModified = response.headers().getDate("Last-Modified"); if (lastModified != null) tempFile.setLastModified(lastModified.getTime()); body.close(); if (!tempFile.renameTo(targetFile)) throw new IllegalStateException("Cannot rename " + tempFile + " to " + targetFile); watch.stop(); log.info("Dynamic fees fetched from {}, took {}", url, watch); } else { log.warn("HTTP status {} when fetching dynamic fees from {}", response.code(), url); } } catch (final Exception x) { log.warn("Problem when fetching dynamic fees rates from " + url, x); } }
From source file:org.apache.jackrabbit.oak.backup.FileStoreBackup.java
public static void backup(@Nonnull SegmentReader reader, @Nonnull Revisions revisions, @Nonnull File destination) throws IOException { Stopwatch watch = Stopwatch.createStarted(); SegmentGCOptions gcOptions = SegmentGCOptions.defaultGCOptions().setOffline(); FileStoreBuilder builder = fileStoreBuilder(destination).withDefaultMemoryMapping(); if (USE_FAKE_BLOBSTORE) { builder.withBlobStore(new BasicReadOnlyBlobStore()); }// ww w.ja v a 2s . c o m builder.withGCOptions(gcOptions); FileStore backup = builder.build(); SegmentNodeState current = reader.readHeadState(revisions); try { int gen = 0; gen = current.getRecordId().getSegment().getGcGeneration(); SegmentBufferWriter bufferWriter = new SegmentBufferWriter(backup, backup.getTracker(), backup.getReader(), "b", gen); SegmentWriter writer = new SegmentWriter(backup, backup.getReader(), backup.getBlobStore(), new WriterCacheManager.Default(), bufferWriter); Compactor compactor = new Compactor(backup.getReader(), writer, backup.getBlobStore(), Suppliers.ofInstance(false), gcOptions); compactor.setContentEqualityCheck(true); SegmentNodeState head = backup.getHead(); SegmentNodeState after = compactor.compact(head, current, head); if (after != null) { backup.getRevisions().setHead(head.getRecordId(), after.getRecordId()); } } finally { backup.close(); backup = null; } FileStoreBuilder builder2 = fileStoreBuilder(destination).withDefaultMemoryMapping(); builder2.withGCOptions(gcOptions); backup = builder2.build(); try { cleanup(backup); } finally { backup.close(); } watch.stop(); log.info("Backup finished in {}.", watch); }
From source file:com.google.api.ads.adwords.jaxws.extensions.processors.onfile.ReportProcessorOnFile.java
/** * Generate all the mapped reports to the given account IDs. * * @param dateRangeType the date range type. * @param dateStart the starting date.//from w w w.j a v a 2 s . c o m * @param dateEnd the ending date. * @param accountIdsSet the account IDs. * @param properties the properties file * @throws Exception error reaching the API. */ @Override public void generateReportsForMCC(String userId, String mccAccountId, ReportDefinitionDateRangeType dateRangeType, String dateStart, String dateEnd, Set<Long> accountIdsSet, Properties properties) throws Exception { LOGGER.info("*** Retrieving account IDs ***"); if (accountIdsSet == null || accountIdsSet.size() == 0) { accountIdsSet = this.retrieveAccountIds(userId, mccAccountId); } else { LOGGER.info("Accounts loaded from file."); } AdWordsSessionBuilderSynchronizer sessionBuilder = new AdWordsSessionBuilderSynchronizer( authenticator.authenticate(userId, mccAccountId, false)); LOGGER.info("*** Generating Reports for " + accountIdsSet.size() + " accounts ***"); Stopwatch stopwatch = Stopwatch.createStarted(); Set<ReportDefinitionReportType> reports = this.csvReportEntitiesMapping.getDefinedReports(); // reports for (ReportDefinitionReportType reportType : reports) { if (properties.containsKey(reportType.name())) { this.downloadAndProcess(userId, mccAccountId, sessionBuilder, reportType, dateRangeType, dateStart, dateEnd, accountIdsSet, properties); } } this.multipleClientReportDownloader.finalizeExecutorService(); stopwatch.stop(); LOGGER.info("*** Finished processing all reports in " + (stopwatch.elapsed(TimeUnit.MILLISECONDS) / 1000) + " seconds ***\n"); }
From source file:com.google.api.ads.adwords.awalerting.processor.AlertActionsProcessor.java
/** * Process the ReportData list with alert actions, all reports with each action per thread. * * @param reports the list of ReportData to run each alert action against. *///from w w w . jav a2 s . c o m public void processReports(List<ReportData> reports) throws AlertProcessingException { // Create one thread for each AlertAction, and process all reports Stopwatch stopwatch = Stopwatch.createStarted(); CountDownLatch latch = new CountDownLatch(actions.size()); ExecutorService executorService = Executors.newFixedThreadPool(numThreads); for (AlertAction action : actions) { RunnableAlertActionProcessor actionProcessor = new RunnableAlertActionProcessor(action, reports); executeRunnableAlertActionProcessor(executorService, actionProcessor, latch); } try { latch.await(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new AlertProcessingException("AlertActionsProcessor encounters InterruptedException.", e); } executorService.shutdown(); stopwatch.stop(); LOGGER.info("*** Processed {} actions on {} reports in {} seconds.", actions.size(), reports.size(), stopwatch.elapsed(TimeUnit.MILLISECONDS) / 1000); }
From source file:uk.ac.open.kmi.iserve.discovery.disco.impl.SparqlLogicConceptMatcher.java
/** * Obtains all the matching resources that have a MatchType with the URIs of {@code origin} of the type provided (inclusive) or more. * * @param origins URIs to match//from w ww.j a va 2s . c o m * @param minType the minimum MatchType we want to obtain * @return a {@link com.google.common.collect.Table} with the result of the matching indexed by origin URI and then destination URI. */ @Override public Table<URI, URI, MatchResult> listMatchesAtLeastOfType(Set<URI> origins, MatchType minType) { Table<URI, URI, MatchResult> matchTable = HashBasedTable.create(); Stopwatch w = new Stopwatch(); for (URI origin : origins) { w.start(); Map<URI, MatchResult> result = listMatchesAtLeastOfType(origin, minType); for (Map.Entry<URI, MatchResult> dest : result.entrySet()) { matchTable.put(origin, dest.getKey(), dest.getValue()); } log.debug("Computed matched types for {} in {}. {} total matches.", origin, w.stop().toString(), result.size()); w.reset(); } return matchTable; // return obtainMatchResults(origins, minType, this.getMatchTypesSupported().getHighest()); // TODO: Use the proper implementation for this }
From source file:org.sonatype.sisu.bl.support.DefaultBundle.java
/** * Starts application and waits for it to boot. if successfully started sets the state to running. * <p/>//from w ww .j a v a 2s.c o m * {@inheritDoc} * * @throws Exception if a problem occurred during startup of application, wait period or it could not determine if * application is started in specified timeout * @see Bundle#start() */ @Override public void doStart() { bootingTime = Time.millis(0); final Stopwatch bootingWatch = Stopwatch.createUnstarted(); try { startApplication(); running = true; getRunningBundles().add(this); bootingWatch.start(); waitForBoot(); } catch (RuntimeException e) { doStop(); throw e; } finally { if (bootingWatch.isRunning()) { bootingWatch.stop(); } bootingTime = Time.millis(bootingWatch.elapsed(TimeUnit.MILLISECONDS)); } }
From source file:org.hawkular.metrics.core.jobs.CompressData.java
@Override public Completable call(JobDetails jobDetails) { // Rewind to previous timeslice Stopwatch stopwatch = Stopwatch.createStarted(); logger.info("Starting execution"); long previousBlock = DateTimeService.getTimeSlice( new DateTime(jobDetails.getTrigger().getTriggerTime(), DateTimeZone.UTC).minus(DEFAULT_BLOCK_SIZE), DEFAULT_BLOCK_SIZE).getMillis(); Observable<? extends MetricId<?>> metricIds = metricsService.findAllMetrics().map(Metric::getMetricId) .filter(m -> (m.getType() == GAUGE || m.getType() == COUNTER || m.getType() == AVAILABILITY)); // Fetch all partition keys and compress the previous timeSlice return Completable.fromObservable(metricsService.compressBlock(metricIds, previousBlock) .doOnError(t -> logger.warn("Failed to compress data", t)).doOnCompleted(() -> { stopwatch.stop(); logger.info("Finished compressing data in " + stopwatch.elapsed(TimeUnit.MILLISECONDS) + " ms"); }));/*from w w w .j a v a2s .c o m*/ // TODO Optimization - new worker per token - use parallelism in Cassandra // Configure the amount of parallelism? }
From source file:com.github.steveash.jg2p.aligntag.AlignTagTrainer.java
private TransducerTrainer trainOnce(Pipe pipe, InstanceList trainData) { Stopwatch watch = Stopwatch.createStarted(); CRF crf = new CRF(pipe, null); crf.addOrderNStates(trainData, new int[] { 1 }, null, null, null, null, false); crf.addStartState();// w w w .ja v a 2 s . c om // crf.addStat(trainData); // crf.addFullyConnectedStatesForBiLabels(); // crf.addFullyConnectedStatesForLabels(); // crf.setWeightsDimensionAsIn(trainData, false); log.info("Starting training..."); CRFTrainerByThreadedLabelLikelihood trainer = new CRFTrainerByThreadedLabelLikelihood(crf, 8); trainer.setGaussianPriorVariance(2); trainer.train(trainData); trainer.shutdown(); watch.stop(); log.info("CRF Training took " + watch.toString()); return trainer; }
From source file:org.jenkinsci.plugins.vsphere.builders.PowerOn.java
private boolean powerOn(final Run<?, ?> run, Launcher launcher, final TaskListener listener) throws VSphereException, IOException, InterruptedException { PrintStream jLogger = listener.getLogger(); EnvVars env;/*from ww w . j a v a2s . c om*/ String expandedVm = vm; env = run.getEnvironment(listener); if (run instanceof AbstractBuild) { env.overrideAll(((AbstractBuild) run).getBuildVariables()); // Add in matrix axes.. expandedVm = env.expand(vm); } Stopwatch stopwatch = new Stopwatch().start(); vsphere.startVm(expandedVm, timeoutInSeconds); long elapsedTime = stopwatch.elapsedTime(TimeUnit.SECONDS); int secondsToWaitForIp = (int) (timeoutInSeconds - elapsedTime); IP = vsphere.getIp(vsphere.getVmByName(expandedVm), secondsToWaitForIp); if (IP == null) { VSphereLogger.vsLogger(jLogger, "Error: Timed out after waiting " + secondsToWaitForIp + " seconds to get IP for \"" + expandedVm + "\" "); return false; } VSphereLogger.vsLogger(jLogger, "Successfully retrieved IP for \"" + expandedVm + "\" : " + IP); stopwatch.stop(); // useful to tell user about the environment variable VSphereLogger.vsLogger(jLogger, "Exposing " + IP + " as environment variable VSPHERE_IP"); if (run instanceof AbstractBuild) { VSphereEnvAction envAction = new VSphereEnvAction(); envAction.add("VSPHERE_IP", IP); run.addAction(envAction); } else { env.put("VSPHERE_IP", IP); } return true; }
From source file:com.springer.omelet.mail.Email.java
@Override public List<Message> filerEmailsBySubject(List<Message> message, String emailSubject) { Stopwatch sw = new Stopwatch(); sw.start();/* ww w . j ava 2 s . c om*/ List<Message> returnMessage = new ArrayList<Message>(); LOGGER.info("Count of the message for filter by Subject" + message.size()); for (Message msg : message) { try { if (msg.getSubject().equalsIgnoreCase(emailSubject)) { returnMessage.add(msg); } } catch (MessagingException e) { // TODO Auto-generated catch block LOGGER.error(e); } } sw.stop(); LOGGER.info("Time Taken by Filter EmailBy Subjects is:" + sw.elapsedTime(TimeUnit.SECONDS)); return returnMessage; }