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.springframework.integration.jms.JmsOutboundGateway.java

/**
 * Set the target timeout for idle containers. Setting this greater than zero enables lazy
 * starting of the reply listener container. The container will be started when a message is sent. It will be
 * stopped when idle for at least this time. The actual stop time may be up to 1.5x this time.
 * @param idleReplyContainerTimeout the timeout in seconds.
 * @param unit the time unit./*from  w  w w.  ja v  a2 s  .  c om*/
 * @since 4.2
 */
public void setIdleReplyContainerTimeout(long idleReplyContainerTimeout, TimeUnit unit) {
    this.idleReplyContainerTimeout = unit.toMillis(idleReplyContainerTimeout);
}

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

@Override
@TransactionalRollbackAllExceptions/* w  ww  .j a v  a 2 s  .co m*/
@Timed
public int ageEvents(long agingInterval, TimeUnit unit, EventSeverity maxSeverity, int limit,
        boolean inclusiveSeverity) throws ZepException {
    TypeConverter<Long> timestampConverter = databaseCompatibility.getTimestampConverter();
    long agingIntervalMs = unit.toMillis(agingInterval);
    if (agingIntervalMs < 0 || agingIntervalMs == Long.MAX_VALUE) {
        throw new ZepException("Invalid aging interval: " + agingIntervalMs);
    }
    if (limit <= 0) {
        throw new ZepException("Limit can't be negative: " + limit);
    }
    List<Integer> severityIds = getSeverityIds(maxSeverity, inclusiveSeverity);
    if (severityIds.isEmpty()) {
        logger.debug("Not aging events - min severity specified");
        return 0;
    }
    long now = System.currentTimeMillis();
    long ageTs = now - agingIntervalMs;

    Map<String, Object> fields = new HashMap<String, Object>();
    fields.put(COLUMN_STATUS_ID, EventStatus.STATUS_AGED.getNumber());
    fields.put(COLUMN_CLOSED_STATUS, ZepConstants.CLOSED_STATUSES.contains(EventStatus.STATUS_AGED));
    fields.put(COLUMN_STATUS_CHANGE, timestampConverter.toDatabaseType(now));
    fields.put(COLUMN_UPDATE_TIME, timestampConverter.toDatabaseType(now));
    fields.put(COLUMN_LAST_SEEN, timestampConverter.toDatabaseType(ageTs));
    fields.put("_severity_ids", severityIds);
    fields.put("_limit", limit);

    final String updateSql;
    if (databaseCompatibility.getDatabaseType() == DatabaseType.MYSQL) {
        String indexSql = "INSERT INTO event_summary_index_queue (uuid, update_time) " + "SELECT uuid, "
                + String.valueOf(now) + " " + "FROM event_summary " + " WHERE last_seen < :last_seen AND"
                + " severity_id IN (:_severity_ids) AND" + " closed_status = FALSE LIMIT :_limit";
        this.template.update(indexSql, fields);

        // Use UPDATE ... LIMIT
        updateSql = "UPDATE event_summary SET"
                + " status_id=:status_id,status_change=:status_change,update_time=:update_time"
                + ",closed_status=:closed_status"
                + " WHERE last_seen < :last_seen AND severity_id IN (:_severity_ids)"
                + " AND closed_status = FALSE LIMIT :_limit";
    } else if (databaseCompatibility.getDatabaseType() == DatabaseType.POSTGRESQL) {
        String indexSql = "INSERT INTO event_summary_index_queue (uuid, update_time) " + "SELECT uuid, "
                + String.valueOf(now) + " " + "FROM event_summary "
                + " WHERE uuid IN (SELECT uuid FROM event_summary WHERE"
                + " last_seen < :last_seen AND severity_id IN (:_severity_ids)"
                + " AND closed_status = FALSE LIMIT :_limit)";
        this.template.update(indexSql, fields);

        // Use UPDATE ... WHERE pk IN (SELECT ... LIMIT)
        updateSql = "UPDATE event_summary SET"
                + " status_id=:status_id,status_change=:status_change,update_time=:update_time"
                + ",closed_status=:closed_status" + " WHERE uuid IN (SELECT uuid FROM event_summary WHERE"
                + " last_seen < :last_seen AND severity_id IN (:_severity_ids)"
                + " AND closed_status = FALSE LIMIT :_limit)";
    } else {
        throw new IllegalStateException(
                "Unsupported database type: " + databaseCompatibility.getDatabaseType());
    }
    final int numRows = this.template.update(updateSql, fields);
    if (numRows > 0) {
        TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
            @Override
            public void afterCommit() {
                counters.addToAgedEventCount(numRows);
            }
        });
    }
    return numRows;
}

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

@Override
public GridServiceAgent startMachine(final ExactZonesConfig zones, final GSAReservationId reservationId,
        final long duration, final TimeUnit unit) throws ElasticMachineProvisioningException,
        ElasticGridServiceAgentProvisioningException, InterruptedException, TimeoutException {

    logger.info("Cloudify Adapter is starting a new machine with zones " + zones.getZones()
            + " and reservation id " + reservationId);

    // calculate timeout
    final long end = System.currentTimeMillis() + unit.toMillis(duration);

    // provision the machine
    logger.info("Calling provisioning implementation for new machine");
    MachineDetails machineDetails;/*  w  w w  .j a va  2s  . com*/
    cloudifyProvisioning.setAdmin(getGlobalAdminInstance(originalESMAdmin));

    final ZonesConfig defaultZones = config.getGridServiceAgentZones();
    logger.fine("default zones = " + defaultZones.getZones());
    if (!defaultZones.isSatisfiedBy(zones)) {
        throw new IllegalArgumentException(
                "The specified zones " + zones + " does not satisfy the configuration zones " + defaultZones);
    }

    String locationId = null;

    logger.fine("searching for cloud specific zone");
    for (final String zone : zones.getZones()) {
        logger.fine("current zone = " + zone);
        if (zone.startsWith(CLOUD_ZONE_PREFIX)) {
            logger.fine("found a zone with " + CLOUD_ZONE_PREFIX + " prefix : " + zone);
            if (locationId == null) {
                locationId = zone.substring(CLOUD_ZONE_PREFIX.length());
                logger.fine("passing locationId to machine provisioning as " + locationId);
            } else {
                throw new IllegalArgumentException(
                        "The specified zones " + zones + " should include only one zone with the "
                                + CLOUD_ZONE_PREFIX + " prefix:" + locationId);
            }
        }
    }

    final MachineStartRequestedCloudifyEvent machineStartEvent = new MachineStartRequestedCloudifyEvent();
    machineStartEvent.setTemplateName(cloudTemplateName);
    machineStartEvent.setLocationId(locationId);
    machineEventListener.elasticMachineProvisioningProgressChanged(machineStartEvent);

    try {
        final ComputeTemplate template = cloud.getCloudCompute().getTemplates().get(this.cloudTemplateName);
        if (locationId == null) {
            locationId = template.getLocationId();
        }

        // This is the call to the actual cloud driver implementation!
        machineDetails = provisionMachine(locationId, reservationId, duration, unit);

        // This is to protect against a bug in the Admin. see CLOUDIFY-1592
        // (https://cloudifysource.atlassian.net/browse/CLOUDIFY-1592)
        if (!machineDetails.isAgentRunning()) {
            validateMachineIp(machineDetails);
        }

        // Auto populate installer configuration with values set in template
        // if they were not previously set.
        if (machineDetails != null && machineDetails.getInstallerConfiguration() == null) {
            machineDetails.setInstallerConfigutation(template.getInstaller());
        }

    } catch (final Exception e) {
        throw new ElasticMachineProvisioningException("Failed to provision machine: " + e.getMessage(), e);
    }

    logger.info("Machine was provisioned by implementation. Machine is: " + machineDetails);

    // which IP should be used in the cluster
    String machineIp;
    if (cloud.getConfiguration().isConnectToPrivateIp()) {
        machineIp = machineDetails.getPrivateAddress();
    } else {
        machineIp = machineDetails.getPublicAddress();
    }
    if (machineIp == null) {
        throw new IllegalStateException(
                "The IP of the new machine is null! Machine Details are: " + machineDetails + " .");
    }

    final MachineStartedCloudifyEvent machineStartedEvent = new MachineStartedCloudifyEvent();
    machineStartedEvent.setMachineDetails(machineDetails);
    machineStartedEvent.setHostAddress(machineIp);
    machineEventListener.elasticMachineProvisioningProgressChanged(machineStartedEvent);

    final GridServiceAgentStartRequestedEvent agentStartEvent = new GridServiceAgentStartRequestedEvent();
    agentStartEvent.setHostAddress(machineIp);
    agentEventListener.elasticGridServiceAgentProvisioningProgressChanged(agentStartEvent);
    final String volumeId = null;
    try {
        // check for timeout
        checkForProvisioningTimeout(end, machineDetails);

        if (machineDetails.isAgentRunning()) {
            logger.info(
                    "Machine provisioning provided a machine and indicated that an agent is already running");
        } else {
            // install gigaspaces and start agent
            logger.info("Cloudify Adapter is installing Cloudify agent with reservation id " + reservationId
                    + " on " + machineIp);
            installAndStartAgent(machineDetails, reservationId, end);
            // check for timeout again - the installation step can also take
            // a while to complete.
            checkForProvisioningTimeout(end, machineDetails);
        }

        // wait for GSA to become available
        logger.info("Cloudify adapter is waiting for GSA on host: " + machineIp + " with reservation id: "
                + reservationId + " to become available");
        final GridServiceAgent gsa = waitForGsa(machineIp, end, reservationId);
        if (gsa == null) {
            // GSA did not start correctly or on time - shutdown the machine
            throw new TimeoutException("New machine was provisioned and Cloudify was installed, "
                    + "but a GSA was not discovered on the new machine: " + machineDetails);
        }

        // TODO: Derive cloudify specific event and include more event details as specified in CLOUDIFY-10651
        agentEventListener.elasticGridServiceAgentProvisioningProgressChanged(
                new GridServiceAgentStartedEvent(machineIp, gsa.getUid()));

        // check that the agent is really started with the expected env variable of the template
        // we inject this variable earlier on to the bootstrap-management.sh script
        if (gsa.getVirtualMachine().getDetails().getEnvironmentVariables()
                .get(CloudifyConstants.GIGASPACES_CLOUD_TEMPLATE_NAME) == null) {
            throw new ElasticGridServiceAgentProvisioningException(
                    "an agent was started. but the property " + CloudifyConstants.GIGASPACES_CLOUD_TEMPLATE_NAME
                            + " was missing from its environment variables.");
        }

        return gsa;
    } catch (final ElasticMachineProvisioningException e) {
        logger.info("ElasticMachineProvisioningException occurred, " + e.getMessage());
        logger.info(ExceptionUtils.getFullStackTrace(e));
        handleExceptionAfterMachineCreated(machineIp, volumeId, machineDetails, end, reservationId);
        throw e;
    } catch (final ElasticGridServiceAgentProvisioningException e) {
        logger.info("ElasticGridServiceAgentProvisioningException occurred, " + e.getMessage());
        logger.info(ExceptionUtils.getFullStackTrace(e));
        handleExceptionAfterMachineCreated(machineIp, volumeId, machineDetails, end, reservationId);
        throw e;
    } catch (final TimeoutException e) {
        logger.info("TimeoutException occurred, " + e.getMessage());
        logger.info(ExceptionUtils.getFullStackTrace(e));
        handleExceptionAfterMachineCreated(machineIp, volumeId, machineDetails, end, reservationId);
        throw e;
    } catch (final InterruptedException e) {
        logger.info("InterruptedException occurred, " + e.getMessage());
        logger.info(ExceptionUtils.getFullStackTrace(e));
        handleExceptionAfterMachineCreated(machineIp, volumeId, machineDetails, end, reservationId);
        throw e;
    } catch (final Throwable e) {
        logger.info("Unexpected exception occurred, " + e.getMessage());
        logger.info(ExceptionUtils.getFullStackTrace(e));
        handleExceptionAfterMachineCreated(machineIp, volumeId, machineDetails, end, reservationId);
        throw new IllegalStateException("Unexpected exception during machine provisioning", e);
    }
}

From source file:org.openspaces.grid.gsm.rebalancing.RebalancingUtils.java

static FutureStatefulProcessingUnitInstance relocateProcessingUnitInstanceAsync(
        final GridServiceContainer targetContainer, final ProcessingUnitInstance puInstance, final Log logger,
        final long duration, final TimeUnit timeUnit) {

    final ProcessingUnit pu = puInstance.getProcessingUnit();
    final GridServiceContainer[] replicationSourceContainers = getReplicationSourceContainers(puInstance);
    final int instanceId = puInstance.getInstanceId();

    final AtomicReference<Throwable> relocateThrowable = new AtomicReference<Throwable>();

    final Admin admin = puInstance.getAdmin();
    final int runningNumber = puInstance.getClusterInfo().getRunningNumber();
    final String puName = puInstance.getName();

    final GridServiceContainer sourceContainer = puInstance.getGridServiceContainer();
    final Set<ProcessingUnitInstance> puInstancesFromSamePartition = getOtherInstancesFromSamePartition(
            puInstance);//from ww w . jav  a  2 s  .  com
    if (logger.isDebugEnabled()) {
        logger.debug(
                "Found instances from the same partition as " + RebalancingUtils.puInstanceToString(puInstance)
                        + " : " + RebalancingUtils.puInstancesToString(puInstancesFromSamePartition));
    }

    if (puInstancesFromSamePartition.size() != pu.getNumberOfBackups()) {
        // total number of instances per partition = numberOfBackups + 1
        throw new IllegalStateException("puInstancesFromSamePartition has "
                + puInstancesFromSamePartition.size() + " instances instead of " + pu.getNumberOfBackups());
    }

    final long start = System.currentTimeMillis();
    final long end = start + timeUnit.toMillis(duration);

    ((InternalAdmin) admin).scheduleAdminOperation(new Runnable() {
        public void run() {
            try {
                logger.debug("Relocation of " + RebalancingUtils.puInstanceToString(puInstance) + " to "
                        + ContainersSlaUtils.gscToString(targetContainer) + " has started.");
                puInstance.relocate(targetContainer);
            } catch (AdminException e) {
                logger.error("Admin exception " + e.getMessage(), e);
                relocateThrowable.set(e);
            } catch (Throwable e) {
                logger.error("Unexpected exception " + e.getMessage(), e);
                relocateThrowable.set(e);
            }
        }
    });

    return new FutureStatefulProcessingUnitInstance() {

        Throwable throwable;
        ProcessingUnitInstance newInstance;

        public boolean isTimedOut() {
            return System.currentTimeMillis() > end;
        }

        public boolean isDone() {

            endRelocation();

            return isTimedOut() || throwable != null || newInstance != null;
        }

        public ProcessingUnitInstance get() throws ExecutionException, IllegalStateException, TimeoutException {

            endRelocation();

            ExecutionException exception = getException();
            if (exception != null) {
                throw exception;
            }
            if (newInstance == null) {
                if (isTimedOut()) {
                    throw new TimeoutException("Relocation timeout");
                }
                throw new IllegalStateException("Async operation is not done yet.");
            }

            return newInstance;
        }

        public Date getTimestamp() {
            return new Date(start);
        }

        public ExecutionException getException() {

            endRelocation();
            if (throwable != null) {
                return new ExecutionException(throwable.getMessage(), throwable);
            }
            return null;
        }

        /**
         * populates this.exception or this.newInstance if relocation is complete
         */
        private void endRelocation() {
            boolean inProgress = true;

            tryStateChange(); // this makes relocation synchronous
            if (newInstance != null || throwable != null) {
                inProgress = false;
            }

            if (inProgress) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Relocation from " + ContainersSlaUtils.gscToString(getSourceContainer())
                            + " to " + ContainersSlaUtils.gscToString(getTargetContainer())
                            + " is in progress.");
                }
                // do nothing. relocate() method running on another thread has not returned yet.
            }
        }

        private void tryStateChange() {
            ProcessingUnitInstance relocatedInstance = getRelocatedProcessingUnitInstance();
            if (relocatedInstance != null) {

                if (relocatedInstance.getGridServiceContainer().equals(targetContainer)) {
                    if (relocatedInstance.getSpaceInstance() != null
                            && relocatedInstance.getSpaceInstance().getMode() != SpaceMode.NONE) {
                        if (logger.isDebugEnabled()) {
                            logger.debug(
                                    "Relocation from " + ContainersSlaUtils.gscToString(getSourceContainer())
                                            + " to " + ContainersSlaUtils.gscToString(getTargetContainer())
                                            + " had ended successfully.");
                        }
                        newInstance = relocatedInstance;
                    }
                } else {
                    if (logger.isDebugEnabled()) {
                        logger.debug("Relocation from " + ContainersSlaUtils.gscToString(getSourceContainer())
                                + " to " + ContainersSlaUtils.gscToString(getTargetContainer())
                                + " has ended with an error.");
                    }
                    throwable = new WrongContainerProcessingUnitRelocationException(puInstance,
                            targetContainer);

                }
            }
        }

        private ProcessingUnitInstance getRelocatedProcessingUnitInstance() {
            for (GridServiceContainer container : admin.getGridServiceContainers()) {
                for (ProcessingUnitInstance instance : container.getProcessingUnitInstances(puName)) {
                    if (!instance.equals(puInstance)
                            && instance.getClusterInfo().getRunningNumber() == runningNumber
                            && !puInstancesFromSamePartition.contains(instance)) {
                        return instance;
                    }
                }
            }
            return null;
        }

        private boolean isAtLeastOneInstanceValid(Set<ProcessingUnitInstance> instances) {
            boolean isValidState = false;
            for (ProcessingUnitInstance instance : instances) {
                if (instance.isDiscovered() && instance.getGridServiceContainer().isDiscovered()) {
                    isValidState = true;
                    break;
                }
            }
            return isValidState;
        }

        public String getFailureMessage() {
            if (isTimedOut()) {
                return "relocation timeout of processing unit instance " + instanceId + " from "
                        + gscToString(sourceContainer) + " to " + gscToString(targetContainer);
            }

            if (getException() != null) {
                return getException().getMessage();
            }

            throw new IllegalStateException("Relocation has not encountered any failure.");

        }

        public GridServiceContainer getTargetContainer() {
            return targetContainer;
        }

        public ProcessingUnit getProcessingUnit() {
            return pu;
        }

        public int getInstanceId() {
            return instanceId;
        }

        public GridServiceContainer getSourceContainer() {
            return sourceContainer;
        }

        public GridServiceContainer[] getReplicaitonSourceContainers() {
            return replicationSourceContainers;
        }

    };
}

From source file:com.alibaba.napoli.gecko.service.timer.HashedWheelTimer.java

/**
 * Creates a new timer./* www  .j  a  v a 2s .  c o m*/
 * 
 * @param threadFactory
 *            a {@link ThreadFactory} that creates a background
 *            {@link Thread} which is dedicated to {@link TimerTask}
 *            execution.
 * @param tickDuration
 *            the duration between tick
 * @param unit
 *            the time unit of the {@code tickDuration}
 * @param ticksPerWheel
 * @param maxTimerCapacity
 *            the size of the wheel
 */
public HashedWheelTimer(final ThreadFactory threadFactory, long tickDuration, final TimeUnit unit,
        final int ticksPerWheel, final int maxTimerCapacity) {

    if (threadFactory == null) {
        throw new NullPointerException("threadFactory");
    }
    if (unit == null) {
        throw new NullPointerException("unit");
    }
    if (tickDuration <= 0) {
        throw new IllegalArgumentException("tickDuration must be greater than 0: " + tickDuration);
    }
    if (ticksPerWheel <= 0) {
        throw new IllegalArgumentException("ticksPerWheel must be greater than 0: " + ticksPerWheel);
    }
    if (maxTimerCapacity <= 0) {
        throw new IllegalArgumentException("maxTimerCapacity must be greater than 0: " + maxTimerCapacity);
    }

    // Normalize ticksPerWheel to power of two and initialize the wheel.
    this.wheel = createWheel(ticksPerWheel);
    this.iterators = createIterators(this.wheel);
    this.maxTimerCapacity = maxTimerCapacity;
    this.mask = this.wheel.length - 1;

    // Convert tickDuration to milliseconds.
    this.tickDuration = tickDuration = unit.toMillis(tickDuration);

    // Prevent overflow.
    if (tickDuration == Long.MAX_VALUE || tickDuration >= Long.MAX_VALUE / this.wheel.length) {
        throw new IllegalArgumentException("tickDuration is too long: " + tickDuration + ' ' + unit);
    }

    this.roundDuration = tickDuration * this.wheel.length;

    this.workerThread = threadFactory
            .newThread(new ThreadRenamingRunnable(this.worker, "Hashed wheel timer #" + id.incrementAndGet()));

    // Misuse check
    final int activeInstances = HashedWheelTimer.activeInstances.incrementAndGet();
    if (activeInstances >= MISUSE_WARNING_THRESHOLD && loggedMisuseWarning.compareAndSet(false, true)) {
        logger.debug("There are too many active " + HashedWheelTimer.class.getSimpleName() + " instances ("
                + activeInstances + ") - you should share the small number "
                + "of instances to avoid excessive resource consumption.");
    }
}

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

private Event createOldEvent(long duration, TimeUnit unit, EventSeverity severity) {
    Event.Builder eventBuilder = Event.newBuilder(createUniqueEvent());
    eventBuilder.setCreatedTime(System.currentTimeMillis() - unit.toMillis(duration));
    eventBuilder.setSeverity(severity);//from  w w w .  j ava 2s.co  m
    return eventBuilder.build();
}

From source file:org.apache.bookkeeper.conf.ServerConfiguration.java

/**
 * Set wait time for garbage collection of overreplicated ledgers. Default: 1 day
 * /*from   w  ww .j  a v a  2 s  . co m*/
 * A ledger can be overreplicated under the following circumstances:
 * 1. The ledger with few entries has bk1 and bk2 as its ensemble.
 * 2. bk1 crashes.
 * 3. bk3 replicates the ledger from bk2 and updates the ensemble to bk2 and bk3.
 * 4. bk1 comes back up.
 * 5. Now there are 3 copies of the ledger.
 *  
 * @param gcWaitTime
 * @return server configuration
 */
public ServerConfiguration setGcOverreplicatedLedgerWaitTime(long gcWaitTime, TimeUnit unit) {
    this.setProperty(GC_OVERREPLICATED_LEDGER_WAIT_TIME, Long.toString(unit.toMillis(gcWaitTime)));
    return this;
}

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

@Override
public boolean waitFor(QuiesceState desiredState, long timeout, TimeUnit timeUnit) {
    if (!isManaged()) {
        throw new AdminException("No managing GSM to execute quiesce");
    }//w  w w .  ja v a  2 s  .c o m
    long interval = 1000;
    long expiration;
    // checking long overflow to set the expiration time properly
    BigInteger sum = BigInteger.valueOf(0);
    sum = sum.add(BigInteger.valueOf(System.currentTimeMillis()))
            .add(BigInteger.valueOf(timeUnit.toMillis(timeout)));
    if (sum.compareTo(BigInteger.valueOf(Long.MAX_VALUE)) > 0)
        expiration = Long.MAX_VALUE;
    else
        expiration = sum.longValue();
    for (;;) {
        QuiesceDetails currentDetails = getQuiesceDetails();
        if (instancesReachedQuiesceState(desiredState, currentDetails)) {
            return true;
        }
        try {
            Thread.sleep(interval);
            if (System.currentTimeMillis() >= expiration) {
                return false;
            }
        } catch (InterruptedException e) {
            return false;
        }
    }
}

From source file:org.openspaces.grid.gsm.machines.plugins.NonBlockingElasticMachineProvisioningAdapter.java

@Override
public FutureGridServiceAgent[] startMachinesAsync(final CapacityRequirements capacityRequirements,
        final ExactZonesConfig zones, final FailedGridServiceAgent[] failedAgents, final long duration,
        final TimeUnit unit) {

    if (!isStartMachineSupported()) {
        throw new UnsupportedOperationException();
    }/*from  w w  w.  j a  va  2 s.  co  m*/

    final GSAReservationId reservationId = GSAReservationId.randomGSAReservationId();
    final CapacityRequirements singleMachineCapacity = machineProvisioning.getCapacityOfSingleMachine();
    int numberOfMachines = calcNumberOfMachines(capacityRequirements, machineProvisioning);
    if (numberOfMachines < failedAgents.length) {
        throw new IllegalArgumentException("capacity requirements should be at least " + failedAgents.length
                + " machines for failure recovery. " + "Instead found " + numberOfMachines
                + " machines, capacity = " + capacityRequirements);
    }
    FutureGridServiceAgent[] futureAgents = new FutureGridServiceAgent[numberOfMachines];

    for (int i = 0; i < futureAgents.length; i++) {
        final AtomicReference<Object> ref = new AtomicReference<Object>(null);

        final int throttlingDelay = i * THROTTLING_DELAY_SECONDS;
        final long start = System.currentTimeMillis();
        final long end = start + throttlingDelay * 1000 + unit.toMillis(duration);
        final FailedGridServiceAgent failedAgent = failedAgents.length > i ? failedAgents[i] : null;
        submit(new Runnable() {
            public void run() {
                try {
                    logger.info("Starting a new machine");
                    StartedGridServiceAgent agent = machineProvisioning.startMachine(zones, reservationId,
                            failedAgent, duration, unit);
                    ref.set(agent);
                    logger.info("New machine started");
                } catch (ElasticMachineProvisioningException e) {
                    ref.set(e);
                } catch (ElasticGridServiceAgentProvisioningException e) {
                    ref.set(e);
                } catch (InterruptedException e) {
                    ref.set(e);
                } catch (TimeoutException e) {
                    ref.set(e);
                } catch (NoClassDefFoundError e) {
                    ref.set((new NoClassDefFoundElasticMachineProvisioningException(e)));
                } catch (Throwable e) {
                    logger.error("Unexpected exception:" + e.getMessage(), e);
                    ref.set(e);
                }
            }

        }, throttlingDelay, TimeUnit.SECONDS);

        futureAgents[i] = new FutureGridServiceAgent() {

            public boolean isDone() {
                return System.currentTimeMillis() > end || ref.get() != null;
            }

            public ExecutionException getException() {
                Object result = ref.get();
                if (result != null && result instanceof Throwable) {
                    Throwable throwable = (Throwable) result;
                    return new ExecutionException(throwable.getMessage(), throwable);
                }
                return null;
            }

            public boolean isTimedOut() {
                Object result = ref.get();
                return System.currentTimeMillis() > end
                        || (result != null && result instanceof TimeoutException);
            }

            public Date getTimestamp() {
                return new Date(start);
            }

            public StartedGridServiceAgent get()
                    throws ExecutionException, IllegalStateException, TimeoutException {

                Object result = ref.get();

                if (result == null) {
                    if (System.currentTimeMillis() > end) {
                        throw new TimeoutException("Starting a new machine took more than "
                                + unit.toSeconds(duration) + " seconds to complete.");
                    }

                    throw new IllegalStateException("Async operation is not done yet.");
                }

                if (getException() != null) {
                    throw getException();
                }

                return (StartedGridServiceAgent) result;
            }

            public NonBlockingElasticMachineProvisioning getMachineProvisioning() {
                return NonBlockingElasticMachineProvisioningAdapter.this;
            }

            public CapacityRequirements getFutureCapacity() {
                return singleMachineCapacity;
            }

            public GSAReservationId getReservationId() {
                return reservationId;
            }

            public FailedGridServiceAgent getFailedGridServiceAgent() {
                return failedAgent;
            }
        };
    }
    return futureAgents;
}

From source file:org.cloudifysource.shell.installer.LocalhostGridAgentBootstrapper.java

/**
 * Shuts down the local agent, if exists, and waits until shutdown is complete or until the timeout is reached.
 * //from w ww .java 2s .c  o  m
 * @param allowManagement
 *            Allow the agent to shut down even the management processes (GSM, ESM, LUS) it started are still active
 * @param allowContainers
 *            Allow the agent to shut down even the GSC still runs active services
 * @param timeout
 *            number of {@link TimeUnit}s to wait
 * @param timeunit
 *            the {@link TimeUnit} to use, to calculate the timeout
 * @throws CLIException
 *             Reporting a failure to shutdown the agent, or the management/services components still require it
 * @throws InterruptedException
 *             Reporting the thread was interrupted while waiting
 * @throws TimeoutException
 *             Reporting the timeout was reached
 */
public void shutdownAgentOnLocalhostAndWaitInternal(final boolean allowManagement,
        final boolean allowContainers, final long timeout, final TimeUnit timeunit)
        throws CLIException, InterruptedException, TimeoutException {

    final long end = System.currentTimeMillis() + timeunit.toMillis(timeout);
    final ConnectionLogsFilter connectionLogs = new ConnectionLogsFilter();
    connectionLogs.supressConnectionErrors();
    adminFacade.disconnect();
    final Admin admin = createAdmin();
    GridServiceAgent agent = null;
    try {
        setLookupDefaults(admin);
        try {
            agent = waitForExistingAgent(admin, WAIT_EXISTING_AGENT_TIMEOUT_SECONDS, TimeUnit.SECONDS);
        } catch (final TimeoutException e) {
            // continue
        }

        if (agent == null) {
            logger.fine("Agent not running on local machine");
            if (verbose) {
                final String agentNotFoundMessage = ShellUtils.getMessageBundle()
                        .getString("agent_not_found_on_teardown_command");
                publishEvent(agentNotFoundMessage);
            }
            throw new CLIStatusException("teardown_failed_agent_not_found");
        } else {
            // If the agent we attempt to shutdown is of a GSC that has
            // active services, allowContainers
            // must be true or an exception will be thrown.
            if (!allowContainers) {
                for (final ProcessingUnit pu : admin.getProcessingUnits()) {
                    for (final ProcessingUnitInstance instance : pu) {
                        if (agent.equals(instance.getGridServiceContainer().getGridServiceAgent())) {
                            throw new CLIException("Cannot shutdown agent since " + pu.getName()
                                    + " service is still running on this machine. Use -force flag.");
                        }
                    }
                }
            }

            // If the agent we attempt to shutdown is a GSM, ESM or LUS,
            // allowManagement must be true or
            // an exception will be thrown.
            if (!allowManagement) {
                final String message = "Cannot shutdown agent since management processes running on this machine. "
                        + "Use the shutdown-management command instead.";

                for (final GridServiceManager gsm : admin.getGridServiceManagers()) {
                    if (agent.equals(gsm.getGridServiceAgent())) {
                        throw new CLIException(message);
                    }
                }

                for (final ElasticServiceManager esm : admin.getElasticServiceManagers()) {
                    if (agent.equals(esm.getGridServiceAgent())) {
                        throw new CLIException(message);
                    }
                }

                for (final LookupService lus : admin.getLookupServices()) {
                    if (agent.equals(lus.getGridServiceAgent())) {
                        throw new CLIException(message);
                    }
                }
            }
            // Close admin before shutting down the agent to avoid false
            // warning messages the admin will
            // create if it concurrently monitor things that are shutting
            // down.
            admin.close();
            shutdownAgentAndWait(agent, ShellUtils.millisUntil(TIMEOUT_ERROR_MESSAGE, end),
                    TimeUnit.MILLISECONDS);
        }
    } finally {
        // close in case of exception, admin support double close if already
        // closed
        admin.close();
        if (agent != null) {
            // admin.close() command does not verify that all of the
            // internal lookup threads are actually
            // terminated
            // therefore we need to suppress connection warnings a little
            // while longer
            Thread.sleep(WAIT_AFTER_ADMIN_CLOSED_MILLIS);
        }
        connectionLogs.restoreConnectionErrors();
    }
}