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:voldemort.client.ClientConfig.java

/**
 * Set the timeout for all blocking operations to complete on all nodes. The
 * number of blocking operations can be configured using the preferred-reads
 * and preferred-writes configuration for the store.
 * //ww w  .ja va2  s  .c om
 * See {@link #GETALL_ROUTING_TIMEOUT_MS_PROPERTY},
 * {@link #GET_ROUTING_TIMEOUT_MS_PROPERTY},
 * {@link #PUT_ROUTING_TIMEOUT_MS_PROPERTY},
 * {@link #DELETE_ROUTING_TIMEOUT_MS_PROPERTY} to override timeouts for
 * specific operations
 * 
 * @param routingTimeout The timeout for all operations to complete.
 * @param unit The time unit of the timeout value
 */
public ClientConfig setRoutingTimeout(int routingTimeout, TimeUnit unit) {
    this.routingTimeoutMs = unit.toMillis(routingTimeout);
    return this;
}

From source file:org.openspaces.admin.internal.gsm.DefaultGridServiceManager.java

@Override
public Application deploy(ApplicationConfig applicationConfig, long timeout, TimeUnit timeUnit)
        throws ApplicationAlreadyDeployedException, ProcessingUnitAlreadyDeployedException {
    long end = SystemTime.timeMillis() + timeUnit.toMillis(timeout);
    String applicationName = applicationConfig.getName();
    if (applicationName == null) {
        throw new IllegalArgumentException("Application Name cannot be null");
    }//from  www. j a  v  a  2  s .  co m
    if (applicationName.length() == 0) {
        throw new IllegalArgumentException("Application Name cannot be an empty string");
    }
    if (admin.getApplications().getApplication(applicationName) != null) {
        throw new ApplicationAlreadyDeployedException(applicationName);
    }

    ProcessingUnitConfigHolder[] processingUnitConfigHolders = applicationConfig.getProcessingUnits();
    if (processingUnitConfigHolders.length == 0) {
        throw new AdminException("Application must contain at least one processing unit.");
    }

    //(if necessary) unzip applicaiton.zip to temp directory 
    File tempDirectory = null;
    File jarsDirectory = applicationConfig.getJarsDirectoryOrZip();
    if (jarsDirectory != null && jarsDirectory.isFile()) {
        tempDirectory = FileUtils.unzipToTempFolder(applicationConfig.getJarsDirectoryOrZip());
        jarsDirectory = tempDirectory;
    }

    try {
        // iterate in a deterministic order, so if deployed in parallel by another admin client, only one will succeed
        boolean timedOut = false;
        Set<String> deployedPuNames = new HashSet<String>();
        for (ProcessingUnitConfigHolder puConfigHolder : processingUnitConfigHolders) {
            try {
                long remaining = end - SystemTime.timeMillis();
                if (remaining <= 0) {
                    timedOut = true;
                    break;
                }

                final ProcessingUnitConfig puConfig = toProcessingUnitConfig(puConfigHolder);

                //handle relative paths to jar files
                boolean isAbsolutePath = new File(puConfig.getProcessingUnit()).isAbsolute();
                boolean isRelativeToGSHomedir = puConfig.getProcessingUnit().trim().startsWith("/");
                boolean isAddDirectory = !isAbsolutePath && !isRelativeToGSHomedir;

                if (logger.isDebugEnabled()) {
                    logger.debug("puConfig.getProcessingUnit()=" + puConfig.getProcessingUnit() + " "
                            + "isAbsolutePath=" + isAbsolutePath + " " + "isRelativeToGSHomedir="
                            + isRelativeToGSHomedir + " " + "isAddDirectory=" + isAddDirectory);
                }
                if (jarsDirectory != null && isAddDirectory) {
                    File jar = new File(jarsDirectory, puConfig.getProcessingUnit());
                    puConfig.setProcessingUnit(jar.getAbsolutePath());
                }

                //deploy pu
                ProcessingUnit pu = deploy(puConfig, applicationName, remaining, TimeUnit.MILLISECONDS);
                if (pu == null) {
                    timedOut = true;
                    break;
                }
                deployedPuNames.add(pu.getName());
            } catch (ProcessingUnitAlreadyDeployedException e) {
                if (deployedPuNames.contains(e.getProcessingUnitName())) {
                    throw new AdminException(
                            "Application deployment contains two Processing Units with the same name "
                                    + e.getProcessingUnitName(),
                            e);
                }
                ProcessingUnit otherPu = admin.getProcessingUnits()
                        .getProcessingUnit(e.getProcessingUnitName());
                if (otherPu != null && otherPu.getApplication() != null
                        && otherPu.getApplication().getName().equals(applicationName)) {
                    throw new ApplicationAlreadyDeployedException(applicationName, e);
                }
                // A PU with the same name from another application (or PU not discovered yet).
                throw e;
            }
        }
        if (timedOut) {
            return null;
        }
        return admin.getApplications().getApplication(applicationName);
    } finally {
        if (tempDirectory != null) {
            try {
                FileUtils.deleteFileOrDirectory(tempDirectory);
            } catch (AdminException e) {
                logger.warn("Failed to delete " + tempDirectory + " will attempt to delete on exit", e);
                tempDirectory.deleteOnExit();
                //do not throw since we may be hiding other exceptions that lock the files in tempDirectory in the first place
            }
        }
    }
}

From source file:voldemort.client.ClientConfig.java

/**
 * Set the maximum allowable time to block waiting for a free connection
 * /*from   w  w w  . ja va2  s.  c o  m*/
 * @param connectionTimeout The connection timeout
 * @param unit The time unit of the given value
 */
public ClientConfig setConnectionTimeout(int connectionTimeout, TimeUnit unit) {
    this.connectionTimeoutMs = unit.toMillis(connectionTimeout);
    return this;
}

From source file:org.apache.http2.impl.conn.tsccm.ConnPoolByRoute.java

/**
 * Closes idle connections.// www . ja  v  a2  s.  c o  m
 *
 * @param idletime  the time the connections should have been idle
 *                  in order to be closed now
 * @param tunit     the unit for the <code>idletime</code>
 */
@Override
public void closeIdleConnections(long idletime, TimeUnit tunit) {
    if (tunit == null) {
        throw new IllegalArgumentException("Time unit must not be null.");
    }
    if (idletime < 0) {
        idletime = 0;
    }
    if (log.isDebugEnabled()) {
        log.debug("Closing connections idle longer than " + idletime + " " + tunit);
    }
    // the latest time for which connections will be closed
    long deadline = System.currentTimeMillis() - tunit.toMillis(idletime);
    poolLock.lock();
    try {
        Iterator<BasicPoolEntry> iter = freeConnections.iterator();
        while (iter.hasNext()) {
            BasicPoolEntry entry = iter.next();
            if (entry.getUpdated() <= deadline) {
                if (log.isDebugEnabled()) {
                    log.debug("Closing connection last used @ " + new Date(entry.getUpdated()));
                }
                iter.remove();
                deleteEntry(entry);
            }
        }
    } finally {
        poolLock.unlock();
    }
}

From source file:voldemort.client.ClientConfig.java

/**
 * The period of time to ban a node that gives an error on an operation.
 * //from   ww w. jav a 2  s  .  com
 * @param nodeBannagePeriod The period of time to ban the node
 * @param unit The time unit of the given value
 * 
 * @deprecated Use {@link #setFailureDetectorBannagePeriod(long)} instead
 */
@Deprecated
public ClientConfig setNodeBannagePeriod(int nodeBannagePeriod, TimeUnit unit) {
    this.failureDetectorBannagePeriod = unit.toMillis(nodeBannagePeriod);
    return this;
}

From source file:org.cloudifysource.esc.driver.provisioning.jclouds.DefaultProvisioningDriver.java

@Override
public MachineDetails startMachine(final String locationId, final long timeout, final TimeUnit unit)
        throws TimeoutException, CloudProvisioningException {

    logger.fine(this.getClass().getName() + ": startMachine, management mode: " + management);
    final long end = System.currentTimeMillis() + unit.toMillis(timeout);

    if (System.currentTimeMillis() > end) {
        throw new TimeoutException("Starting a new machine timed out");
    }//  w  w  w. j  a  v a  2s  .c om

    try {
        final String groupName = createNewServerName();
        logger.fine("Starting a new cloud server with group: " + groupName);
        final MachineDetails md = createServer(end, groupName, locationId);
        return md;
    } catch (final Exception e) {
        throw new CloudProvisioningException("Failed to start cloud machine", e);
    }
}

From source file:org.cloudifysource.esc.driver.provisioning.jclouds.DefaultProvisioningDriver.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");
    }// w w  w .ja  v  a 2 s  .c  o  m
    final long endTime = System.currentTimeMillis() + unit.toMillis(duration);

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

    final String managementMachinePrefix = this.cloud.getProvider().getManagementGroup();
    if (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 = getExistingManagementServers();
    if (existingManagementServers.length > 0) {
        final String serverDescriptions = createExistingServersDescription(managementMachinePrefix,
                existingManagementServers);
        throw new CloudProvisioningException(
                "Found existing servers matching group " + managementMachinePrefix + ": " + serverDescriptions);

    }

    // launch the management machines
    publishEvent(EVENT_ATTEMPT_START_MGMT_VMS);
    final int numberOfManagementMachines = this.cloud.getProvider().getNumberOfManagementMachines();
    final MachineDetails[] createdMachines = doStartManagementMachines(endTime, numberOfManagementMachines);
    publishEvent(EVENT_MGMT_VMS_STARTED);
    return createdMachines;
}

From source file:net.pms.service.ProcessManager.java

/**
 * Adds a {@link Process} to be managed by this {@link ProcessManager}.
 *
 * @param process the {@link Process} to manage.
 * @param processName the name of the process used for
 *            logging/identification.//from   w  w  w . ja  v a 2  s. c o  m
 * @param timeout the timeout for this {@link Process} in {@code timeUnit}.
 *            When this time has expired, the process will be shut down if
 *            it isn't already finished. If it's already finished, it will
 *            simply be removed from the schedule.
 * @param timeUnit the {@link TimeUnit} for {@code timeout}.
 * @param terminateTimeoutMS the timeout for shutdown attempts in
 *            milliseconds. This timeout is used for each shutdown attempt
 *            before escalating to the next level. Any value below 100
 *            milliseconds will be set to 100 milliseconds.
 */
public void addProcess(@Nonnull Process process, @Nonnull String processName, long timeout,
        @Nonnull TimeUnit timeUnit, long terminateTimeoutMS) {
    addTicket(new ProcessTicket(process, processName, ProcessTicketAction.ADD, timeUnit.toMillis(timeout),
            terminateTimeoutMS));
}

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

private void waitRunningAgent(final String host, final long duration, final TimeUnit unit) {
    long endTime = System.currentTimeMillis() + unit.toMillis(duration);
    while (System.currentTimeMillis() < endTime) {
        if (this.isPortReachable(host, DEFAULT_CLOUDIFY_AGENT_PORT)) {
            logger.fine("Agent is reachable on: " + host + ":" + DEFAULT_CLOUDIFY_AGENT_PORT);
            break;
        } else {/*  w ww .j  a v  a 2  s.co  m*/
            this.sleep();
        }
    }

}

From source file:org.cloudifysource.esc.driver.provisioning.ElasticMachineProvisioningCloudifyAdapter.java

@Override
public boolean stopMachine(final GridServiceAgent agent, final long duration, final TimeUnit unit)
        throws ElasticMachineProvisioningException, ElasticGridServiceAgentProvisioningException,
        InterruptedException, TimeoutException {

    final long endTime = System.currentTimeMillis() + unit.toMillis(duration);
    final String machineIp = agent.getMachine().getHostAddress();

    Exception failedToShutdownAgentException = null;
    final GridServiceAgentStopRequestedEvent agentStopEvent = new GridServiceAgentStopRequestedEvent();
    agentStopEvent.setHostAddress(machineIp);
    agentStopEvent.setAgentUid(agent.getUid());
    agentEventListener.elasticGridServiceAgentProvisioningProgressChanged(agentStopEvent);

    logger.fine("Shutting down agent: " + agent + " on host: " + machineIp);
    try {// w w w . j  a  v  a2s.  c o  m
        agent.shutdown();
        logger.fine("Agent on host: " + machineIp + " successfully shut down");

        final GridServiceAgentStoppedEvent agentStoppedEvent = new GridServiceAgentStoppedEvent();
        agentStoppedEvent.setHostAddress(machineIp);
        agentStoppedEvent.setAgentUid(agent.getUid());
        agentEventListener.elasticGridServiceAgentProvisioningProgressChanged(agentStoppedEvent);
    } catch (final Exception e) {
        failedToShutdownAgentException = e;
        logger.log(Level.FINE,
                "Failed to shutdown agent on host: " + machineIp + ". Continuing with shutdown of machine.", e);
    }

    try {

        final MachineStopRequestedEvent machineStopEvent = new MachineStopRequestedEvent();
        machineStopEvent.setHostAddress(machineIp);
        machineEventListener.elasticMachineProvisioningProgressChanged(machineStopEvent);

        logger.fine("Cloudify Adapter is shutting down machine with ip: " + machineIp);
        final boolean shutdownSuccessful = this.cloudifyProvisioning.stopMachine(machineIp, duration, unit);
        logger.fine("Shutdown result of machine: " + machineIp + " was: " + shutdownSuccessful);

        if (shutdownSuccessful) {
            final MachineStoppedEvent machineStoppedEvent = new MachineStoppedEvent();
            machineStoppedEvent.setHostAddress(machineIp);
            machineEventListener.elasticMachineProvisioningProgressChanged(machineStoppedEvent);

            // machine was shutdown, but an error happened while shutting
            // down agent.
            // lets wait for the agent to not be discovered until we reach
            // the timeout.

            while (agent.isDiscovered()) {
                Thread.sleep(DEFAULT_AGENT_DISCOVERY_INTERVAL);
                if (System.currentTimeMillis() > endTime && agent.isDiscovered()) {
                    if (failedToShutdownAgentException != null) {
                        throw new ElasticGridServiceAgentProvisioningException(
                                "Machine is stopped but agent [" + agent.getUid() + "] is still discovered."
                                        + "Failed to shutdown agent:"
                                        + failedToShutdownAgentException.getMessage(),
                                failedToShutdownAgentException);
                    }
                    throw new ElasticGridServiceAgentProvisioningException(
                            "Machine is stopped but agent[" + agent.getUid() + "] is still discovered.");

                }
            }
        }

        return shutdownSuccessful;

    } catch (final CloudProvisioningException e) {
        throw new ElasticMachineProvisioningException("Attempt to shutdown machine with IP: " + machineIp
                + " for agent with UID: " + agent.getUid() + " has failed with error: " + e.getMessage(), e);
    }
}