View Javadoc
1   /*
2    * Copyright 2012-2021 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  public class ScriptEngineFactory {
27      private static final Logger logger = LogManager.getLogger(ScriptEngineFactory.class);
28  
29      protected Map<String, ScriptEngine> scriptEngineMap = new LinkedHashMap<>();
30  
31      public void add(final String name, final ScriptEngine scriptEngine) {
32          if (name == null || scriptEngine == null) {
33              throw new IllegalArgumentException("name or scriptEngine is null.");
34          }
35          if (logger.isDebugEnabled()) {
36              logger.debug("Loaded {}", name);
37          }
38          scriptEngineMap.put(name.toLowerCase(Locale.ROOT), scriptEngine);
39          scriptEngineMap.put(scriptEngine.getClass().getSimpleName().toLowerCase(Locale.ROOT), scriptEngine);
40      }
41  
42      public ScriptEngine getScriptEngine(final String name) {
43          if (name == null) {
44              throw new ScriptEngineException("script name is null.");
45          }
46          final ScriptEngine scriptEngine = scriptEngineMap.get(name.toLowerCase(Locale.ROOT));
47          if (scriptEngine != null) {
48              return scriptEngine;
49          }
50          throw new ScriptEngineException(name + " is not found.");
51      }
52  }