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     */
017    package org.apache.camel.component.file.strategy;
018    
019    import java.io.File;
020    
021    import org.apache.camel.Exchange;
022    import org.apache.camel.component.file.FileComponent;
023    import org.apache.camel.component.file.GenericFile;
024    import org.apache.camel.component.file.GenericFileEndpoint;
025    import org.apache.camel.component.file.GenericFileExclusiveReadLockStrategy;
026    import org.apache.camel.component.file.GenericFileOperations;
027    import org.apache.camel.util.FileUtil;
028    import org.slf4j.Logger;
029    import org.slf4j.LoggerFactory;
030    
031    /**
032     * Acquires read lock to the given file using a marker file so other Camel consumers wont acquire the same file.
033     * This is the default behavior in Camel 1.x.
034     */
035    public class MarkerFileExclusiveReadLockStrategy implements GenericFileExclusiveReadLockStrategy<File> {
036        private static final transient Logger LOG = LoggerFactory.getLogger(MarkerFileExclusiveReadLockStrategy.class);
037    
038        public void prepareOnStartup(GenericFileOperations<File> operations, GenericFileEndpoint<File> endpoint) {
039            String dir = endpoint.getConfiguration().getDirectory();
040            File file = new File(dir);
041    
042            LOG.debug("Prepare on startup by deleting orphaned lock files from: {}", dir);
043    
044            deleteLockFiles(file, endpoint.isRecursive());
045        }
046    
047        public boolean acquireExclusiveReadLock(GenericFileOperations<File> operations,
048                                                GenericFile<File> file, Exchange exchange) throws Exception {
049            String lockFileName = getLockFileName(file);
050            LOG.trace("Locking the file: {} using the lock file name: {}", file, lockFileName);
051    
052            // create a plain file as marker filer for locking (do not use FileLock)
053            boolean acquired = FileUtil.createNewFile(new File(lockFileName));
054            exchange.setProperty(Exchange.FILE_LOCK_FILE_ACQUIRED, acquired);
055    
056            return acquired;
057        }
058    
059        public void releaseExclusiveReadLock(GenericFileOperations<File> operations,
060                                             GenericFile<File> file, Exchange exchange) throws Exception {
061            String lockFileName = getLockFileName(file);
062            File lock = new File(lockFileName);
063            // only release the file if camel get the lock before
064            if (exchange.getProperty(Exchange.FILE_LOCK_FILE_ACQUIRED, false, Boolean.class)) {
065                LOG.trace("Unlocking file: {}", lockFileName);
066                boolean deleted = FileUtil.deleteFile(lock);
067                LOG.trace("Lock file: {} was deleted: {}", lockFileName, deleted);
068            } else {
069                LOG.trace("Don't try to delete the Lock file: {} as camel doesn't get to lock before.", lockFileName);
070            }
071        }
072    
073        public void setTimeout(long timeout) {
074            // noop
075        }
076    
077        public void setCheckInterval(long checkInterval) {
078            // noop
079        }
080    
081        private static void deleteLockFiles(File dir, boolean recursive) {
082            File[] files = dir.listFiles();
083            if (files == null || files.length == 0) {
084                return;
085            }
086    
087            for (File file : files) {
088                if (file.getName().startsWith(".")) {
089                    // files starting with dot should be skipped
090                    continue;
091                } else if (file.getName().endsWith(FileComponent.DEFAULT_LOCK_FILE_POSTFIX)) {
092                    LOG.warn("Deleting orphaned lock file: " + file);
093                    FileUtil.deleteFile(file);
094                } else if (recursive && file.isDirectory()) {
095                    deleteLockFiles(file, true);
096                }
097            }
098        }
099    
100        private static String getLockFileName(GenericFile<File> file) {
101            return file.getAbsoluteFilePath() + FileComponent.DEFAULT_LOCK_FILE_POSTFIX;
102        }
103    
104    }