Search in sources :

Example 36 with HttpString

use of io.undertow.util.HttpString in project camel by apache.

the class DefaultUndertowHttpBinding method toHttpRequest.

@Override
public Object toHttpRequest(ClientRequest clientRequest, Message message) {
    Object body = message.getBody();
    final HeaderMap requestHeaders = clientRequest.getRequestHeaders();
    // set the content type in the response.
    String contentType = MessageHelper.getContentType(message);
    if (contentType != null) {
        // set content-type
        requestHeaders.put(Headers.CONTENT_TYPE, contentType);
        LOG.trace("Content-Type: {}", contentType);
    }
    TypeConverter tc = message.getExchange().getContext().getTypeConverter();
    //copy headers from Message to Request
    for (Map.Entry<String, Object> entry : message.getHeaders().entrySet()) {
        String key = entry.getKey();
        Object value = entry.getValue();
        // use an iterator as there can be multiple values. (must not use a delimiter)
        final Iterator<?> it = ObjectHelper.createIterator(value, null);
        while (it.hasNext()) {
            String headerValue = tc.convertTo(String.class, it.next());
            if (headerValue != null && headerFilterStrategy != null && !headerFilterStrategy.applyFilterToCamelHeaders(key, headerValue, message.getExchange())) {
                LOG.trace("HTTP-Header: {}={}", key, headerValue);
                requestHeaders.add(new HttpString(key), headerValue);
            }
        }
    }
    return body;
}
Also used : TypeConverter(org.apache.camel.TypeConverter) HeaderMap(io.undertow.util.HeaderMap) HttpString(io.undertow.util.HttpString) HashMap(java.util.HashMap) HeaderMap(io.undertow.util.HeaderMap) Map(java.util.Map) HttpString(io.undertow.util.HttpString)

Example 37 with HttpString

use of io.undertow.util.HttpString in project camel by apache.

the class DefaultUndertowHttpBinding method toHttpResponse.

@Override
public Object toHttpResponse(HttpServerExchange httpExchange, Message message) throws IOException {
    boolean failed = message.getExchange().isFailed();
    int defaultCode = failed ? 500 : 200;
    int code = message.getHeader(Exchange.HTTP_RESPONSE_CODE, defaultCode, int.class);
    httpExchange.setResponseCode(code);
    TypeConverter tc = message.getExchange().getContext().getTypeConverter();
    //copy headers from Message to Response
    for (Map.Entry<String, Object> entry : message.getHeaders().entrySet()) {
        String key = entry.getKey();
        Object value = entry.getValue();
        // use an iterator as there can be multiple values. (must not use a delimiter)
        final Iterator<?> it = ObjectHelper.createIterator(value, null);
        while (it.hasNext()) {
            String headerValue = tc.convertTo(String.class, it.next());
            if (headerValue != null && headerFilterStrategy != null && !headerFilterStrategy.applyFilterToCamelHeaders(key, headerValue, message.getExchange())) {
                LOG.trace("HTTP-Header: {}={}", key, headerValue);
                httpExchange.getResponseHeaders().add(new HttpString(key), headerValue);
            }
        }
    }
    Object body = message.getBody();
    Exception exception = message.getExchange().getException();
    if (exception != null) {
        if (isTransferException()) {
            // we failed due an exception, and transfer it as java serialized object
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(bos);
            oos.writeObject(exception.getCause());
            oos.flush();
            IOHelper.close(oos, bos);
            // the body should be the serialized java object of the exception
            body = ByteBuffer.wrap(bos.toByteArray());
            // force content type to be serialized java object
            message.setHeader(Exchange.CONTENT_TYPE, "application/x-java-serialized-object");
        } else {
            // we failed due an exception so print it as plain text
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            exception.getCause().printStackTrace(pw);
            // the body should then be the stacktrace
            body = ByteBuffer.wrap(sw.toString().getBytes());
            // force content type to be text/plain as that is what the stacktrace is
            message.setHeader(Exchange.CONTENT_TYPE, "text/plain");
        }
        // and mark the exception as failure handled, as we handled it by returning it as the response
        ExchangeHelper.setFailureHandled(message.getExchange());
    }
    // set the content type in the response.
    String contentType = MessageHelper.getContentType(message);
    if (contentType != null) {
        // set content-type
        httpExchange.getResponseHeaders().put(Headers.CONTENT_TYPE, contentType);
        LOG.trace("Content-Type: {}", contentType);
    }
    return body;
}
Also used : HttpString(io.undertow.util.HttpString) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ObjectOutputStream(java.io.ObjectOutputStream) IOException(java.io.IOException) TypeConverter(org.apache.camel.TypeConverter) StringWriter(java.io.StringWriter) HashMap(java.util.HashMap) HeaderMap(io.undertow.util.HeaderMap) Map(java.util.Map) HttpString(io.undertow.util.HttpString) PrintWriter(java.io.PrintWriter)

Example 38 with HttpString

use of io.undertow.util.HttpString in project spring-framework by spring-projects.

the class UndertowXhrTransport method executeReceiveRequest.

private void executeReceiveRequest(final TransportRequest transportRequest, final URI url, final HttpHeaders headers, final XhrClientSockJsSession session, final SettableListenableFuture<WebSocketSession> connectFuture) {
    if (logger.isTraceEnabled()) {
        logger.trace("Starting XHR receive request for " + url);
    }
    ClientCallback<ClientConnection> clientCallback = new ClientCallback<ClientConnection>() {

        @Override
        public void completed(ClientConnection connection) {
            ClientRequest request = new ClientRequest().setMethod(Methods.POST).setPath(url.getPath());
            HttpString headerName = HttpString.tryFromString(HttpHeaders.HOST);
            request.getRequestHeaders().add(headerName, url.getHost());
            addHttpHeaders(request, headers);
            HttpHeaders httpHeaders = transportRequest.getHttpRequestHeaders();
            connection.sendRequest(request, createReceiveCallback(transportRequest, url, httpHeaders, session, connectFuture));
        }

        @Override
        public void failed(IOException ex) {
            throw new SockJsTransportFailureException("Failed to execute request to " + url, ex);
        }
    };
    this.httpClient.connect(clientCallback, url, this.worker, this.bufferPool, this.optionMap);
}
Also used : SockJsTransportFailureException(org.springframework.web.socket.sockjs.SockJsTransportFailureException) ClientCallback(io.undertow.client.ClientCallback) HttpHeaders(org.springframework.http.HttpHeaders) ClientConnection(io.undertow.client.ClientConnection) IOException(java.io.IOException) ClientRequest(io.undertow.client.ClientRequest) HttpString(io.undertow.util.HttpString)

Example 39 with HttpString

use of io.undertow.util.HttpString in project spring-framework by spring-projects.

the class UndertowServerHttpResponse method applyHeaders.

@Override
protected void applyHeaders() {
    for (Map.Entry<String, List<String>> entry : getHeaders().entrySet()) {
        HttpString headerName = HttpString.tryFromString(entry.getKey());
        this.exchange.getResponseHeaders().addAll(headerName, entry.getValue());
    }
}
Also used : List(java.util.List) HttpString(io.undertow.util.HttpString) Map(java.util.Map) HttpString(io.undertow.util.HttpString)

Example 40 with HttpString

use of io.undertow.util.HttpString in project undertow by undertow-io.

the class HttpClientConnection method prepareResponseChannel.

private void prepareResponseChannel(ClientResponse response, ClientExchange exchange) {
    String encoding = response.getResponseHeaders().getLast(TRANSFER_ENCODING);
    boolean chunked = encoding != null && Headers.CHUNKED.equals(new HttpString(encoding));
    String length = response.getResponseHeaders().getFirst(CONTENT_LENGTH);
    if (exchange.getRequest().getMethod().equals(Methods.HEAD)) {
        connection.getSourceChannel().setConduit(new FixedLengthStreamSourceConduit(connection.getSourceChannel().getConduit(), 0, responseFinishedListener));
    } else if (chunked) {
        connection.getSourceChannel().setConduit(new ChunkedStreamSourceConduit(connection.getSourceChannel().getConduit(), pushBackStreamSourceConduit, bufferPool, responseFinishedListener, exchange));
    } else if (length != null) {
        try {
            long contentLength = Long.parseLong(length);
            connection.getSourceChannel().setConduit(new FixedLengthStreamSourceConduit(connection.getSourceChannel().getConduit(), contentLength, responseFinishedListener));
        } catch (NumberFormatException e) {
            handleError(new IOException(e));
            throw e;
        }
    } else if (response.getProtocol().equals(Protocols.HTTP_1_1) && !Connectors.isEntityBodyAllowed(response.getResponseCode())) {
        connection.getSourceChannel().setConduit(new FixedLengthStreamSourceConduit(connection.getSourceChannel().getConduit(), 0, responseFinishedListener));
    } else {
        state |= CLOSE_REQ;
    }
}
Also used : HttpString(io.undertow.util.HttpString) IOException(java.io.IOException) FixedLengthStreamSourceConduit(io.undertow.conduits.FixedLengthStreamSourceConduit) ChunkedStreamSourceConduit(io.undertow.conduits.ChunkedStreamSourceConduit) HttpString(io.undertow.util.HttpString)

Aggregations

HttpString (io.undertow.util.HttpString)59 IOException (java.io.IOException)18 HttpServerExchange (io.undertow.server.HttpServerExchange)16 HeaderMap (io.undertow.util.HeaderMap)15 HttpHandler (io.undertow.server.HttpHandler)9 ByteBuffer (java.nio.ByteBuffer)9 Map (java.util.Map)8 HashMap (java.util.HashMap)7 PooledByteBuffer (io.undertow.connector.PooledByteBuffer)6 HeaderValues (io.undertow.util.HeaderValues)6 ClientRequest (io.undertow.client.ClientRequest)5 Session (io.undertow.server.session.Session)5 URISyntaxException (java.net.URISyntaxException)5 ArrayList (java.util.ArrayList)5 Test (org.junit.Test)5 InMemorySessionManager (io.undertow.server.session.InMemorySessionManager)4 SessionAttachmentHandler (io.undertow.server.session.SessionAttachmentHandler)4 SessionManager (io.undertow.server.session.SessionManager)4 List (java.util.List)4 TypeConverter (org.apache.camel.TypeConverter)4