Search in sources :

Example 1 with FileBodyGenerator

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

the class SimpleAsyncHttpClientTest method testPutZeroBytesFileTest.

/**
     * See https://issues.sonatype.org/browse/AHC-5
     */
@Test(groups = "standalone", enabled = true)
public void testPutZeroBytesFileTest() throws Exception {
    try (SimpleAsyncHttpClient client = //
    new SimpleAsyncHttpClient.Builder().setPooledConnectionIdleTimeout(//
    100).setMaxConnections(//
    50).setRequestTimeout(//
    5 * 1000).setUrl(//
    getTargetUrl() + "/testPutZeroBytesFileTest.txt").setHeader("Content-Type", "text/plain").build()) {
        File tmpfile = File.createTempFile("testPutZeroBytesFile", ".tmp");
        tmpfile.deleteOnExit();
        Future<Response> future = client.put(new FileBodyGenerator(tmpfile));
        System.out.println("waiting for response");
        Response response = future.get();
        tmpfile.delete();
        assertEquals(response.getStatusCode(), 200);
    }
}
Also used : Response(org.asynchttpclient.Response) FileBodyGenerator(org.asynchttpclient.request.body.generator.FileBodyGenerator) File(java.io.File) Test(org.testng.annotations.Test) AbstractBasicTest(org.asynchttpclient.AbstractBasicTest)

Example 2 with FileBodyGenerator

use of org.asynchttpclient.request.body.generator.FileBodyGenerator 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 3 with FileBodyGenerator

use of org.asynchttpclient.request.body.generator.FileBodyGenerator 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 4 with FileBodyGenerator

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

the class TransferListenerTest method basicPutFileBodyGeneratorTest.

@Test(groups = "standalone")
public void basicPutFileBodyGeneratorTest() throws Exception {
    try (AsyncHttpClient client = asyncHttpClient()) {
        final AtomicReference<Throwable> throwable = new AtomicReference<>();
        final AtomicReference<HttpHeaders> hSent = new AtomicReference<>();
        final AtomicReference<HttpHeaders> hRead = new AtomicReference<>();
        final AtomicInteger bbReceivedLenght = new AtomicInteger(0);
        final AtomicLong bbSentLenght = new AtomicLong(0L);
        final AtomicBoolean completed = new AtomicBoolean(false);
        File file = createTempFile(1024 * 100 * 10);
        TransferCompletionHandler tl = new TransferCompletionHandler();
        tl.addTransferListener(new TransferListener() {

            public void onRequestHeadersSent(HttpHeaders headers) {
                hSent.set(headers);
            }

            public void onResponseHeadersReceived(HttpHeaders headers) {
                hRead.set(headers);
            }

            public void onBytesReceived(byte[] b) {
                bbReceivedLenght.addAndGet(b.length);
            }

            public void onBytesSent(long amount, long current, long total) {
                bbSentLenght.addAndGet(amount);
            }

            public void onRequestResponseCompleted() {
                completed.set(true);
            }

            public void onThrowable(Throwable t) {
                throwable.set(t);
            }
        });
        Response response = client.preparePut(getTargetUrl()).setBody(new FileBodyGenerator(file)).execute(tl).get();
        assertNotNull(response);
        assertEquals(response.getStatusCode(), 200);
        assertNotNull(hRead.get());
        assertNotNull(hSent.get());
        assertEquals(bbReceivedLenght.get(), file.length(), "Number of received bytes incorrect");
        assertEquals(bbSentLenght.get(), file.length(), "Number of sent bytes incorrect");
    }
}
Also used : TransferListener(org.asynchttpclient.handler.TransferListener) HttpHeaders(io.netty.handler.codec.http.HttpHeaders) TransferCompletionHandler(org.asynchttpclient.handler.TransferCompletionHandler) AtomicReference(java.util.concurrent.atomic.AtomicReference) FileBodyGenerator(org.asynchttpclient.request.body.generator.FileBodyGenerator) HttpServletResponse(javax.servlet.http.HttpServletResponse) Response(org.asynchttpclient.Response) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) AtomicLong(java.util.concurrent.atomic.AtomicLong) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) File(java.io.File) TestUtils.createTempFile(org.asynchttpclient.test.TestUtils.createTempFile) AsyncHttpClient(org.asynchttpclient.AsyncHttpClient) Test(org.testng.annotations.Test) AbstractBasicTest(org.asynchttpclient.AbstractBasicTest)

Aggregations

FileBodyGenerator (org.asynchttpclient.request.body.generator.FileBodyGenerator)4 File (java.io.File)3 AbstractBasicTest (org.asynchttpclient.AbstractBasicTest)2 Response (org.asynchttpclient.Response)2 InputStreamBodyGenerator (org.asynchttpclient.request.body.generator.InputStreamBodyGenerator)2 Test (org.testng.annotations.Test)2 HttpHeaders (io.netty.handler.codec.http.HttpHeaders)1 ByteArrayInputStream (java.io.ByteArrayInputStream)1 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1 IOException (java.io.IOException)1 InputStream (java.io.InputStream)1 Serializable (java.io.Serializable)1 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1 Charset (java.nio.charset.Charset)1 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)1 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)1 AtomicLong (java.util.concurrent.atomic.AtomicLong)1 AtomicReference (java.util.concurrent.atomic.AtomicReference)1 HttpServletResponse (javax.servlet.http.HttpServletResponse)1 CamelExchangeException (org.apache.camel.CamelExchangeException)1