Example usage for java.util.concurrent TimeUnit toSeconds

List of usage examples for java.util.concurrent TimeUnit toSeconds

Introduction

In this page you can find the example usage for java.util.concurrent TimeUnit toSeconds.

Prototype

public long toSeconds(long duration) 

Source Link

Document

Equivalent to #convert(long,TimeUnit) SECONDS.convert(duration, this) .

Usage

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

/**
 * Set the time for which a bookie will be quarantined. Default is 30 minutes.
 *
 * <p>//from  w  ww  .  j av a  2 s  . c  o  m
 * Note: Please {@link #enableBookieHealthCheck()} to use this configuration.
 * </p>
 *
 * @param quarantineTime
 * @param unit
 * @return client configuration
 */
public ClientConfiguration setBookieQuarantineTime(int quarantineTime, TimeUnit unit) {
    setProperty(BOOKIE_QUARANTINE_TIME_SECONDS, unit.toSeconds(quarantineTime));
    return this;
}

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

/**
 * Set the bookie health check interval. Default is 60 seconds.
 *
 * <p>//w w w .  j a  va  2  s.  c  o  m
 * Note: Please {@link #enableBookieHealthCheck()} to use this configuration.
 * </p>
 *
 * @param interval
 * @param unit
 * @return client configuration
 */
public ClientConfiguration setBookieHealthCheckInterval(int interval, TimeUnit unit) {
    setProperty(BOOKIE_HEALTH_CHECK_INTERVAL_SECONDS, unit.toSeconds(interval));
    return this;
}

From source file:org.eclipse.che.plugin.docker.client.DockerConnector.java

/**
 * Stops container./*  www. j  av a 2s.  co  m*/
 *
 * @param container
 *         container identifier, either id or name
 * @param timeout
 *         time to wait for the container to stop before killing it
 * @param timeunit
 *         time unit of the timeout parameter
 * @throws IOException
 */
public void stopContainer(String container, long timeout, TimeUnit timeunit) throws IOException {
    final List<Pair<String, ?>> headers = new ArrayList<>(2);
    headers.add(Pair.of("Content-Type", MediaType.TEXT_PLAIN));
    headers.add(Pair.of("Content-Length", 0));
    try (DockerConnection connection = connectionFactory.openConnection(dockerDaemonUri).method("POST")
            .path("/containers/" + container + "/stop").query("t", timeunit.toSeconds(timeout))
            .headers(headers)) {
        final DockerResponse response = connection.request();
        final int status = response.getStatus();
        if (!(NO_CONTENT.getStatusCode() == status || NOT_MODIFIED.getStatusCode() == status)) {
            throw getDockerException(response);
        }
    }
}

From source file:org.apache.nifi.controller.StandardProcessorNode.java

@Override
public void setRunDuration(final long duration, final TimeUnit timeUnit) {
    if (duration < 0) {
        throw new IllegalArgumentException("Run Duration must be non-negative value; cannot set to "
                + timeUnit.toSeconds(duration) + " seconds");
    }//from   www .  jav a  2 s  .c  om

    this.runNanos = timeUnit.toNanos(duration);
}

From source file:com.couchbase.client.CouchbaseClient.java

/**
 * Poll and observe a key with the given CAS and persist settings.
 *
 * Based on the given persistence and replication settings, it observes the
 * key and raises an exception if a timeout has been reached. This method is
 * normally utilized through higher-level methods but can also be used
 * directly.//from  ww  w.  j  a v  a2  s. co  m
 *
 * If persist is null, it will default to PersistTo.ZERO and if replicate is
 * null, it will default to ReplicateTo.ZERO. This is the default behavior
 * and is the same as not observing at all.
 *
 * @param key the key to observe.
 * @param cas the CAS value for the key.
 * @param persist the persistence settings.
 * @param replicate the replication settings.
 * @param isDelete if the key is to be deleted.
 */
public void observePoll(String key, long cas, PersistTo persist, ReplicateTo replicate, boolean isDelete) {
    if (persist == null) {
        persist = PersistTo.ZERO;
    }
    if (replicate == null) {
        replicate = ReplicateTo.ZERO;
    }
    ((CouchbaseConnectionFactory) connFactory).checkConfigAgainstPersistence(persist, replicate);

    int persistReplica = persist.getValue() > 0 ? persist.getValue() - 1 : 0;
    int replicateTo = replicate.getValue();
    int obsPolls = 0;
    int obsPollMax = cbConnFactory.getObsPollMax();
    long obsPollInterval = cbConnFactory.getObsPollInterval();
    boolean persistMaster = persist.getValue() > 0;

    Config cfg = ((CouchbaseConnectionFactory) connFactory).getVBucketConfig();
    VBucketNodeLocator locator = ((VBucketNodeLocator) ((CouchbaseConnection) mconn).getLocator());

    checkObserveReplica(key, persistReplica, replicateTo);

    int replicaPersistedTo = 0;
    int replicatedTo = 0;
    boolean persistedMaster = false;
    while (replicateTo > replicatedTo || persistReplica - 1 > replicaPersistedTo
            || (!persistedMaster && persistMaster)) {
        checkObserveReplica(key, persistReplica, replicateTo);

        if (++obsPolls >= obsPollMax) {
            long timeTried = obsPollMax * obsPollInterval;
            TimeUnit tu = TimeUnit.MILLISECONDS;
            throw new ObservedTimeoutException("Observe Timeout - Polled" + " Unsuccessfully for at least "
                    + tu.toSeconds(timeTried) + " seconds.");
        }

        Map<MemcachedNode, ObserveResponse> response = observe(key, cas);

        int vb = locator.getVBucketIndex(key);
        MemcachedNode master = locator.getServerByIndex(cfg.getMaster(vb));

        replicaPersistedTo = 0;
        replicatedTo = 0;
        persistedMaster = false;
        for (Entry<MemcachedNode, ObserveResponse> r : response.entrySet()) {
            boolean isMaster = r.getKey() == master ? true : false;
            if (isMaster && r.getValue() == ObserveResponse.MODIFIED) {
                throw new ObservedModifiedException("Key was modified");
            }
            if (!isDelete) {
                if (!isMaster && r.getValue() == ObserveResponse.FOUND_NOT_PERSISTED) {
                    replicatedTo++;
                }
                if (r.getValue() == ObserveResponse.FOUND_PERSISTED) {
                    if (isMaster) {
                        persistedMaster = true;
                    } else {
                        replicatedTo++;
                        replicaPersistedTo++;
                    }
                }
            } else {
                if (r.getValue() == ObserveResponse.NOT_FOUND_NOT_PERSISTED) {
                    replicatedTo++;
                }
                if (r.getValue() == ObserveResponse.NOT_FOUND_PERSISTED) {
                    replicatedTo++;
                    replicaPersistedTo++;
                    if (isMaster) {
                        persistedMaster = true;
                    } else {
                        replicaPersistedTo++;
                    }
                }
            }
        }
        try {
            Thread.sleep(obsPollInterval);
        } catch (InterruptedException e) {
            getLogger().error("Interrupted while in observe loop.", e);
            throw new ObservedException("Observe was Interrupted ");
        }
    }
}

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

@Override
public FutureGridServiceAgents getDiscoveredMachinesAsync(final long duration, final TimeUnit unit) {

    final AtomicReference<Object> ref = new AtomicReference<Object>(null);
    final long start = System.currentTimeMillis();
    final long end = start + unit.toMillis(duration);

    submit(new Runnable() {
        public void run() {
            try {
                GridServiceAgent[] agents = machineProvisioning.getDiscoveredMachines(duration, unit);
                ref.set(agents);/*from  w w  w . j a  va2s  .  c o m*/
            } 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);
                ref.set(e);
            }
        }

    });

    return new FutureGridServiceAgents() {

        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 GridServiceAgent[] 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 (GridServiceAgent[]) result;

        }
    };
}

From source file:org.openspaces.grid.gsm.containers.ContainersSlaUtils.java

static FutureGridServiceContainer startGridServiceContainerAsync(final InternalAdmin admin,
        final InternalGridServiceAgent gsa, final GridServiceContainerConfig config, final Log logger,
        final long duration, final TimeUnit timeUnit) {

    final AtomicReference<Object> ref = new AtomicReference<Object>(null);
    final long startTimestamp = System.currentTimeMillis();
    final long end = startTimestamp + timeUnit.toMillis(duration);

    admin.scheduleAdminOperation(new Runnable() {
        public void run() {
            try {
                final OperatingSystemStatistics operatingSystemStatistics = gsa.getMachine()
                        .getOperatingSystem().getStatistics();

                // get total free system memory + cached (without sigar returns -1)
                long freeBytes = operatingSystemStatistics.getActualFreePhysicalMemorySizeInBytes();
                if (freeBytes <= 0) {
                    // fallback - no sigar. Provides a pessimistic number since does not take into
                    // account OS cache that can be allocated.
                    freeBytes = operatingSystemStatistics.getFreePhysicalMemorySizeInBytes();
                    if (freeBytes <= 0) {
                        // machine is probably going down.
                        ref.set(new AdminException("Cannot determine machine "
                                + machineToString(gsa.getMachine()) + " free memory."));
                    }//from  ww w .ja v a  2 s .  c  o m
                }

                final long freeInMB = MemoryUnit.MEGABYTES.convert(freeBytes, MemoryUnit.BYTES);
                if (freeInMB < config.getMaximumJavaHeapSizeInMB()) {
                    ref.set(new AdminException("Machine " + machineToString(gsa.getMachine()) + " free memory "
                            + freeInMB + "MB is not enough to start a container with "
                            + config.getMaximumJavaHeapSizeInMB()
                            + "MB. Free machine memory or increase machine provisioning reservedMemoryPerMachine property."));
                } else {
                    ref.set(gsa.internalStartGridService(config));
                }
            } catch (AdminException e) {
                ref.set(e);
            } catch (Throwable e) {
                logger.error("Unexpected Exception " + e.getMessage(), e);
                ref.set(e);
            }
        }
    });

    FutureGridServiceContainer future = new FutureGridServiceContainer() {

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

        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 GridServiceContainer get() throws ExecutionException, IllegalStateException, TimeoutException {

            Object result = ref.get();

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

            GridServiceContainer container = null;
            if (result != null) {
                int agentId = (Integer) result;
                container = getGridServiceContainerInternal(agentId);
                //container could still be null if not discovered
            }

            if (container == null) {
                if (isTimedOut()) {
                    throw new TimeoutException("Starting a new container took more than "
                            + timeUnit.toSeconds(duration) + " seconds to complete.");
                }

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

            return container;

        }

        public boolean isDone() {
            Object result = ref.get();

            if (System.currentTimeMillis() > end) {
                return true;
            }

            if (result == null) {
                return false;
            }

            if (result instanceof Throwable) {
                return true;
            }

            GridServiceContainer container = getGridServiceContainerInternal((Integer) result);
            if (container != null) {
                return true;
            }

            return false;
        }

        public GridServiceContainer getGridServiceContainerInternal(int agentId) {
            for (GridServiceContainer container : admin.getGridServiceContainers()) {

                String agentUid = ((InternalGridServiceContainer) container).getAgentUid();
                if (agentUid != null && agentUid.equals(gsa.getUid())) {
                    if (agentId == container.getAgentId()) {
                        return container;
                    }
                }
            }
            return null;
        }

        public GridServiceAgent getGridServiceAgent() {
            return gsa;
        }

        public GridServiceContainerConfig getGridServiceContainerConfig() {
            return config;
        }

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

        @Override
        public int getAgentId() throws ExecutionException, TimeoutException {
            ExecutionException exception = getException();
            if (exception != null) {
                throw exception;
            }

            if (isTimedOut() && ref.get() == null) {
                throw new TimeoutException(
                        "Starting a new container on machine " + gsa.getMachine().getHostAddress()
                                + " took more than " + timeUnit.toSeconds(duration) + " seconds to complete.");
            }

            if (ref.get() == null) {
                throw new IllegalStateException("Async operation is not done yet.");
            }

            return (Integer) ref.get();
        }

        public boolean isStarted() {
            return ref.get() != null;
        }
    };

    return future;
}

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  ww w .  j a v a  2s  .  c om*/

    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;
}