View Javadoc
1   /*
2    *    Copyright 2009-2021 the original author or authors.
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, either express or implied.
13   *    See the License for the specific language governing permissions and
14   *    limitations under the License.
15   */
16  package org.apache.ibatis.scripting;
17  
18  import java.util.HashMap;
19  import java.util.Map;
20  
21  import org.apache.ibatis.util.MapUtil;
22  
23  /**
24   * @author Frank D. Martinez [mnesarco]
25   */
26  public class LanguageDriverRegistry {
27  
28    private final Map<Class<? extends LanguageDriver>, LanguageDriver> LANGUAGE_DRIVER_MAP = new HashMap<>();
29  
30    private Class<? extends LanguageDriver> defaultDriverClass;
31  
32    public void register(Class<? extends LanguageDriver> cls) {
33      if (cls == null) {
34        throw new IllegalArgumentException("null is not a valid Language Driver");
35      }
36      MapUtil.computeIfAbsent(LANGUAGE_DRIVER_MAP, cls, k -> {
37        try {
38          return k.getDeclaredConstructor().newInstance();
39        } catch (Exception ex) {
40          throw new ScriptingException("Failed to load language driver for " + cls.getName(), ex);
41        }
42      });
43    }
44  
45    public void register(LanguageDriver instance) {
46      if (instance == null) {
47        throw new IllegalArgumentException("null is not a valid Language Driver");
48      }
49      Class<? extends LanguageDriver> cls = instance.getClass();
50      if (!LANGUAGE_DRIVER_MAP.containsKey(cls)) {
51        LANGUAGE_DRIVER_MAP.put(cls, instance);
52      }
53    }
54  
55    public LanguageDriver getDriver(Class<? extends LanguageDriver> cls) {
56      return LANGUAGE_DRIVER_MAP.get(cls);
57    }
58  
59    public LanguageDriver getDefaultDriver() {
60      return getDriver(getDefaultDriverClass());
61    }
62  
63    public Class<? extends LanguageDriver> getDefaultDriverClass() {
64      return defaultDriverClass;
65    }
66  
67    public void setDefaultDriverClass(Class<? extends LanguageDriver> defaultDriverClass) {
68      register(defaultDriverClass);
69      this.defaultDriverClass = defaultDriverClass;
70    }
71  
72  }