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