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.script;
17  
18  import java.util.LinkedHashMap;
19  import java.util.Locale;
20  import java.util.Map;
21  
22  import org.apache.logging.log4j.LogManager;
23  import org.apache.logging.log4j.Logger;
24  import org.codelibs.fess.exception.ScriptEngineException;
25  
26  /**
27   * This class is a factory for script engines.
28   */
29  public class ScriptEngineFactory {
30      /**
31       * Constructor.
32       */
33      public ScriptEngineFactory() {
34          super();
35      }
36  
37      private static final Logger logger = LogManager.getLogger(ScriptEngineFactory.class);
38  
39      /**
40       * A map of script engines.
41       */
42      protected Map<String, ScriptEngine> scriptEngineMap = new LinkedHashMap<>();
43  
44      /**
45       * Adds a script engine.
46       * @param name The name of the script engine.
47       * @param scriptEngine The script engine.
48       */
49      public void add(final String name, final ScriptEngine scriptEngine) {
50          if (name == null || scriptEngine == null) {
51              throw new IllegalArgumentException(
52                      "Both name and scriptEngine parameters are required. name: " + name + ", scriptEngine: " + scriptEngine);
53          }
54          if (logger.isDebugEnabled()) {
55              logger.debug("Loaded ScriptEngine: {}", name);
56          }
57          scriptEngineMap.put(name.toLowerCase(Locale.ROOT), scriptEngine);
58          scriptEngineMap.put(scriptEngine.getClass().getSimpleName().toLowerCase(Locale.ROOT), scriptEngine);
59      }
60  
61      /**
62       * Gets a script engine.
63       * @param name The name of the script engine.
64       * @return The script engine.
65       */
66      public ScriptEngine getScriptEngine(final String name) {
67          if (name == null) {
68              throw new ScriptEngineException("Script engine name parameter is null. A valid script engine name must be provided.");
69          }
70          final ScriptEngine scriptEngine = scriptEngineMap.get(name.toLowerCase(Locale.ROOT));
71          if (scriptEngine != null) {
72              return scriptEngine;
73          }
74          throw new ScriptEngineException(name + " is not found.");
75      }
76  }