Search in sources :

Example 1 with TimeoutException

use of java.util.concurrent.TimeoutException in project camel by apache.

the class EtcdKeysProducer method processGet.

private void processGet(EtcdClient client, String path, Exchange exchange) throws Exception {
    EtcdKeyGetRequest request = client.get(path);
    setRequestTimeout(request, exchange);
    setRequestRecursive(request, exchange);
    try {
        exchange.getIn().setHeader(EtcdConstants.ETCD_NAMESPACE, getNamespace());
        exchange.getIn().setBody(request.send().get());
    } catch (TimeoutException e) {
        throw new ExchangeTimedOutException(exchange, configuration.getTimeout());
    }
}
Also used : EtcdKeyGetRequest(mousio.etcd4j.requests.EtcdKeyGetRequest) ExchangeTimedOutException(org.apache.camel.ExchangeTimedOutException) TimeoutException(java.util.concurrent.TimeoutException)

Example 2 with TimeoutException

use of java.util.concurrent.TimeoutException in project camel by apache.

the class EtcdKeysProducer method processDel.

private void processDel(EtcdClient client, String path, boolean dir, Exchange exchange) throws Exception {
    EtcdKeyDeleteRequest request = client.delete(path);
    setRequestTimeout(request, exchange);
    setRequestRecursive(request, exchange);
    if (dir) {
        request.dir();
    }
    try {
        exchange.getIn().setHeader(EtcdConstants.ETCD_NAMESPACE, getNamespace());
        exchange.getIn().setBody(request.send().get());
    } catch (TimeoutException e) {
        throw new ExchangeTimedOutException(exchange, configuration.getTimeout());
    }
}
Also used : EtcdKeyDeleteRequest(mousio.etcd4j.requests.EtcdKeyDeleteRequest) ExchangeTimedOutException(org.apache.camel.ExchangeTimedOutException) TimeoutException(java.util.concurrent.TimeoutException)

Example 3 with TimeoutException

use of java.util.concurrent.TimeoutException in project camel by apache.

the class EtcdWatchConsumer method onResponse.

@Override
public void onResponse(ResponsePromise<EtcdKeysResponse> promise) {
    if (!isRunAllowed()) {
        return;
    }
    Exchange exchange = null;
    Throwable throwable = promise.getException();
    if (throwable != null && throwable instanceof EtcdException) {
        EtcdException exception = (EtcdException) throwable;
        // So we set the index to the one returned by the exception + 1
        if (EtcdHelper.isOutdatedIndexException(exception)) {
            LOGGER.debug("Outdated index, key: {}, cause={}", getPath(), exception.etcdCause);
            // We set the index to the one returned by the exception + 1.
            index.set(exception.index + 1);
            // Clean-up the exception so it is not rethrown/handled
            throwable = null;
        }
    } else {
        try {
            EtcdKeysResponse response = promise.get();
            exchange = endpoint.createExchange();
            exchange.getIn().setHeader(EtcdConstants.ETCD_NAMESPACE, getNamespace());
            exchange.getIn().setHeader(EtcdConstants.ETCD_PATH, response.node.key);
            exchange.getIn().setBody(response);
            // Watch from the modifiedIndex + 1 of the node we got for ensuring
            // no events are missed between watch commands
            index.set(response.node.modifiedIndex + 1);
        } catch (TimeoutException e) {
            LOGGER.debug("Timeout watching for {}", getPath());
            if (configuration.isSendEmptyExchangeOnTimeout()) {
                exchange = endpoint.createExchange();
                exchange.getIn().setHeader(EtcdConstants.ETCD_NAMESPACE, getNamespace());
                exchange.getIn().setHeader(EtcdConstants.ETCD_TIMEOUT, true);
                exchange.getIn().setHeader(EtcdConstants.ETCD_PATH, getPath());
                exchange.getIn().setBody(null);
            }
            throwable = null;
        } catch (Exception e1) {
            throwable = e1;
        }
        if (exchange != null) {
            try {
                throwable = null;
                getProcessor().process(exchange);
            } catch (Exception e) {
                getExceptionHandler().handleException("Error processing exchange", exchange, e);
            }
        }
    }
    if (throwable != null) {
        handleException("Error processing etcd response", throwable);
    }
    try {
        watch();
    } catch (Exception e) {
        handleException("Error watching key " + getPath(), e);
    }
}
Also used : Exchange(org.apache.camel.Exchange) EtcdKeysResponse(mousio.etcd4j.responses.EtcdKeysResponse) EtcdException(mousio.etcd4j.responses.EtcdException) EtcdException(mousio.etcd4j.responses.EtcdException) TimeoutException(java.util.concurrent.TimeoutException) TimeoutException(java.util.concurrent.TimeoutException)

Example 4 with TimeoutException

use of java.util.concurrent.TimeoutException in project camel by apache.

the class CamelContinuationServlet method doService.

@Override
protected void doService(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
    log.trace("Service: {}", request);
    // is there a consumer registered for the request.
    HttpConsumer consumer = getServletResolveConsumerStrategy().resolve(request, getConsumers());
    if (consumer == null) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }
    // figure out if continuation is enabled and what timeout to use
    boolean useContinuation = false;
    Long continuationTimeout = null;
    HttpCommonEndpoint endpoint = consumer.getEndpoint();
    if (endpoint instanceof JettyHttpEndpoint) {
        JettyHttpEndpoint jettyEndpoint = (JettyHttpEndpoint) endpoint;
        Boolean epUseContinuation = jettyEndpoint.getUseContinuation();
        Long epContinuationTimeout = jettyEndpoint.getContinuationTimeout();
        if (epUseContinuation != null) {
            useContinuation = epUseContinuation;
        } else {
            useContinuation = jettyEndpoint.getComponent().isUseContinuation();
        }
        if (epContinuationTimeout != null) {
            continuationTimeout = epContinuationTimeout;
        } else {
            continuationTimeout = jettyEndpoint.getComponent().getContinuationTimeout();
        }
    }
    if (useContinuation) {
        log.trace("Start request with continuation timeout of {}", continuationTimeout != null ? continuationTimeout : "jetty default");
    } else {
        log.trace("Usage of continuation is disabled, either by component or endpoint configuration, fallback to normal servlet processing instead");
        super.doService(request, response);
        return;
    }
    if (consumer.getEndpoint().getHttpMethodRestrict() != null) {
        Iterator<?> it = ObjectHelper.createIterable(consumer.getEndpoint().getHttpMethodRestrict()).iterator();
        boolean match = false;
        while (it.hasNext()) {
            String method = it.next().toString();
            if (method.equalsIgnoreCase(request.getMethod())) {
                match = true;
                break;
            }
        }
        if (!match) {
            response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
            return;
        }
    }
    if ("TRACE".equals(request.getMethod()) && !consumer.isTraceEnabled()) {
        response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
        return;
    }
    // we do not support java serialized objects unless explicit enabled
    String contentType = request.getContentType();
    if (HttpConstants.CONTENT_TYPE_JAVA_SERIALIZED_OBJECT.equals(contentType) && !consumer.getEndpoint().getComponent().isAllowJavaSerializedObject()) {
        response.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE);
        return;
    }
    final Exchange result = (Exchange) request.getAttribute(EXCHANGE_ATTRIBUTE_NAME);
    if (result == null) {
        // no asynchronous result so leverage continuation
        final Continuation continuation = ContinuationSupport.getContinuation(request);
        if (continuation.isInitial() && continuationTimeout != null) {
            // set timeout on initial
            continuation.setTimeout(continuationTimeout);
        }
        // are we suspended and a request is dispatched initially?
        if (consumer.isSuspended() && continuation.isInitial()) {
            response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
            return;
        }
        if (continuation.isExpired()) {
            String id = (String) continuation.getAttribute(EXCHANGE_ATTRIBUTE_ID);
            // remember this id as expired
            expiredExchanges.put(id, id);
            log.warn("Continuation expired of exchangeId: {}", id);
            consumer.getBinding().doWriteExceptionResponse(new TimeoutException(), response);
            return;
        }
        // a new request so create an exchange
        final Exchange exchange = new DefaultExchange(consumer.getEndpoint(), ExchangePattern.InOut);
        if (consumer.getEndpoint().isBridgeEndpoint()) {
            exchange.setProperty(Exchange.SKIP_GZIP_ENCODING, Boolean.TRUE);
            exchange.setProperty(Exchange.SKIP_WWW_FORM_URLENCODED, Boolean.TRUE);
        }
        if (consumer.getEndpoint().isDisableStreamCache()) {
            exchange.setProperty(Exchange.DISABLE_HTTP_STREAM_CACHE, Boolean.TRUE);
        }
        HttpHelper.setCharsetFromContentType(request.getContentType(), exchange);
        exchange.setIn(new HttpMessage(exchange, request, response));
        // set context path as header
        String contextPath = consumer.getEndpoint().getPath();
        exchange.getIn().setHeader("CamelServletContextPath", contextPath);
        updateHttpPath(exchange, contextPath);
        if (log.isTraceEnabled()) {
            log.trace("Suspending continuation of exchangeId: {}", exchange.getExchangeId());
        }
        continuation.setAttribute(EXCHANGE_ATTRIBUTE_ID, exchange.getExchangeId());
        // we want to handle the UoW
        try {
            consumer.createUoW(exchange);
        } catch (Exception e) {
            log.error("Error processing request", e);
            throw new ServletException(e);
        }
        // must suspend before we process the exchange
        continuation.suspend();
        ClassLoader oldTccl = overrideTccl(exchange);
        if (log.isTraceEnabled()) {
            log.trace("Processing request for exchangeId: {}", exchange.getExchangeId());
        }
        // use the asynchronous API to process the exchange
        consumer.getAsyncProcessor().process(exchange, new AsyncCallback() {

            public void done(boolean doneSync) {
                // check if the exchange id is already expired
                boolean expired = expiredExchanges.remove(exchange.getExchangeId()) != null;
                if (!expired) {
                    if (log.isTraceEnabled()) {
                        log.trace("Resuming continuation of exchangeId: {}", exchange.getExchangeId());
                    }
                    // resume processing after both, sync and async callbacks
                    continuation.setAttribute(EXCHANGE_ATTRIBUTE_NAME, exchange);
                    continuation.resume();
                } else {
                    log.warn("Cannot resume expired continuation of exchangeId: {}", exchange.getExchangeId());
                }
            }
        });
        if (oldTccl != null) {
            restoreTccl(exchange, oldTccl);
        }
        // method again when its resumed
        return;
    }
    try {
        // now lets output to the response
        if (log.isTraceEnabled()) {
            log.trace("Resumed continuation and writing response for exchangeId: {}", result.getExchangeId());
        }
        Integer bs = consumer.getEndpoint().getResponseBufferSize();
        if (bs != null) {
            log.trace("Using response buffer size: {}", bs);
            response.setBufferSize(bs);
        }
        consumer.getBinding().writeResponse(result, response);
    } catch (IOException e) {
        log.error("Error processing request", e);
        throw e;
    } catch (Exception e) {
        log.error("Error processing request", e);
        throw new ServletException(e);
    } finally {
        consumer.doneUoW(result);
    }
}
Also used : DefaultExchange(org.apache.camel.impl.DefaultExchange) Continuation(org.eclipse.jetty.continuation.Continuation) AsyncCallback(org.apache.camel.AsyncCallback) IOException(java.io.IOException) HttpConsumer(org.apache.camel.http.common.HttpConsumer) ServletException(javax.servlet.ServletException) TimeoutException(java.util.concurrent.TimeoutException) IOException(java.io.IOException) DefaultExchange(org.apache.camel.impl.DefaultExchange) Exchange(org.apache.camel.Exchange) ServletException(javax.servlet.ServletException) HttpMessage(org.apache.camel.http.common.HttpMessage) HttpCommonEndpoint(org.apache.camel.http.common.HttpCommonEndpoint) TimeoutException(java.util.concurrent.TimeoutException)

Example 5 with TimeoutException

use of java.util.concurrent.TimeoutException in project flink by apache.

the class JobManagerRetriever method awaitJobManagerGatewayAndWebPort.

/**
	 * Awaits the leading job manager gateway and its web monitor port.
	 */
public Tuple2<ActorGateway, Integer> awaitJobManagerGatewayAndWebPort() throws Exception {
    Future<Tuple2<ActorGateway, Integer>> gatewayPortFuture = null;
    Deadline deadline = timeout.fromNow();
    while (!deadline.isOverdue()) {
        synchronized (waitLock) {
            gatewayPortFuture = leaderGatewayPortFuture;
            if (gatewayPortFuture != null) {
                break;
            }
            waitLock.wait(deadline.timeLeft().toMillis());
        }
    }
    if (gatewayPortFuture == null) {
        throw new TimeoutException("There is no JobManager available.");
    } else {
        return Await.result(gatewayPortFuture, deadline.timeLeft());
    }
}
Also used : Tuple2(scala.Tuple2) Deadline(scala.concurrent.duration.Deadline) TimeoutException(java.util.concurrent.TimeoutException)

Aggregations

TimeoutException (java.util.concurrent.TimeoutException)717 ExecutionException (java.util.concurrent.ExecutionException)229 IOException (java.io.IOException)167 Test (org.junit.Test)131 CountDownLatch (java.util.concurrent.CountDownLatch)73 ArrayList (java.util.ArrayList)67 ExecutorService (java.util.concurrent.ExecutorService)62 Future (java.util.concurrent.Future)45 CancellationException (java.util.concurrent.CancellationException)44 Test (org.testng.annotations.Test)44 File (java.io.File)34 List (java.util.List)34 Map (java.util.Map)32 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)32 HashMap (java.util.HashMap)26 TimeUnit (java.util.concurrent.TimeUnit)26 AtomicReference (java.util.concurrent.atomic.AtomicReference)23 RejectedExecutionException (java.util.concurrent.RejectedExecutionException)21 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)21 URI (java.net.URI)20