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.wicket.request.resource.caching.version;
018
019import java.time.Instant;
020import java.util.regex.Pattern;
021import org.apache.wicket.request.resource.caching.IStaticCacheableResource;
022import org.apache.wicket.util.resource.IResourceStream;
023
024/**
025 * Uses the last modified timestamp of a {@link org.apache.wicket.request.resource.caching.IStaticCacheableResource} 
026 * converted to milliseconds as a version string.
027 *
028 * @author Peter Ertl
029 *
030 * @since 1.5
031 */
032public class LastModifiedResourceVersion implements IResourceVersion
033{
034        /**
035         * A valid pattern is a sequence of digits
036         */
037        private static final Pattern TIMESTAMP_PATTERN = Pattern.compile("[0-9]+");
038
039        @Override
040        public String getVersion(IStaticCacheableResource resource)
041        {
042                // get last modified timestamp of resource
043                IResourceStream stream = resource.getResourceStream();
044
045                // if resource stream can not be found do not cache
046                if (stream == null)
047                {
048                        return null;
049                }
050
051                final Instant lastModified = stream.lastModifiedTime();
052
053                // if no timestamp is available we can not provide a version
054                if (lastModified == null)
055                {
056                        return null;
057                }
058                // version string = last modified timestamp converted to milliseconds
059                return String.valueOf(lastModified.toEpochMilli()).intern();
060        }
061
062        @Override
063        public Pattern getVersionPattern()
064        {
065                return TIMESTAMP_PATTERN;
066        }
067}