Search in sources :

Example 11 with GenericFile

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);
}
Also used : Exchange(org.apache.camel.Exchange) GenericFileOperationFailedException(org.apache.camel.component.file.GenericFileOperationFailedException) GenericFile(org.apache.camel.component.file.GenericFile)

Example 12 with GenericFile

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;
}
Also used : FileContent(com.google.api.client.http.FileContent) InputStream(java.io.InputStream) InputStreamContent(com.google.api.client.http.InputStreamContent) GenericFile(org.apache.camel.component.file.GenericFile) File(java.io.File) Converter(org.apache.camel.Converter)

Example 13 with GenericFile

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;
}
Also used : CamelExchangeException(org.apache.camel.CamelExchangeException) Serializable(java.io.Serializable) StringRequestEntity(org.apache.commons.httpclient.methods.StringRequestEntity) InputStreamRequestEntity(org.apache.commons.httpclient.methods.InputStreamRequestEntity) Message(org.apache.camel.Message) InputStream(java.io.InputStream) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) FileRequestEntity(org.apache.commons.httpclient.methods.FileRequestEntity) FileRequestEntity(org.apache.commons.httpclient.methods.FileRequestEntity) ByteArrayRequestEntity(org.apache.commons.httpclient.methods.ByteArrayRequestEntity) InputStreamRequestEntity(org.apache.commons.httpclient.methods.InputStreamRequestEntity) StringRequestEntity(org.apache.commons.httpclient.methods.StringRequestEntity) RequestEntity(org.apache.commons.httpclient.methods.RequestEntity) GenericFile(org.apache.camel.component.file.GenericFile) File(java.io.File) GenericFile(org.apache.camel.component.file.GenericFile) ByteArrayRequestEntity(org.apache.commons.httpclient.methods.ByteArrayRequestEntity)

Example 14 with GenericFile

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;
}
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 15 with GenericFile

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

Aggregations

GenericFile (org.apache.camel.component.file.GenericFile)34 File (java.io.File)25 IOException (java.io.IOException)11 InputStream (java.io.InputStream)11 Exchange (org.apache.camel.Exchange)8 ByteArrayOutputStream (java.io.ByteArrayOutputStream)7 GenericFileOperationFailedException (org.apache.camel.component.file.GenericFileOperationFailedException)7 UnsupportedEncodingException (java.io.UnsupportedEncodingException)4 CamelExchangeException (org.apache.camel.CamelExchangeException)4 Message (org.apache.camel.Message)4 ByteArrayInputStream (java.io.ByteArrayInputStream)3 FileOutputStream (java.io.FileOutputStream)3 OutputStream (java.io.OutputStream)3 Serializable (java.io.Serializable)3 FallbackConverter (org.apache.camel.FallbackConverter)3 TypeConverter (org.apache.camel.TypeConverter)3 WrappedFile (org.apache.camel.WrappedFile)3 FileEndpoint (org.apache.camel.component.file.FileEndpoint)3 MockEndpoint (org.apache.camel.component.mock.MockEndpoint)3 Test (org.junit.Test)3