Example usage for com.google.common.base Stopwatch stop

List of usage examples for com.google.common.base Stopwatch stop

Introduction

In this page you can find the example usage for com.google.common.base Stopwatch stop.

Prototype

public Stopwatch stop() 

Source Link

Document

Stops the stopwatch.

Usage

From source file:com.vmware.photon.controller.apife.backends.VmDcpBackend.java

@Override
public void tombstone(VmEntity vm) throws ExternalException {
    Stopwatch tombstoneWatch = Stopwatch.createStarted();
    String resourceTickedId = projectBackend.findById(vm.getProjectId()).getResourceTicketId();
    ImageEntity image = null;//from  w ww  .  j ava2  s  .  co  m
    if (StringUtils.isNotBlank(vm.getImageId())) {
        image = imageBackend.findById(vm.getImageId());
    }

    FlavorEntity flavor = null;
    if (StringUtils.isNotBlank(vm.getFlavorId())) {
        flavor = flavorBackend.getEntityById(vm.getFlavorId());
    }

    List<NetworkEntity> networkList = new LinkedList<>();
    if (null != vm.getNetworks()) {
        for (String network : vm.getNetworks()) {
            networkList.add(networkBackend.findById(network));
        }
    }

    Stopwatch resourceTicketWatch = Stopwatch.createStarted();
    resourceTicketBackend.returnQuota(resourceTickedId, new QuotaCost(vm.getCost()));
    resourceTicketWatch.stop();
    logger.info("VmSqlBackend.tombstone for Vm Id: {}, resourceTicket {}, returnQuota in {} milliseconds",
            vm.getId(), resourceTickedId, resourceTicketWatch.elapsed(TimeUnit.MILLISECONDS));

    tombstoneBackend.create(Vm.KIND, vm.getId());

    dcpClient.delete(VmServiceFactory.SELF_LINK + "/" + vm.getId(), new VmService.State());

    for (AttachedDiskEntity attachedDisk : attachedDiskBackend.findByVmId(vm.getId())) {
        attachedDiskBackend.deleteAttachedDiskById(attachedDisk.getId());
    }

    if (image != null && ImageState.PENDING_DELETE.equals(image.getState())) {
        imageBackend.tombstone(image);
    }

    if (flavor != null && FlavorState.PENDING_DELETE.equals(flavor.getState())) {
        flavorBackend.tombstone(flavor);
    }

    for (NetworkEntity network : networkList) {
        if (NetworkState.PENDING_DELETE.equals(network.getState())) {
            networkBackend.tombstone(network);
        }
    }

    tombstoneWatch.stop();
    logger.info("VmDcpBackend.tombstone for Vm Id: {} took {} milliseconds", vm.getId(),
            tombstoneWatch.elapsed(TimeUnit.MILLISECONDS));
}

From source file:com.twitter.hraven.rest.RestJSONResource.java

@GET
@Path("job/{cluster}/{jobId}")
@Produces(MediaType.APPLICATION_JSON)//from   ww  w . java  2s . c  o m
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:com.vmware.photon.controller.apife.backends.VmDcpBackend.java

private VmEntity create(ProjectEntity project, VmCreateSpec spec) throws ExternalException {
    Stopwatch createWatch = Stopwatch.createStarted();
    FlavorEntity flavorEntity = flavorBackend.getEntityByNameAndKind(spec.getFlavor(), Vm.KIND);
    if (!FlavorState.READY.equals(flavorEntity.getState())) {
        throw new InvalidFlavorStateException(
                String.format("Create vm using flavor with name: %s is in invalid state %s.",
                        flavorEntity.getName(), flavorEntity.getState()));
    }//from  w w  w. j a  va2 s .co  m

    VmService.State vm = new VmService.State();

    vm.name = spec.getName();
    vm.flavorId = flavorEntity.getId();
    List<QuotaLineItemEntity> cost = new ArrayList<>(flavorEntity.getCost());
    for (QuotaLineItemEntity quotaLineItemEntity : cost) {
        QuotaLineItem quotaLineItem = new QuotaLineItem();
        quotaLineItem.setKey(quotaLineItemEntity.getKey());
        quotaLineItem.setValue(quotaLineItemEntity.getValue());
        quotaLineItem.setUnit(quotaLineItemEntity.getUnit());

        if (vm.cost == null) {
            vm.cost = new ArrayList<>();
        }
        vm.cost.add(quotaLineItem);
    }

    vm.tags = new HashSet<>();
    if (spec.getTags() != null) {
        for (String tagText : spec.getTags()) {
            vm.tags.add(tagText);
        }
    }

    vm.networks = spec.getNetworks();

    ImageEntity image = imageBackend.findById(spec.getSourceImageId());

    if (!ImageState.READY.equals(image.getState())) {
        throw new InvalidImageStateException(
                String.format("Image %s is in %s state", image.getId(), image.getState()));
    }

    vm.imageId = image.getId();
    List<Throwable> warnings = new ArrayList<>();
    updateBootDiskCapacity(spec.getAttachedDisks(), image, warnings);

    vm.projectId = project.getId();
    vm.vmState = VmState.CREATING;

    String resourceTickedId = project.getResourceTicketId();

    Stopwatch resourceTicketWatch = Stopwatch.createStarted();
    resourceTicketBackend.consumeQuota(resourceTickedId, new QuotaCost(cost));
    resourceTicketWatch.stop();
    logger.info("VmDcpBackend.create for Vm Name: {}, resourceTicket {}, consumeQuota in {} milliseconds",
            vm.name, resourceTickedId, resourceTicketWatch.elapsed(TimeUnit.MILLISECONDS));

    vm.affinities = spec.getAffinities();

    com.vmware.xenon.common.Operation createOperation = dcpClient.post(VmServiceFactory.SELF_LINK, vm);
    VmService.State createdVm = createOperation.getBody(VmService.State.class);

    VmEntity vmEntity = toVmEntity(createdVm);

    //set transient properties of vm entity
    vmEntity.setAttachedDisks(attachedDiskBackend.createAttachedDisks(vmEntity, spec.getAttachedDisks()));
    vmEntity.setWarnings(warnings);
    vmEntity.setEnvironment(spec.getEnvironment());

    createWatch.stop();
    logger.info("VmDcpBackend.create for Vm Id: {} and name: {} took {} milliseconds", vmEntity.getId(),
            vm.name, createWatch.elapsed(TimeUnit.MILLISECONDS));

    return vmEntity;
}

From source file:org.hawkular.metrics.core.util.GCGraceSecondsManager.java

/**
 * Asynchronously performs gc_grace_seconds updates if necessary. This method should <strong>not</strong> be called
 * until schema updates have finished./*from  www. j a va  2s  .  co m*/
 */
public void maybeUpdateGCGraceSeconds() {
    logger.info("Checking tables in " + keyspace + " to see if gc_grace_seconds needs to be updated");
    Stopwatch stopwatch = Stopwatch.createStarted();
    Map<String, String> replication = session.getCluster().getMetadata().getKeyspace(keyspace).getReplication();
    String replicationFactor = replication.get("replication_factor");
    Completable check;

    if (getClusterSize() == 1 || replicationFactor.equals("1")) {
        check = updateAllGCGraceSeconds(0);
    } else {
        // Need to call Completable.merge in order for subscriptions to happen correctly. See https://goo.gl/l15CRV
        check = Completable.merge(configurationService.load("org.hawkular.metrics", "gcGraceSeconds")
                .switchIfEmpty(Observable.just(Integer.toString(DEFAULT_GC_GRACE_SECONDS))).map(property -> {
                    int gcGraceSeconds = Integer.parseInt(property);
                    return updateAllGCGraceSeconds(gcGraceSeconds);
                }));
    }

    check.subscribe(() -> {
        stopwatch.stop();
        logger.info("Finished gc_grace_seconds updates in " + stopwatch.elapsed(TimeUnit.MILLISECONDS) + " ms");
        updatesFinished.ifPresent(subject -> subject.onNext(null));
    }, t -> {
        logger.warn("There was an error checking and updating gc_grace_seconds");
        updatesFinished.ifPresent(subject -> subject.onNext(t));
    });
}

From source file:org.apache.distributedlog.BKLogHandler.java

public CompletableFuture<LogRecordWithDLSN> asyncReadLastRecord(final LogSegmentMetadata l, final boolean fence,
        final boolean includeControl, final boolean includeEndOfStream) {
    final AtomicInteger numRecordsScanned = new AtomicInteger(0);
    final Stopwatch stopwatch = Stopwatch.createStarted();
    return ReadUtils.asyncReadLastRecord(getFullyQualifiedName(), l, fence, includeControl, includeEndOfStream,
            firstNumEntriesPerReadLastRecordScan, maxNumEntriesPerReadLastRecordScan, numRecordsScanned,
            scheduler, entryStore).whenComplete(new FutureEventListener<LogRecordWithDLSN>() {
                @Override//from  w  w w.  j a  va  2  s .c  o  m
                public void onSuccess(LogRecordWithDLSN value) {
                    recoverLastEntryStats.registerSuccessfulEvent(
                            stopwatch.stop().elapsed(TimeUnit.MICROSECONDS), TimeUnit.MICROSECONDS);
                    recoverScannedEntriesStats.registerSuccessfulValue(numRecordsScanned.get());
                }

                @Override
                public void onFailure(Throwable cause) {
                    recoverLastEntryStats.registerFailedEvent(stopwatch.stop().elapsed(TimeUnit.MICROSECONDS),
                            TimeUnit.MICROSECONDS);
                }
            });
}

From source file:org.balloon_project.overflight.task.indexing.IndexingTask.java

private void dumpIndexedTriples(List<Triple> results) throws IOException {
    Stopwatch storeTimer = Stopwatch.createStarted();

    if (results.size() > 0) {
        BufferedWriter writer = new BufferedWriter(new FileWriter(file, true));

        try {//from w w w.  jav  a2 s  .com
            for (Triple triple : results) {
                StringBuilder sb = new StringBuilder();
                sb.append("<").append(triple.getSubject()).append("> <")
                        .append(triple.getRelEntity().getPredicate()).append("> <").append(triple.getObject())
                        .append(">.\n");
                writer.append(sb.toString());
            }
        } finally {
            writer.flush();
            writer.close();
        }
    }

    logger.debug(this.endpoint.getEndpointID() + ": Intermediate result persisted (Size = " + results.size()
            + ") Continue query process" + " (save duration: "
            + storeTimer.stop().elapsed(TimeUnit.MILLISECONDS) + " ms) predicate " + relEntity.getPredicate());
}

From source file:de.blizzy.documentr.markdown.macro.impl.NeighborsMacro.java

@Override
public String getHtml(IMacroContext macroContext) {

    htmlSerializerContext = macroContext.getHtmlSerializerContext();
    path = htmlSerializerContext.getPagePath();
    if (path != null) {
        Map<String, String> params = Util.parseParameters(macroContext.getParameters());
        try {//w  ww  .  ja va 2s.co m
            String childrenStr = StringUtils.defaultIfBlank(params.get("children"), "1"); //$NON-NLS-1$ //$NON-NLS-2$
            if (childrenStr.equals("all")) { //$NON-NLS-1$
                maxChildren = Integer.MAX_VALUE;
            } else {
                maxChildren = Integer.parseInt(childrenStr);
                maxChildren = Math.max(maxChildren, 1);
            }
        } catch (NumberFormatException e) {
            maxChildren = 1;
        }

        pageStore = macroContext.getPageStore();
        permissionEvaluator = macroContext.getPermissionEvaluator();
        locale = macroContext.getLocale();
        messageSource = macroContext.getMessageSource();
        projectName = htmlSerializerContext.getProjectName();
        branchName = htmlSerializerContext.getBranchName();

        Authentication authentication = htmlSerializerContext.getAuthentication();
        reorderAllowed = (locale != null) && (messageSource != null) && permissionEvaluator
                .hasBranchPermission(authentication, projectName, branchName, Permission.EDIT_PAGE);

        if (log.isInfoEnabled()) {
            log.info("rendering neighbors for page: {}/{}/{}, user: {}", //$NON-NLS-1$
                    projectName, branchName, Util.toUrlPagePath(path), authentication.getName());
        }

        Stopwatch stopwatch = new Stopwatch().start();
        try {
            StringBuilder buf = new StringBuilder();
            Page page = getPage(path);
            buf.append("<span class=\"well well-small neighbors pull-right\"><ul class=\"nav nav-list\">") //$NON-NLS-1$
                    .append(printParent(printLinkListItem(page, 1, maxChildren), path));
            if ((locale != null) && (messageSource != null)) {
                String hoverInfoText = messageSource.getMessage("neighborsItemsHoverExpandHelp", null, locale); //$NON-NLS-1$
                buf.append("<div class=\"hover-help\">").append(hoverInfoText).append("</div>"); //$NON-NLS-1$ //$NON-NLS-2$
            }
            buf.append("</ul></span>"); //$NON-NLS-1$
            return buf.toString();
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            log.trace("rendering neighbors took {} ms", stopwatch.stop().elapsed(TimeUnit.MILLISECONDS)); //$NON-NLS-1$
        }
    } else {
        return null;
    }
}

From source file:com.twitter.hraven.rest.RestJSONResource.java

@GET
@Path("appVersion/{cluster}/{user}/{appId}/")
@Produces(MediaType.APPLICATION_JSON)//  w  w w. j  av a  2 s  .  c  om
public List<VersionInfo> getDistinctVersions(@PathParam("cluster") String cluster,
        @PathParam("user") String user, @PathParam("appId") String appId, @QueryParam("limit") int limit)
        throws IOException {
    Stopwatch timer = new Stopwatch().start();

    if (LOG.isTraceEnabled()) {
        LOG.trace("Fetching App Versions for cluster=" + cluster + " user=" + user + " app=" + appId);
    }
    serializationContext.set(new SerializationContext(SerializationContext.DetailLevel.EVERYTHING));
    List<VersionInfo> distinctVersions = serviceThreadLocalAppVersion.get().getDistinctVersions(
            StringUtils.trimToEmpty(cluster), StringUtils.trimToEmpty(user), StringUtils.trimToEmpty(appId));
    timer.stop();

    LOG.info("For appVersion/{cluster}/{user}/{appId}/ with input query " + "appVersion/" + cluster + SLASH
            + user + SLASH + appId + "?limit=" + limit + " fetched #number of VersionInfo "
            + distinctVersions.size() + " in ");//+ timer);

    // export latency metrics
    HravenResponseMetrics.APPVERSIONS_API_LATENCY_VALUE.set(timer.elapsed(TimeUnit.MILLISECONDS));
    return distinctVersions;
}

From source file:com.google.api.ads.adwords.awalerting.processor.AlertProcessor.java

/**
 * Generate all the alerts for the given account IDs under the manager account.
 *
 * @param clientCustomerIds the client customer IDs
 * @param alertsConfig the JSON config of the alerts
 *//*from  w  ww.j  a v a2  s .  c o m*/
public void generateAlerts(Set<Long> clientCustomerIds, JsonObject alertsConfig)
        throws AlertConfigLoadException, AlertProcessingException {
    Stopwatch stopwatch = Stopwatch.createStarted();

    ImmutableAdWordsSession session = null;
    try {
        session = authenticator.authenticate();
    } catch (OAuthException e) {
        throw new AlertConfigLoadException("Failed to authenticate AdWordsSession.", e);
    } catch (ValidationException e) {
        throw new AlertConfigLoadException("Failed to build AdWordsSession.", e);
    }

    if (clientCustomerIds == null) {
        clientCustomerIds = retrieveClientCustomerIds(session);

        // Write the client customer IDs into debug log.
        LOGGER.debug("Client customer IDs retrieved:{}{}", SEPARATOR,
                Joiner.on(SEPARATOR).join(clientCustomerIds));
    }

    int count = 0;
    for (JsonElement alertConfig : alertsConfig.getAsJsonArray(ConfigTags.ALERTS)) {
        count++;
        processAlert(clientCustomerIds, session, alertConfig.getAsJsonObject(), count);
    }

    stopwatch.stop();
    LOGGER.info("*** Finished all processing in {} seconds ***",
            stopwatch.elapsed(TimeUnit.MILLISECONDS) / 1000);
}

From source file:io.dropwizard.revolver.core.RevolverCommand.java

@SuppressWarnings("unchecked")
public ResponseType execute(final RequestType request) throws RevolverExecutionException, TimeoutException {
    final CommandHandlerConfigType apiConfiguration = this.apiConfigurations.get(request.getApi());
    if (null == apiConfiguration) {
        throw new RevolverExecutionException(RevolverExecutionException.Type.BAD_REQUEST,
                "No api spec defined for key: " + request.getApi());
    }//from w  w  w.  j  ava  2 s .  c o  m
    final RequestType normalizedRequest = RevolverCommandHelper.normalize(request);
    final TraceInfo traceInfo = normalizedRequest.getTrace();
    addContextInfo(request, traceInfo);
    final Stopwatch watch = Stopwatch.createStarted();
    String errorMessage = null;
    try {
        ResponseType response = (ResponseType) new RevolverCommandHandler(
                RevolverCommandHelper.setter(this, request.getApi()), this.context, this, normalizedRequest)
                        .execute();
        log.debug("Command response: " + response);
        return response;
    } catch (Throwable t) {
        val rootCause = ExceptionUtils.getRootCause(t);
        if (rootCause instanceof TimeoutException) {
            throw (TimeoutException) rootCause;
        }
        errorMessage = rootCause.getLocalizedMessage();
        throw new RevolverExecutionException(RevolverExecutionException.Type.SERVICE_ERROR, rootCause);
    } finally {
        publishTrace(Trace.builder().caller(this.clientConfiguration.getClientName())
                .service(this.serviceConfiguration.getService()).api(apiConfiguration.getApi())
                .duration(watch.stop().elapsed(TimeUnit.MILLISECONDS))
                .transactionId(traceInfo.getTransactionId()).requestId(traceInfo.getRequestId())
                .parentRequestId(traceInfo.getParentRequestId()).timestamp(traceInfo.getTimestamp())
                .attributes(traceInfo.getAttributes()).error(!Strings.isNullOrEmpty(errorMessage))
                .errorReason(errorMessage).build());
    }
}