View Javadoc
1   /*
2    * Copyright 2012-2025 CodeLibs Project and the Others.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *     http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
13   * either express or implied. See the License for the specific language
14   * governing permissions and limitations under the License.
15   */
16  package org.codelibs.fess.cors;
17  
18  import java.util.HashMap;
19  import java.util.Map;
20  
21  import org.apache.logging.log4j.LogManager;
22  import org.apache.logging.log4j.Logger;
23  
24  /**
25   * Factory for managing CORS handlers based on origin.
26   * Maintains a registry of CORS handlers for different origins and provides lookup functionality.
27   */
28  public class CorsHandlerFactory {
29  
30      /**
31       * Creates a new instance of CorsHandlerFactory.
32       */
33      public CorsHandlerFactory() {
34          // Default constructor
35      }
36  
37      private static final Logger logger = LogManager.getLogger(CorsHandlerFactory.class);
38  
39      /**
40       * Map of origin patterns to their corresponding CORS handlers.
41       */
42      protected Map<String, CorsHandler> handerMap = new HashMap<>();
43  
44      /**
45       * Adds a CORS handler for the specified origin.
46       *
47       * @param origin the origin pattern (can be "*" for wildcard)
48       * @param handler the CORS handler to associate with the origin
49       */
50      public void add(final String origin, final CorsHandler handler) {
51          if (logger.isDebugEnabled()) {
52              logger.debug("Loaded CorsHandler: origin={}", origin);
53          }
54          handerMap.put(origin, handler);
55      }
56  
57      /**
58       * Gets the CORS handler for the specified origin.
59       * If no specific handler is found, returns the wildcard handler.
60       *
61       * @param origin the origin to look up
62       * @return the CORS handler for the origin, or null if none found
63       */
64      public CorsHandler get(final String origin) {
65          final CorsHandler handler = handerMap.get(origin);
66          if (handler != null) {
67              return handler;
68          }
69          return handerMap.get("*");
70      }
71  }