use of org.apache.camel.WrappedFile in project camel by apache.
the class DefaultRestletBinding method populateRestletResponseFromExchange.
public void populateRestletResponseFromExchange(Exchange exchange, Response response) throws Exception {
Message out;
if (exchange.isFailed()) {
// 500 for internal server error which can be overridden by response code in header
response.setStatus(Status.valueOf(500));
Message msg = exchange.hasOut() ? exchange.getOut() : exchange.getIn();
if (msg.isFault()) {
out = msg;
} else {
// print exception as message and stacktrace
Exception t = exchange.getException();
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
t.printStackTrace(pw);
response.setEntity(sw.toString(), MediaType.TEXT_PLAIN);
return;
}
} else {
out = exchange.hasOut() ? exchange.getOut() : exchange.getIn();
}
// get content type
MediaType mediaType = out.getHeader(Exchange.CONTENT_TYPE, MediaType.class);
if (mediaType == null) {
Object body = out.getBody();
mediaType = MediaType.TEXT_PLAIN;
if (body instanceof String) {
mediaType = MediaType.TEXT_PLAIN;
} else if (body instanceof StringSource || body instanceof DOMSource) {
mediaType = MediaType.TEXT_XML;
}
}
// get response code
Integer responseCode = out.getHeader(Exchange.HTTP_RESPONSE_CODE, Integer.class);
if (responseCode != null) {
response.setStatus(Status.valueOf(responseCode));
}
// set response body according to the message body
Object body = out.getBody();
if (body instanceof WrappedFile) {
// grab body from generic file holder
GenericFile<?> gf = (GenericFile<?>) body;
body = gf.getBody();
}
if (body == null) {
// empty response
response.setEntity("", MediaType.TEXT_PLAIN);
} else if (body instanceof Response) {
// its already a restlet response, so dont do anything
LOG.debug("Using existing Restlet Response from exchange body: {}", body);
} else if (body instanceof Representation) {
response.setEntity(out.getBody(Representation.class));
} else if (body instanceof InputStream) {
response.setEntity(new InputRepresentation(out.getBody(InputStream.class), mediaType));
} else if (body instanceof File) {
response.setEntity(new FileRepresentation(out.getBody(File.class), mediaType));
} else if (body instanceof byte[]) {
byte[] bytes = out.getBody(byte[].class);
response.setEntity(new ByteArrayRepresentation(bytes, mediaType, bytes.length));
} else {
// fallback and use string
String text = out.getBody(String.class);
response.setEntity(text, mediaType);
}
LOG.debug("Populate Restlet response from exchange body: {}", body);
if (exchange.getProperty(Exchange.CHARSET_NAME) != null) {
CharacterSet cs = CharacterSet.valueOf(exchange.getProperty(Exchange.CHARSET_NAME, String.class));
response.getEntity().setCharacterSet(cs);
}
// set headers at the end, as the entity must be set first
// NOTE: setting HTTP headers on restlet is cumbersome and its API is "weird" and has some flaws
// so we need to headers two times, and the 2nd time we add the non-internal headers once more
Series<Header> series = new Series<Header>(Header.class);
for (Map.Entry<String, Object> entry : out.getHeaders().entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
if (!headerFilterStrategy.applyFilterToCamelHeaders(key, value, exchange)) {
boolean added = setResponseHeader(exchange, response, key, value);
if (!added) {
// we only want non internal headers
if (!key.startsWith("Camel") && !key.startsWith("org.restlet")) {
String text = exchange.getContext().getTypeConverter().tryConvertTo(String.class, exchange, value);
if (text != null) {
series.add(key, text);
}
}
}
}
}
// set HTTP headers so we return these in the response
if (!series.isEmpty()) {
response.getAttributes().put(HeaderConstants.ATTRIBUTE_HEADERS, series);
}
}
use of org.apache.camel.WrappedFile in project camel by apache.
the class TarAggregationStrategy method aggregate.
@Override
public Exchange aggregate(Exchange oldExchange, Exchange newExchange) {
File tarFile;
Exchange answer = oldExchange;
// Guard against empty new exchanges
if (newExchange == null) {
return oldExchange;
}
// First time for this aggregation
if (oldExchange == null) {
try {
tarFile = FileUtil.createTempFile(this.filePrefix, this.fileSuffix, parentDir);
LOG.trace("Created temporary file: {}", tarFile);
} catch (IOException e) {
throw new GenericFileOperationFailedException(e.getMessage(), e);
}
answer = newExchange;
answer.addOnCompletion(new DeleteTarFileOnCompletion(tarFile));
} else {
tarFile = oldExchange.getIn().getBody(File.class);
}
Object body = newExchange.getIn().getBody();
if (body instanceof WrappedFile) {
body = ((WrappedFile) body).getFile();
}
if (body instanceof File) {
try {
File appendFile = (File) body;
// do not try to append empty files
if (appendFile.length() > 0) {
String entryName = preserveFolderStructure ? newExchange.getIn().getHeader(Exchange.FILE_NAME, String.class) : newExchange.getIn().getMessageId();
addFileToTar(tarFile, appendFile, this.preserveFolderStructure ? entryName : null);
GenericFile<File> genericFile = FileConsumer.asGenericFile(tarFile.getParent(), tarFile, Charset.defaultCharset().toString(), false);
genericFile.bindToExchange(answer);
}
} catch (Exception e) {
throw new GenericFileOperationFailedException(e.getMessage(), e);
}
} else {
// Handle all other messages
try {
byte[] buffer = newExchange.getIn().getMandatoryBody(byte[].class);
// do not try to append empty data
if (buffer.length > 0) {
String entryName = useFilenameHeader ? newExchange.getIn().getHeader(Exchange.FILE_NAME, String.class) : newExchange.getIn().getMessageId();
addEntryToTar(tarFile, entryName, buffer, buffer.length);
GenericFile<File> genericFile = FileConsumer.asGenericFile(tarFile.getParent(), tarFile, Charset.defaultCharset().toString(), false);
genericFile.bindToExchange(answer);
}
} catch (Exception e) {
throw new GenericFileOperationFailedException(e.getMessage(), e);
}
}
return answer;
}
use of org.apache.camel.WrappedFile in project camel by apache.
the class S3Producer method processSingleOp.
public void processSingleOp(final Exchange exchange) throws Exception {
ObjectMetadata objectMetadata = determineMetadata(exchange);
File filePayload = null;
InputStream is = null;
Object obj = exchange.getIn().getMandatoryBody();
PutObjectRequest putObjectRequest = null;
// Need to check if the message body is WrappedFile
if (obj instanceof WrappedFile) {
obj = ((WrappedFile<?>) obj).getFile();
}
if (obj instanceof File) {
filePayload = (File) obj;
is = new FileInputStream(filePayload);
} else {
is = exchange.getIn().getMandatoryBody(InputStream.class);
}
putObjectRequest = new PutObjectRequest(getConfiguration().getBucketName(), determineKey(exchange), is, objectMetadata);
String storageClass = determineStorageClass(exchange);
if (storageClass != null) {
putObjectRequest.setStorageClass(storageClass);
}
String cannedAcl = exchange.getIn().getHeader(S3Constants.CANNED_ACL, String.class);
if (cannedAcl != null) {
CannedAccessControlList objectAcl = CannedAccessControlList.valueOf(cannedAcl);
putObjectRequest.setCannedAcl(objectAcl);
}
AccessControlList acl = exchange.getIn().getHeader(S3Constants.ACL, AccessControlList.class);
if (acl != null) {
// note: if cannedacl and acl are both specified the last one will be used. refer to
// PutObjectRequest#setAccessControlList for more details
putObjectRequest.setAccessControlList(acl);
}
LOG.trace("Put object [{}] from exchange [{}]...", putObjectRequest, exchange);
PutObjectResult putObjectResult = getEndpoint().getS3Client().putObject(putObjectRequest);
LOG.trace("Received result [{}]", putObjectResult);
Message message = getMessageForResponse(exchange);
message.setHeader(S3Constants.E_TAG, putObjectResult.getETag());
if (putObjectResult.getVersionId() != null) {
message.setHeader(S3Constants.VERSION_ID, putObjectResult.getVersionId());
}
if (getConfiguration().isDeleteAfterWrite() && filePayload != null) {
// close streams
IOHelper.close(putObjectRequest.getInputStream());
IOHelper.close(is);
FileUtil.deleteFile(filePayload);
}
}
use of org.apache.camel.WrappedFile in project camel by apache.
the class BeanIOSplitter method evaluate.
public Object evaluate(Exchange exchange) throws Exception {
Message msg = exchange.getIn();
Object body = msg.getBody();
if (factory == null) {
factory = createStreamFactory(exchange.getContext());
}
BeanReader beanReader = null;
if (body instanceof WrappedFile) {
body = ((WrappedFile) body).getFile();
}
if (body instanceof File) {
File file = (File) body;
beanReader = factory.createReader(getStreamName(), file);
}
if (beanReader == null) {
Reader reader = msg.getMandatoryBody(Reader.class);
beanReader = factory.createReader(getStreamName(), reader);
}
BeanIOIterator iterator = new BeanIOIterator(beanReader);
BeanReaderErrorHandler errorHandler = getOrCreateBeanReaderErrorHandler(configuration, exchange, null, iterator);
beanReader.setErrorHandler(errorHandler);
return iterator;
}
use of org.apache.camel.WrappedFile in project camel by apache.
the class ObjectHelper method getScanner.
/**
* Creates a {@link Scanner} for scanning the given value.
*
* @param exchange the current exchange
* @param value the value, typically the message IN body
* @return the scanner, is newer <tt>null</tt>
*/
public static Scanner getScanner(Exchange exchange, Object value) {
if (value instanceof WrappedFile) {
WrappedFile<?> gf = (WrappedFile<?>) value;
Object body = gf.getBody();
if (body != null) {
// we have loaded the file content into the body so use that
value = body;
} else {
// generic file is just a wrapper for the real file so call again with the real file
return getScanner(exchange, gf.getFile());
}
}
String charset = exchange.getProperty(Exchange.CHARSET_NAME, String.class);
Scanner scanner = null;
if (value instanceof Readable) {
scanner = new Scanner((Readable) value);
} else if (value instanceof InputStream) {
scanner = charset == null ? new Scanner((InputStream) value) : new Scanner((InputStream) value, charset);
} else if (value instanceof File) {
try {
scanner = charset == null ? new Scanner((File) value) : new Scanner((File) value, charset);
} catch (FileNotFoundException e) {
throw new RuntimeCamelException(e);
}
} else if (value instanceof String) {
scanner = new Scanner((String) value);
} else if (value instanceof ReadableByteChannel) {
scanner = charset == null ? new Scanner((ReadableByteChannel) value) : new Scanner((ReadableByteChannel) value, charset);
}
if (scanner == null) {
// value is not a suitable type, try to convert value to a string
String text = exchange.getContext().getTypeConverter().convertTo(String.class, exchange, value);
if (text != null) {
scanner = new Scanner(text);
}
}
if (scanner == null) {
scanner = new Scanner("");
}
return scanner;
}
Aggregations