Package org.apache.camel

Examples of org.apache.camel.Message


    private static int port2 = CXFTestSupport.getPort("CxfRsProducerTest.jetty");
   
    public static class JettyProcessor implements Processor {
        public void process(Exchange exchange) throws Exception {
            // check the query
            Message inMessage = exchange.getIn();
            exchange.getOut().setBody(inMessage.getHeader(Exchange.HTTP_QUERY, String.class));
        }
View Full Code Here


    private static final Logger LOG = LoggerFactory.getLogger(DefaultRestletBinding.class);
    private static final String RFC_2822_DATE_PATTERN = "EEE, dd MMM yyyy HH:mm:ss Z";
    private HeaderFilterStrategy headerFilterStrategy;

    public void populateExchangeFromRestletRequest(Request request, Response response, Exchange exchange) throws Exception {
        Message inMessage = exchange.getIn();

        inMessage.setHeader(RestletConstants.RESTLET_REQUEST, request);
        inMessage.setHeader(RestletConstants.RESTLET_RESPONSE, response);

        // extract headers from restlet
        for (Map.Entry<String, Object> entry : request.getAttributes().entrySet()) {
            if (!headerFilterStrategy.applyFilterToExternalHeaders(entry.getKey(), entry.getValue(), exchange)) {
                String key = entry.getKey();
                Object value = entry.getValue();
                inMessage.setHeader(key, value);
                LOG.debug("Populate exchange from Restlet request header: {} value: {}", key, value);
            }
        }

        // we need to dig a bit to grab the content-type
        Series<Header> series = (Series<Header>) request.getAttributes().get(HeaderConstants.ATTRIBUTE_HEADERS);
        if (series != null) {
            String type = series.getFirstValue(Exchange.CONTENT_TYPE, true);
            if (type != null) {
                inMessage.setHeader(Exchange.CONTENT_TYPE, type);
            }
        }

        // copy query string to header
        String query = request.getResourceRef().getQuery();
        if (query != null) {
            inMessage.setHeader(Exchange.HTTP_QUERY, query);
        }

        // copy URI to header
        inMessage.setHeader(Exchange.HTTP_URI, request.getResourceRef().getIdentifier(true));

        // copy HTTP method to header
        inMessage.setHeader(Exchange.HTTP_METHOD, request.getMethod().toString());

        if (!request.isEntityAvailable()) {
            return;
        }

        // only deal with the form if the content type is "application/x-www-form-urlencoded"
        if (request.getEntity().getMediaType() != null && request.getEntity().getMediaType().equals(MediaType.APPLICATION_WWW_FORM)) {
            Form form = new Form(request.getEntity());
            for (Map.Entry<String, String> entry : form.getValuesMap().entrySet()) {
                String key = entry.getKey();
                String value = entry.getValue();
                if (value == null) {
                    inMessage.setBody(key);
                    LOG.debug("Populate exchange from Restlet request body: {}", key);
                } else {
                    if (!headerFilterStrategy.applyFilterToExternalHeaders(key, value, exchange)) {
                        inMessage.setHeader(key, value);
                        LOG.debug("Populate exchange from Restlet request user header: {} value: {}", key, value);
                    }
                }
            }
        } else {
            InputStream is = request.getEntity().getStream();
            Object body = RestletHelper.readResponseBodyFromInputStream(is, exchange);
            inMessage.setBody(body);
        }

    }
View Full Code Here

        }

    }

    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));
            if (exchange.hasOut() && exchange.getOut().isFault()) {
                out = exchange.getOut();
            } 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 {
            // 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) {
View Full Code Here

            // we just ignore the received message as the channel is closed
            return;
        }
        AsyncCallback callback = getAsyncCallback(ctx);

        Message message;
        try {
            message = getResponseMessage(exchange, messageEvent);
        } catch (Exception e) {
            exchange.setException(e);
            callback.done(false);
View Full Code Here

    public void process(Exchange exchange) throws Exception { //NOPMD
        InputStream stream = exchange.getIn().getMandatoryBody(InputStream.class);
        try {
            // lets setup the out message before we invoke the signing
            // so that it can mutate it if necessary
            Message out = exchange.getOut();
            out.copyFrom(exchange.getIn());
            verify(stream, out);
            clearMessageHeaders(out);
        } catch (Exception e) {
            // remove OUT message, as an exception occurred
            exchange.setOut(null);
View Full Code Here

    private Exchange createExchange(Object data) {
        final MyBatisEndpoint endpoint = getEndpoint();
        final Exchange exchange = endpoint.createExchange(ExchangePattern.InOnly);

        Message msg = exchange.getIn();
        msg.setBody(data);
        msg.setHeader(MyBatisConstants.MYBATIS_STATEMENT_NAME, endpoint.getStatement());

        return exchange;
    }
View Full Code Here

            }
            // Need to remove the Host key as it should be not used
            exchange.getIn().getHeaders().remove("host");
        }
        HttpRequestBase httpRequest = createMethod(exchange);
        Message in = exchange.getIn();
        String httpProtocolVersion = in.getHeader(Exchange.HTTP_PROTOCOL_VERSION, String.class);
        if (httpProtocolVersion != null) {
            // set the HTTP protocol version
            httpRequest.setProtocolVersion(HttpHelper.parserHttpVersion(httpProtocolVersion));
        }
        HeaderFilterStrategy strategy = getEndpoint().getHeaderFilterStrategy();

        // propagate headers as HTTP headers
        for (Map.Entry<String, Object> entry : in.getHeaders().entrySet()) {
            String key = entry.getKey();
            Object headerValue = in.getHeader(key);

            if (headerValue != null) {
                // use an iterator as there can be multiple values. (must not use a delimiter, and allow empty values)
                final Iterator<?> it = ObjectHelper.createIterator(headerValue, null, true);
View Full Code Here

    public void process(Exchange exchange) throws Exception {
       
        DockerCmd<?> dockerCmd = null;
       
        Message message = exchange.getIn();
        DockerClient client = DockerClientFactory.getDockerClient(configuration, message);
       
        DockerOperation operation = configuration.getOperation();
       
        switch(operation) {
View Full Code Here

    protected void populateResponse(Exchange exchange, HttpRequestBase httpRequest, HttpResponse httpResponse,
                                    Message in, HeaderFilterStrategy strategy, int responseCode) throws IOException, ClassNotFoundException {
        // We just make the out message is not create when extractResponseBody throws exception
        Object response = extractResponseBody(httpRequest, httpResponse, exchange);
        Message answer = exchange.getOut();

        answer.setHeader(Exchange.HTTP_RESPONSE_CODE, responseCode);
        answer.setBody(response);

        // propagate HTTP response headers
        Header[] headers = httpResponse.getAllHeaders();
        for (Header header : headers) {
            String name = header.getName();
            String value = header.getValue();
            if (name.toLowerCase().equals("content-type")) {
                name = Exchange.CONTENT_TYPE;
                exchange.setProperty(Exchange.CHARSET_NAME, IOHelper.getCharsetNameFromContentType(value));
            }
            // use http helper to extract parameter value as it may contain multiple values
            Object extracted = HttpHelper.extractHttpParameterValue(value);
            if (strategy != null && !strategy.applyFilterToExternalHeaders(name, extracted, exchange)) {
                HttpHelper.appendHeader(answer.getHeaders(), name, extracted);
            }
        }

        // preserve headers from in by copying any non existing headers
        // to avoid overriding existing headers with old values
View Full Code Here

     * @param exchange the exchange with the IN message with data to send
     * @return the data holder
     * @throws CamelExchangeException is thrown if error creating RequestEntity
     */
    protected HttpEntity createRequestEntity(Exchange exchange) throws CamelExchangeException {
        Message in = exchange.getIn();
        if (in.getBody() == null) {
            return null;
        }

        HttpEntity answer = in.getBody(HttpEntity.class);
        if (answer == null) {
            try {
                Object data = in.getBody();
                if (data != null) {
                    String contentTypeString = ExchangeHelper.getContentType(exchange);
                    ContentType contentType = null;
                   
                    //Check the contentType is valid or not, If not it throws an exception.
                    //When ContentType.parse parse method parse "multipart/form-data;boundary=---------------------------j2radvtrk",
                    //it removes "boundary" from Content-Type; I have to use contentType.create method.
                    if (contentTypeString != null) {
                        // using ContentType.parser for charset
                        if (contentTypeString.indexOf("charset") > 0) {
                            contentType = ContentType.parse(contentTypeString);
                        } else {
                            contentType = ContentType.create(contentTypeString);
                        }
                    }
                                       
                    if (contentTypeString != null && HttpConstants.CONTENT_TYPE_JAVA_SERIALIZED_OBJECT.equals(contentTypeString)) {
                        // serialized java object
                        Serializable obj = in.getMandatoryBody(Serializable.class);
                        // write object to output stream
                        ByteArrayOutputStream bos = new ByteArrayOutputStream();
                        HttpHelper.writeObjectToStream(bos, obj);
                        ByteArrayEntity entity = new ByteArrayEntity(bos.toByteArray());
                        entity.setContentType(HttpConstants.CONTENT_TYPE_JAVA_SERIALIZED_OBJECT);
                        IOHelper.close(bos);
                        answer = entity;
                    } else if (data instanceof File || data instanceof GenericFile) {
                        // file based (could potentially also be a FTP file etc)
                        File file = in.getBody(File.class);
                        if (file != null) {
                            if (contentType != null) {
                                answer = new FileEntity(file, contentType);
                            } else {
                                answer = new FileEntity(file);
                            }
                        }
                    } else if (data instanceof String) {
                        // be a bit careful with String as any type can most likely be converted to String
                        // so we only do an instanceof check and accept String if the body is really a String
                        // do not fallback to use the default charset as it can influence the request
                        // (for example application/x-www-form-urlencoded forms being sent)
                        String charset = IOHelper.getCharsetName(exchange, false);
                        if (charset == null && contentType != null) {
                            // okay try to get the charset from the content-type
                            Charset cs = contentType.getCharset();
                            if (cs != null) {
                                charset = cs.name();
                            }
                        }
                        StringEntity entity = new StringEntity((String) data, charset);
                        if (contentType != null) {
                            entity.setContentType(contentType.toString());
                        }
                        answer = entity;
                    }

                    // fallback as input stream
                    if (answer == null) {
                        // force the body as an input stream since this is the fallback
                        InputStream is = in.getMandatoryBody(InputStream.class);
                        InputStreamEntity entity = new InputStreamEntity(is, -1);
                        if (contentType != null) {
                            entity.setContentType(contentType.toString());
                        }
                        answer = entity;
View Full Code Here

TOP

Related Classes of org.apache.camel.Message

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.