org.apache.camel.http.common.HttpOperationFailedException Java Examples

The following examples show how to use org.apache.camel.http.common.HttpOperationFailedException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: OAuthRefreshTokenOnFailProcessor.java    From syndesis with Apache License 2.0 6 votes vote down vote up
@Override
public void process(final Exchange exchange) throws Exception {
    final Exception caught = (Exception) exchange.getProperty(Exchange.EXCEPTION_CAUGHT);
    if (caught instanceof HttpOperationFailedException) {
        final HttpOperationFailedException httpFailure = (HttpOperationFailedException) caught;
        LOG.warn("Failed invoking the remote API, status: {} {}, response body: {}", httpFailure.getStatusCode(),
            httpFailure.getStatusText(), httpFailure.getResponseBody());

        if (!shouldTryRefreshingAccessCode(httpFailure)) {
            throw httpFailure;
        }

        // we don't check the return value as we will throw `httpFailure`
        // anyhow
        tryToRefreshAccessToken();

        // we need to throw the failure so that the exchange fails,
        // otherwise it might be considered successful and we do not perform
        // any retry, and that would lead to data inconsistencies
        throw httpFailure;
    }

    super.process(exchange);
}
 
Example #2
Source File: HttpErrorDetailRule.java    From syndesis with Apache License 2.0 6 votes vote down vote up
@Override
public Statement apply(final Statement base, final Description description) {
    return new Statement() {
        @Override
        public void evaluate() throws Throwable {
            try {
                base.evaluate();
            } catch (final CamelExecutionException camelError) {
                final Throwable cause = camelError.getCause();
                if (cause instanceof HttpOperationFailedException) {
                    final HttpOperationFailedException httpError = (HttpOperationFailedException) cause;

                    final List<ServeEvent> events = WireMock.getAllServeEvents();
                    final String message = "Received HTTP status: " + httpError.getStatusCode() + " " + httpError.getStatusText() + "\n\n"
                        + httpError.getResponseBody() + "\nRequests received:\n"
                        + Joiner.on('\n').join(events.stream().map(e -> e.getRequest()).iterator());

                    throw new AssertionError(message, httpError);
                }

                throw camelError;
            }
        }
    };
}
 
Example #3
Source File: CustomerCamelRoute.java    From istio-tutorial with Apache License 2.0 6 votes vote down vote up
@Override
public void configure() throws Exception {
    restConfiguration()
            .component("servlet")
            .enableCORS(true)
            .contextPath("/")
            .bindingMode(RestBindingMode.auto);

    rest("/").get().consumes(MediaType.TEXT_PLAIN_VALUE)
            .route().routeId("root")
            .pipeline()
                .bean("CustomerCamelRoute", "addTracer")
                .to("http4:preference:8080/?httpClient.connectTimeout=1000&bridgeEndpoint=true&copyHeaders=true&connectionClose=true")
            .end()
            .convertBodyTo(String.class)
            .onException(HttpOperationFailedException.class)
                .handled(true)
                .process(this::handleHttpFailure)
                .setHeader(Exchange.HTTP_RESPONSE_CODE, constant(503))
            .end()
            .onException(Exception.class)
                .log(exceptionMessage().toString())
                .handled(true)
                .transform(simpleF(RESPONSE_STRING_FORMAT, exceptionMessage()))
                .setHeader(Exchange.HTTP_RESPONSE_CODE, constant(503))
            .end()
            .transform(simpleF(RESPONSE_STRING_FORMAT, "${body}"))
    .endRest();
}
 
Example #4
Source File: PreferenceCamelRoute.java    From istio-tutorial with Apache License 2.0 6 votes vote down vote up
@Override
public void configure() throws Exception {
    restConfiguration()
            .component("servlet")
            .enableCORS(true)
            .contextPath("/")
            .bindingMode(RestBindingMode.auto);

    rest("/").get().produces("text/plain")
            .route().routeId("root")
            .to("http4:recommendation:8080/?httpClient.connectTimeout=1000&bridgeEndpoint=true&copyHeaders=true&connectionClose=true")
            .routeId("recommendation")
            .onException(HttpOperationFailedException.class)
                .handled(true)
                .process(this::handleHttpFailure)
                .setHeader(Exchange.HTTP_RESPONSE_CODE, constant(503))
                .end()
            .onException(Exception.class)
                .handled(true)
                .transform(simpleF(RESPONSE_STRING_FORMAT, exceptionMessage()) )
                .setHeader(Exchange.HTTP_RESPONSE_CODE, constant(503))
                .end()
            .transform(simpleF(RESPONSE_STRING_FORMAT, "${body}"))
            .endRest();
}
 
Example #5
Source File: UseCaseRoute.java    From camelinaction2 with Apache License 2.0 6 votes vote down vote up
@Override
public void configure() throws Exception {
    getContext().setTracing(true);

    // general error handler
    errorHandler(defaultErrorHandler()
        .maximumRedeliveries(5)
        .redeliveryDelay(2000)
        .retryAttemptedLogLevel(LoggingLevel.WARN));

    // in case of a http exception then retry at most 3 times
    // and if exhausted then upload using ftp instead
    onException(HttpOperationFailedException.class).maximumRedeliveries(3)
        .handled(true)
        // use file instead of ftp as its easier to play with
        .to("file:target/ftp/upload");

    // poll files every 5th second and send them to the HTTP server
    from("file:target/rider?delay=5000&readLock=none")
        .to("http://localhost:8765/rider");
}
 
Example #6
Source File: UseCaseRoute.java    From camelinaction2 with Apache License 2.0 6 votes vote down vote up
@Override
public void configure() throws Exception {
    getContext().setTracing(true);

    // general error handler
    errorHandler(defaultErrorHandler()
        .maximumRedeliveries(5)
        .redeliveryDelay(2000)
        .retryAttemptedLogLevel(LoggingLevel.WARN));

    // in case of a http exception then retry at most 3 times
    // and if exhausted then upload using ftp instead
    onException(IOException.class, HttpOperationFailedException.class)
        .maximumRedeliveries(3)
        .handled(true)
        .to(ftp);

    // poll files send them to the HTTP server
    from(file).to(http);
}
 
Example #7
Source File: CafeErrorTest.java    From camel-cookbook-examples with Apache License 2.0 6 votes vote down vote up
@Test
public void testInvalidJson() throws Exception {
    try {
        String out = fluentTemplate().to("undertow:http://localhost:" + port1 + "/cafe/menu/items/1")
                .withHeader(Exchange.HTTP_METHOD, "PUT")
                .withBody("This is not JSON format")
                .request(String.class);

        fail("Expected exception to be thrown");
    } catch (CamelExecutionException e) {
        HttpOperationFailedException httpException = assertIsInstanceOf(HttpOperationFailedException.class, e.getCause());

        assertEquals(400, httpException.getStatusCode());
        assertEquals("text/plain", httpException.getResponseHeaders().get(Exchange.CONTENT_TYPE));
        assertEquals("Invalid json data", httpException.getResponseBody());
    }
}
 
Example #8
Source File: CafeErrorSpringTest.java    From camel-cookbook-examples with Apache License 2.0 6 votes vote down vote up
@Test
public void testInvalidJson() throws Exception {
    try {
        String out = fluentTemplate().to("undertow:http://localhost:" + port1 + "/cafe/menu/items/1")
                .withHeader(Exchange.HTTP_METHOD, "PUT")
                .withBody("This is not JSON format")
                .request(String.class);

        fail("Expected exception to be thrown");
    } catch (CamelExecutionException e) {
        HttpOperationFailedException httpException = assertIsInstanceOf(HttpOperationFailedException.class, e.getCause());

        assertEquals(400, httpException.getStatusCode());
        assertEquals("text/plain", httpException.getResponseHeaders().get(Exchange.CONTENT_TYPE));
        assertEquals("Invalid json data", httpException.getResponseBody());
    }
}
 
Example #9
Source File: CustomerCamelRoute.java    From istio-tutorial with Apache License 2.0 5 votes vote down vote up
private void handleHttpFailure(Exchange exchange) {
    HttpOperationFailedException e = exchange.getProperty(Exchange.EXCEPTION_CAUGHT, HttpOperationFailedException.class);
    exchange.getOut().setHeaders(exchange.getIn().getHeaders());
    exchange.getOut().setBody(String.format(RESPONSE_STRING_FORMAT,
            String.format("%d %s", e.getStatusCode(), e.getResponseBody())
    ));
}
 
Example #10
Source File: PreferenceCamelRoute.java    From istio-tutorial with Apache License 2.0 5 votes vote down vote up
private void handleHttpFailure(Exchange exchange) {
    HttpOperationFailedException e = exchange.getProperty(Exchange.EXCEPTION_CAUGHT, HttpOperationFailedException.class);
    exchange.getOut().setHeaders(exchange.getIn().getHeaders());
    exchange.getOut().setBody(String.format(RESPONSE_STRING_FORMAT,
            String.format("%d %s", e.getStatusCode(), e.getResponseBody())
    ));
}
 
Example #11
Source File: OAuthRefreshTokenOnFailProcessor.java    From syndesis with Apache License 2.0 4 votes vote down vote up
boolean shouldTryRefreshingAccessCode(final HttpOperationFailedException httpFailure) {
    final int statusCode = httpFailure.getStatusCode();

    return statusesToRefreshFor.contains(statusCode);
}