Example usage for org.joda.time Duration getMillis

List of usage examples for org.joda.time Duration getMillis

Introduction

In this page you can find the example usage for org.joda.time Duration getMillis.

Prototype

public long getMillis() 

Source Link

Document

Gets the length of this duration in milliseconds.

Usage

From source file:com.solidfire.core.serialization.DurationAdapter.java

License:Open Source License

/**
 * Writes a Duration object./*from   w  w w  .  j a  v  a2 s .  co m*/
 *
 * @param writer the JSON writer to write to.
 * @param value  the Duration object to write.
 * @throws IOException
 */
@Override
public void write(JsonWriter writer, Duration value) throws IOException {
    long total = value.getMillis();
    String neg = total < 0 ? "-" : "";
    if (total < 0)
        total = -total;
    long millis = total % 1000;
    total /= 1000;
    long seconds = total % 60;
    total /= 60;
    long minutes = total % 60;
    total /= 60;
    long hours = total;
    writer.value(String.format("%s%02d:%02d:%02d.%03d000", neg, hours, minutes, seconds, millis));
}

From source file:com.spotify.scio.bigtable.BigtableUtil.java

License:Apache License

/**
 * Updates all clusters within the specified Bigtable instance to a specified number of nodes.
 * Useful for increasing the number of nodes at the beginning of a job and decreasing it at
 * the end to lower costs yet still get high throughput during bulk ingests/dumps.
 *
 * @param bigtableOptions Bigtable Options
 * @param numberOfNodes New number of nodes in the cluster
 * @param sleepDuration How long to sleep after updating the number of nodes. Google recommends
 *                      at least 20 minutes before the new nodes are fully functional
 * @throws IOException If setting up channel pool fails
 * @throws InterruptedException If sleep fails
 *//*from w w  w . j a v  a  2s . co m*/
public static void updateNumberOfBigtableNodes(final BigtableOptions bigtableOptions, final int numberOfNodes,
        final Duration sleepDuration) throws IOException, InterruptedException {
    final ChannelPool channelPool = ChannelPoolCreator.createPool(bigtableOptions.getInstanceAdminHost());

    try {
        final BigtableInstanceClient bigtableInstanceClient = new BigtableInstanceGrpcClient(channelPool);

        final String instanceName = bigtableOptions.getInstanceName().toString();

        // Fetch clusters in Bigtable instance
        final ListClustersRequest clustersRequest = ListClustersRequest.newBuilder().setParent(instanceName)
                .build();
        final ListClustersResponse clustersResponse = bigtableInstanceClient.listCluster(clustersRequest);

        // For each cluster update the number of nodes
        for (Cluster cluster : clustersResponse.getClustersList()) {
            final Cluster updatedCluster = Cluster.newBuilder().setName(cluster.getName())
                    .setServeNodes(numberOfNodes).build();
            LOG.info("Updating number of nodes to {} for cluster {}", numberOfNodes, cluster.getName());
            bigtableInstanceClient.updateCluster(updatedCluster);
        }

        // Wait for the new nodes to be provisioned
        if (sleepDuration.getMillis() > 0) {
            LOG.info("Sleeping for {} after update", formatter.print(sleepDuration.toPeriod()));
            Thread.sleep(sleepDuration.getMillis());
        }
    } finally {
        channelPool.shutdownNow();
    }
}

From source file:com.studium.joda.converters.JodaDurationConverter.java

License:Apache License

public Long convertToDatabaseColumn(Duration duration) {
    return duration == null ? null : duration.getMillis();
}

From source file:com.teamlazerbeez.crm.sf.soap.BindingConfigurer.java

License:Apache License

/**
 * Use the binding to get the config data for the org that the username and password points to..
 *
 * @param username      the username to log in with
 * @param password      the password to log in with
 * @param binding       the Soap binding to configure
 * @param callSemaphore the call semaphore to use when logging in
 * @param sandboxOrg    true if this is a login to a sandbox org
 *
 * @return a result object containing a few useful bits of info discovered during the login process
 *
 * @throws ApiException if login fails/*from w  w  w  .  jav  a 2 s .com*/
 */
@Nonnull
BindingConfig loginAndGetBindingConfigData(@Nonnull String username, @Nonnull String password,
        @Nonnull Soap binding, @Nonnull CallSemaphore callSemaphore, boolean sandboxOrg) throws ApiException {
    Login loginParam = new Login();
    loginParam.setPassword(password);
    loginParam.setUsername(username);

    // Get a BindingProvider ref to the port
    WSBindingProvider wsBindingProvider = (WSBindingProvider) binding;

    // reset initial endpoint

    if (sandboxOrg) {
        wsBindingProvider.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY,
                SANDBOX_INITIAL_ENDPOINT);
    } else {
        wsBindingProvider.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY,
                NORMAL_INITIAL_ENDPOINT);
    }

    logger.trace("Using initial endpoint: "
            + wsBindingProvider.getRequestContext().get(BindingProvider.ENDPOINT_ADDRESS_PROPERTY));

    // reset headers to just be CallOptions
    CallOptions callOpts = new CallOptions();
    callOpts.setClient(this.partnerKey);
    wsBindingProvider.setOutboundHeaders(Headers.create(this.partnerJaxbContext, callOpts));
    this.configureRequestContextConnectionParams(wsBindingProvider);

    try {
        callSemaphore.acquire();
    } catch (InterruptedException e) {
        // we're not throwing a raw InterruptedException, so re-interrupt the thread for later detection
        Thread.currentThread().interrupt();
        throw ApiException.getNewWithCause("Interrupted while getting a call token to make the login call",
                username, e);
    }

    DateTime start = new DateTime();

    LoginResponse response;
    try {
        response = binding.login(loginParam);
    } catch (InvalidIdFault_Exception e) {
        throw ApiException.getNewWithCauseAndStubApiFault("Invalid Id", username, e, e.getFaultInfo());
    } catch (LoginFault_Exception e) {
        throw ApiException.getNewWithCauseAndStubApiFault("Bad credentials for user '" + username + "'",
                username, e, e.getFaultInfo());
    } catch (UnexpectedErrorFault_Exception e) {
        throw ApiException.getNewWithCauseAndStubApiFault("Unexpected error", username, e, e.getFaultInfo());
    } catch (WebServiceException e) {
        throw ApiException.getNewWithCause("Web Service exception", username, e);
    } finally {
        callSemaphore.release();

        DateTime finish = new DateTime();
        Duration duration = new Duration(start, finish);

        long actualDuration = duration.getMillis();
        if (actualDuration > EXPECTED_LOGIN_DURATION) {
            logger.warn("Login took " + actualDuration + "ms, expected to take no more than "
                    + EXPECTED_LOGIN_DURATION + "ms, user = " + username);
        } else {
            logger.trace("Login took " + actualDuration);
        }
    }

    LoginResultType loginResult = response.getResult();
    logger.debug("User " + username + " using partner endpoint " + loginResult.getServerUrl());

    // don't bother checking if the password is expired; wait for them to try and do something
    // with it...

    Id orgId = new Id(loginResult.getUserInfo().getOrganizationId());
    String sessionId = loginResult.getSessionId();

    return new BindingConfig(orgId, sessionId, loginResult.getServerUrl(), loginResult.getMetadataServerUrl(),
            username);
}

From source file:com.thoughtworks.go.server.ui.JobInstanceModel.java

License:Apache License

public int getPercentComplete() {
    Duration eta = eta();
    if (eta.getMillis() == 0) {
        return 0;
    }/*w  w  w . j a v  a  2  s.  c  o  m*/
    if (eta.isShorterThan(getElapsedTime())) {
        return 100;
    }
    return (int) ((getElapsedTime().getMillis() * 100) / eta.getMillis());
}

From source file:com.tkmtwo.timex.WallClock.java

License:Apache License

/**
 * Returns a copy of this <code>WallClock</code> plus
 * the specified <code>Duration</code>.
 * <p>//from   w ww.j  a va2  s .com
 *
 *
 * @param d an <code>Duration</code> representing the amount of time
 * @param rm a <code>RoundingMode</code> used to deal with long to int division
 * @return a <code>WallClock</code> value
 */
public WallClock plus(Duration d, RoundingMode rm) {
    checkNotNull(d, "Need a Duration.");
    checkNotNull(rm, "Need a RoundingMode.");
    return plus(Ints.checkedCast(LongMath.divide(d.getMillis(), 1000L, rm)));
}

From source file:com.tkmtwo.timex.WallClock.java

License:Apache License

/**
 * Returns a copy of this <code>WallClock</code> minus
 * the specified <code>Duration</code>.
 * <p>// ww  w .  j ava 2s.c om
 *
 *
 * @param d an <code>Duration</code> representing the amount of time
 * @param rm a <code>RoundingMode</code> used to deal with long to int division
 * @return a <code>WallClock</code> value
 */
public WallClock minus(Duration d, RoundingMode rm) {
    checkNotNull(d, "Need a Duration.");
    checkNotNull(rm, "Need a RoundingMode.");
    return minus(Ints.checkedCast(LongMath.divide(d.getMillis(), 1000L, rm)));
}

From source file:com.tomtom.speedtools.metrics.MetricsCollector.java

License:Apache License

public MetricsCollector(@Nonnull final Duration totalMetricDuration, final int maxEntries) {
    assert totalMetricDuration != null;
    assert totalMetricDuration.isLongerThan(Duration.millis(1));
    assert maxEntries > 0;
    this.totalMetricDuration = totalMetricDuration;
    this.timeSlotDuration = Duration.millis(totalMetricDuration.getMillis() / maxEntries);
    this.values = new ArrayDeque<>();
}

From source file:com.tomtom.speedtools.testutils.resteasy.AsynchronousTestResponse.java

License:Apache License

/**
 * Verify that the resource invocation resulted in an entity-response within given time. The status code is verified
 * to be 200 (OK)./*from w  w w  .  jav  a 2 s .  c o m*/
 *
 * @param timeout Time out value.
 * @return Entity of the response.
 * @throws UnexpectedResponseException If error.
 */
@Nonnull
public T verifyEntity(@Nonnull final Duration timeout) throws UnexpectedResponseException {
    return verifyEntity(timeout.getMillis(), TimeUnit.MILLISECONDS);
}

From source file:com.tomtom.speedtools.testutils.resteasy.AsynchronousTestResponse.java

License:Apache License

/**
 * Verify that the resource invocation resulted in an entity-response within given time. Optionally the response
 * status code is checked simultaneously.
 *
 * @param expectedStatus When set, the expected status code of the response.
 * @param timeout        Time out value.
 * @return Entity of the response./*from  w  ww .  j ava  2s  .c  o m*/
 * @throws UnexpectedResponseException If error.
 */
@Nonnull
public T verifyEntity(@Nullable final Integer expectedStatus, @Nonnull final Duration timeout)
        throws UnexpectedResponseException {
    return verifyEntity(expectedStatus, timeout.getMillis(), TimeUnit.MILLISECONDS);
}