Example usage for java.util.concurrent TimeoutException TimeoutException

List of usage examples for java.util.concurrent TimeoutException TimeoutException

Introduction

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

Prototype

public TimeoutException(String message) 

Source Link

Document

Constructs a TimeoutException with the specified detail message.

Usage

From source file:org.apache.solr.client.solrj.impl.CloudSolrClient.java

/**
 * Connect to a cluster.  If the cluster is not ready, retry connection up to a given timeout.
 * @param duration the timeout//  w  ww. j ava  2s .c om
 * @param timeUnit the units of the timeout
 * @throws TimeoutException if the cluster is not ready after the timeout
 * @throws InterruptedException if the wait is interrupted
 */
public void connect(long duration, TimeUnit timeUnit) throws TimeoutException, InterruptedException {
    log.info("Waiting for {} {} for cluster at {} to be ready", duration, timeUnit, zkHost);
    long timeout = System.nanoTime() + timeUnit.toNanos(duration);
    while (System.nanoTime() < timeout) {
        try {
            connect();
            log.info("Cluster at {} ready", zkHost);
            return;
        } catch (RuntimeException e) {
            // not ready yet, then...
        }
        TimeUnit.MILLISECONDS.sleep(250);
    }
    throw new TimeoutException("Timed out waiting for cluster");
}

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

private void waitStopInstanceStatus(final String instanceId, final long duration, final TimeUnit unit)
        throws CloudProvisioningException, TimeoutException {
    final long endTime = System.currentTimeMillis() + unit.toMillis(duration);
    while (System.currentTimeMillis() < endTime) {

        final DescribeInstancesRequest describeRequest = new DescribeInstancesRequest();
        describeRequest.withInstanceIds(instanceId);
        final DescribeInstancesResult describeInstances = ec2.describeInstances(describeRequest);

        for (final Reservation resa : describeInstances.getReservations()) {
            for (final Instance instance : resa.getInstances()) {
                final InstanceStateType state = InstanceStateType.valueOf(instance.getState().getCode());
                if (logger.isLoggable(Level.FINEST)) {
                    logger.finest("instance= " + instance.getInstanceId() + " state=" + state);
                }//from  ww w.  j a va 2s  .  c  o m
                switch (state) {
                case PENDING:
                case RUNNING:
                case STOPPING:
                case SHUTTING_DOWN:
                    this.sleep();
                    break;
                case STOPPED:
                case TERMINATED:
                    if (logger.isLoggable(Level.FINEST)) {
                        logger.finest("instance (id=" + instanceId + ") was shutdown");
                    }
                    return;
                default:
                    throw new CloudProvisioningException(
                            "Failed to stop server - Cloud reported node in " + state.getName() + " state.");

                }

            }
        }
    }

    throw new TimeoutException("Stopping instace timed out (id=" + instanceId + ")");
}

From source file:com.vmware.admiral.host.BaseManagementHostClusterIT.java

protected static void waitFor(Condition condition) throws InterruptedException, TimeoutException {
    long start = System.currentTimeMillis();
    long end = start + TIMEOUT_FOR_WAIT_CONDITION; // Wait 1 minute.

    while (!condition.isReady()) {
        Thread.sleep(DELAY_BETWEEN_RETRIES_IN_MILISEC);
        if (System.currentTimeMillis() > end) {
            throw new TimeoutException(String.format("Timeout waiting for: [%s]", condition.getDescription()));
        }/*from  w w w.  j  a va2s  . com*/
    }
}

From source file:org.cloudifysource.esc.driver.provisioning.azure.client.MicrosoftAzureRestClient.java

private void waitForDiskToDetach(final String diskName, final String roleName, long endTime)
        throws TimeoutException, MicrosoftAzureException, InterruptedException {

    while (true) {
        Disks disks = listOSDisks();/*from ww w  .  j  a  v  a  2 s .  c  om*/
        Disk osDisk = null;
        for (Disk disk : disks) {
            if (disk.getName().equals(diskName)) {
                osDisk = disk;
                break;
            }
        }
        if (osDisk != null) {
            if (osDisk.getAttachedTo() == null) {
                return;
            } else {
                logger.fine("Disk " + diskName + " is still attached to role "
                        + osDisk.getAttachedTo().getRoleName());
                Thread.sleep(DEFAULT_POLLING_INTERVAL);
            }
        } else {
            throw new MicrosoftAzureException("Disk " + diskName + " does not exist");
        }

        if (System.currentTimeMillis() > endTime) {
            throw new TimeoutException(
                    "Timed out waiting for disk " + diskName + " to detach from role " + roleName);
        }
    }

}

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

private void checkForProvisioningTimeout(final long end, final MachineDetails machineDetails)
        throws TimeoutException, ElasticMachineProvisioningException, InterruptedException {
    if (System.currentTimeMillis() > end) {
        logger.warning(/*from   w  w  w .  j a  va  2 s.co  m*/
                "Provisioning of new machine exceeded the required timeout. Shutting down the new machine ("
                        + machineDetails.toString() + ")");
        // creating the new machine took too long! clean up and throw a
        // timeout
        throw new TimeoutException("New machine provisioning exceeded the required timeout");

    }
}

From source file:org.ow2.proactive.scheduler.rest.SchedulerClient.java

@Override
public JobResult waitForJob(String jobId, long timeout)
        throws NotConnectedException, UnknownJobException, PermissionException, TimeoutException {
    timeout += currentTimeMillis();//  www  . j  a  v  a2  s  . c om
    while (currentTimeMillis() < timeout) {
        if (isJobFinished(jobId)) {
            return getJobResult(jobId);
        }
        if (currentTimeMillis() + RETRY_INTERVAL < timeout) {
            sleep(RETRY_INTERVAL);
        } else {
            break;
        }
    }
    throw new TimeoutException(format("Timeout waiting for the job: job-id=%s", jobId));
}

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

private long remainingTimeTill(final long end) throws TimeoutException {
    final long remaining = end - System.currentTimeMillis();
    if (remaining <= 0) {
        throw new TimeoutException("Passed target end time " + new Date(end));
    }//w  w w .  ja  v  a2s . c o m
    return remaining;
}

From source file:com.microsoft.azurebatch.jenkins.azurebatch.AzureBatchHelper.java

private void waitForAllTasksCompleted(int waitTimeoutInMin)
        throws InterruptedException, BatchErrorException, IOException, TimeoutException {
    long startTime = System.currentTimeMillis();
    long elapsedTime = 0;
    boolean completed = false;
    String poolId = client.jobOperations().getJob(jobId).executionInfo().poolId();
    int lastTotalNodeCount = 0;
    int lastActiveNodeCount = 0;
    boolean allJobPrepTasksDone = false;

    // wait for all tasks to complete
    while (elapsedTime < (long) waitTimeoutInMin * 60 * 1000) {
        // Check all JobPrep tasks and retrieve logs
        if (!allJobPrepTasksDone) {
            allJobPrepTasksDone = checkAndRetrieveAllJobPrepTasksOutput(poolId);
        }//from   w w w  .jav a  2s. com

        List<CloudTask> taskCollection = client.taskOperations().listTasks(jobId,
                new DetailLevel.Builder().withSelectClause("id, state").build());

        // Try to shrink the pool if needed
        tryToShrinkPool(poolId, waitTimeoutInMin, taskCollection);

        int activeTasksCount = 0;
        int preparingTasksCount = 0;
        int runningTasksCount = 0;
        int completedTasksCount = 0;

        for (CloudTask task : taskCollection) {
            switch (task.state()) {
            case ACTIVE:
                activeTasksCount++;
                break;
            case PREPARING:
                preparingTasksCount++;
                break;
            case RUNNING:
                runningTasksCount++;
                break;
            case COMPLETED:
                completedTasksCount++;
                if (!retrievedTasks.contains(task.id())) {
                    // If task completed, retrieve task log
                    retrieveTaskLogs(task);

                    // Mark task as log retrieved
                    retrievedTasks.add(task.id());
                }
                break;
            default:
                break;
            }
        }

        if (completedTasksCount == taskCollection.size()) {
            completed = true;
            break;
        }

        int currentActiveNodeCount = 0;
        List<ComputeNode> nodes = client.computeNodeOperations().listComputeNodes(poolId,
                new DetailLevel.Builder().withSelectClause("state").build());
        if (nodes != null) {
            for (ComputeNode node : nodes) {
                if (node.state() != ComputeNodeState.LEAVINGPOOL) {
                    currentActiveNodeCount++;
                }
            }
        }

        if (nodes != null && nodes.size() != lastTotalNodeCount
                || currentActiveNodeCount != lastActiveNodeCount) {
            Logger.log(listener,
                    "Waiting for all tasks to complete, %d/%d active VM(s) running tasks. Task statistics: %d active, %d preparing, %d running, %d completed.",
                    currentActiveNodeCount, nodes.size(), activeTasksCount, preparingTasksCount,
                    runningTasksCount, completedTasksCount);
        }
        if (nodes != null) {
            lastTotalNodeCount = nodes.size();
        }
        lastActiveNodeCount = currentActiveNodeCount;

        long nextWaitTime = 15 * 1000 - (System.currentTimeMillis() - startTime - elapsedTime);
        if (nextWaitTime > 0) {
            Thread.sleep(nextWaitTime);
        }

        elapsedTime = System.currentTimeMillis() - startTime;
    }

    if (!completed) {
        throw new TimeoutException(
                String.format("Job %s not all tasks are completed after %d minutes.", jobId, waitTimeoutInMin));
    } else {
        Logger.log(listener, "Job %s all tasks are completed.", jobId);
    }
}

From source file:org.ow2.proactive.scheduler.rest.SchedulerClient.java

@Override
public TaskResult waitForTask(String jobId, String taskName, long timeout) throws UnknownJobException,
        NotConnectedException, PermissionException, UnknownTaskException, TimeoutException {
    timeout += currentTimeMillis();//from  w ww  . j a va  2s.  com
    while (currentTimeMillis() < timeout) {
        if (isTaskFinished(jobId, taskName)) {
            return getTaskResult(jobId, taskName);
        }
        if (currentTimeMillis() + RETRY_INTERVAL < timeout) {
            sleep(RETRY_INTERVAL);
        } else {
            break;
        }
    }
    throw new TimeoutException(format("Timeout waiting for the task: job-id=%s, task-id=%s", jobId, taskName));
}

From source file:org.cloudifysource.esc.driver.provisioning.azure.client.MicrosoftAzureRestClient.java

/**
 * This method deletes just the virtual machine from the specified cloud service.
 * associated OS Disk and cloud service are not removed.
 * @param hostedServiceName//w  w  w  . j  av  a  2 s  .  c o m
 *            .
 * @param deploymentName
 *            .
 * @param endTime
 *            .
 * @return - true if the operation was successful, throws otherwise.
 * @throws MicrosoftAzureException .
 * @throws TimeoutException .
 * @throws InterruptedException .
 */
public boolean deleteDeployment(final String hostedServiceName, final String deploymentName, final long endTime)
        throws MicrosoftAzureException, TimeoutException, InterruptedException {

    if (!deploymentExists(hostedServiceName, deploymentName)) {
        logger.info("Deployment " + deploymentName + " does not exist");
        return true;
    }

    long currentTimeInMillis = System.currentTimeMillis();
    long lockTimeout = endTime - currentTimeInMillis;

    logger.fine(getThreadIdentity() + "Waiting for pending request lock...");
    boolean lockAcquired = pendingRequest.tryLock(lockTimeout, TimeUnit.MILLISECONDS);

    if (lockAcquired) {

        logger.fine(getThreadIdentity() + "Lock acquired : " + pendingRequest.hashCode());
        logger.fine(getThreadIdentity() + "Executing a request to delete virtual machine");

        try {

            logger.fine(
                    getThreadIdentity() + "Deleting deployment of virtual machine from : " + deploymentName);

            ClientResponse response = doDelete(
                    "/services/hostedservices/" + hostedServiceName + "/deployments/" + deploymentName);
            String requestId = extractRequestId(response);
            waitForRequestToFinish(requestId, endTime);
            pendingRequest.unlock();
            logger.fine(getThreadIdentity() + "Lock unlcoked");
        } catch (final Exception e) {
            logger.fine(getThreadIdentity() + "About to release lock " + pendingRequest.hashCode());
            pendingRequest.unlock();
            if (e instanceof MicrosoftAzureException) {
                throw (MicrosoftAzureException) e;
            }
            if (e instanceof TimeoutException) {
                throw (TimeoutException) e;
            }
            if (e instanceof InterruptedException) {
                throw (InterruptedException) e;
            }
        }
        return true;
    } else {
        throw new TimeoutException(
                "Failed to acquire lock for deleteDeployment request after + " + lockTimeout + " milliseconds");
    }

}