Example usage for java.util.concurrent TimeUnit toMillis

List of usage examples for java.util.concurrent TimeUnit toMillis

Introduction

In this page you can find the example usage for java.util.concurrent TimeUnit toMillis.

Prototype

public long toMillis(long duration) 

Source Link

Document

Equivalent to #convert(long,TimeUnit) MILLISECONDS.convert(duration, this) .

Usage

From source file:org.cloudifysource.esc.driver.provisioning.storage.aws.EbsStorageDriver.java

@Override
public void detachVolume(final String volumeId, final String ip, final long duration, final TimeUnit timeUnit)
        throws TimeoutException, StorageProvisioningException {

    final long end = System.currentTimeMillis() + timeUnit.toMillis(duration);
    NodeMetadata nodeMetadata = deployer.getServerWithIP(ip);

    try {//from   ww  w  .  j  av a 2s. c  o m
        logger.fine("Detaching volume with id " + volumeId + " from machine with id " + nodeMetadata.getId());
        this.ebsClient.detachVolumeInRegion(this.region, volumeId, false,
                DetachVolumeOptions.Builder.fromInstance(nodeMetadata.getProviderId()));
    } catch (Exception e) {
        logger.log(Level.WARNING, "Failed detaching node with id " + volumeId + " Reason: " + e.getMessage(),
                e);
        throw new StorageProvisioningException(
                "Failed detaching node with id " + volumeId + " Reason: " + e.getMessage(), e);
    }
    try {
        waitForVolumeToReachStatus(Status.AVAILABLE, end, volumeId);
    } catch (final TimeoutException e) {
        logger.warning("Timed out while waiting for volume[" + volumeId + "] to "
                + "become available after detachment. this may cause this volume to leak");
        throw e;
    }
}

From source file:net.pms.io.SimpleProcessWrapper.java

/**
 * Runs a process with the given command {@link List}.
 *
 * @param command an array of {@link String} used to build the command line.
 * @param timeout the process timeout in {@code timeUnit} after which the
 *            process is terminated. Use zero for no timeout, but be aware
 *            of the <a href=//from w  ww  . j  ava  2 s. c  o m
 *            "https://web.archive.org/web/20121201070147/http://kylecartmell.com/?p=9"
 *            >pitfalls</a>
 * @param timeUnit the {@link TimeUnit} for {@code timeout}.
 * @param terminateTimeoutMS the timeout in milliseconds to wait for each
 *            termination attempt.
 * @return The {@link ProcessWrapperResult} from running the process.
 * @throws InterruptedException If the operation is interrupted.
 * @throws IllegalArgumentException If {@code command} is {@code null} or
 *             empty.
 */
@Nonnull
public R runProcess(@Nonnull List<String> command, long timeout, @Nonnull TimeUnit timeUnit,
        long terminateTimeoutMS) throws InterruptedException {
    return runProcess(command, timeUnit.toMillis(timeout), terminateTimeoutMS);
}

From source file:com.amazon.kinesis.streaming.agent.tailing.FileTailer.java

/**
 * @param timeout Use a value {@code <= 0} to wait indefinitely.
 * @param unit/* w w w  .  ja  v a  2 s .  c  o m*/
 * @return {@code true} if idle state was reached before the timeout
 *         expired, or {@code false} if idle state was not successfully
 *         reached.
 */
public boolean waitForIdle(long timeout, TimeUnit unit) {
    Stopwatch timer = Stopwatch.createStarted();
    while (!isIdle()) {
        long remaining = timeout > 0 ? (unit.toMillis(timeout) - timer.elapsed(TimeUnit.MILLISECONDS))
                : Long.MAX_VALUE;
        if (remaining <= 0)
            return false;
        long sleepTime = Math.min(MAX_SPIN_WAIT_TIME_MILLIS, remaining);
        LOGGER.trace("{}: Waiting IDLE. Sleeping {}ms. {}", serviceName(), sleepTime, toString());
        publisher.flush();
        try {
            Thread.sleep(sleepTime);
        } catch (InterruptedException e) {
            // No need to make this method interruptible. Just return false signifying timeout.
            Thread.currentThread().interrupt();
            LOGGER.trace("{}: Thread interrupted while waiting for tailer to go idle.", serviceName(), e);
            return false;
        }
    }
    return true;
}

From source file:org.encos.flydown.limiters.cache.impl.RedisRatingCache.java

public long suspend(String suspensionKey, long suspensionTime, TimeUnit suspensionTimeUnit) {
    cacheTemplate.opsForValue().set(suspensionKey, System.currentTimeMillis());

    //suspending action for evaluationKey
    cacheTemplate.expire(suspensionKey, suspensionTime, suspensionTimeUnit);
    cacheTemplate.opsForList().leftPush(SUSPENSION_KEY_LIST, suspensionKey);
    log.info(MessageFormat.format("suspend({0}, {1}, {2})", suspensionKey, String.valueOf(suspensionTime),
            suspensionTimeUnit.name()));

    return suspensionTimeUnit.toMillis(suspensionTime);
}

From source file:net.pms.io.ThreadedProcessWrapper.java

/**
 * Runs a process with the given command array.
 *
 * @param timeout the process timeout in {@code timeUnit} after which the
 *            process is terminated. Use zero for no timeout, but be aware
 *            of the <a href=/* w  w  w .  ja  v a 2 s.  c o  m*/
 *            "https://web.archive.org/web/20121201070147/http://kylecartmell.com/?p=9"
 *            >pitfalls</a>
 * @param timeUnit the {@link TimeUnit} for {@code timeout}.
 * @param terminateTimeoutMS the timeout in milliseconds to wait for each
 *            termination attempt.
 * @param command the {@link String}s used to build the command line.
 * @return The {@link ProcessWrapperResult} from running the process.
 * @throws IllegalArgumentException If {@code command} is {@code null} or
 *             empty.
 */
@Nonnull
public Future<R> runProcess(long timeout, @Nonnull TimeUnit timeUnit, long terminateTimeoutMS,
        @Nonnull String... command) {
    return runProcess(Arrays.asList(command), timeUnit.toMillis(timeout), terminateTimeoutMS);
}

From source file:com.splicemachine.test_dao.JDBCTemplate.java

/**
 * Same as query() method in this class, but retries for up to the specified time.
 *//*from w  w w. ja  va2s  .  co m*/
public <T> List<T> queryWithWait(long waitTime, TimeUnit waitUnit, String sql, RowMapper<T> rowMapper,
        Object... args) throws SQLException {
    long startTime = currentTimeMillis();
    do {
        List<T> histories = query(sql, rowMapper, args);
        if (!histories.isEmpty()) {
            return histories;
        }
        Threads.sleep(250, TimeUnit.MILLISECONDS);
    } while ((currentTimeMillis() - startTime) < waitUnit.toMillis(waitTime));

    return Lists.newArrayList();
}

From source file:com.splicemachine.test_dao.JDBCTemplate.java

/**
 * Same as queryForObject() method in this class, but retries for up to the specified time.
 *///from  w w  w  .j ava  2s  .  co m
public <T> T queryForObjectWithWait(long waitTime, TimeUnit waitUnit, String sql, RowMapper<T> rowMapper,
        Object... args) throws SQLException {
    long startTime = currentTimeMillis();
    do {
        T histories = queryForObject(sql, rowMapper, args);
        if (histories != null) {
            return histories;
        }
        Threads.sleep(250, TimeUnit.MILLISECONDS);
    } while ((currentTimeMillis() - startTime) < waitUnit.toMillis(waitTime));

    return null;
}

From source file:org.keycloak.adapters.installed.KeycloakInstalled.java

public String getTokenString(long minValidity, TimeUnit unit)
        throws VerificationException, IOException, ServerRequest.HttpFailure {
    long expires = ((long) token.getExpiration()) * 1000 - unit.toMillis(minValidity);
    if (expires < System.currentTimeMillis()) {
        refreshToken();//  w  w w .  j a  v a2s .c om
    }

    return tokenString;
}

From source file:org.cloudifysource.esc.driver.provisioning.storage.openstack.OpenstackStorageDriver.java

@Override
public void detachVolume(final String volumeId, final String machineIp, final long duration,
        final TimeUnit timeUnit) throws TimeoutException, StorageProvisioningException {

    final long endTime = System.currentTimeMillis() + timeUnit.toMillis(duration);
    NodeMetadata node = deployer.getServerWithIP(machineIp);
    if (node == null) {
        throw new StorageProvisioningException(
                "Failed to detach volume " + volumeId + " from server " + machineIp + ". Server not found.");
    }//  w w w.j av  a  2 s . c o m

    //TODO might be faster without the location at all
    Optional<? extends VolumeApi> volumeApi = getVolumeApi();
    Optional<? extends VolumeAttachmentApi> volumeAttachmentApi = getAttachmentApi();

    if (!volumeApi.isPresent() || !volumeAttachmentApi.isPresent()) {
        throw new StorageProvisioningException(
                "Failed to detach volume " + volumeId + ", Openstack API is not initialized.");
    }

    volumeAttachmentApi.get().detachVolumeFromServer(volumeId, node.getProviderId());

    try {
        waitForVolumeToReachStatus(Volume.Status.AVAILABLE, volumeApi, volumeId, endTime);
        logger.fine("Volume " + volumeId + " detached successfully from machine : " + machineIp);
    } catch (final Exception e) {
        logger.log(Level.WARNING, "volume: " + volumeId + " failed to detach from machine " + machineIp
                + ". Error was: " + e.getMessage(), e);
        throw new StorageProvisioningException(e);
    }

}

From source file:org.cloudifysource.esc.driver.provisioning.storage.openstack.OpenstackStorageDriver.java

@Override
public void attachVolume(final String volumeId, final String device, final String machineIp,
        final long duration, final TimeUnit timeUnit) throws TimeoutException, StorageProvisioningException {

    final long endTime = System.currentTimeMillis() + timeUnit.toMillis(duration);
    NodeMetadata node = deployer.getServerWithIP(machineIp);
    if (node == null) {
        throw new StorageProvisioningException("Failed to attach volume " + volumeId + " to server. Server "
                + "with ip: " + machineIp + " not found");
    }/*from  w w w. j a  v  a  2s  . c om*/

    Optional<? extends VolumeAttachmentApi> volumeAttachmentApi = getAttachmentApi();
    Optional<? extends VolumeApi> volumeApi = getVolumeApi();

    if (!volumeApi.isPresent() || !volumeAttachmentApi.isPresent()) {
        throw new StorageProvisioningException(
                "Failed to attach volume " + volumeId + ", Openstack API is not initialized.");
    }
    logger.fine("Attaching volume on Openstack");

    volumeAttachmentApi.get().attachVolumeToServerAsDevice(volumeId, node.getProviderId(), device);

    try {
        waitForVolumeToReachStatus(Volume.Status.IN_USE, volumeApi, volumeId, endTime);
        logger.fine("Volume " + volumeId + " attached successfully to machine : " + machineIp);
    } catch (final Exception e) {
        logger.log(Level.WARNING, "volume: " + volumeId + " failed to attach to machine " + machineIp
                + ". Error was: " + e.getMessage(), e);
        try {
            detachVolume(region, volumeId, duration, timeUnit);
        } catch (final Exception e2) {
            logger.log(Level.WARNING, "Error while detaching volume: " + volumeId
                    + " after a failed attachment. Error was: " + e.getMessage() + ". It may be leaking.", e);
        }
        throw new StorageProvisioningException(e);
    }

}