001/*
002 * Copyright 2002-2017 the original author or authors.
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 *      https://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
017package org.springframework.web.servlet.config.annotation;
018
019import java.util.ArrayList;
020import java.util.LinkedHashMap;
021import java.util.List;
022import java.util.Map;
023
024import org.springframework.web.cors.CorsConfiguration;
025
026/**
027 * {@code CorsRegistry} assists with the registration of {@link CorsConfiguration}
028 * mapped to a path pattern.
029 *
030 * @author Sebastien Deleuze
031 * @since 4.2
032 * @see CorsRegistration
033 */
034public class CorsRegistry {
035
036        private final List<CorsRegistration> registrations = new ArrayList<CorsRegistration>();
037
038
039        /**
040         * Enable cross-origin request handling for the specified path pattern.
041         * <p>Exact path mapping URIs (such as {@code "/admin"}) are supported as
042         * well as Ant-style path patterns (such as {@code "/admin/**"}).
043         * <p>By default, all origins, all headers, credentials and {@code GET},
044         * {@code HEAD}, and {@code POST} methods are allowed, and the max age
045         * is set to 30 minutes.
046         * @param pathPattern the path pattern to enable CORS handling for
047         * @return CorsRegistration the corresponding registration object,
048         * allowing for further fine-tuning
049         */
050        public CorsRegistration addMapping(String pathPattern) {
051                CorsRegistration registration = new CorsRegistration(pathPattern);
052                this.registrations.add(registration);
053                return registration;
054        }
055
056        /**
057         * Return the registered {@link CorsConfiguration} objects,
058         * keyed by path pattern.
059         */
060        protected Map<String, CorsConfiguration> getCorsConfigurations() {
061                Map<String, CorsConfiguration> configs = new LinkedHashMap<String, CorsConfiguration>(this.registrations.size());
062                for (CorsRegistration registration : this.registrations) {
063                        configs.put(registration.getPathPattern(), registration.getCorsConfiguration());
064                }
065                return configs;
066        }
067
068}