001// Copyright 2008 The Apache Software Foundation
002//
003// Licensed under the Apache License, Version 2.0 (the "License");
004// you may not use this file except in compliance with the License.
005// You may obtain a copy of the License at
006//
007//     http://www.apache.org/licenses/LICENSE-2.0
008//
009// Unless required by applicable law or agreed to in writing, software
010// distributed under the License is distributed on an "AS IS" BASIS,
011// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
012// See the License for the specific language governing permissions and
013// limitations under the License.
014
015package org.apache.tapestry5.internal.services;
016
017import org.apache.tapestry5.http.services.HttpServletRequestFilter;
018import org.apache.tapestry5.http.services.HttpServletRequestHandler;
019
020import javax.servlet.http.HttpServletRequest;
021import javax.servlet.http.HttpServletResponse;
022import java.io.IOException;
023import java.util.Collection;
024import java.util.regex.Pattern;
025
026public class IgnoredPathsFilter implements HttpServletRequestFilter
027{
028    private final Pattern[] ignoredPatterns;
029
030    // if there are no ignore patterns, just pass every request to the next item in the pipeline
031    private final boolean passThrough;
032
033    public IgnoredPathsFilter(Collection<String> configuration)
034    {
035        ignoredPatterns = new Pattern[configuration.size()];
036
037        int i = 0;
038
039        for (String regexp : configuration)
040        {
041            Pattern p = Pattern.compile(regexp, Pattern.CASE_INSENSITIVE);
042
043            ignoredPatterns[i++] = p;
044        }
045        passThrough = ignoredPatterns.length == 0;
046    }
047
048    public boolean service(HttpServletRequest request, HttpServletResponse response, HttpServletRequestHandler handler)
049            throws IOException
050    {
051        // The servlet path should be "/", and path info is everything after that.
052
053        if (!passThrough)
054        {
055            String path = request.getServletPath();
056            String pathInfo = request.getPathInfo();
057
058            if (pathInfo != null) path += pathInfo;
059
060
061            for (Pattern p : ignoredPatterns)
062            {
063                if (p.matcher(path).matches()) return false;
064            }
065        }
066
067        // Not a match, so let it go.
068
069        return handler.service(request, response);
070    }
071}