001/*
002 * (C) Copyright 2006-2010 Nuxeo SAS (http://nuxeo.com/) and contributors.
003 *
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the GNU Lesser General Public License
006 * (LGPL) version 2.1 which accompanies this distribution, and is available at
007 * http://www.gnu.org/licenses/lgpl.html
008 *
009 * This library is distributed in the hope that it will be useful,
010 * but WITHOUT ANY WARRANTY; without even the implied warranty of
011 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
012 * Lesser General Public License for more details.
013 *
014 * Contributors:
015 *     bstefanescu
016 */
017package org.nuxeo.ecm.webengine;
018
019import java.util.Arrays;
020import java.util.Collections;
021import java.util.HashSet;
022import java.util.Set;
023
024import javax.servlet.http.HttpServletRequest;
025
026/**
027 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a>
028 */
029public class RequestConfiguration {
030
031    /**
032     * Synchronized list of configured paths
033     */
034    protected Set<PathDescriptor> paths;
035
036    /**
037     * Thread safe cache
038     */
039    protected volatile PathDescriptor[] cache;
040
041    public RequestConfiguration() {
042        paths = Collections.synchronizedSet(new HashSet<PathDescriptor>());
043    }
044
045    public void addPathDescriptor(PathDescriptor path) {
046        path.createMatcher();
047        paths.add(path);
048        cache = null;
049    }
050
051    public void removePathDescriptor(PathDescriptor path) {
052        paths.remove(path);
053        cache = null;
054    }
055
056    public PathDescriptor[] getPaths() {
057        PathDescriptor[] result = cache;
058        if (result == null) {
059            result = paths.toArray(new PathDescriptor[paths.size()]);
060            Arrays.sort(result);
061            cache = result;
062        }
063        return result;
064    }
065
066    public PathDescriptor getMatchingConfiguration(HttpServletRequest req) {
067        String pathInfo = req.getPathInfo();
068        if (pathInfo == null || pathInfo.length() == 0) {
069            pathInfo = "/";
070        }
071        for (PathDescriptor pd : getPaths()) {
072            if (pd.match(pathInfo)) {
073                return pd;
074            }
075        }
076        return null;
077    }
078
079}