001/**
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.camel.component.file;
018
019import java.io.File;
020import java.util.concurrent.locks.Lock;
021import java.util.concurrent.locks.ReentrantLock;
022
023import org.apache.camel.Exchange;
024import org.apache.camel.Expression;
025import org.apache.camel.impl.DefaultExchange;
026import org.apache.camel.impl.DefaultProducer;
027import org.apache.camel.util.FileUtil;
028import org.apache.camel.util.LRUCache;
029import org.apache.camel.util.LRUCacheFactory;
030import org.apache.camel.util.ObjectHelper;
031import org.apache.camel.util.ServiceHelper;
032import org.apache.camel.util.StringHelper;
033import org.slf4j.Logger;
034import org.slf4j.LoggerFactory;
035
036/**
037 * Generic file producer
038 */
039public class GenericFileProducer<T> extends DefaultProducer {
040    protected final Logger log = LoggerFactory.getLogger(getClass());
041    protected final GenericFileEndpoint<T> endpoint;
042    protected GenericFileOperations<T> operations;
043    // assume writing to 100 different files concurrently at most for the same file producer
044    private final LRUCache<String, Lock> locks = LRUCacheFactory.newLRUCache(100);
045
046    protected GenericFileProducer(GenericFileEndpoint<T> endpoint, GenericFileOperations<T> operations) {
047        super(endpoint);
048        this.endpoint = endpoint;
049        this.operations = operations;
050    }
051
052    public String getFileSeparator() {
053        return File.separator;
054    }
055
056    public String normalizePath(String name) {
057        return FileUtil.normalizePath(name);
058    }
059
060    public void process(Exchange exchange) throws Exception {
061        // store any existing file header which we want to keep and propagate
062        final String existing = exchange.getIn().getHeader(Exchange.FILE_NAME, String.class);
063
064        // create the target file name
065        String target = createFileName(exchange);
066
067        // use lock for same file name to avoid concurrent writes to the same file
068        // for example when you concurrently append to the same file
069        Lock lock;
070        synchronized (locks) {
071            lock = locks.get(target);
072            if (lock == null) {
073                lock = new ReentrantLock();
074                locks.put(target, lock);
075            }
076        }
077
078        lock.lock();
079        try {
080            processExchange(exchange, target);
081        } finally {
082            // do not remove as the locks cache has an upper bound
083            // this ensure the locks is appropriate reused
084            lock.unlock();
085            // and remove the write file name header as we only want to use it once (by design)
086            exchange.getIn().removeHeader(Exchange.OVERRULE_FILE_NAME);
087            // and restore existing file name
088            exchange.getIn().setHeader(Exchange.FILE_NAME, existing);
089        }
090    }
091
092    /**
093     * Sets the operations to be used.
094     * <p/>
095     * Can be used to set a fresh operations in case of recovery attempts
096     *
097     * @param operations the operations
098     */
099    public void setOperations(GenericFileOperations<T> operations) {
100        this.operations = operations;
101    }
102
103    /**
104     * Perform the work to process the fileExchange
105     *
106     * @param exchange fileExchange
107     * @param target   the target filename
108     * @throws Exception is thrown if some error
109     */
110    protected void processExchange(Exchange exchange, String target) throws Exception {
111        log.trace("Processing file: {} for exchange: {}", target, exchange);
112
113        try {
114            preWriteCheck();
115
116            // should we write to a temporary name and then afterwards rename to real target
117            boolean writeAsTempAndRename = ObjectHelper.isNotEmpty(endpoint.getTempFileName());
118            String tempTarget = null;
119            // remember if target exists to avoid checking twice
120            Boolean targetExists = null;
121            if (writeAsTempAndRename) {
122                // compute temporary name with the temp prefix
123                tempTarget = createTempFileName(exchange, target);
124
125                log.trace("Writing using tempNameFile: {}", tempTarget);
126               
127                //if we should eager delete target file before deploying temporary file
128                if (endpoint.getFileExist() != GenericFileExist.TryRename && endpoint.isEagerDeleteTargetFile()) {
129                    
130                    // cater for file exists option on the real target as
131                    // the file operations code will work on the temp file
132
133                    // if an existing file already exists what should we do?
134                    targetExists = operations.existsFile(target);
135                    if (targetExists) {
136                        
137                        log.trace("EagerDeleteTargetFile, target exists");
138                        
139                        if (endpoint.getFileExist() == GenericFileExist.Ignore) {
140                            // ignore but indicate that the file was written
141                            log.trace("An existing file already exists: {}. Ignore and do not override it.", target);
142                            return;
143                        } else if (endpoint.getFileExist() == GenericFileExist.Fail) {
144                            throw new GenericFileOperationFailedException("File already exist: " + target + ". Cannot write new file.");
145                        } else if (endpoint.isEagerDeleteTargetFile() && endpoint.getFileExist() == GenericFileExist.Override) {
146                            // we override the target so we do this by deleting it so the temp file can be renamed later
147                            // with success as the existing target file have been deleted
148                            log.trace("Eagerly deleting existing file: {}", target);
149                            if (!operations.deleteFile(target)) {
150                                throw new GenericFileOperationFailedException("Cannot delete file: " + target);
151                            }
152                        }
153                    }
154                }
155
156                // delete any pre existing temp file
157                if (operations.existsFile(tempTarget)) {
158                    log.trace("Deleting existing temp file: {}", tempTarget);
159                    if (!operations.deleteFile(tempTarget)) {
160                        throw new GenericFileOperationFailedException("Cannot delete file: " + tempTarget);
161                    }
162                }
163            }
164
165            // write/upload the file
166            writeFile(exchange, tempTarget != null ? tempTarget : target);
167
168            // if we did write to a temporary name then rename it to the real
169            // name after we have written the file
170            if (tempTarget != null) {
171                // if we did not eager delete the target file
172                if (endpoint.getFileExist() != GenericFileExist.TryRename && !endpoint.isEagerDeleteTargetFile()) {
173
174                    // if an existing file already exists what should we do?
175                    targetExists = operations.existsFile(target);
176                    if (targetExists) {
177
178                        log.trace("Not using EagerDeleteTargetFile, target exists");
179
180                        if (endpoint.getFileExist() == GenericFileExist.Ignore) {
181                            // ignore but indicate that the file was written
182                            log.trace("An existing file already exists: {}. Ignore and do not override it.", target);
183                            return;
184                        } else if (endpoint.getFileExist() == GenericFileExist.Fail) {
185                            throw new GenericFileOperationFailedException("File already exist: " + target + ". Cannot write new file.");
186                        } else if (endpoint.getFileExist() == GenericFileExist.Override) {
187                            // we override the target so we do this by deleting it so the temp file can be renamed later
188                            // with success as the existing target file have been deleted
189                            log.trace("Deleting existing file: {}", target);
190                            if (!operations.deleteFile(target)) {
191                                throw new GenericFileOperationFailedException("Cannot delete file: " + target);
192                            }
193                        }
194                    }
195                }
196
197                // now we are ready to rename the temp file to the target file
198                log.trace("Renaming file: [{}] to: [{}]", tempTarget, target);
199                boolean renamed = operations.renameFile(tempTarget, target);
200                if (!renamed) {
201                    throw new GenericFileOperationFailedException("Cannot rename file from: " + tempTarget + " to: " + target);
202                }
203            }
204
205            // any done file to write?
206            if (endpoint.getDoneFileName() != null) {
207                String doneFileName = endpoint.createDoneFileName(target);
208                ObjectHelper.notEmpty(doneFileName, "doneFileName", endpoint);
209
210                // create empty exchange with empty body to write as the done file
211                Exchange empty = new DefaultExchange(exchange);
212                empty.getIn().setBody("");
213
214                log.trace("Writing done file: [{}]", doneFileName);
215                // delete any existing done file
216                if (operations.existsFile(doneFileName)) {
217                    if (!operations.deleteFile(doneFileName)) {
218                        throw new GenericFileOperationFailedException("Cannot delete existing done file: " + doneFileName);
219                    }
220                }
221                writeFile(empty, doneFileName);
222            }
223
224            // let's store the name we really used in the header, so end-users
225            // can retrieve it
226            exchange.getIn().setHeader(Exchange.FILE_NAME_PRODUCED, target);
227        } catch (Exception e) {
228            handleFailedWrite(exchange, e);
229        }
230
231        postWriteCheck(exchange);
232    }
233
234    /**
235     * If we fail writing out a file, we will call this method. This hook is
236     * provided to disconnect from servers or clean up files we created (if needed).
237     */
238    public void handleFailedWrite(Exchange exchange, Exception exception) throws Exception {
239        throw exception;
240    }
241
242    /**
243     * Perform any actions that need to occur before we write such as connecting to an FTP server etc.
244     */
245    public void preWriteCheck() throws Exception {
246        // nothing needed to check
247    }
248
249    /**
250     * Perform any actions that need to occur after we are done such as disconnecting.
251     */
252    public void postWriteCheck(Exchange exchange) {
253        // nothing needed to check
254    }
255
256    public void writeFile(Exchange exchange, String fileName) throws GenericFileOperationFailedException {
257        // build directory if auto create is enabled
258        if (endpoint.isAutoCreate()) {
259            // we must normalize it (to avoid having both \ and / in the name which confuses java.io.File)
260            String name = FileUtil.normalizePath(fileName);
261
262            // use java.io.File to compute the file path
263            File file = new File(name);
264            String directory = file.getParent();
265            boolean absolute = FileUtil.isAbsolute(file);
266            if (directory != null) {
267                if (!operations.buildDirectory(directory, absolute)) {
268                    log.debug("Cannot build directory [{}] (could be because of denied permissions)", directory);
269                }
270            }
271        }
272
273        // upload
274        if (log.isTraceEnabled()) {
275            log.trace("About to write [{}] to [{}] from exchange [{}]", new Object[]{fileName, getEndpoint(), exchange});
276        }
277
278        boolean success = operations.storeFile(fileName, exchange);
279        if (!success) {
280            throw new GenericFileOperationFailedException("Error writing file [" + fileName + "]");
281        }
282        log.debug("Wrote [{}] to [{}]", fileName, getEndpoint());
283    }
284
285    public String createFileName(Exchange exchange) {
286        String answer;
287
288        // overrule takes precedence
289        Object value;
290
291        Object overrule = exchange.getIn().getHeader(Exchange.OVERRULE_FILE_NAME);
292        if (overrule != null) {
293            if (overrule instanceof Expression) {
294                value = overrule;
295            } else {
296                value = exchange.getContext().getTypeConverter().convertTo(String.class, exchange, overrule);
297            }
298        } else {
299            value = exchange.getIn().getHeader(Exchange.FILE_NAME);
300        }
301
302        // if we have an overrule then override the existing header to use the overrule computed name from this point forward
303        if (overrule != null) {
304            exchange.getIn().setHeader(Exchange.FILE_NAME, value);
305        }
306
307        if (value != null && value instanceof String && StringHelper.hasStartToken((String) value, "simple")) {
308            log.warn("Simple expression: {} detected in header: {} of type String. This feature has been removed (see CAMEL-6748).", value, Exchange.FILE_NAME);
309        }
310
311        // expression support
312        Expression expression = endpoint.getFileName();
313        if (value != null && value instanceof Expression) {
314            expression = (Expression) value;
315        }
316
317        // evaluate the name as a String from the value
318        String name;
319        if (expression != null) {
320            log.trace("Filename evaluated as expression: {}", expression);
321            name = expression.evaluate(exchange, String.class);
322        } else {
323            name = exchange.getContext().getTypeConverter().convertTo(String.class, exchange, value);
324        }
325
326        // flatten name
327        if (name != null && endpoint.isFlatten()) {
328            // check for both windows and unix separators
329            int pos = Math.max(name.lastIndexOf("/"), name.lastIndexOf("\\"));
330            if (pos != -1) {
331                name = name.substring(pos + 1);
332            }
333        }
334
335        // compute path by adding endpoint starting directory
336        String endpointPath = endpoint.getConfiguration().getDirectory();
337        String baseDir = "";
338        if (endpointPath.length() > 0) {
339            // Its a directory so we should use it as a base path for the filename
340            // If the path isn't empty, we need to add a trailing / if it isn't already there
341            baseDir = endpointPath;
342            boolean trailingSlash = endpointPath.endsWith("/") || endpointPath.endsWith("\\");
343            if (!trailingSlash) {
344                baseDir += getFileSeparator();
345            }
346        }
347        if (name != null) {
348            answer = baseDir + name;
349        } else {
350            // use a generated filename if no name provided
351            answer = baseDir + endpoint.getGeneratedFileName(exchange.getIn());
352        }
353
354        if (endpoint.getConfiguration().needToNormalize()) {
355            // must normalize path to cater for Windows and other OS
356            answer = normalizePath(answer);
357        }
358
359        return answer;
360    }
361
362    public String createTempFileName(Exchange exchange, String fileName) {
363        String answer = fileName;
364
365        String tempName;
366        if (exchange.getIn().getHeader(Exchange.FILE_NAME) == null) {
367            // its a generated filename then add it to header so we can evaluate the expression
368            exchange.getIn().setHeader(Exchange.FILE_NAME, FileUtil.stripPath(fileName));
369            tempName = endpoint.getTempFileName().evaluate(exchange, String.class);
370            // and remove it again after evaluation
371            exchange.getIn().removeHeader(Exchange.FILE_NAME);
372        } else {
373            tempName = endpoint.getTempFileName().evaluate(exchange, String.class);
374        }
375
376        // check for both windows and unix separators
377        int pos = Math.max(answer.lastIndexOf("/"), answer.lastIndexOf("\\"));
378        if (pos == -1) {
379            // no path so use temp name as calculated
380            answer = tempName;
381        } else {
382            // path should be prefixed before the temp name
383            StringBuilder sb = new StringBuilder(answer.substring(0, pos + 1));
384            sb.append(tempName);
385            answer = sb.toString();
386        }
387
388        if (endpoint.getConfiguration().needToNormalize()) {
389            // must normalize path to cater for Windows and other OS
390            answer = normalizePath(answer);
391        }
392
393        // stack path in case the temporary file uses .. paths
394        answer = FileUtil.compactPath(answer, getFileSeparator());
395
396        return answer;
397    }
398
399    @Override
400    @SuppressWarnings("unchecked")
401    protected void doStart() throws Exception {
402        ServiceHelper.startService(locks);
403        super.doStart();
404    }
405
406    @Override
407    protected void doStop() throws Exception {
408        super.doStop();
409        ServiceHelper.stopService(locks);
410    }
411}