Search in sources :

Example 81 with HttpString

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

the class MinijaxUndertowServer method handleRequest.

@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
    final MinijaxApplication application = minijax.getDefaultApplication();
    try (final MinijaxRequestContext ctx = new MinijaxUndertowRequestContext(application, exchange)) {
        final Response response = application.handle(ctx);
        exchange.setStatusCode(response.getStatus());
        for (final Entry<String, List<Object>> entry : response.getHeaders().entrySet()) {
            final String name = entry.getKey();
            for (final Object value : entry.getValue()) {
                HttpString headerString = Headers.fromCache(name);
                if (headerString == null) {
                    headerString = HttpString.tryFromString(name);
                }
                exchange.getResponseHeaders().add(headerString, value.toString());
            }
        }
        final MediaType mediaType = response.getMediaType();
        if (mediaType != null) {
            exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, mediaType.toString());
        }
        EntityUtils.writeEntity(response.getEntity(), mediaType, ctx.getProviders(), exchange.getOutputStream());
    } catch (final Exception ex) {
        // NOSONAR
        LOG.error("Unhandled exception: {}", ex.getMessage(), ex);
        // NOSONAR
        throw ex;
    }
}
Also used : Response(jakarta.ws.rs.core.Response) MinijaxApplication(org.minijax.rs.MinijaxApplication) MinijaxRequestContext(org.minijax.rs.MinijaxRequestContext) MediaType(jakarta.ws.rs.core.MediaType) List(java.util.List) HttpString(io.undertow.util.HttpString) HttpString(io.undertow.util.HttpString)

Example 82 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 83 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 84 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 85 with HttpString

use of io.undertow.util.HttpString in project light-rest-4j by networknt.

the class ValidatorHandlerTest method testDeleteWithHeader.

@Test
public void testDeleteWithHeader() throws Exception {
    final Http2Client client = Http2Client.getInstance();
    final CountDownLatch latch = new CountDownLatch(1);
    final ClientConnection connection;
    try {
        connection = client.connect(new URI("http://localhost:8080"), Http2Client.WORKER, Http2Client.SSL, Http2Client.POOL, OptionMap.EMPTY).get();
    } catch (Exception e) {
        throw new ClientException(e);
    }
    final AtomicReference<ClientResponse> reference = new AtomicReference<>();
    try {
        ClientRequest request = new ClientRequest().setPath("/v2/pet/111").setMethod(Methods.DELETE);
        request.getRequestHeaders().put(new HttpString("api_key"), "key");
        connection.sendRequest(request, client.createClientCallback(reference, latch));
        latch.await();
    } catch (Exception e) {
        logger.error("Exception: ", e);
        throw new ClientException(e);
    } finally {
        IoUtils.safeClose(connection);
    }
    int statusCode = reference.get().getResponseCode();
    String body = reference.get().getAttachment(Http2Client.RESPONSE_BODY);
    Assert.assertEquals(200, statusCode);
    if (statusCode == 200) {
        Assert.assertNotNull(body);
        Assert.assertEquals("deletePet", body);
    }
}
Also used : ClientResponse(io.undertow.client.ClientResponse) AtomicReference(java.util.concurrent.atomic.AtomicReference) HttpString(io.undertow.util.HttpString) CountDownLatch(java.util.concurrent.CountDownLatch) URI(java.net.URI) ClientException(com.networknt.exception.ClientException) IOException(java.io.IOException) ClientConnection(io.undertow.client.ClientConnection) Http2Client(com.networknt.client.Http2Client) ClientException(com.networknt.exception.ClientException) ClientRequest(io.undertow.client.ClientRequest) HttpString(io.undertow.util.HttpString) Test(org.junit.Test)

Aggregations

HttpString (io.undertow.util.HttpString)147 HeaderMap (io.undertow.util.HeaderMap)31 HttpServerExchange (io.undertow.server.HttpServerExchange)27 Test (org.junit.Test)25 ClientRequest (io.undertow.client.ClientRequest)23 Map (java.util.Map)23 ClientResponse (io.undertow.client.ClientResponse)21 IOException (java.io.IOException)21 HashMap (java.util.HashMap)21 URI (java.net.URI)19 ClientConnection (io.undertow.client.ClientConnection)17 HttpHandler (io.undertow.server.HttpHandler)17 Http2Client (com.networknt.client.Http2Client)14 ClientException (com.networknt.exception.ClientException)14 AtomicReference (java.util.concurrent.atomic.AtomicReference)14 User (com.networknt.portal.usermanagement.model.common.model.user.User)13 URISyntaxException (java.net.URISyntaxException)13 ArrayList (java.util.ArrayList)13 List (java.util.List)13 CountDownLatch (java.util.concurrent.CountDownLatch)11