• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

mybatis / freemarker-scripting / #281

pending completion
#281

Pull #150

github

web-flow
Merge 3411c6de0 into 9185d6a44
Pull Request #150: Update dependency org.mybatis:mybatis-parent to v38

243 of 260 relevant lines covered (93.46%)

0.93 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

97.47
/src/main/java/org/mybatis/scripting/freemarker/FreeMarkerLanguageDriverConfig.java
1
/*
2
 *    Copyright 2015-2022 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
 *       https://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.mybatis.scripting.freemarker;
17

18
import java.io.BufferedReader;
19
import java.io.IOException;
20
import java.io.InputStream;
21
import java.io.InputStreamReader;
22
import java.nio.charset.Charset;
23
import java.nio.charset.StandardCharsets;
24
import java.util.Collections;
25
import java.util.HashMap;
26
import java.util.Map;
27
import java.util.Objects;
28
import java.util.Optional;
29
import java.util.Properties;
30
import java.util.function.Consumer;
31
import java.util.function.Function;
32

33
import org.apache.commons.text.WordUtils;
34
import org.apache.ibatis.io.Resources;
35
import org.apache.ibatis.logging.Log;
36
import org.apache.ibatis.logging.LogFactory;
37
import org.apache.ibatis.reflection.DefaultReflectorFactory;
38
import org.apache.ibatis.reflection.MetaObject;
39
import org.apache.ibatis.reflection.factory.DefaultObjectFactory;
40
import org.apache.ibatis.reflection.wrapper.DefaultObjectWrapperFactory;
41

42
import freemarker.template.Configuration;
43

44
/**
45
 * Configuration class for {@link FreeMarkerLanguageDriver}.
46
 *
47
 * @author Kazuki Shimizu
48
 *
49
 * @since 1.2.0
1✔
50
 */
51
public class FreeMarkerLanguageDriverConfig {
52
  private static final String PROPERTY_KEY_CONFIG_FILE = "mybatis-freemarker.config.file";
53
  private static final String PROPERTY_KEY_CONFIG_ENCODING = "mybatis-freemarker.config.encoding";
54
  private static final String DEFAULT_PROPERTIES_FILE = "mybatis-freemarker.properties";
55
  private static final Map<Class<?>, Function<String, Object>> TYPE_CONVERTERS;
56

1✔
57
  static {
1✔
58
    Map<Class<?>, Function<String, Object>> converters = new HashMap<>();
1✔
59
    converters.put(String.class, String::trim);
1✔
60
    converters.put(boolean.class, v -> Boolean.valueOf(v.trim()));
1✔
61
    converters.put(Object.class, v -> v);
62
    TYPE_CONVERTERS = Collections.unmodifiableMap(converters);
63
  }
1✔
64

65
  private static final Log log = LogFactory.getLog(FreeMarkerLanguageDriverConfig.class);
66

67
  /**
68
   * The configuration properties.
1✔
69
   */
70
  private final Map<String, String> freemarkerSettings = new HashMap<>();
71

72
  /**
73
   * Template file configuration.
1✔
74
   */
75
  private final TemplateFileConfig templateFile = new TemplateFileConfig();
76

77
  /**
78
   * Get FreeMarker settings.
79
   *
80
   * @return FreeMarker settings
81
   */
1✔
82
  public Map<String, String> getFreemarkerSettings() {
83
    return freemarkerSettings;
84
  }
85

86
  /**
87
   * Get a base directory for reading template resources.
88
   * <p>
89
   * Default is none (just under classpath).
90
   * </p>
91
   *
92
   * @return a base directory for reading template resources
93
   *
94
   * @deprecated Recommend to use the {@link TemplateFileConfig#getBaseDir()}} because this method defined for keeping
95
   *             backward compatibility (There is possibility that this method removed at a future version)
96
   */
97
  @Deprecated
1✔
98
  public String getBasePackage() {
99
    return templateFile.getBaseDir();
100
  }
101

102
  /**
103
   * Set a base directory for reading template resources.
104
   *
105
   * @param basePackage
106
   *          a base directory for reading template resources
107
   *
108
   * @deprecated Recommend to use the {@link TemplateFileConfig#setBaseDir(String)} because this method defined for
109
   *             keeping backward compatibility (There is possibility that this method removed at a future version)
110
   */
111
  @Deprecated
1✔
112
  public void setBasePackage(String basePackage) {
1✔
113
    log.warn("The 'basePackage' has been deprecated since 1.2.0. Please use the 'templateFile.baseDir'.");
1✔
114
    templateFile.setBaseDir(basePackage);
115
  }
116

117
  /**
118
   * Get a template file configuration.
119
   *
120
   * @return a template file configuration
121
   */
1✔
122
  public TemplateFileConfig getTemplateFile() {
123
    return templateFile;
124
  }
125

126
  /**
127
   * Template file configuration.
1✔
128
   */
129
  public static class TemplateFileConfig {
130

131
    /**
132
     * The base directory for reading template resources.
1✔
133
     */
134
    private String baseDir = "";
135

136
    /**
137
     * The template file path provider configuration.
1✔
138
     */
139
    private final PathProviderConfig pathProvider = new PathProviderConfig();
140

141
    /**
142
     * Get the base directory for reading template resource file.
143
     * <p>
144
     * Default is {@code ""}(none).
145
     * </p>
146
     *
147
     * @return the base directory for reading template resource file
148
     */
1✔
149
    public String getBaseDir() {
150
      return baseDir;
151
    }
152

153
    /**
154
     * Set the base directory for reading template resource file.
155
     *
156
     * @param baseDir
157
     *          the base directory for reading template resource file
158
     */
1✔
159
    public void setBaseDir(String baseDir) {
1✔
160
      this.baseDir = baseDir;
161
    }
162

163
    /**
164
     * Get the template file path provider configuration.
165
     *
166
     * @return the template file path provider configuration
167
     */
1✔
168
    public PathProviderConfig getPathProvider() {
169
      return pathProvider;
170
    }
171

172
    /**
173
     * The template file path provider configuration.
1✔
174
     */
175
    public static class PathProviderConfig {
176

177
      /**
178
       * The prefix for adding to template file path.
1✔
179
       */
180
      private String prefix = "";
181

182
      /**
183
       * Whether includes package path part.
1✔
184
       */
185
      private boolean includesPackagePath = true;
186

187
      /**
188
       * Whether separate directory per mapper.
1✔
189
       */
190
      private boolean separateDirectoryPerMapper = true;
191

192
      /**
193
       * Whether includes mapper name into file name when separate directory per mapper.
1✔
194
       */
195
      private boolean includesMapperNameWhenSeparateDirectory = true;
196

197
      /**
198
       * Whether cache a resolved template file path.
1✔
199
       */
200
      private boolean cacheEnabled = true;
201

202
      /**
203
       * Get a prefix for adding to template file path.
204
       * <p>
205
       * Default is {@code ""}.
206
       * </p>
207
       *
208
       * @return a prefix for adding to template file path
209
       */
1✔
210
      public String getPrefix() {
211
        return prefix;
212
      }
213

214
      /**
215
       * Set the prefix for adding to template file path.
216
       *
217
       * @param prefix
218
       *          The prefix for adding to template file path
219
       */
1✔
220
      public void setPrefix(String prefix) {
1✔
221
        this.prefix = prefix;
222
      }
223

224
      /**
225
       * Get whether includes package path part.
226
       * <p>
227
       * Default is {@code true}.
228
       * </p>
229
       *
230
       * @return If includes package path, return {@code true}
231
       */
1✔
232
      public boolean isIncludesPackagePath() {
233
        return includesPackagePath;
234
      }
235

236
      /**
237
       * Set whether includes package path part.
238
       *
239
       * @param includesPackagePath
240
       *          If want to includes, set {@code true}
241
       */
1✔
242
      public void setIncludesPackagePath(boolean includesPackagePath) {
1✔
243
        this.includesPackagePath = includesPackagePath;
244
      }
245

246
      /**
247
       * Get whether separate directory per mapper.
248
       *
249
       * @return If separate directory per mapper, return {@code true}
250
       */
1✔
251
      public boolean isSeparateDirectoryPerMapper() {
252
        return separateDirectoryPerMapper;
253
      }
254

255
      /**
256
       * Set whether separate directory per mapper.
257
       * <p>
258
       * Default is {@code true}.
259
       * </p>
260
       *
261
       * @param separateDirectoryPerMapper
262
       *          If want to separate directory, set {@code true}
263
       */
1✔
264
      public void setSeparateDirectoryPerMapper(boolean separateDirectoryPerMapper) {
1✔
265
        this.separateDirectoryPerMapper = separateDirectoryPerMapper;
266
      }
267

268
      /**
269
       * Get whether includes mapper name into file name when separate directory per mapper.
270
       * <p>
271
       * Default is {@code true}.
272
       * </p>
273
       *
274
       * @return If includes mapper name, return {@code true}
275
       */
1✔
276
      public boolean isIncludesMapperNameWhenSeparateDirectory() {
277
        return includesMapperNameWhenSeparateDirectory;
278
      }
279

280
      /**
281
       * Set whether includes mapper name into file name when separate directory per mapper.
282
       * <p>
283
       * Default is {@code true}.
284
       * </p>
285
       *
286
       * @param includesMapperNameWhenSeparateDirectory
287
       *          If want to includes, set {@code true}
288
       */
1✔
289
      public void setIncludesMapperNameWhenSeparateDirectory(boolean includesMapperNameWhenSeparateDirectory) {
1✔
290
        this.includesMapperNameWhenSeparateDirectory = includesMapperNameWhenSeparateDirectory;
291
      }
292

293
      /**
294
       * Get whether cache a resolved template file path.
295
       * <p>
296
       * Default is {@code true}.
297
       * </p>
298
       *
299
       * @return If cache a resolved template file path, return {@code true}
300
       */
1✔
301
      public boolean isCacheEnabled() {
302
        return cacheEnabled;
303
      }
304

305
      /**
306
       * Set whether cache a resolved template file path.
307
       *
308
       * @param cacheEnabled
309
       *          If want to cache, set {@code true}
310
       */
1✔
311
      public void setCacheEnabled(boolean cacheEnabled) {
1✔
312
        this.cacheEnabled = cacheEnabled;
313
      }
314

315
    }
316

317
  }
318

319
  /**
320
   * Create an instance from default properties file. <br>
321
   * If you want to customize a default {@code TemplateEngine}, you can configure some property using
322
   * mybatis-freemarker.properties that encoded by UTF-8. Also, you can change the properties file that will read using
323
   * system property (-Dmybatis-freemarker.config.file=... -Dmybatis-freemarker.config.encoding=...). <br>
324
   * Supported properties are as follows:
325
   * <table border="1">
326
   * <caption>Supported properties</caption>
327
   * <tr>
328
   * <th>Property Key</th>
329
   * <th>Description</th>
330
   * <th>Default</th>
331
   * </tr>
332
   * <tr>
333
   * <th colspan="3">General configuration</th>
334
   * </tr>
335
   * <tr>
336
   * <td>base-package</td>
337
   * <td>The base directory for reading template resources</td>
338
   * <td>None(just under classpath)</td>
339
   * </tr>
340
   * <tr>
341
   * <td>freemarker-settings.*</td>
342
   * <td>The settings of freemarker {@link freemarker.core.Configurable#setSetting(String, String)}).</td>
343
   * <td>-</td>
344
   * </tr>
345
   * </table>
346
   *
347
   * @return a configuration instance
348
   */
1✔
349
  public static FreeMarkerLanguageDriverConfig newInstance() {
350
    return newInstance(loadDefaultProperties());
351
  }
352

353
  /**
354
   * Create an instance from specified properties.
355
   *
356
   * @param customProperties
357
   *          custom configuration properties
358
   *
359
   * @return a configuration instance
360
   *
361
   * @see #newInstance()
362
   */
1✔
363
  public static FreeMarkerLanguageDriverConfig newInstance(Properties customProperties) {
1✔
364
    FreeMarkerLanguageDriverConfig config = new FreeMarkerLanguageDriverConfig();
1✔
365
    Properties properties = loadDefaultProperties();
1✔
366
    Optional.ofNullable(customProperties).ifPresent(properties::putAll);
1✔
367
    override(config, properties);
368
    return config;
369
  }
370

371
  /**
372
   * Create an instance using specified customizer and override using a default properties file.
373
   *
374
   * @param customizer
375
   *          baseline customizer
376
   *
377
   * @return a configuration instance
378
   *
379
   * @see #newInstance()
380
   */
1✔
381
  public static FreeMarkerLanguageDriverConfig newInstance(Consumer<FreeMarkerLanguageDriverConfig> customizer) {
1✔
382
    FreeMarkerLanguageDriverConfig config = new FreeMarkerLanguageDriverConfig();
1✔
383
    customizer.accept(config);
1✔
384
    override(config, loadDefaultProperties());
385
    return config;
386
  }
387

1✔
388
  private static void override(FreeMarkerLanguageDriverConfig config, Properties properties) {
389
    MetaObject metaObject = MetaObject.forObject(config, new DefaultObjectFactory(), new DefaultObjectWrapperFactory(),
1✔
390
        new DefaultReflectorFactory());
1✔
391
    properties.forEach((key, value) -> {
1✔
392
      String propertyPath = WordUtils
1✔
393
          .uncapitalize(WordUtils.capitalize(Objects.toString(key), '-').replaceAll("-", ""));
1✔
394
      Optional.ofNullable(value).ifPresent(v -> {
1✔
395
        Object convertedValue = TYPE_CONVERTERS.get(metaObject.getSetterType(propertyPath)).apply(value.toString());
1✔
396
        metaObject.setValue(propertyPath, convertedValue);
1✔
397
      });
1✔
398
    });
399
  }
400

1✔
401
  private static Properties loadDefaultProperties() {
402
    return loadProperties(System.getProperty(PROPERTY_KEY_CONFIG_FILE, DEFAULT_PROPERTIES_FILE));
403
  }
404

1✔
405
  private static Properties loadProperties(String resourcePath) {
406
    Properties properties = new Properties();
407
    InputStream in;
1✔
408
    try {
1✔
409
      in = Resources.getResourceAsStream(resourcePath);
1✔
410
    } catch (IOException e) {
1✔
411
      in = null;
1✔
412
    }
1✔
413
    if (in != null) {
1✔
414
      Charset encoding = Optional.ofNullable(System.getProperty(PROPERTY_KEY_CONFIG_ENCODING)).map(Charset::forName)
1✔
415
          .orElse(StandardCharsets.UTF_8);
1✔
416
      try (InputStreamReader inReader = new InputStreamReader(in, encoding);
1✔
417
          BufferedReader bufReader = new BufferedReader(inReader)) {
×
418
        properties.load(bufReader);
×
419
      } catch (IOException e) {
1✔
420
        throw new IllegalStateException(e);
421
      }
1✔
422
    }
423
    return properties;
424
  }
425

426
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc