001    /**
002     * Copyright (c) 2000-2013 Liferay, Inc. All rights reserved.
003     *
004     * This library is free software; you can redistribute it and/or modify it under
005     * the terms of the GNU Lesser General Public License as published by the Free
006     * Software Foundation; either version 2.1 of the License, or (at your option)
007     * any later version.
008     *
009     * This library is distributed in the hope that it will be useful, but WITHOUT
010     * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
011     * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
012     * details.
013     */
014    
015    package com.liferay.portal.kernel.servlet;
016    
017    import com.liferay.portal.kernel.util.CharPool;
018    import com.liferay.portal.kernel.util.Validator;
019    
020    import java.io.File;
021    
022    import java.util.Map;
023    import java.util.concurrent.ConcurrentHashMap;
024    
025    import javax.servlet.ServletContext;
026    
027    /**
028     * @author Shuyang Zhou
029     */
030    public class FileTimestampUtil {
031    
032            public static long getTimestamp(
033                    ServletContext servletContext, String path) {
034    
035                    return getTimestamp(servletContext, path, 0);
036            }
037    
038            public static long getTimestamp(
039                    ServletContext servletContext, String path, long defaultTimestamp) {
040    
041                    if (Validator.isNull(path)) {
042                            return defaultTimestamp;
043                    }
044    
045                    if (path.charAt(0) != CharPool.SLASH) {
046                            return defaultTimestamp;
047                    }
048    
049                    Long timestamp = _timestamps.get(path);
050    
051                    if (timestamp != null) {
052                            return timestamp;
053                    }
054    
055                    timestamp = defaultTimestamp;
056    
057                    String uriRealPath = ServletContextUtil.getRealPath(
058                            servletContext, path);
059    
060                    if (uriRealPath != null) {
061                            File uriFile = new File(uriRealPath);
062    
063                            if (uriFile.exists()) {
064                                    timestamp = uriFile.lastModified();
065                            }
066                    }
067    
068                    _timestamps.put(path, timestamp);
069    
070                    return timestamp;
071            }
072    
073            public static void reset() {
074                    _timestamps.clear();
075            }
076    
077            private static Map<String, Long> _timestamps =
078                    new ConcurrentHashMap<String, Long>();
079    
080    }