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.openspaces.admin.internal.pu.DefaultProcessingUnit.java

@Override
public synchronized void setStatisticsInterval(long interval, TimeUnit timeUnit) {
    statisticsInterval = timeUnit.toMillis(interval);
    for (ProcessingUnitInstance processingUnitInstance : processingUnitInstances.values()) {
        processingUnitInstance.setStatisticsInterval(interval, timeUnit);
    }//from   w  w w .  j av  a 2s  .  c  o m
}

From source file:org.openspaces.admin.internal.pu.DefaultProcessingUnit.java

@Override
public boolean scaleAndWait(ScaleStrategyConfig strategyConfig, long timeout, TimeUnit timeunit) {
    long end = SystemTime.timeMillis() + timeunit.toMillis(timeout);
    scale(strategyConfig);//from   w  ww .j  a  v a  2  s .  c  o m

    while (true) {

        ElasticServiceManager[] elasticManagers = ((InternalElasticServiceManagers) admin
                .getElasticServiceManagers()).getManagersNonFiltered();
        if (elasticManagers.length == 1) {
            InternalElasticServiceManager esm = (InternalElasticServiceManager) elasticManagers[0];
            // we use the nocache method since the local cache does not contain the strategyConfig
            // so the cache may relate to the old startegyConfig
            // see GS-9999 for more details
            if (esm.isManagingProcessingUnitAndScaleNotInProgressNoCache(this)) {
                //done waiting
                break;
            }
        }

        long sleepDuration = end - SystemTime.timeMillis();
        if (sleepDuration <= 0) {
            //timeout
            return false;
        }

        try {
            Thread.sleep(Math.min(1000, sleepDuration));
        } catch (InterruptedException e) {
            throw new AdminException("scaleAndWait interrupted", e);
        }
    }
    return true;
}

From source file:org.cloudifysource.esc.driver.provisioning.privateEc2.PrivateEC2CloudifyDriver.java

private void waitStopInstanceStatus(final String instanceId, final long duration, final TimeUnit unit)
        throws CloudProvisioningException, TimeoutException {
    final long endTime = System.currentTimeMillis() + unit.toMillis(duration);
    while (System.currentTimeMillis() < endTime) {

        final DescribeInstancesRequest describeRequest = new DescribeInstancesRequest();
        describeRequest.withInstanceIds(instanceId);
        final DescribeInstancesResult describeInstances = ec2.describeInstances(describeRequest);

        for (final Reservation resa : describeInstances.getReservations()) {
            for (final Instance instance : resa.getInstances()) {
                final InstanceStateType state = InstanceStateType.valueOf(instance.getState().getCode());
                if (logger.isLoggable(Level.FINEST)) {
                    logger.finest("instance= " + instance.getInstanceId() + " state=" + state);
                }/*  w  ww.  j a  v a  2  s  .c  o m*/
                switch (state) {
                case PENDING:
                case RUNNING:
                case STOPPING:
                case SHUTTING_DOWN:
                    this.sleep();
                    break;
                case STOPPED:
                case TERMINATED:
                    if (logger.isLoggable(Level.FINEST)) {
                        logger.finest("instance (id=" + instanceId + ") was shutdown");
                    }
                    return;
                default:
                    throw new CloudProvisioningException(
                            "Failed to stop server - Cloud reported node in " + state.getName() + " state.");

                }

            }
        }
    }

    throw new TimeoutException("Stopping instace timed out (id=" + instanceId + ")");
}

From source file:org.cloudifysource.esc.driver.provisioning.privateEc2.PrivateEC2CloudifyDriver.java

private Instance waitRunningInstance(final Instance ec2instance, final long duration, final TimeUnit unit)
        throws CloudProvisioningException, TimeoutException {

    final long endTime = System.currentTimeMillis() + unit.toMillis(duration);

    while (System.currentTimeMillis() < endTime) {
        // Sleep before requesting the instance description
        // because we can get a AWS Error Code: InvalidInstanceID.NotFound if the request is too early.
        this.sleep();

        final DescribeInstancesRequest describeRequest = new DescribeInstancesRequest();
        describeRequest.setInstanceIds(Arrays.asList(ec2instance.getInstanceId()));
        final DescribeInstancesResult describeInstances = this.ec2.describeInstances(describeRequest);

        for (final Reservation resa : describeInstances.getReservations()) {
            for (final Instance instance : resa.getInstances()) {
                final InstanceStateType state = InstanceStateType.valueOf(instance.getState().getCode());
                if (logger.isLoggable(Level.FINER)) {
                    logger.finer("instance= " + instance.getInstanceId() + " state=" + state);
                }//  w  w  w.  j a v a  2 s  .  c om
                switch (state) {
                case PENDING:
                    break;
                case RUNNING:
                    logger.fine("running okay...");
                    return instance;
                case STOPPING:
                case SHUTTING_DOWN:
                case TERMINATED:
                case STOPPED:
                default:
                    throw new CloudProvisioningException("Failed to allocate server - Cloud reported node in "
                            + state.getName() + " state. Node details: " + ec2instance);

                }
            }
        }
    }

    throw new TimeoutException("Node failed to reach RUNNING mode in time");
}

From source file:com.serphacker.serposcope.scraper.http.extensions.CloseableBasicHttpClientConnectionManager.java

@Override
public synchronized void releaseConnection(final HttpClientConnection conn, final Object state,
        final long keepalive, final TimeUnit tunit) {
    Args.notNull(conn, "Connection");
    Asserts.check(conn == this.conn, "Connection not obtained from this manager");
    if (this.log.isDebugEnabled()) {
        this.log.debug("Releasing connection " + conn);
    }//from   w w w.ja v a  2 s . c  om
    if (this.isShutdown.get()) {
        return;
    }
    try {
        this.updated = System.currentTimeMillis();
        if (!this.conn.isOpen()) {
            this.conn = null;
            this.route = null;
            this.conn = null;
            this.expiry = Long.MAX_VALUE;
        } else {
            this.state = state;
            if (this.log.isDebugEnabled()) {
                final String s;
                if (keepalive > 0) {
                    s = "for " + keepalive + " " + tunit;
                } else {
                    s = "indefinitely";
                }
                this.log.debug("Connection can be kept alive " + s);
            }
            if (keepalive > 0) {
                this.expiry = this.updated + tunit.toMillis(keepalive);
            } else {
                this.expiry = Long.MAX_VALUE;
            }
        }
    } finally {
        this.leased = false;
    }
}

From source file:org.zenoss.zep.dao.impl.EventSummaryDaoImpl.java

private Map<String, Object> createSharedFields(long duration, TimeUnit unit) {
    TypeConverter<Long> timestampConverter = databaseCompatibility.getTimestampConverter();
    long delta = System.currentTimeMillis() - unit.toMillis(duration);
    Object lastSeen = timestampConverter.toDatabaseType(delta);
    Map<String, Object> fields = new HashMap<String, Object>();
    fields.put("_last_seen", lastSeen);
    return fields;
}

From source file:com.epam.reportportal.apache.http.impl.conn.BasicHttpClientConnectionManager.java

public synchronized void releaseConnection(final HttpClientConnection conn, final Object state,
        final long keepalive, final TimeUnit tunit) {
    Args.notNull(conn, "Connection");
    Asserts.check(conn == this.conn, "Connection not obtained from this manager");
    if (this.log.isDebugEnabled()) {
        this.log.debug("Releasing connection " + conn);
    }//from  ww  w  .  ja  v  a  2s  . com
    if (this.shutdown) {
        shutdownConnection();
        return;
    }
    try {
        this.updated = System.currentTimeMillis();
        if (!this.conn.isOpen()) {
            this.conn = null;
            this.route = null;
            this.conn = null;
            this.expiry = Long.MAX_VALUE;
        } else {
            this.state = state;
            if (this.log.isDebugEnabled()) {
                final String s;
                if (keepalive > 0) {
                    s = "for " + keepalive + " " + tunit;
                } else {
                    s = "indefinitely";
                }
                this.log.debug("Connection can be kept alive " + s);
            }
            if (keepalive > 0) {
                this.expiry = this.updated + tunit.toMillis(keepalive);
            } else {
                this.expiry = Long.MAX_VALUE;
            }
        }
    } finally {
        this.leased = false;
    }
}

From source file:org.cloudifysource.esc.driver.provisioning.byon.DynamicByonProvisioningDriver.java

@Override
public MachineDetails[] startManagementMachines(long duration, TimeUnit unit)
        throws TimeoutException, CloudProvisioningException {
    publishEvent(EVENT_ATTEMPT_START_MGMT_VMS);

    final ComputeTemplate managementTemplate = this.cloud.getCloudCompute().getTemplates()
            .get(this.cloud.getConfiguration().getManagementMachineTemplate());
    Map<String, Object> custom = managementTemplate.getCustom();
    @SuppressWarnings("unchecked")
    Closure<List<String>> getNodesClosure = (Closure<List<String>>) custom
            .get(CloudifyConstants.DYNAMIC_BYON_START_MNG_MACHINES_KEY);
    List<String> ips = getNodesClosure.call();

    final int numberOfManagementMachines = this.cloud.getProvider().getNumberOfManagementMachines();
    final int size = ips.size();
    if (size != numberOfManagementMachines) {
        throw new CloudProvisioningException(
                "DynamicByonProvisioningDriver [startManagementMachines] - expected "
                        + numberOfManagementMachines + " management machines, but got " + size + " machines.");
    }//from  w ww.ja  v  a 2s  .  c  om
    synchronized (mutex) {
        managementMachines.addAll(ips);
    }

    logger.info("Starting " + numberOfManagementMachines + " management machines.");
    final long endTime = System.currentTimeMillis() + unit.toMillis(duration);
    final MachineDetails[] createdMachines = doStartManagementMachines(endTime, numberOfManagementMachines);
    publishEvent(EVENT_MGMT_VMS_STARTED);
    logger.info("Successfully added " + numberOfManagementMachines + " management machines: " + ips);
    return createdMachines;
}

From source file:org.dcache.webdav.transfer.CredentialServiceClient.java

public X509Credential getDelegatedCredential(String dn, String primaryFqan, int minimumValidity, TimeUnit units)
        throws InterruptedException, ErrorResponseException {
    long bestRemainingLifetime = 0;
    X509Credential bestCredential = null;

    for (CellAddressCore address : cache.asMap().keySet()) {
        CellPath path = new CellPath(address);
        SrmRequestCredentialMessage msg = new SrmRequestCredentialMessage(dn, primaryFqan);
        try {/*from  ww  w  .  ja  v  a2s  .  co  m*/
            msg = topic.sendAndWait(path, msg);

            if (!msg.hasCredential()) {
                continue;
            }

            X509Certificate[] certificates = msg.getCertificateChain();
            long lifetime = calculateRemainingLifetime(certificates);
            if (lifetime > bestRemainingLifetime) {
                bestCredential = new KeyAndCertCredential(msg.getPrivateKey(), certificates);
                bestRemainingLifetime = lifetime;
            }
        } catch (CacheException | NoRouteToCellException e) {
            LOGGER.debug("failed to contact {} querying for {}, {}: {}", path, dn, primaryFqan, e.getMessage());
        } catch (KeyStoreException e) {
            LOGGER.warn("Received invalid key pair from {} for {}, {}: {}", path, dn, primaryFqan,
                    e.getMessage());
        }
    }

    return bestRemainingLifetime < units.toMillis(minimumValidity) ? null : bestCredential;
}

From source file:org.cloudifysource.esc.driver.provisioning.privateEc2.PrivateEC2CloudifyDriver.java

@Override
public MachineDetails[] startManagementMachines(final long duration, final TimeUnit unit)
        throws TimeoutException, CloudProvisioningException {

    if (duration < 0) {
        throw new TimeoutException("Starting a new machine timed out");
    }//from w ww.  j  a v a  2 s .  co  m

    final long endTime = System.currentTimeMillis() + unit.toMillis(duration);

    logger.fine("DefaultCloudProvisioning: startMachine - management == " + management);

    try {
        final File cloudDirectory = new ProvisioningContextAccess().getManagementProvisioiningContext()
                .getCloudFile().getParentFile();
        this.cloud.getCustom().put("###CLOUD_DIRECTORY###", cloudDirectory);
        this.privateEc2Template = this.getManagerPrivateEc2Template(cloudDirectory,
                this.managerCfnTemplateFileName);
    } catch (PrivateEc2ParserException e) {
        throw new CloudProvisioningException("Failed to read management template: " + e.getMessage(), e);
    } catch (IOException e) {
        throw new CloudProvisioningException("Failed to read management template: " + e.getMessage(), e);
    }

    final String managementMachinePrefix = this.cloud.getProvider().getManagementGroup();
    if (org.apache.commons.lang.StringUtils.isBlank(managementMachinePrefix)) {
        throw new CloudProvisioningException(
                "The management group name is missing - can't locate existing servers!");
    }

    // first check if management already exists
    final MachineDetails[] existingManagementServers = this.getManagementServersMachineDetails();
    if (existingManagementServers.length > 0) {
        final String serverDescriptions = this.createExistingServersDescription(managementMachinePrefix,
                existingManagementServers);
        throw new CloudProvisioningException(
                "Found existing servers matching group " + managementMachinePrefix + ": " + serverDescriptions);

    }

    // launch the management machines
    final int numberOfManagementMachines = this.cloud.getProvider().getNumberOfManagementMachines();
    MachineDetails[] createdMachines;
    try {
        createdMachines = this.doStartManagementMachines(numberOfManagementMachines, endTime, unit);
    } catch (final PrivateEc2ParserException e) {
        throw new CloudProvisioningException(e);
    }
    return createdMachines;
}