Search in sources :

Example 6 with InputStreamBodyGenerator

use of org.asynchttpclient.request.body.generator.InputStreamBodyGenerator in project async-http-client by AsyncHttpClient.

the class NettyRequestFactory method body.

private NettyBody body(Request request, boolean connect) {
    NettyBody nettyBody = null;
    if (!connect) {
        Charset bodyCharset = withDefault(request.getCharset(), DEFAULT_CHARSET);
        if (request.getByteData() != null) {
            nettyBody = new NettyByteArrayBody(request.getByteData());
        } else if (request.getCompositeByteData() != null) {
            nettyBody = new NettyCompositeByteArrayBody(request.getCompositeByteData());
        } else if (request.getStringData() != null) {
            nettyBody = new NettyByteBufferBody(StringUtils.charSequence2ByteBuffer(request.getStringData(), bodyCharset));
        } else if (request.getByteBufferData() != null) {
            nettyBody = new NettyByteBufferBody(request.getByteBufferData());
        } else if (request.getStreamData() != null) {
            nettyBody = new NettyInputStreamBody(request.getStreamData());
        } else if (isNonEmpty(request.getFormParams())) {
            CharSequence contentType = null;
            if (!request.getHeaders().contains(CONTENT_TYPE)) {
                contentType = HttpHeaderValues.APPLICATION_X_WWW_FORM_URLENCODED;
            }
            nettyBody = new NettyByteBufferBody(urlEncodeFormParams(request.getFormParams(), bodyCharset), contentType);
        } else if (isNonEmpty(request.getBodyParts())) {
            nettyBody = new NettyMultipartBody(request.getBodyParts(), request.getHeaders(), config);
        } else if (request.getFile() != null) {
            nettyBody = new NettyFileBody(request.getFile(), config);
        } else if (request.getBodyGenerator() instanceof FileBodyGenerator) {
            FileBodyGenerator fileBodyGenerator = (FileBodyGenerator) request.getBodyGenerator();
            nettyBody = new NettyFileBody(fileBodyGenerator.getFile(), fileBodyGenerator.getRegionSeek(), fileBodyGenerator.getRegionLength(), config);
        } else if (request.getBodyGenerator() instanceof InputStreamBodyGenerator) {
            InputStreamBodyGenerator inStreamGenerator = InputStreamBodyGenerator.class.cast(request.getBodyGenerator());
            nettyBody = new NettyInputStreamBody(inStreamGenerator.getInputStream(), inStreamGenerator.getContentLength());
        } else if (request.getBodyGenerator() instanceof ReactiveStreamsBodyGenerator) {
            ReactiveStreamsBodyGenerator reactiveStreamsBodyGenerator = (ReactiveStreamsBodyGenerator) request.getBodyGenerator();
            nettyBody = new NettyReactiveStreamsBody(reactiveStreamsBodyGenerator.getPublisher(), reactiveStreamsBodyGenerator.getContentLength());
        } else if (request.getBodyGenerator() != null) {
            nettyBody = new NettyBodyBody(request.getBodyGenerator().createBody(), config);
        }
    }
    return nettyBody;
}
Also used : InputStreamBodyGenerator(org.asynchttpclient.request.body.generator.InputStreamBodyGenerator) NettyMultipartBody(org.asynchttpclient.netty.request.body.NettyMultipartBody) NettyInputStreamBody(org.asynchttpclient.netty.request.body.NettyInputStreamBody) Charset(java.nio.charset.Charset) NettyCompositeByteArrayBody(org.asynchttpclient.netty.request.body.NettyCompositeByteArrayBody) FileBodyGenerator(org.asynchttpclient.request.body.generator.FileBodyGenerator) NettyByteBufferBody(org.asynchttpclient.netty.request.body.NettyByteBufferBody) NettyByteArrayBody(org.asynchttpclient.netty.request.body.NettyByteArrayBody) ReactiveStreamsBodyGenerator(org.asynchttpclient.request.body.generator.ReactiveStreamsBodyGenerator) NettyBodyBody(org.asynchttpclient.netty.request.body.NettyBodyBody) NettyBody(org.asynchttpclient.netty.request.body.NettyBody) NettyFileBody(org.asynchttpclient.netty.request.body.NettyFileBody) NettyReactiveStreamsBody(org.asynchttpclient.netty.request.body.NettyReactiveStreamsBody)

Example 7 with InputStreamBodyGenerator

use of org.asynchttpclient.request.body.generator.InputStreamBodyGenerator in project camel by apache.

the class DefaultAhcBinding method populateBody.

protected void populateBody(RequestBuilder builder, AhcEndpoint endpoint, Exchange exchange) throws CamelExchangeException {
    Message in = exchange.getIn();
    if (in.getBody() == null) {
        return;
    }
    String contentType = ExchangeHelper.getContentType(exchange);
    BodyGenerator body = in.getBody(BodyGenerator.class);
    String charset = IOHelper.getCharsetName(exchange, false);
    if (body == null) {
        try {
            Object data = in.getBody();
            if (data != null) {
                if (contentType != null && AhcConstants.CONTENT_TYPE_JAVA_SERIALIZED_OBJECT.equals(contentType)) {
                    if (!endpoint.getComponent().isAllowJavaSerializedObject()) {
                        throw new CamelExchangeException("Content-type " + AhcConstants.CONTENT_TYPE_JAVA_SERIALIZED_OBJECT + " is not allowed", exchange);
                    }
                    // serialized java object
                    Serializable obj = in.getMandatoryBody(Serializable.class);
                    // write object to output stream
                    ByteArrayOutputStream bos = new ByteArrayOutputStream(endpoint.getBufferSize());
                    AhcHelper.writeObjectToStream(bos, obj);
                    byte[] bytes = bos.toByteArray();
                    body = new ByteArrayBodyGenerator(bytes);
                    IOHelper.close(bos);
                } 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) {
                        body = new FileBodyGenerator(file);
                    }
                } else if (data instanceof String) {
                    // (for example application/x-www-form-urlencoded forms being sent)
                    if (charset != null) {
                        body = new ByteArrayBodyGenerator(((String) data).getBytes(charset));
                    } else {
                        body = new ByteArrayBodyGenerator(((String) data).getBytes());
                    }
                }
                // fallback as input stream
                if (body == null) {
                    // force the body as an input stream since this is the fallback
                    InputStream is = in.getMandatoryBody(InputStream.class);
                    body = new InputStreamBodyGenerator(is);
                }
            }
        } catch (UnsupportedEncodingException e) {
            throw new CamelExchangeException("Error creating BodyGenerator from message body", exchange, e);
        } catch (IOException e) {
            throw new CamelExchangeException("Error serializing message body", exchange, e);
        }
    }
    if (body != null) {
        log.trace("Setting body {}", body);
        builder.setBody(body);
    }
    if (charset != null) {
        log.trace("Setting body charset {}", charset);
        builder.setCharset(Charset.forName(charset));
    }
    // must set content type, even if its null, otherwise it may default to
    // application/x-www-form-urlencoded which may not be your intention
    log.trace("Setting Content-Type {}", contentType);
    if (ObjectHelper.isNotEmpty(contentType)) {
        builder.setHeader(Exchange.CONTENT_TYPE, contentType);
    }
}
Also used : CamelExchangeException(org.apache.camel.CamelExchangeException) Serializable(java.io.Serializable) Message(org.apache.camel.Message) InputStreamBodyGenerator(org.asynchttpclient.request.body.generator.InputStreamBodyGenerator) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) UnsupportedEncodingException(java.io.UnsupportedEncodingException) FileBodyGenerator(org.asynchttpclient.request.body.generator.FileBodyGenerator) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) BodyGenerator(org.asynchttpclient.request.body.generator.BodyGenerator) FileBodyGenerator(org.asynchttpclient.request.body.generator.FileBodyGenerator) InputStreamBodyGenerator(org.asynchttpclient.request.body.generator.InputStreamBodyGenerator) ByteArrayBodyGenerator(org.asynchttpclient.request.body.generator.ByteArrayBodyGenerator) ByteArrayBodyGenerator(org.asynchttpclient.request.body.generator.ByteArrayBodyGenerator) GenericFile(org.apache.camel.component.file.GenericFile) File(java.io.File) GenericFile(org.apache.camel.component.file.GenericFile)

Example 8 with InputStreamBodyGenerator

use of org.asynchttpclient.request.body.generator.InputStreamBodyGenerator in project async-http-client by AsyncHttpClient.

the class BasicHttpTest method postInputStreamWithContentLengthAsBodyGenerator.

@Test
public void postInputStreamWithContentLengthAsBodyGenerator() throws Throwable {
    withClient().run(client -> {
        withServer(server).run(server -> {
            HttpHeaders h = new DefaultHttpHeaders();
            h.add(CONTENT_TYPE, HttpHeaderValues.APPLICATION_JSON);
            server.enqueue(new AbstractHandler() {

                EchoHandler chain = new EchoHandler();

                @Override
                public void handle(String target, org.eclipse.jetty.server.Request request, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException, ServletException {
                    assertNull(request.getHeader(TRANSFER_ENCODING.toString()));
                    assertEquals(request.getHeader(CONTENT_LENGTH.toString()), Integer.toString("{}".getBytes(StandardCharsets.ISO_8859_1).length));
                    chain.handle(target, request, httpServletRequest, httpServletResponse);
                }
            });
            byte[] bodyBytes = "{}".getBytes(StandardCharsets.ISO_8859_1);
            InputStream bodyStream = new ByteArrayInputStream(bodyBytes);
            client.preparePost(getTargetUrl()).setHeaders(h).setBody(new InputStreamBodyGenerator(bodyStream, bodyBytes.length)).execute(new AsyncCompletionHandlerAdapter() {

                @Override
                public Response onCompleted(Response response) throws Exception {
                    assertEquals(response.getStatusCode(), 200);
                    assertEquals(response.getResponseBody(), "{}");
                    return response;
                }
            }).get(TIMEOUT, SECONDS);
        });
    });
}
Also used : HttpHeaders(io.netty.handler.codec.http.HttpHeaders) DefaultHttpHeaders(io.netty.handler.codec.http.DefaultHttpHeaders) InputStreamBodyGenerator(org.asynchttpclient.request.body.generator.InputStreamBodyGenerator) AsyncCompletionHandlerAdapter(org.asynchttpclient.test.TestUtils.AsyncCompletionHandlerAdapter) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) AbstractHandler(org.eclipse.jetty.server.handler.AbstractHandler) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) HttpServletResponse(javax.servlet.http.HttpServletResponse) DefaultHttpHeaders(io.netty.handler.codec.http.DefaultHttpHeaders) ByteArrayInputStream(java.io.ByteArrayInputStream) EchoHandler(org.asynchttpclient.testserver.HttpServer.EchoHandler) Test(org.testng.annotations.Test) HttpTest(org.asynchttpclient.testserver.HttpTest)

Example 9 with InputStreamBodyGenerator

use of org.asynchttpclient.request.body.generator.InputStreamBodyGenerator in project async-http-client by AsyncHttpClient.

the class SimpleAsyncHttpClientTest method stringBuilderBodyConsumerTest.

@Test(groups = "standalone")
public void stringBuilderBodyConsumerTest() throws Exception {
    try (SimpleAsyncHttpClient client = //
    new SimpleAsyncHttpClient.Builder().setPooledConnectionIdleTimeout(//
    100).setMaxConnections(//
    50).setRequestTimeout(//
    5 * 60 * 1000).setUrl(//
    getTargetUrl()).setHeader("Content-Type", "text/html").build()) {
        StringBuilder s = new StringBuilder();
        Future<Response> future = client.post(new InputStreamBodyGenerator(new ByteArrayInputStream(MY_MESSAGE.getBytes())), new AppendableBodyConsumer(s));
        Response response = future.get();
        assertEquals(response.getStatusCode(), 200);
        assertEquals(s.toString(), MY_MESSAGE);
    }
}
Also used : Response(org.asynchttpclient.Response) InputStreamBodyGenerator(org.asynchttpclient.request.body.generator.InputStreamBodyGenerator) ByteArrayInputStream(java.io.ByteArrayInputStream) Test(org.testng.annotations.Test) AbstractBasicTest(org.asynchttpclient.AbstractBasicTest)

Example 10 with InputStreamBodyGenerator

use of org.asynchttpclient.request.body.generator.InputStreamBodyGenerator in project async-http-client by AsyncHttpClient.

the class SimpleAsyncHttpClientTest method requestByteArrayOutputStreamBodyConsumerTest.

@Test(groups = "standalone")
public void requestByteArrayOutputStreamBodyConsumerTest() throws Exception {
    try (SimpleAsyncHttpClient client = new SimpleAsyncHttpClient.Builder().setUrl(getTargetUrl()).build()) {
        ByteArrayOutputStream o = new ByteArrayOutputStream(10);
        Future<Response> future = client.post(new InputStreamBodyGenerator(new ByteArrayInputStream(MY_MESSAGE.getBytes())), new OutputStreamBodyConsumer(o));
        Response response = future.get();
        assertEquals(response.getStatusCode(), 200);
        assertEquals(o.toString(), MY_MESSAGE);
    }
}
Also used : Response(org.asynchttpclient.Response) InputStreamBodyGenerator(org.asynchttpclient.request.body.generator.InputStreamBodyGenerator) ByteArrayInputStream(java.io.ByteArrayInputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Test(org.testng.annotations.Test) AbstractBasicTest(org.asynchttpclient.AbstractBasicTest)

Aggregations

InputStreamBodyGenerator (org.asynchttpclient.request.body.generator.InputStreamBodyGenerator)11 ByteArrayInputStream (java.io.ByteArrayInputStream)9 Response (org.asynchttpclient.Response)8 Test (org.testng.annotations.Test)8 AbstractBasicTest (org.asynchttpclient.AbstractBasicTest)7 ByteArrayOutputStream (java.io.ByteArrayOutputStream)5 HttpHeaders (io.netty.handler.codec.http.HttpHeaders)2 IOException (java.io.IOException)2 InputStream (java.io.InputStream)2 AsyncHttpClient (org.asynchttpclient.AsyncHttpClient)2 RequestBuilder (org.asynchttpclient.RequestBuilder)2 FileBodyGenerator (org.asynchttpclient.request.body.generator.FileBodyGenerator)2 DefaultHttpHeaders (io.netty.handler.codec.http.DefaultHttpHeaders)1 File (java.io.File)1 Serializable (java.io.Serializable)1 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1 Charset (java.nio.charset.Charset)1 ServletException (javax.servlet.ServletException)1 HttpServletRequest (javax.servlet.http.HttpServletRequest)1 HttpServletResponse (javax.servlet.http.HttpServletResponse)1