001/*
002 * Copyright 2002-2016 the original author or authors.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *      https://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package org.springframework.web.reactive.resource;
018
019import java.util.regex.Matcher;
020import java.util.regex.Pattern;
021
022import org.apache.commons.logging.Log;
023import org.apache.commons.logging.LogFactory;
024
025import org.springframework.util.StringUtils;
026
027/**
028 * Abstract base class for filename suffix based {@link VersionStrategy}
029 * implementations, e.g. "static/myresource-version.js"
030 *
031 * @author Rossen Stoyanchev
032 * @author Brian Clozel
033 * @since 5.0
034 */
035public abstract class AbstractFileNameVersionStrategy implements VersionStrategy {
036
037        protected final Log logger = LogFactory.getLog(getClass());
038
039        private static final Pattern pattern = Pattern.compile("-(\\S*)\\.");
040
041
042        @Override
043        public String extractVersion(String requestPath) {
044                Matcher matcher = pattern.matcher(requestPath);
045                if (matcher.find()) {
046                        String match = matcher.group(1);
047                        return (match.contains("-") ? match.substring(match.lastIndexOf('-') + 1) : match);
048                }
049                else {
050                        return null;
051                }
052        }
053
054        @Override
055        public String removeVersion(String requestPath, String version) {
056                return StringUtils.delete(requestPath, "-" + version);
057        }
058
059        @Override
060        public String addVersion(String requestPath, String version) {
061                String baseFilename = StringUtils.stripFilenameExtension(requestPath);
062                String extension = StringUtils.getFilenameExtension(requestPath);
063                return (baseFilename + '-' + version + '.' + extension);
064        }
065
066}