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:com.zenkey.net.prowser.Tab.java

/**************************************************************************
 * Executes the specified {@link Request} and returns a new
 * {@link Response} object./*from w ww.  ja va2s  .  c  o  m*/
 * <p>
 * At the end of the transaction, the <code>Request</code> argument and
 * <code>Response</code> result are saved as the "current" request and
 * response in order to provide browser functionality like
 * {@link #refresh() page refreshing} and
 * {@link #getPageSource() source viewing}.
 * 
 * @param request
 *        The <code>Request</code> object representing the page request
 *        to be made.
 * @return A new <code>Response</code> object for the specified
 *         <code>Request</code>.
 * @throws IllegalArgumentException
 *         If <code>request</code> is <code>null</code>.
 */
private Response processRequest(Request request) {

    // Mark the start time for calculating the request's duration
    long requestStartTime = System.currentTimeMillis();

    // Make sure the tab is still open
    if (isClosed)
        throw new IllegalStateException("Tab is closed");

    // Validate request argument
    if (request == null) {
        history.remove(historyIndex--);
        throw new IllegalArgumentException("Tab request is null");
    }

    // If defined, use the temp timeout (set in a call to stop()), else if
    // the Request object explictly specifies a timeout, use it, else use
    // the Tab's default request timeout
    Integer timeout;
    if (tempTimeout != null) {
        timeout = tempTimeout;
        tempTimeout = null;
    } else if (request.getTimeout() != null)
        timeout = request.getTimeout();
    else
        timeout = prowser.getDefaultTimeout();

    // Set up an object to run the request
    RequestRunnable requestRunnable = new RequestRunnable(this, request, timeout);

    // If timeout is not "infinite", run request in a timed thread
    Thread requestThread = null;
    if (timeout.intValue() != Request.TIMEOUT_INFINITE) {

        // Start the request in a different thread
        requestThread = new Thread(requestRunnable);
        requestThread.setDaemon(true);
        requestThread.start();

        // Wait as long as the timeout for the request thread to complete
        try {
            requestThread.join(timeout);
        } catch (InterruptedException e) {
            throw new IllegalStateException("Request thread was unexpectedly interrupted");
        }

        // If timeout occurred, stop the request thread and set resulting
        // values for this special case
        if (!requestRunnable.requestCompleted) {

            // Tell the request thread to stop processing the request
            requestRunnable.requestTimedOut = true;

            // Create an exception and error state for the timeout
            requestRunnable.exception = new TimeoutException("Tab request timed out after " + timeout
                    + " milliseconds [" + request.getUri().toString() + "]");
            requestRunnable.error = Response.ERR_TIMEOUT;
            requestRunnable.errorText = "Request timeout. " + requestRunnable.exception.getClass().getName()
                    + ": " + requestRunnable.exception.getMessage();

            // Specify values for response status and content
            requestRunnable.status = Response.STATUS_NOT_OBTAINED;
            requestRunnable.statusText = null;
            requestRunnable.statusVersion = null;
            requestRunnable.pageBytes = null;
            requestRunnable.responseCharset = null;
        }
    }

    // Else an "infinite" timeout means request doesn't need a timed thread
    else
        requestRunnable.run();

    // Build the new response
    Response response = new Response();
    response.setError(requestRunnable.error);
    response.setErrorText(requestRunnable.errorText);
    response.setStatus(requestRunnable.status);
    response.setStatusText(requestRunnable.statusText);
    response.setStatusVersion(requestRunnable.statusVersion);
    response.setPageBytes(requestRunnable.pageBytes);
    response.setPageCharset(requestRunnable.responseCharset);
    response.setPageContentType(requestRunnable.responseContentType);
    response.setUri(requestRunnable.uriFinal);
    response.setTab(this);

    // Save the request in the response, and vice versa
    response.setRequest(request);
    request.setResponse(response);

    // Save the request and response as the current request and response
    currentRequest = request;
    currentResponse = response;

    if (traceLevel > TRACE_OFF && requestRunnable.exception != null) {
        requestRunnable.exception.printStackTrace();
    }

    // Record the request's duration in the new response
    response.setDuration(System.currentTimeMillis() - requestStartTime);

    // Return the response resulting from the request
    return response;
}

From source file:com.microsoft.azure.storage.core.Utility.java

/**
 * Reads data from an input stream and writes it to an output stream, calculates the length of the data written, and
 * optionally calculates the MD5 hash for the data.
 * //from w w  w.  j  a  va 2  s.  co m
 * @param sourceStream
 *            An <code>InputStream</code> object that represents the input stream to use as the source.
 * @param outStream
 *            An <code>OutputStream</code> object that represents the output stream to use as the destination.
 * @param writeLength
 *            The number of bytes to read from the stream.
 * @param rewindSourceStream
 *            <code>true</code> if the input stream should be rewound <strong>before</strong> it is read; otherwise,
 *            <code>false</code>
 * @param calculateMD5
 *            <code>true</code> if an MD5 hash will be calculated; otherwise, <code>false</code>.
 * @param opContext
 *            An {@link OperationContext} object that represents the context for the current operation. This object
 *            is used to track requests to the storage service, and to provide additional runtime information about
 *            the operation.
 * @param options
 *            A {@link RequestOptions} object that specifies any additional options for the request. Namely, the
 *            maximum execution time.
 * @param request
 *            Used by download resume to set currentRequestByteCount on the request. Otherwise, null is always used.
 * @return A {@link StreamMd5AndLength} object that contains the output stream length, and optionally the MD5 hash.
 * 
 * @throws IOException
 *             If an I/O error occurs.
 * @throws StorageException
 *             If a storage service error occurred.
 */
public static StreamMd5AndLength writeToOutputStream(final InputStream sourceStream,
        final OutputStream outStream, long writeLength, final boolean rewindSourceStream,
        final boolean calculateMD5, OperationContext opContext, final RequestOptions options,
        final Boolean shouldFlush, StorageRequest<?, ?, Integer> request) throws IOException, StorageException {
    if (rewindSourceStream && sourceStream.markSupported()) {
        sourceStream.reset();
        sourceStream.mark(Constants.MAX_MARK_LENGTH);
    }

    final StreamMd5AndLength retVal = new StreamMd5AndLength();

    if (calculateMD5) {
        try {
            retVal.setDigest(MessageDigest.getInstance("MD5"));
        } catch (final NoSuchAlgorithmException e) {
            // This wont happen, throw fatal.
            throw Utility.generateNewUnexpectedStorageException(e);
        }
    }

    if (writeLength < 0) {
        writeLength = Long.MAX_VALUE;
    }

    final byte[] retrievedBuff = new byte[Constants.BUFFER_COPY_LENGTH];
    int nextCopy = (int) Math.min(retrievedBuff.length, writeLength);
    int count = sourceStream.read(retrievedBuff, 0, nextCopy);

    while (nextCopy > 0 && count != -1) {

        // if maximum execution time would be exceeded
        if (Utility.validateMaxExecutionTimeout(options.getOperationExpiryTimeInMs())) {
            // throw an exception
            TimeoutException timeoutException = new TimeoutException(SR.MAXIMUM_EXECUTION_TIMEOUT_EXCEPTION);
            throw Utility.initIOException(timeoutException);
        }

        if (outStream != null) {
            outStream.write(retrievedBuff, 0, count);
        }

        if (calculateMD5) {
            retVal.getDigest().update(retrievedBuff, 0, count);
        }

        retVal.setLength(retVal.getLength() + count);
        retVal.setCurrentOperationByteCount(retVal.getCurrentOperationByteCount() + count);

        if (request != null) {
            request.setCurrentRequestByteCount(request.getCurrentRequestByteCount() + count);
        }

        nextCopy = (int) Math.min(retrievedBuff.length, writeLength - retVal.getLength());
        count = sourceStream.read(retrievedBuff, 0, nextCopy);
    }

    if (outStream != null && shouldFlush) {
        outStream.flush();
    }

    return retVal;
}

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

private NovaServer waitForServerToBecomeReady(final String serverId, final long endTime)
        throws CloudProvisioningException, InterruptedException, TimeoutException {

    while (System.currentTimeMillis() < endTime) {
        final NovaServer server;
        try {//from  ww w  .  j  a  v  a 2  s .  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, please wait...");
            Thread.sleep(CLOUD_NODE_STATE_POLLING_INTERVAL);
            break;
        } else {
            switch (server.getStatus()) {
            case ACTIVE:
                return server;
            case BUILD:
                logger.fine("Server Status (" + serverId + ") still PENDING, please wait...");
                Thread.sleep(CLOUD_NODE_STATE_POLLING_INTERVAL);
                break;
            default:
                throw new CloudProvisioningException("Failed to allocate server - Cloud reported node in "
                        + server.getStatus().toString() + " state. Node details: " + server);
            }
        }

    }

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

From source file:org.opendaylight.controller.cluster.datastore.shardmanager.ShardManager.java

private static Exception getServerChangeException(Class<?> serverChange, ServerChangeStatus serverChangeStatus,
        String leaderPath, ShardIdentifier shardId) {
    Exception failure;// w  ww .ja  v a 2  s  . co m
    switch (serverChangeStatus) {
    case TIMEOUT:
        failure = new TimeoutException(String.format(
                "The shard leader %s timed out trying to replicate the initial data to the new shard %s."
                        + "Possible causes - there was a problem replicating the data or shard leadership changed while replicating the shard data",
                leaderPath, shardId.getShardName()));
        break;
    case NO_LEADER:
        failure = createNoShardLeaderException(shardId);
        break;
    case NOT_SUPPORTED:
        failure = new UnsupportedOperationException(String.format("%s request is not supported for shard %s",
                serverChange.getSimpleName(), shardId.getShardName()));
        break;
    default:
        failure = new RuntimeException(
                String.format("%s request to leader %s for shard %s failed with status %s",
                        serverChange.getSimpleName(), leaderPath, shardId.getShardName(), serverChangeStatus));
    }
    return failure;
}

From source file:org.opendaylight.controller.cluster.datastore.ShardManager.java

private Exception getServerChangeException(Class<?> serverChange, ServerChangeStatus serverChangeStatus,
        String leaderPath, ShardIdentifier shardId) {
    Exception failure;//ww  w.  j  a  v a2  s  .  c  o  m
    switch (serverChangeStatus) {
    case TIMEOUT:
        failure = new TimeoutException(String.format(
                "The shard leader %s timed out trying to replicate the initial data to the new shard %s."
                        + "Possible causes - there was a problem replicating the data or shard leadership changed while replicating the shard data",
                leaderPath, shardId.getShardName()));
        break;
    case NO_LEADER:
        failure = createNoShardLeaderException(shardId);
        break;
    case NOT_SUPPORTED:
        failure = new UnsupportedOperationException(String.format("%s request is not supported for shard %s",
                serverChange.getSimpleName(), shardId.getShardName()));
        break;
    default:
        failure = new RuntimeException(
                String.format("%s request to leader %s for shard %s failed with status %s",
                        serverChange.getSimpleName(), leaderPath, shardId.getShardName(), serverChangeStatus));
    }
    return failure;
}

From source file:org.cloudifysource.rest.controllers.DeploymentsController.java

private ProcessingUnit deployAndWait(final String serviceName, final ElasticDeploymentTopology deployment)
        throws TimeoutException {
    GridServiceManager gsm = getGridServiceManager();
    ProcessingUnit pu = null;/*from w  w w.  j a  v a 2s  . c  o  m*/
    if (deployment instanceof ElasticStatelessProcessingUnitDeployment) {
        pu = gsm.deploy((ElasticStatelessProcessingUnitDeployment) deployment, DEPLOYMENT_TIMEOUT_SECONDS,
                TimeUnit.SECONDS);
    } else if (deployment instanceof ElasticStatefulProcessingUnitDeployment) {
        pu = gsm.deploy((ElasticStatefulProcessingUnitDeployment) deployment, DEPLOYMENT_TIMEOUT_SECONDS,
                TimeUnit.SECONDS);
    } else if (deployment instanceof ElasticSpaceDeployment) {
        pu = gsm.deploy((ElasticSpaceDeployment) deployment, DEPLOYMENT_TIMEOUT_SECONDS, TimeUnit.SECONDS);
    }
    if (pu == null) {
        throw new TimeoutException("Timed out waiting for Service " + serviceName + " deployment.");
    }
    return pu;
}

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  ww. j a va 2s.c om*/
            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.slider.common.tools.SliderUtils.java

/**
 * Execute a command for a test operation
 * @param name name in error//from   w w  w.  j  av a 2  s .  c  o m
 * @param status status code expected
 * @param timeoutMillis timeout in millis for process to finish
 * @param logger
 * @param outputString optional string to grep for (must not span a line)
 * @param commands commands   @return the process
 * @throws IOException on any failure.
 */
public static ForkedProcessService execCommand(String name, int status, long timeoutMillis, Logger logger,
        String outputString, String... commands) throws IOException, SliderException {
    Preconditions.checkArgument(isSet(name), "no name");
    Preconditions.checkArgument(commands.length > 0, "no commands");
    Preconditions.checkArgument(isSet(commands[0]), "empty command");

    ForkedProcessService process;

    process = new ForkedProcessService(name, new HashMap<String, String>(), Arrays.asList(commands));
    process.setProcessLog(logger);
    process.init(new Configuration());
    String errorText = null;
    process.start();
    try {
        if (!process.waitForServiceToStop(timeoutMillis)) {
            throw new TimeoutException("Process did not stop in " + timeoutMillis + "mS");
        }
        int exitCode = process.getExitCode();
        List<String> recentOutput = process.getRecentOutput();
        if (status != exitCode) {
            // error condition
            errorText = "Expected exit code={" + status + "}, " + "actual exit code={" + exitCode + "}";
        } else {
            if (isSet(outputString)) {
                boolean found = false;
                for (String line : recentOutput) {
                    if (line.contains(outputString)) {
                        found = true;
                        break;
                    }
                }
                if (!found) {
                    errorText = "Did not find \"" + outputString + "\"" + " in output";
                }
            }
        }
        if (errorText == null) {
            return process;
        }

    } catch (TimeoutException e) {
        errorText = e.toString();
    }
    // error text: non null ==> operation failed
    log.warn(errorText);
    List<String> recentOutput = process.getRecentOutput();
    for (String line : recentOutput) {
        log.info(line);
    }
    throw new SliderException(LauncherExitCodes.EXIT_OTHER_FAILURE, "Process %s failed: %s", name, errorText);

}

From source file:com.palantir.atlasdb.keyvalue.cassandra.CassandraKeyValueService.java

private void trySchemaMutationLock() throws InterruptedException, TimeoutException {
    if (!schemaMutationLock.tryLock(CassandraConstants.SECONDS_TO_WAIT_FOR_SCHEMA_MUTATION_LOCK,
            TimeUnit.SECONDS)) {/*from   w w  w .  j a v  a  2 s .c o m*/
        throw new TimeoutException(
                "AtlasDB was unable to get a lock on Cassandra system schema mutations for your cluster. Likely cause: performing heavy schema mutations in parallel, or extremely heavy Cassandra cluster load.");
    }
}

From source file:org.cloudifysource.rest.controllers.ServiceController.java

private void deployAndWait(final String serviceName, final ElasticStatelessProcessingUnitDeployment deployment)
        throws TimeoutException, RestErrorException {
    try {//from   w  ww . j a v a2 s .  c  om
        final ProcessingUnit pu = getGridServiceManager().deploy(deployment, 60, TimeUnit.SECONDS);
        if (pu == null) {
            throw new TimeoutException("Timed out waiting for Service " + serviceName + " deployment.");
        }
    } catch (final ProcessingUnitAlreadyDeployedException e) {
        throw new RestErrorException(CloudifyErrorMessages.SERVICE_ALREADY_INSTALLED.getName(), serviceName);
    }
}