001/* 002 * Copyright 2002-2020 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 * Assists with the registration of global, URL pattern based 028 * {@link CorsConfiguration} mappings. 029 * 030 * @author Sebastien Deleuze 031 * @author Rossen Stoyanchev 032 * @since 4.2 033 * @see CorsRegistration 034 */ 035public class CorsRegistry { 036 037 private final List<CorsRegistration> registrations = new ArrayList<>(); 038 039 040 /** 041 * Enable cross-origin request handling for the specified path pattern. 042 * <p>Exact path mapping URIs (such as {@code "/admin"}) are supported as 043 * well as Ant-style path patterns (such as {@code "/admin/**"}). 044 * <p>By default, the {@code CorsConfiguration} for this mapping is 045 * initialized with default values as described in 046 * {@link CorsConfiguration#applyPermitDefaultValues()}. 047 */ 048 public CorsRegistration addMapping(String pathPattern) { 049 CorsRegistration registration = new CorsRegistration(pathPattern); 050 this.registrations.add(registration); 051 return registration; 052 } 053 054 /** 055 * Return the registered {@link CorsConfiguration} objects, 056 * keyed by path pattern. 057 */ 058 protected Map<String, CorsConfiguration> getCorsConfigurations() { 059 Map<String, CorsConfiguration> configs = new LinkedHashMap<>(this.registrations.size()); 060 for (CorsRegistration registration : this.registrations) { 061 configs.put(registration.getPathPattern(), registration.getCorsConfiguration()); 062 } 063 return configs; 064 } 065 066}