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.gsm.DefaultGridServiceManager.java

private ProcessingUnit deploy(ProcessingUnitConfig puConfig, String applicationName, long timeout,
        TimeUnit timeUnit) {

    long end = SystemTime.timeMillis() + timeUnit.toMillis(timeout);

    Deploy deploy = new Deploy();
    Deploy.setDisableInfoLogging(true);// w  w w  .java  2 s . c om
    deploy.setGroups(getAdmin().getGroups());
    StringBuilder locatorsString = new StringBuilder();
    for (LookupLocator locator : getAdmin().getLocators()) {
        locatorsString.append(locator).append(',');
    }
    deploy.setLocators(locatorsString.toString());
    deploy.initializeDiscovery(gsm);
    if (puConfig.getSecured() != null) {
        deploy.setSecured(puConfig.getSecured());
    }
    UserDetailsConfig userDetailsConfig = puConfig.getUserDetails();
    if (userDetailsConfig != null) {
        deploy.setUserDetails(new User(userDetailsConfig.getUsername(), userDetailsConfig.getPassword()));
    }
    deploy.setApplicationName(applicationName);
    final OperationalString operationalString;
    try {
        operationalString = deploy.buildOperationalString(puConfig.toDeploymentOptions());
    } catch (Exception e) {
        throw new AdminException("Failed to deploy [" + puConfig.getProcessingUnit() + "]", e);
    }

    boolean alreadyDeployed = false;
    try {
        alreadyDeployed = getGSMAdmin().hasDeployed(operationalString.getName());
    } catch (Exception e) {
        throw new AdminException(
                "Failed to check if processing unit [" + operationalString.getName() + "] is deployed", e);
    }

    if (alreadyDeployed) {
        throw new ProcessingUnitAlreadyDeployedException(operationalString.getName());
    }

    final AtomicReference<ProcessingUnit> ref = new AtomicReference<ProcessingUnit>();

    final CountDownLatch latch = new CountDownLatch(1);
    ProcessingUnitAddedEventListener added = new ProcessingUnitAddedEventListener() {
        public void processingUnitAdded(ProcessingUnit processingUnit) {
            if (operationalString.getName().equals(processingUnit.getName())) {
                ref.set(processingUnit);
                latch.countDown();
            }
        }
    };
    getAdmin().getProcessingUnits().getProcessingUnitAdded().add(added);
    ProcessingUnit pu = null;
    try {
        getGSMAdmin().deploy(operationalString);
        latch.await(timeout, timeUnit);
        pu = ref.get();
    } catch (SecurityException se) {
        throw new AdminException("No privileges to deploy a processing unit", se);
    } catch (Exception e) {
        throw new AdminException("Failed to deploy [" + puConfig.getProcessingUnit() + "]", e);
    } finally {
        Deploy.setDisableInfoLogging(false);
        getAdmin().getProcessingUnits().getProcessingUnitAdded().remove(added);
    }

    if (!puConfig.getElasticProperties().isEmpty()) {
        // wait until elastic scale strategy is being enforced
        while (SystemTime.timeMillis() < end) {
            InternalGridServiceManager gridServiceManager = (InternalGridServiceManager) pu
                    .getManagingGridServiceManager();
            if (gridServiceManager != null && gridServiceManager.isManagedByElasticServiceManager(pu)) {
                break;
            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                break;
            }
        }
    }
    return pu;
}

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

/**
 * Closes idle connections.//from   www .  ja  va 2s.  c om
 *
 * @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(final long idletime, final TimeUnit tunit) {
    Args.notNull(tunit, "Time unit");
    final long t = idletime > 0 ? idletime : 0;
    if (log.isDebugEnabled()) {
        log.debug("Closing connections idle longer than " + t + " " + tunit);
    }
    // the latest time for which connections will be closed
    final long deadline = System.currentTimeMillis() - tunit.toMillis(t);
    poolLock.lock();
    try {
        final Iterator<BasicPoolEntry> iter = freeConnections.iterator();
        while (iter.hasNext()) {
            final 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:org.apache.james.queue.file.FileMailQueue.java

@Override
public void enQueue(Mail mail, long delay, TimeUnit unit) throws MailQueueException {
    final String key = mail.getName() + "-" + COUNTER.incrementAndGet();
    FileOutputStream out = null;// w  w  w  .  j av a 2  s .com
    FileOutputStream foout = null;
    ObjectOutputStream oout = null;
    try {
        int i = (int) (Math.random() * SPLITCOUNT + 1);

        String name = queueDirName + "/" + i + "/" + key;

        final FileItem item = new FileItem(name + OBJECT_EXTENSION, name + MSG_EXTENSION);
        if (delay > 0) {
            mail.setAttribute(NEXT_DELIVERY, System.currentTimeMillis() + unit.toMillis(delay));
        }
        foout = new FileOutputStream(item.getObjectFile());
        oout = new ObjectOutputStream(foout);
        oout.writeObject(mail);
        oout.flush();
        if (sync)
            foout.getFD().sync();
        out = new FileOutputStream(item.getMessageFile());

        mail.getMessage().writeTo(out);
        out.flush();
        if (sync)
            out.getFD().sync();

        keyMappings.put(key, item);

        if (delay > 0) {
            // The message should get delayed so schedule it for later
            scheduler.schedule(new Runnable() {

                @Override
                public void run() {
                    try {
                        inmemoryQueue.put(key);

                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                        throw new RuntimeException("Unable to init", e);
                    }
                }
            }, delay, unit);

        } else {
            inmemoryQueue.put(key);
        }

        //TODO: Think about exception handling in detail
    } catch (FileNotFoundException e) {
        throw new MailQueueException("Unable to enqueue mail", e);
    } catch (IOException e) {
        throw new MailQueueException("Unable to enqueue mail", e);

    } catch (MessagingException e) {
        throw new MailQueueException("Unable to enqueue mail", e);
    } catch (InterruptedException e) {
        throw new MailQueueException("Unable to enqueue mail", e);

    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
                // ignore on close
            }
        }
        if (oout != null) {
            try {
                oout.close();
            } catch (IOException e) {
                // ignore on close
            }
        }
        if (foout != null) {
            try {
                foout.close();
            } catch (IOException e) {
                // ignore on close
            }
        }
    }

}

From source file:org.cloudifysource.esc.shell.installer.CloudGridAgentBootstrapper.java

/**
 * //  w  ww  . j  av a  2s . c  om
 * @param timeout
 *            The number of {@link TimeUnit}s to wait before timing out
 * @param timeoutUnit
 *            The time unit to use (seconds, minutes etc.)
 * @throws TimeoutException
 *             Indicates the time out was reached before the tear-down completed
 * @throws CLIException
 *             Indicates a basic failure tear-down the cloud. a detailed message is included
 * @throws InterruptedException
 *             Indicates a thread was interrupted while waiting
 */
public void teardownCloudAndWait(final long timeout, final TimeUnit timeoutUnit)
        throws TimeoutException, CLIException, InterruptedException {

    final long end = System.currentTimeMillis() + timeoutUnit.toMillis(timeout);

    createProvisioningDriver(false /* performValidation */);
    ShellUtils.checkNotNull("providerDirectory", providerDirectory);

    if (terminateNow) {
        try {
            provisioning.terminateAllResources(timeout, timeoutUnit);
        } catch (final CloudProvisioningException e) {
            throw new CLIException("Failed to terminate resources: " + e.getMessage(), e);
        }
    } else {
        destroyManagementServers(CalcUtils.millisUntil(end), TimeUnit.MILLISECONDS);
    }

    if (StringUtils.isNotBlank(cloud.getConfiguration().getStorageClassName())) {
        createStorageDriver();
        destroyVolumes(CalcUtils.millisUntil(end), TimeUnit.MILLISECONDS);
    }
}

From source file:org.cloudifysource.esc.shell.installer.CloudGridAgentBootstrapper.java

private void destroyManagementServers(final long timeout, final TimeUnit timeoutUnit)
        throws CLIException, InterruptedException, TimeoutException {

    final long end = System.currentTimeMillis() + timeoutUnit.toMillis(timeout);

    if (!force) {

        if (!adminFacade.isConnected()) {
            throw new CLIException("Please connect to the cloud before tearing down");
        }//  ww w.  j  a va2 s .c o m
        uninstallApplications(end);

    } else {
        // try to shutdown gracefully - uninstall applications
        if (adminFacade.isConnected()) {
            try {
                uninstallApplications(end);
            } catch (final InterruptedException e) {
                throw e;
            } catch (final TimeoutException e) {
                logger.fine("Failed to uninstall applications. Shut down of management machines will continue");
            } catch (final CLIException e) {
                logger.fine("Failed to uninstall applications. Shut down of management machines will continue");
            }
        } else {
            logger.info("Teardown performed without connection to the cloud, only management machines will be "
                    + "terminated.");
        }
    }

    logger.info("Terminating cloud machines");

    try {
        provisioning.stopManagementMachines();
    } catch (final CloudProvisioningException e) {
        throw new CLIException(
                "Failed to shut down management machine during tear down of cloud: " + e.getMessage(), e);
    }
    adminFacade.disconnect();

}

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

private void undeployProcessingUnitsAndWaitInternal(ProcessingUnit[] processingUnits, long timeout,
        TimeUnit timeUnit) throws TimeoutException, InterruptedException {
    long end = SystemTime.timeMillis() + timeUnit.toMillis(timeout);

    List<GridServiceContainer> containersPendingRemoval = new ArrayList<GridServiceContainer>();
    List<ProcessingUnitInstance> puInstancesPendingRemoval = new ArrayList<ProcessingUnitInstance>();
    List<SpaceInstance> spaceInstancesPendingRemoval = new ArrayList<SpaceInstance>();

    for (ProcessingUnit pu : processingUnits) {
        for (GridServiceContainer container : admin.getGridServiceContainers()) {
            ProcessingUnitInstance[] processingUnitInstances = container
                    .getProcessingUnitInstances(pu.getName());
            if (processingUnitInstances.length > 0) {
                puInstancesPendingRemoval.addAll(Arrays.asList(processingUnitInstances));
                for (ProcessingUnitInstance puInstance : processingUnitInstances) {
                    SpaceInstance spaceInstance = puInstance.getSpaceInstance();
                    if (spaceInstance != null) {
                        spaceInstancesPendingRemoval.add(spaceInstance);
                    }// w ww .j a  va  2 s  .  com
                }
                if (isManagedByElasticServiceManager(pu)) {
                    // add all containers that are managed by the elastic pu
                    containersPendingRemoval.add(container);
                }
            }
        }
    }

    final Map<String, CountDownLatch> latches = new HashMap<String, CountDownLatch>();
    for (ProcessingUnit pu : processingUnits) {
        latches.put(pu.getName(), new CountDownLatch(1));
    }

    ProcessingUnitRemovedEventListener listener = new ProcessingUnitRemovedEventListener() {
        public void processingUnitRemoved(ProcessingUnit removedPu) {
            CountDownLatch latch = latches.get(removedPu.getName());
            if (latch != null) {
                latch.countDown();
            }
        }
    };
    admin.getProcessingUnits().getProcessingUnitRemoved().add(listener);
    try {
        for (final ProcessingUnit pu : processingUnits) {
            long gsmTimeout = end - SystemTime.timeMillis();
            if (gsmTimeout < 0) {
                throw new TimeoutException("Timeout expired before udeploying processing unit " + pu);
            }
            final InternalGridServiceManager managingGsm = (InternalGridServiceManager) pu
                    .waitForManaged(gsmTimeout, TimeUnit.MILLISECONDS);
            if (managingGsm == null) {
                throw new TimeoutException(
                        "Timeout expired while waiting for GSM that manages processing unit " + pu);
            }

            admin.scheduleAdminOperation(new Runnable() {
                @Override
                public void run() {
                    managingGsm.undeployProcessingUnit(pu.getName());
                }
            });
        }
        for (ProcessingUnit pu : processingUnits) {
            long puRemovedTimeout = end - SystemTime.timeMillis();
            if (puRemovedTimeout < 0) {
                throw new TimeoutException(
                        "Timeout expired before waiting for processing unit " + pu + " to undeploy");
            }
            if (!latches.get(pu.getName()).await(puRemovedTimeout, TimeUnit.MILLISECONDS)) {
                throw new TimeoutException(
                        "Timeout expired while waiting for processing unit " + pu + " to undeploy");
            }
        }
    } finally {
        admin.getProcessingUnits().getProcessingUnitRemoved().remove(listener);
    }

    // use polling to determine elastic pu completed undeploy cleanup of containers (and machines)
    // and that the admin has been updated with the relevant lookup service remove events.
    while (true) {
        try {
            verifyUndeployComplete(processingUnits);
            verifyNotDiscovered(puInstancesPendingRemoval);
            verifyNotDiscovered(spaceInstancesPendingRemoval);
            verifyNotDiscovered(containersPendingRemoval);
            verifyInstancesNotUndeploying(puInstancesPendingRemoval);
            verifyOrphanInstancesNotDeploying(processingUnits);
            verifyOrphanInstancesNotDeployed(processingUnits);
            break;
        } catch (TimeoutException e) {
            long sleepDuration = end - SystemTime.timeMillis();
            if (sleepDuration < 0) {
                throw e;
            }
            //suppress and retry
            Thread.sleep(Math.min(1000, sleepDuration));
        }
    }
}

From source file:org.cloudifysource.esc.shell.installer.CloudGridAgentBootstrapper.java

/**
 * Bootstraps and waits until the management machines are running, or until the timeout is reached.
 * /* ww w.  j  a  v  a2  s  .c o  m*/
 * @param securityProfile
 *            set security profile (nonsecure/secure/ssl)
 * @param username
 *            The username for a secure connection to the server
 * @param password
 *            The password for a secure connection to the server
 * @param keystorePassword
 *            The password to the keystore to set on the rest server
 * @param performValidation
 *            true to perform configuration validations before bootstrap, false otherwise
 * @param timeout
 *            The number of {@link TimeUnit}s to wait before timing out
 * @param timeoutUnit
 *            The time unit to use (seconds, minutes etc.)
 * @throws InstallerException
 *             Indicates the provisioning driver failed to start management machines or that the management
 *             processes failed to start
 * @throws CLIException
 *             Indicates a basic failure or a time out. a detailed message is included
 * @throws InterruptedException
 *             Indicates a thread was interrupted while waiting
 */
public void bootstrapCloudAndWait(final String securityProfile, final String username, final String password,
        final String keystorePassword, final boolean performValidation, final long timeout,
        final TimeUnit timeoutUnit) throws InstallerException, CLIException, InterruptedException {

    final long end = System.currentTimeMillis() + timeoutUnit.toMillis(timeout);

    createProvisioningDriver(performValidation);

    // Start the cloud machines!!!
    final MachineDetails[] servers = getOrCreateManagementServers(timeout, timeoutUnit, keystorePassword,
            securityProfile);

    // from this point on - close machines if an exception is thrown (to
    // avoid leaks).
    try {

        // log details in FINE
        if (logger.isLoggable(Level.FINE)) {
            for (final MachineDetails server : servers) {
                logServerDetails(server);
            }
        }

        validateServers(servers);

        // Start the management agents and other processes
        // if (servers[0].isAgentRunning()) {
        // // must be using existing machines.
        // throw new IllegalStateException(
        // "Cloud bootstrapper found existing management machines with the same name. "
        // + "Please shut them down before continuing");
        // }

        if (servers[0].isAgentRunning()) {
            logger.fine(
                    "Management servers are already running Cloudify agent - skipping default bootstrapping");
        } else {
            startManagememntProcesses(servers, securityProfile, keystorePassword, end);
        }

        if (!isNoWebServices()) {
            final Integer restPort = getRestPort(cloud.getConfiguration().getComponents().getRest().getPort(),
                    ShellUtils.isSecureConnection(securityProfile));
            final Integer webuiPort = getWebuiPort(
                    cloud.getConfiguration().getComponents().getWebui().getPort(),
                    ShellUtils.isSecureConnection(securityProfile));
            waitForManagementWebServices(ShellUtils.isSecureConnection(securityProfile), username, password,
                    restPort, webuiPort, end, servers);
        }

    } catch (final IOException e) {
        stopManagementMachines();
        throw new CLIException("Cloudify bootstrap on provider " + this.cloud.getProvider().getProvider()
                + " failed. Reason: " + e.getMessage(), e);
    } catch (final URISyntaxException e) {
        stopManagementMachines();
        throw new CLIException("Bootstrap-cloud failed. Reason: " + e.getMessage(), e);
    } catch (final TimeoutException e) {
        stopManagementMachines();
        throw new CLIException("Cloudify bootstrap on provider " + this.cloud.getProvider().getProvider()
                + " timed-out. " + "Please try to run again using the timeout option.", e);
    } catch (final CLIException e) {
        stopManagementMachines();
        throw e;
    } catch (final InstallerException e) {
        stopManagementMachines();
        throw e;
    } catch (final InterruptedException e) {
        stopManagementMachines();
        throw e;
    }
}

From source file:org.nuxeo.ecm.core.work.WorkManagerImpl.java

protected boolean shutdownExecutors(Collection<WorkThreadPoolExecutor> list, long timeout, TimeUnit unit)
        throws InterruptedException {
    // mark executors as shutting down
    for (WorkThreadPoolExecutor executor : list) {
        executor.shutdownAndSuspend();//  w w  w. j av  a  2  s  .c o m
    }

    long t0 = System.currentTimeMillis();
    long delay = unit.toMillis(timeout);

    // wait for termination or suspension
    boolean terminated = true;
    for (WorkThreadPoolExecutor executor : list) {
        long remaining = remainingMillis(t0, delay);
        if (!executor.awaitTerminationOrSave(remaining, TimeUnit.MILLISECONDS)) {
            terminated = false;
            // hard shutdown for remaining tasks
            executor.shutdownNow();
        }
    }

    return terminated;
}

From source file:voldemort.client.ClientConfig.java

/**
 * The amount of time to keep an idle client thread alive
 * //  w ww .j  a v a2 s.c  o  m
 * @param threadIdleTime
 */
@Deprecated
public ClientConfig setThreadIdleTime(long threadIdleTime, TimeUnit unit) {
    this.threadIdleMs = unit.toMillis(threadIdleTime);
    return this;
}

From source file:voldemort.client.ClientConfig.java

/**
 * Set the SO_TIMEOUT for the socket if using HTTP or socket based network
 * communication. This is the maximum amount of time the socket will block
 * waiting for network activity./* ww  w  .  j a va 2s.  co  m*/
 * 
 * @param socketTimeout The socket timeout
 * @param unit The time unit of the timeout value
 */
public ClientConfig setSocketTimeout(int socketTimeout, TimeUnit unit) {
    this.socketTimeoutMs = unit.toMillis(socketTimeout);
    return this;
}