Search in sources :

Example 1 with WrappedFile

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);
    }
}
Also used : DOMSource(javax.xml.transform.dom.DOMSource) Message(org.apache.camel.Message) StringWriter(java.io.StringWriter) WrappedFile(org.apache.camel.WrappedFile) MediaType(org.restlet.data.MediaType) CharacterSet(org.restlet.data.CharacterSet) PrintWriter(java.io.PrintWriter) InputRepresentation(org.restlet.representation.InputRepresentation) InputStream(java.io.InputStream) EmptyRepresentation(org.restlet.representation.EmptyRepresentation) StringRepresentation(org.restlet.representation.StringRepresentation) InputRepresentation(org.restlet.representation.InputRepresentation) ByteArrayRepresentation(org.restlet.representation.ByteArrayRepresentation) FileRepresentation(org.restlet.representation.FileRepresentation) StreamRepresentation(org.restlet.representation.StreamRepresentation) Representation(org.restlet.representation.Representation) DecodeRepresentation(org.restlet.engine.application.DecodeRepresentation) ParseException(java.text.ParseException) RuntimeCamelException(org.apache.camel.RuntimeCamelException) ChallengeResponse(org.restlet.data.ChallengeResponse) Response(org.restlet.Response) Series(org.restlet.util.Series) Header(org.restlet.data.Header) FileRepresentation(org.restlet.representation.FileRepresentation) ByteArrayRepresentation(org.restlet.representation.ByteArrayRepresentation) StringSource(org.apache.camel.StringSource) WrappedFile(org.apache.camel.WrappedFile) GenericFile(org.apache.camel.component.file.GenericFile) File(java.io.File) Map(java.util.Map) GenericFile(org.apache.camel.component.file.GenericFile)

Example 2 with WrappedFile

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;
}
Also used : Exchange(org.apache.camel.Exchange) GenericFileOperationFailedException(org.apache.camel.component.file.GenericFileOperationFailedException) WrappedFile(org.apache.camel.WrappedFile) IOException(java.io.IOException) GenericFile(org.apache.camel.component.file.GenericFile) File(java.io.File) WrappedFile(org.apache.camel.WrappedFile) ArchiveException(org.apache.commons.compress.archivers.ArchiveException) GenericFileOperationFailedException(org.apache.camel.component.file.GenericFileOperationFailedException) IOException(java.io.IOException)

Example 3 with WrappedFile

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);
    }
}
Also used : CannedAccessControlList(com.amazonaws.services.s3.model.CannedAccessControlList) AccessControlList(com.amazonaws.services.s3.model.AccessControlList) Message(org.apache.camel.Message) WrappedFile(org.apache.camel.WrappedFile) PutObjectResult(com.amazonaws.services.s3.model.PutObjectResult) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) CannedAccessControlList(com.amazonaws.services.s3.model.CannedAccessControlList) ObjectMetadata(com.amazonaws.services.s3.model.ObjectMetadata) File(java.io.File) WrappedFile(org.apache.camel.WrappedFile) PutObjectRequest(com.amazonaws.services.s3.model.PutObjectRequest) FileInputStream(java.io.FileInputStream)

Example 4 with WrappedFile

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;
}
Also used : Message(org.apache.camel.Message) BeanIOHelper.getOrCreateBeanReaderErrorHandler(org.apache.camel.dataformat.beanio.BeanIOHelper.getOrCreateBeanReaderErrorHandler) BeanReaderErrorHandler(org.beanio.BeanReaderErrorHandler) WrappedFile(org.apache.camel.WrappedFile) BeanReader(org.beanio.BeanReader) Reader(java.io.Reader) BeanReader(org.beanio.BeanReader) File(java.io.File) WrappedFile(org.apache.camel.WrappedFile)

Example 5 with WrappedFile

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;
}
Also used : Scanner(java.util.Scanner) ReadableByteChannel(java.nio.channels.ReadableByteChannel) WrappedFile(org.apache.camel.WrappedFile) InputStream(java.io.InputStream) FileNotFoundException(java.io.FileNotFoundException) RuntimeCamelException(org.apache.camel.RuntimeCamelException) File(java.io.File) WrappedFile(org.apache.camel.WrappedFile)

Aggregations

WrappedFile (org.apache.camel.WrappedFile)12 File (java.io.File)11 InputStream (java.io.InputStream)6 IOException (java.io.IOException)4 Message (org.apache.camel.Message)4 GenericFile (org.apache.camel.component.file.GenericFile)4 Reader (java.io.Reader)3 Exchange (org.apache.camel.Exchange)3 AccessControlList (com.amazonaws.services.s3.model.AccessControlList)2 CannedAccessControlList (com.amazonaws.services.s3.model.CannedAccessControlList)2 ObjectMetadata (com.amazonaws.services.s3.model.ObjectMetadata)2 FileInputStream (java.io.FileInputStream)2 ArrayList (java.util.ArrayList)2 Map (java.util.Map)2 RuntimeCamelException (org.apache.camel.RuntimeCamelException)2 StringSource (org.apache.camel.StringSource)2 GenericFileOperationFailedException (org.apache.camel.component.file.GenericFileOperationFailedException)2 InvalidArgumentException (com.amazonaws.services.cloudfront.model.InvalidArgumentException)1 AbortMultipartUploadRequest (com.amazonaws.services.s3.model.AbortMultipartUploadRequest)1 CompleteMultipartUploadRequest (com.amazonaws.services.s3.model.CompleteMultipartUploadRequest)1