001/*
002 * (C) Copyright 2013 Nuxeo SA (http://nuxeo.com/) and others.
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 *
016 * Contributors:
017 *     Arnaud Kervern
018 */
019
020package org.nuxeo.ecm.platform.web.common.requestcontroller.service;
021
022import java.util.HashMap;
023import java.util.Map;
024import java.util.regex.Pattern;
025
026import org.nuxeo.runtime.model.ContributionFragmentRegistry;
027
028/**
029 * Nuxeo Cors filter description registry model.
030 *
031 * @author <a href="mailto:ak@nuxeo.com">Arnaud Kervern</a>
032 * @since 5.7.2
033 */
034public class NuxeoCorsFilterDescriptorRegistry extends ContributionFragmentRegistry<NuxeoCorsFilterDescriptor> {
035
036    protected Map<String, NuxeoCorsFilterDescriptor> descs = new HashMap<>();
037
038    @Override
039    public String getContributionId(NuxeoCorsFilterDescriptor contrib) {
040        return contrib.name;
041    }
042
043    @Override
044    public void contributionUpdated(String id, NuxeoCorsFilterDescriptor contrib,
045            NuxeoCorsFilterDescriptor newOrigContrib) {
046        if (descs.containsKey(id)) {
047            descs.remove(id);
048        }
049
050        if (contrib.enabled) {
051            descs.put(id, contrib);
052        }
053    }
054
055    @Override
056    public void contributionRemoved(String id, NuxeoCorsFilterDescriptor origContrib) {
057        if (descs.containsKey(id)) {
058            descs.remove(id);
059        }
060    }
061
062    @Override
063    public NuxeoCorsFilterDescriptor clone(NuxeoCorsFilterDescriptor orig) {
064        try {
065            return orig.clone();
066        } catch (CloneNotSupportedException e) {
067            // Should never happens...
068            return null;
069        }
070    }
071
072    @Override
073    public void merge(NuxeoCorsFilterDescriptor src, NuxeoCorsFilterDescriptor dst) {
074        dst.merge(src);
075    }
076
077    public NuxeoCorsFilterDescriptor getFirstMatchingDescriptor(String uri) {
078        for (NuxeoCorsFilterDescriptor filterDesc : descs.values()) {
079            Pattern pattern = filterDesc.pattern;
080            if (pattern == null || pattern.matcher(uri).matches()) {
081                return filterDesc;
082            }
083        }
084        return null;
085    }
086}