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);
}
}
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;
}
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);
}
}
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");
}
}
Aggregations