use of org.apache.camel.component.file.GenericFile in project camel by apache.
the class GenericFileDeleteProcessStrategyTest method testCannotDeleteFile.
public void testCannotDeleteFile() throws Exception {
deleteCounter = 0;
existsCounter = 0;
@SuppressWarnings("unchecked") GenericFileEndpoint<Object> endpoint = context.getEndpoint("file://target/foo", GenericFileEndpoint.class);
Exchange exchange = endpoint.createExchange();
GenericFile<Object> file = new GenericFile<Object>();
file.setAbsoluteFilePath("target/foo/boom.txt");
GenericFileDeleteProcessStrategy<Object> strategy = new GenericFileDeleteProcessStrategy<Object>();
try {
strategy.commit(new MyGenericFileOperations(), endpoint, exchange, file);
fail("Should have thrown an exception");
} catch (GenericFileOperationFailedException e) {
// expected
}
assertEquals("Should have tried to delete file 3 times", 3, deleteCounter);
assertEquals("Should have tried to delete file 3 times", 3, existsCounter);
}
use of org.apache.camel.component.file.GenericFile in project camel by apache.
the class GoogleDriveFilesConverter method genericFileToGoogleDriveFile.
@Converter
public static com.google.api.services.drive.model.File genericFileToGoogleDriveFile(GenericFile<?> file, Exchange exchange) throws Exception {
if (file.getFile() instanceof File) {
File f = (File) file.getFile();
com.google.api.services.drive.model.File fileMetadata = new com.google.api.services.drive.model.File();
fileMetadata.setTitle(f.getName());
FileContent mediaContent = new FileContent(null, f);
if (exchange != null) {
exchange.getIn().setHeader("CamelGoogleDrive.content", fileMetadata);
exchange.getIn().setHeader("CamelGoogleDrive.mediaContent", mediaContent);
}
return fileMetadata;
}
if (exchange != null) {
// body wasn't a java.io.File so let's try to convert it
file.getBinding().loadContent(exchange, file);
InputStream is = exchange.getContext().getTypeConverter().convertTo(InputStream.class, exchange, file.getBody());
com.google.api.services.drive.model.File fileMetadata = new com.google.api.services.drive.model.File();
fileMetadata.setTitle(file.getFileName());
InputStreamContent mediaContent = new InputStreamContent(null, is);
if (exchange != null) {
exchange.getIn().setHeader("CamelGoogleDrive.content", fileMetadata);
exchange.getIn().setHeader("CamelGoogleDrive.mediaContent", mediaContent);
}
return fileMetadata;
}
return null;
}
use of org.apache.camel.component.file.GenericFile in project camel by apache.
the class HttpProducer method createRequestEntity.
/**
* Creates a holder object for the data to send to the remote server.
*
* @param exchange the exchange with the IN message with data to send
* @return the data holder
* @throws CamelExchangeException is thrown if error creating RequestEntity
*/
protected RequestEntity createRequestEntity(Exchange exchange) throws CamelExchangeException {
Message in = exchange.getIn();
if (in.getBody() == null) {
return null;
}
RequestEntity answer = in.getBody(RequestEntity.class);
if (answer == null) {
try {
Object data = in.getBody();
if (data != null) {
String contentType = ExchangeHelper.getContentType(exchange);
if (contentType != null && HttpConstants.CONTENT_TYPE_JAVA_SERIALIZED_OBJECT.equals(contentType)) {
if (!getEndpoint().getComponent().isAllowJavaSerializedObject()) {
throw new CamelExchangeException("Content-type " + HttpConstants.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();
HttpHelper.writeObjectToStream(bos, obj);
answer = new ByteArrayRequestEntity(bos.toByteArray(), HttpConstants.CONTENT_TYPE_JAVA_SERIALIZED_OBJECT);
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) {
answer = new FileRequestEntity(file, contentType);
}
} else if (data instanceof String) {
// be a bit careful with String as any type can most likely be converted to String
// so we only do an instanceof check and accept String if the body is really a String
// do not fallback to use the default charset as it can influence the request
// (for example application/x-www-form-urlencoded forms being sent)
String charset = IOHelper.getCharsetName(exchange, false);
answer = new StringRequestEntity((String) data, contentType, charset);
}
// fallback as input stream
if (answer == null) {
// force the body as an input stream since this is the fallback
InputStream is = in.getMandatoryBody(InputStream.class);
answer = new InputStreamRequestEntity(is, contentType);
}
}
} catch (UnsupportedEncodingException e) {
throw new CamelExchangeException("Error creating RequestEntity from message body", exchange, e);
} catch (IOException e) {
throw new CamelExchangeException("Error serializing message body", exchange, e);
}
}
return answer;
}
use of org.apache.camel.component.file.GenericFile 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.component.file.GenericFile 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);
}
}
Aggregations