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.shell.installer.LocalhostGridAgentBootstrapper.java

/**
 * Starts management processes (LUS, GSM, ESM), and waits until the requested service installations complete (space,
 * webui, REST), or until the timeout is reached.
 * //from w  w  w .  j av a 2s.c o  m
 * @param gsAgentArgs
 *            GS agent start-up switches
 * @param securityProfile
 *            set security profile (nonsecure/secure/ssl)
 * @param securityFilePath
 *            path to the security configuration file
 * @param username
 *            The username for a secure connection to the server
 * @param password
 *            The password for a secure connection to the server
 * @param keystoreFilePath
 *            path to the keystore file
 * @param keystorePassword
 *            The password to the keystore set on the rest server
 * @param timeout
 *            number of {@link TimeUnit}s to wait
 * @param timeunit
 *            the {@link TimeUnit} to use, to calculate the timeout
 * @param isLocalCloud
 *            Is this a local cloud (true - yes, false - no)
 * @throws CLIException
 *             Reporting a failure to start the processes and services
 * @throws InterruptedException
 *             Reporting the thread was interrupted while waiting
 * @throws TimeoutException
 *             Reporting the timeout was reached
 */
private void startManagementOnLocalhostAndWaitInternal(final String[] gsAgentArgs, final String securityProfile,
        final String securityFilePath, final String username, final String password,
        final String keystoreFilePath, final String keystorePassword, final int timeout,
        final TimeUnit timeunit, final boolean isLocalCloud)
        throws CLIException, InterruptedException, TimeoutException {

    setIsLocalCloud(isLocalCloud);

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

    final ConnectionLogsFilter connectionLogs = new ConnectionLogsFilter();
    connectionLogs.supressConnectionErrors();
    final Admin admin = createAdmin();
    try {
        setLookupDefaults(admin);
        GridServiceAgent agent;
        try {
            try {
                if (!isLocalCloud || fastExistingAgentCheck()) {
                    waitForExistingAgent(admin, progressInSeconds, TimeUnit.SECONDS);
                    throw new CLIException("Agent already running on local machine.");
                }
            } catch (final TimeoutException e) {
                // no existing agent running on local machine
            }

            runGsAgentOnLocalHost("agent and management processes", gsAgentArgs, securityProfile,
                    securityFilePath, keystoreFilePath, keystorePassword);
            agent = waitForNewAgent(admin, ShellUtils.millisUntil(TIMEOUT_ERROR_MESSAGE, end),
                    TimeUnit.MILLISECONDS);
        } finally {
            connectionLogs.restoreConnectionErrors();
        }

        // waiting for LUS, GSM and ESM services to start
        waitForManagementProcesses(agent, ShellUtils.millisUntil(TIMEOUT_ERROR_MESSAGE, end),
                TimeUnit.MILLISECONDS);

        final List<AbstractManagementServiceInstaller> waitForManagementServices = new LinkedList<AbstractManagementServiceInstaller>();

        if (isLocalCloud) {
            startLocalCloudManagementServicesContainer(agent);
        }

        connectionLogs.supressConnectionErrors();
        try {
            ManagementSpaceServiceInstaller managementSpaceInstaller = null;
            if (!noManagementSpace) {
                final boolean highlyAvailable = !isLocalCloud && !notHighlyAvailableManagementSpace;
                final String gscLrmiCommandLineArg = getGscLrmiCommandLineArg();
                managementSpaceInstaller = new ManagementSpaceServiceInstaller();
                managementSpaceInstaller.setAdmin(agent.getAdmin());
                managementSpaceInstaller.setVerbose(verbose);
                managementSpaceInstaller.setProgress(progressInSeconds, TimeUnit.SECONDS);
                managementSpaceInstaller.setMemory(CloudifyConstants.MANAGEMENT_SPACE_MEMORY_IN_MB,
                        MemoryUnit.MEGABYTES);
                managementSpaceInstaller.setServiceName(MANAGEMENT_SPACE_NAME);
                managementSpaceInstaller.setManagementZone(MANAGEMENT_ZONE);
                managementSpaceInstaller.setHighlyAvailable(highlyAvailable);
                managementSpaceInstaller.addListeners(this.eventsListenersList);
                managementSpaceInstaller.setIsLocalCloud(isLocalCloud);
                managementSpaceInstaller.setLrmiCommandLineArgument(gscLrmiCommandLineArg);

                if (!this.isLocalCloud) {
                    final String persistentStoragePath = this.cloud.getConfiguration()
                            .getPersistentStoragePath();
                    if (persistentStoragePath != null) {
                        final String spaceStoragePath = persistentStoragePath + "/management-space/db.h2";
                        managementSpaceInstaller.setPersistentStoragePath(spaceStoragePath);
                    }
                }
                try {
                    managementSpaceInstaller.installSpace();
                    waitForManagementServices.add(managementSpaceInstaller);
                } catch (final ProcessingUnitAlreadyDeployedException e) {
                    if (verbose) {
                        logger.fine("Service " + MANAGEMENT_SPACE_NAME + " already installed");
                        publishEvent("Service " + MANAGEMENT_SPACE_NAME + " already installed");
                    }
                }
            }

            if (!noWebServices) {
                installWebServices(username, password, isLocalCloud,
                        ShellUtils.isSecureConnection(securityProfile), agent, waitForManagementServices);
            }

            for (final AbstractManagementServiceInstaller managementServiceInstaller : waitForManagementServices) {
                managementServiceInstaller.waitForInstallation(adminFacade, agent,
                        ShellUtils.millisUntil(TIMEOUT_ERROR_MESSAGE, end), TimeUnit.MILLISECONDS);
                if (managementServiceInstaller instanceof ManagementSpaceServiceInstaller) {
                    logger.fine("Writing cloud configuration to space.");
                    if (verbose) {
                        publishEvent("Writing cloud configuration to space.");
                    }
                    final GigaSpace gigaspace = managementSpaceInstaller.getGigaSpace();

                    final CloudConfigurationHolder holder = new CloudConfigurationHolder(null,
                            getCloudFilePath());
                    logger.fine("Writing cloud Configuration to space: " + holder);
                    gigaspace.write(holder);
                    // Shut down the space proxy so that if the cloud is
                    // turned down later, there will not
                    // be any discovery errors.
                    // Note: in a spring environment, the bean shutdown
                    // would clean this up.
                    // TODO - Move the space writing part into the
                    // management space
                    // installer and do the clean up there.
                    ((ISpaceProxy) gigaspace.getSpace()).close();
                }
            }

        } finally {
            connectionLogs.restoreConnectionErrors();
        }
    } finally {
        admin.close();
    }
}

From source file:org.apache.ogt.http.impl.conn.SingleClientConnManager.java

public synchronized void releaseConnection(ManagedClientConnection conn, long validDuration,
        TimeUnit timeUnit) {
    assertStillUp();//from w w  w  .  ja  v  a  2  s  .  co  m

    if (!(conn instanceof ConnAdapter)) {
        throw new IllegalArgumentException(
                "Connection class mismatch, " + "connection not obtained from this manager.");
    }

    if (log.isDebugEnabled()) {
        log.debug("Releasing connection " + conn);
    }

    ConnAdapter sca = (ConnAdapter) conn;
    if (sca.poolEntry == null)
        return; // already released
    ClientConnectionManager manager = sca.getManager();
    if (manager != null && manager != this) {
        throw new IllegalArgumentException("Connection not obtained from this manager.");
    }

    try {
        // make sure that the response has been read completely
        if (sca.isOpen() && (this.alwaysShutDown || !sca.isMarkedReusable())) {
            if (log.isDebugEnabled()) {
                log.debug("Released connection open but not reusable.");
            }

            // make sure this connection will not be re-used
            // we might have gotten here because of a shutdown trigger
            // shutdown of the adapter also clears the tracked route
            sca.shutdown();
        }
    } catch (IOException iox) {
        if (log.isDebugEnabled())
            log.debug("Exception shutting down released connection.", iox);
    } finally {
        sca.detach();
        managedConn = null;
        lastReleaseTime = System.currentTimeMillis();
        if (validDuration > 0)
            connectionExpiresTime = timeUnit.toMillis(validDuration) + lastReleaseTime;
        else
            connectionExpiresTime = Long.MAX_VALUE;
    }
}

From source file:org.apache.geode.distributed.LocatorLauncher.java

/**
 * Waits for a Locator status request response to be returned up to the specified timeout in the
 * given unit of time. This call will send status requests at fixed intervals in the given unit of
 * time until the timeout expires. If the request to determine the Locator's status is successful,
 * then the Locator is considered to be 'ONLINE'. Otherwise, the Locator is considered to be
 * unresponsive to the status request./*from   w  w  w .j  a  v  a  2s .co m*/
 *
 * However, this does not necessarily imply the Locator start was unsuccessful, only that a
 * response was not received in the given time period.
 *
 * Note, this method does not block or cause the Locator's location-based services (daemon
 * Threads) to continue running in anyway if the main application Thread terminates when running
 * the Locator in-process. If the caller wishes to start a Locator in an asynchronous manner
 * within the application process, then a call should be made to <code>waitOnLocator</code>.
 *
 * @param timeout a long value in time unit indicating when the period of time should expire in
 *        attempting to determine the Locator's status.
 * @param interval a long value in time unit for how frequent the requests should be sent to the
 *        Locator.
 * @param timeUnit the unit of time in which the timeout and interval are measured.
 * @return the state of the Locator, which will either be 'ONLINE' or "NOT RESPONDING'. If the
 *         status returned is 'NOT RESPONDING', it just means the Locator did not respond to the
 *         status request within the given time period. It should not be taken as the Locator
 *         failed to start.
 * @see #waitOnLocator()
 */
public LocatorState waitOnStatusResponse(final long timeout, final long interval, final TimeUnit timeUnit) {
    final long endTimeInMilliseconds = (System.currentTimeMillis() + timeUnit.toMillis(timeout));

    while (System.currentTimeMillis() < endTimeInMilliseconds) {
        try {
            LocatorStatusResponse response = statusLocator(getPort(), getBindAddress());
            return new LocatorState(this, Status.ONLINE, response);
        } catch (Exception handled) {
            timedWait(interval, timeUnit);
        }
    }

    // NOTE just because we were not able to communicate with the Locator in the given amount of
    // time does not mean
    // the Locator is having problems. The Locator could be slow in starting up and the timeout may
    // not be
    // long enough.
    return new LocatorState(this, Status.NOT_RESPONDING);
}

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

@Override
public MachineDetails startMachine(final ProvisioningContext context, final long duration, final TimeUnit unit)
        throws TimeoutException, CloudProvisioningException {
    logger.fine(this.getClass().getName() + ": startMachine, management mode: " + management);
    final long end = System.currentTimeMillis() + unit.toMillis(duration);

    if (System.currentTimeMillis() > end) {
        throw new TimeoutException("Starting a new machine timed out");
    }/*  w w w. jav a  2 s .c  o m*/

    try {
        // Create application secgroups
        this.createSecurityGroup(this.openstackPrefixes.getApplicationName());
        this.createSecurityGroup(this.openstackPrefixes.getServiceName());
        this.createSecurityGroupsRules();

        if (networkHelper.useApplicationNetworkTemplate()) {
            // Network
            final Network network = this
                    .getOrCreateNetwork(this.networkHelper.getApplicationNetworkPrefixedName());
            if (network != null) {
                // Subnets
                final NetworkConfiguration networkTemplate = this.networkHelper.getApplicationNetworkTemplate();
                final List<org.cloudifysource.domain.cloud.network.Subnet> subnets = networkTemplate
                        .getSubnets();
                for (final org.cloudifysource.domain.cloud.network.Subnet subnetConfig : subnets) {
                    this.getOrCreateSubnet(subnetConfig, network);
                }
            }
        }

        final String groupName = serverNamePrefix + this.configuration.getServiceName() + "-"
                + counter.incrementAndGet();
        logger.fine("Starting a new cloud server with group: " + groupName);
        final ComputeTemplate computeTemplate = this.cloud.getCloudCompute().getTemplates()
                .get(this.cloudTemplateName);

        final MachineDetails md = this.createServer(groupName, end, computeTemplate, context.getLocationId());
        return md;
    } catch (final OpenstackException e) {
        throw new CloudProvisioningException("Failed to start cloud machine", e);
    }
}

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

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

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

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

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

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

    // Create management secgroups and rules
    this.initManagementSecurityGroups();

    // Create management networks
    if (networkHelper.useManagementNetwork()) {
        this.createManagementNetworkAndSubnets();
    }

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

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

private void waitForServerToBeShutdown(final String serverId, final long duration, final TimeUnit unit)
        throws CloudProvisioningException, InterruptedException, TimeoutException {

    logger.finer("Wait server '" + serverId + "' to shutdown (" + duration + " " + unit + ")");

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

    while (System.currentTimeMillis() < endTime) {
        final NovaServer server;
        try {/*w w w .j a v a 2s  .  c  o  m*/
            server = computeApi.getServerDetails(serverId);
        } catch (final OpenstackException e) {
            throw new CloudProvisioningException(e);
        }

        if (server == null) {
            logger.fine("Server Status (" + serverId + ") Not Found. Considered deleted.");
            return;
        } else {
            switch (server.getStatus()) {
            case STOPPED:
            case DELETED:
                return;
            case ERROR:
            case UNKNOWN:
            case UNRECOGNIZED:
                throw new CloudProvisioningException("Failed to allocate server - Cloud reported node in "
                        + server.getStatus().toString() + " state. Node details: " + server);
            default:
                logger.fine("Server Status (" + serverId + ") is " + server.getStatus()
                        + ", please wait until shutdown...");
                Thread.sleep(CLOUD_NODE_STATE_POLLING_INTERVAL);
                break;
            }
        }

    }

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

From source file:org.apache.http.impl.conn.SingleClientConnManager.java

public void releaseConnection(final ManagedClientConnection conn, final long validDuration,
        final TimeUnit timeUnit) {
    Args.check(conn instanceof ConnAdapter,
            "Connection class mismatch, " + "connection not obtained from this manager");
    assertStillUp();/*from w  w w.j ava2 s .c o m*/

    if (log.isDebugEnabled()) {
        log.debug("Releasing connection " + conn);
    }

    final ConnAdapter sca = (ConnAdapter) conn;
    synchronized (sca) {
        if (sca.poolEntry == null) {
            return; // already released
        }
        final ClientConnectionManager manager = sca.getManager();
        Asserts.check(manager == this, "Connection not obtained from this manager");
        try {
            // make sure that the response has been read completely
            if (sca.isOpen() && (this.alwaysShutDown || !sca.isMarkedReusable())) {
                if (log.isDebugEnabled()) {
                    log.debug("Released connection open but not reusable.");
                }

                // make sure this connection will not be re-used
                // we might have gotten here because of a shutdown trigger
                // shutdown of the adapter also clears the tracked route
                sca.shutdown();
            }
        } catch (final IOException iox) {
            if (log.isDebugEnabled()) {
                log.debug("Exception shutting down released connection.", iox);
            }
        } finally {
            sca.detach();
            synchronized (this) {
                managedConn = null;
                lastReleaseTime = System.currentTimeMillis();
                if (validDuration > 0) {
                    connectionExpiresTime = timeUnit.toMillis(validDuration) + lastReleaseTime;
                } else {
                    connectionExpiresTime = Long.MAX_VALUE;
                }
            }
        }
    }
}

From source file:org.apache.http2.impl.conn.SingleClientConnManager.java

public void releaseConnection(ManagedClientConnection conn, long validDuration, TimeUnit timeUnit) {
    assertStillUp();//from   ww  w  . ja va 2  s .c om

    if (!(conn instanceof ConnAdapter)) {
        throw new IllegalArgumentException(
                "Connection class mismatch, " + "connection not obtained from this manager.");
    }

    if (log.isDebugEnabled()) {
        log.debug("Releasing connection " + conn);
    }

    ConnAdapter sca = (ConnAdapter) conn;
    synchronized (sca) {
        if (sca.poolEntry == null)
            return; // already released
        ClientConnectionManager manager = sca.getManager();
        if (manager != null && manager != this) {
            throw new IllegalArgumentException("Connection not obtained from this manager.");
        }
        try {
            // make sure that the response has been read completely
            if (sca.isOpen() && (this.alwaysShutDown || !sca.isMarkedReusable())) {
                if (log.isDebugEnabled()) {
                    log.debug("Released connection open but not reusable.");
                }

                // make sure this connection will not be re-used
                // we might have gotten here because of a shutdown trigger
                // shutdown of the adapter also clears the tracked route
                sca.shutdown();
            }
        } catch (IOException iox) {
            if (log.isDebugEnabled())
                log.debug("Exception shutting down released connection.", iox);
        } finally {
            sca.detach();
            synchronized (this) {
                managedConn = null;
                lastReleaseTime = System.currentTimeMillis();
                if (validDuration > 0)
                    connectionExpiresTime = timeUnit.toMillis(validDuration) + lastReleaseTime;
                else
                    connectionExpiresTime = Long.MAX_VALUE;
            }
        }
    }
}

From source file:org.openspaces.admin.internal.admin.DefaultAdmin.java

@Override
public void setStatisticsInterval(long interval, TimeUnit timeUnit) {
    this.statisticsInterval = timeUnit.toMillis(interval);
    this.spaces.setStatisticsInterval(interval, timeUnit);
    this.virtualMachines.setStatisticsInterval(interval, timeUnit);
    this.transports.setStatisticsInterval(interval, timeUnit);
    this.operatingSystems.setStatisticsInterval(interval, timeUnit);
    this.processingUnits.setStatisticsInterval(interval, timeUnit);
}