/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

package org.apache.myfaces.orchestra.lib;

import javax.servlet.FilterConfig;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;

/**
 * Provides the ability to test the url of a servlet-request against a set of criteria to determine
 * whether to "accept" the url or not.
 * <p>
 * This can be used for a number of purposes. One example is that servlet filters can use this to
 * extend the very primitive "filter-mapping" facilities of the web.xml configuration file, giving
 * the ability for the filter to be matched more precisely to the incoming url.
 * <p>
 * Initially the matching facilities are fairly primitive; just a single "excludePrefix" and
 * "excludeSuffix" string can be defined. However this class can be extended later and classes which
 * use this to filter their urls will transparently get the new features.
 */
public class _UrlMatcher
{
    private final String excludePrefix;
    private final String excludeSuffix;

    public _UrlMatcher(FilterConfig config)
    {
        this.excludePrefix = config.getInitParameter("excludePrefix");
        this.excludeSuffix = config.getInitParameter("excludeSuffix");
    }

    public boolean accept(ServletRequest req)
    {
        if ((excludePrefix == null) && (excludeSuffix == null))
        {
            return true;
        }

        if (req instanceof HttpServletRequest == false)
        {
            return true;
        }

        HttpServletRequest hreq = (HttpServletRequest) req;
        String pathInfo = hreq.getPathInfo();
        String servletPath = hreq.getServletPath();

        if (excludePrefix != null)
        {
            if (servletPath.startsWith(excludePrefix))
            {
                return false;
            }
        }

        if (excludeSuffix != null)
        {
            if ((pathInfo == null) && servletPath.endsWith(excludeSuffix))
            {
                return false;
            }
    
            if ((pathInfo != null) && pathInfo.endsWith(excludeSuffix))
            {
                return false;
            }
        }

        return true;
    }
}
