001/*
002 *  Copyright 2020 Anyware Services
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 *      http://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 */
016package org.ametys.runtime.cocoon;
017
018import java.util.HashMap;
019import java.util.Map;
020import java.util.concurrent.ConcurrentHashMap;
021import java.util.regex.Pattern;
022
023import org.apache.avalon.framework.logger.AbstractLogEnabled;
024import org.apache.avalon.framework.parameters.Parameters;
025import org.apache.avalon.framework.thread.ThreadSafe;
026import org.apache.cocoon.environment.ObjectModelHelper;
027import org.apache.cocoon.matching.Matcher;
028import org.apache.cocoon.sitemap.PatternException;
029
030/**
031 * Regexp matcher for URI. Unlike Cocoon's native RegexpMatcher, it uses JDK's {@link Pattern}.
032 */
033public class RegexpURIMatcher extends AbstractLogEnabled implements Matcher, ThreadSafe
034{
035    private Map<String, Pattern> _patterns = new ConcurrentHashMap<>();
036    
037    public Map match(String pattern, Map objectModel, Parameters parameters) throws PatternException
038    {
039        Pattern p = _patterns.computeIfAbsent("^" + pattern + "$", Pattern::compile);
040
041        String uri = ObjectModelHelper.getRequest(objectModel).getSitemapURI();
042
043        if (uri.startsWith("/")) 
044        {
045            uri = uri.substring(1);
046        }
047        
048        java.util.regex.Matcher matcher = p.matcher(uri);
049        if (!matcher.matches())
050        {
051            return null;
052        }
053
054        Map<String, String> result = new HashMap<>();
055
056        for (int i = 0; i <= matcher.groupCount(); i++)
057        {
058            result.put(String.valueOf(i), matcher.group(i));
059        }
060        
061        return result;
062    }
063}