Search in sources :

Example 16 with Response

use of org.restlet.Response in project camel by apache.

the class RestletConsumer method createRestlet.

protected Restlet createRestlet() {
    return new Restlet() {

        @Override
        public void handle(Request request, Response response) {
            // must call super according to restlet documentation
            super.handle(request, response);
            LOG.debug("Consumer restlet handle request method: {}", request.getMethod());
            Exchange exchange = null;
            try {
                // we want to handle the UoW
                exchange = getEndpoint().createExchange();
                createUoW(exchange);
                RestletBinding binding = getEndpoint().getRestletBinding();
                binding.populateExchangeFromRestletRequest(request, response, exchange);
                try {
                    getProcessor().process(exchange);
                } catch (Exception e) {
                    exchange.setException(e);
                }
                binding.populateRestletResponseFromExchange(exchange, response);
                // resetlet will call the callback when its done sending where it would be safe
                // to call doneUoW
                Uniform callback = newResponseUniform(exchange);
                response.setOnError(callback);
                response.setOnSent(callback);
            } catch (Throwable e) {
                getExceptionHandler().handleException("Error processing request", exchange, e);
                if (exchange != null) {
                    doneUoW(exchange);
                }
            }
        }
    };
}
Also used : Response(org.restlet.Response) Exchange(org.apache.camel.Exchange) Restlet(org.restlet.Restlet) Request(org.restlet.Request) Uniform(org.restlet.Uniform)

Example 17 with Response

use of org.restlet.Response in project camel by apache.

the class RestletProducer method process.

@Override
public boolean process(final Exchange exchange, final AsyncCallback callback) {
    RestletEndpoint endpoint = (RestletEndpoint) getEndpoint();
    // force processing synchronously using different api
    if (endpoint.isSynchronous()) {
        try {
            process(exchange);
        } catch (Throwable e) {
            exchange.setException(e);
        }
        callback.done(true);
        return true;
    }
    LOG.trace("Processing asynchronously");
    final RestletBinding binding = endpoint.getRestletBinding();
    Request request;
    try {
        String resourceUri = buildUri(endpoint, exchange);
        URI uri = new URI(resourceUri);
        request = new Request(endpoint.getRestletMethod(), resourceUri);
        binding.populateRestletRequestFromExchange(request, exchange);
        loadCookies(exchange, uri, request);
    } catch (Throwable e) {
        // break out in case of exception
        exchange.setException(e);
        callback.done(true);
        return true;
    }
    // process the request asynchronously
    LOG.debug("Sending request asynchronously: {} for exchangeId: {}", request, exchange.getExchangeId());
    client.handle(request, new Uniform() {

        @Override
        public void handle(Request request, Response response) {
            LOG.debug("Received response asynchronously: {} for exchangeId: {}", response, exchange.getExchangeId());
            try {
                if (response != null) {
                    String resourceUri = buildUri(endpoint, exchange);
                    URI uri = new URI(resourceUri);
                    Integer respCode = response.getStatus().getCode();
                    storeCookies(exchange, uri, response);
                    if (respCode > 207 && throwException) {
                        exchange.setException(populateRestletProducerException(exchange, response, respCode));
                    } else {
                        binding.populateExchangeFromRestletResponse(exchange, response);
                    }
                }
            } catch (Throwable e) {
                exchange.setException(e);
            } finally {
                callback.done(false);
            }
        }
    });
    // we continue routing async
    return false;
}
Also used : Response(org.restlet.Response) Request(org.restlet.Request) Uniform(org.restlet.Uniform) URI(java.net.URI)

Example 18 with Response

use of org.restlet.Response in project camel by apache.

the class RestletRequestAndResponseAPITest method createRouteBuilder.

@Override
protected RouteBuilder createRouteBuilder() throws Exception {
    return new RouteBuilder() {

        @Override
        public void configure() throws Exception {
            from("direct:start").to("restlet:http://localhost:" + portNum + "/users/{id}/like/{beverage.beer}");
            // START SNIPPET: e1
            from("restlet:http://localhost:" + portNum + "/users/{id}/like/{beer}").process(new Processor() {

                public void process(Exchange exchange) throws Exception {
                    // the Restlet request should be available if needed
                    Request request = exchange.getIn().getHeader(RestletConstants.RESTLET_REQUEST, Request.class);
                    assertNotNull("Restlet Request", request);
                    // use Restlet API to create the response
                    Response response = exchange.getIn().getHeader(RestletConstants.RESTLET_RESPONSE, Response.class);
                    assertNotNull("Restlet Response", response);
                    response.setStatus(Status.SUCCESS_OK);
                    response.setEntity("<response>Beer is Good</response>", MediaType.TEXT_XML);
                    exchange.getOut().setBody(response);
                }
            });
        // END SNIPPET: e1
        }
    };
}
Also used : Exchange(org.apache.camel.Exchange) Response(org.restlet.Response) Processor(org.apache.camel.Processor) RouteBuilder(org.apache.camel.builder.RouteBuilder) Request(org.restlet.Request)

Example 19 with Response

use of org.restlet.Response in project camel by apache.

the class RestletRouteBuilderTest method testUnhandledConsumer.

@Test
public void testUnhandledConsumer() throws IOException {
    Client client = new Client(Protocol.HTTP);
    Response response = client.handle(new Request(Method.POST, "http://localhost:" + portNum + "/orders/99991/6"));
    // expect error status as no Restlet consumer to handle POST method
    assertEquals(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED, response.getStatus());
    assertNotNull(response.getEntity().getText());
}
Also used : Response(org.restlet.Response) Request(org.restlet.Request) Client(org.restlet.Client) Test(org.junit.Test)

Example 20 with Response

use of org.restlet.Response in project camel by apache.

the class DefaultRestletBinding method populateRestletResponseFromExchange.

public void populateRestletResponseFromExchange(Exchange exchange, Response response) throws Exception {
    Message out;
    if (exchange.isFailed()) {
        // 500 for internal server error which can be overridden by response code in header
        response.setStatus(Status.valueOf(500));
        Message msg = exchange.hasOut() ? exchange.getOut() : exchange.getIn();
        if (msg.isFault()) {
            out = msg;
        } else {
            // print exception as message and stacktrace
            Exception t = exchange.getException();
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            t.printStackTrace(pw);
            response.setEntity(sw.toString(), MediaType.TEXT_PLAIN);
            return;
        }
    } else {
        out = exchange.hasOut() ? exchange.getOut() : exchange.getIn();
    }
    // get content type
    MediaType mediaType = out.getHeader(Exchange.CONTENT_TYPE, MediaType.class);
    if (mediaType == null) {
        Object body = out.getBody();
        mediaType = MediaType.TEXT_PLAIN;
        if (body instanceof String) {
            mediaType = MediaType.TEXT_PLAIN;
        } else if (body instanceof StringSource || body instanceof DOMSource) {
            mediaType = MediaType.TEXT_XML;
        }
    }
    // get response code
    Integer responseCode = out.getHeader(Exchange.HTTP_RESPONSE_CODE, Integer.class);
    if (responseCode != null) {
        response.setStatus(Status.valueOf(responseCode));
    }
    // set response body according to the message body
    Object body = out.getBody();
    if (body instanceof WrappedFile) {
        // grab body from generic file holder
        GenericFile<?> gf = (GenericFile<?>) body;
        body = gf.getBody();
    }
    if (body == null) {
        // empty response
        response.setEntity("", MediaType.TEXT_PLAIN);
    } else if (body instanceof Response) {
        // its already a restlet response, so dont do anything
        LOG.debug("Using existing Restlet Response from exchange body: {}", body);
    } else if (body instanceof Representation) {
        response.setEntity(out.getBody(Representation.class));
    } else if (body instanceof InputStream) {
        response.setEntity(new InputRepresentation(out.getBody(InputStream.class), mediaType));
    } else if (body instanceof File) {
        response.setEntity(new FileRepresentation(out.getBody(File.class), mediaType));
    } else if (body instanceof byte[]) {
        byte[] bytes = out.getBody(byte[].class);
        response.setEntity(new ByteArrayRepresentation(bytes, mediaType, bytes.length));
    } else {
        // fallback and use string
        String text = out.getBody(String.class);
        response.setEntity(text, mediaType);
    }
    LOG.debug("Populate Restlet response from exchange body: {}", body);
    if (exchange.getProperty(Exchange.CHARSET_NAME) != null) {
        CharacterSet cs = CharacterSet.valueOf(exchange.getProperty(Exchange.CHARSET_NAME, String.class));
        response.getEntity().setCharacterSet(cs);
    }
    // set headers at the end, as the entity must be set first
    // NOTE: setting HTTP headers on restlet is cumbersome and its API is "weird" and has some flaws
    // so we need to headers two times, and the 2nd time we add the non-internal headers once more
    Series<Header> series = new Series<Header>(Header.class);
    for (Map.Entry<String, Object> entry : out.getHeaders().entrySet()) {
        String key = entry.getKey();
        Object value = entry.getValue();
        if (!headerFilterStrategy.applyFilterToCamelHeaders(key, value, exchange)) {
            boolean added = setResponseHeader(exchange, response, key, value);
            if (!added) {
                // we only want non internal headers
                if (!key.startsWith("Camel") && !key.startsWith("org.restlet")) {
                    String text = exchange.getContext().getTypeConverter().tryConvertTo(String.class, exchange, value);
                    if (text != null) {
                        series.add(key, text);
                    }
                }
            }
        }
    }
    // set HTTP headers so we return these in the response
    if (!series.isEmpty()) {
        response.getAttributes().put(HeaderConstants.ATTRIBUTE_HEADERS, series);
    }
}
Also used : DOMSource(javax.xml.transform.dom.DOMSource) Message(org.apache.camel.Message) StringWriter(java.io.StringWriter) WrappedFile(org.apache.camel.WrappedFile) MediaType(org.restlet.data.MediaType) CharacterSet(org.restlet.data.CharacterSet) PrintWriter(java.io.PrintWriter) InputRepresentation(org.restlet.representation.InputRepresentation) InputStream(java.io.InputStream) EmptyRepresentation(org.restlet.representation.EmptyRepresentation) StringRepresentation(org.restlet.representation.StringRepresentation) InputRepresentation(org.restlet.representation.InputRepresentation) ByteArrayRepresentation(org.restlet.representation.ByteArrayRepresentation) FileRepresentation(org.restlet.representation.FileRepresentation) StreamRepresentation(org.restlet.representation.StreamRepresentation) Representation(org.restlet.representation.Representation) DecodeRepresentation(org.restlet.engine.application.DecodeRepresentation) ParseException(java.text.ParseException) RuntimeCamelException(org.apache.camel.RuntimeCamelException) ChallengeResponse(org.restlet.data.ChallengeResponse) Response(org.restlet.Response) Series(org.restlet.util.Series) Header(org.restlet.data.Header) FileRepresentation(org.restlet.representation.FileRepresentation) ByteArrayRepresentation(org.restlet.representation.ByteArrayRepresentation) StringSource(org.apache.camel.StringSource) WrappedFile(org.apache.camel.WrappedFile) GenericFile(org.apache.camel.component.file.GenericFile) File(java.io.File) Map(java.util.Map) GenericFile(org.apache.camel.component.file.GenericFile)

Aggregations

Response (org.restlet.Response)82 Request (org.restlet.Request)64 Test (org.testng.annotations.Test)28 Reference (org.restlet.data.Reference)26 Representation (org.restlet.representation.Representation)24 Status (org.restlet.data.Status)17 StringWriter (java.io.StringWriter)16 ChallengeResponse (org.restlet.data.ChallengeResponse)15 OAuth2Request (org.forgerock.oauth2.core.OAuth2Request)12 ResponseHandler (org.qi4j.library.rest.client.spi.ResponseHandler)12 HashMap (java.util.HashMap)11 ZNRecord (org.apache.helix.ZNRecord)11 StringReader (java.io.StringReader)10 Map (java.util.Map)10 TypeReference (org.codehaus.jackson.type.TypeReference)10 Test (org.junit.Test)10 Client (org.restlet.Client)10 ObjectMapper (org.codehaus.jackson.map.ObjectMapper)9 ContextResourceClient (org.qi4j.library.rest.client.api.ContextResourceClient)7 HandlerCommand (org.qi4j.library.rest.client.api.HandlerCommand)7