1   /*
2    * SPDX-FileCopyrightText: none
3    * SPDX-License-Identifier: CC0-1.0
4    */
5   
6   package dev.metaschema.databind;
7   
8   import dev.metaschema.core.model.IModule;
9   import dev.metaschema.core.model.MetaschemaException;
10  import dev.metaschema.databind.codegen.IModuleBindingGenerator;
11  import dev.metaschema.databind.model.IBoundModule;
12  import edu.umd.cs.findbugs.annotations.NonNull;
13  
14  /**
15   * A simple module loader strategy that supports optional dynamic code
16   * generation.
17   * <p>
18   * By default, dynamic compilation is disabled. To enable dynamic compilation of
19   * Metaschema modules into bound Java classes, provide an
20   * {@link IModuleBindingGenerator} implementation to the constructor.
21   *
22   * @since 2.0.0
23   */
24  public class SimpleModuleLoaderStrategy
25      extends AbstractModuleLoaderStrategy {
26    @NonNull
27    private static final IModuleBindingGenerator COMPILATION_DISABLED_GENERATOR = module -> {
28      throw new UnsupportedOperationException(
29          "Dynamic compilation of Metaschema modules is not enabled by default." +
30              " Configure a different IModuleBindingGenerator with the IModuleLoaderStrategy" +
31              " used with the IBindignContext.");
32    };
33  
34    @NonNull
35    private final IModuleBindingGenerator generator;
36  
37    /**
38     * Construct a new simple module loader strategy with dynamic compilation
39     * disabled.
40     */
41    public SimpleModuleLoaderStrategy() {
42      this(COMPILATION_DISABLED_GENERATOR);
43    }
44  
45    /**
46     * Construct a new simple module loader strategy with the provided binding
47     * generator.
48     *
49     * @param generator
50     *          the generator to use for dynamic module compilation
51     */
52    public SimpleModuleLoaderStrategy(@NonNull IModuleBindingGenerator generator) {
53      this.generator = generator;
54    }
55  
56    @Override
57    protected Class<? extends IBoundModule> handleUnboundModule(IModule module) throws MetaschemaException {
58      return generator.generate(module);
59    }
60  }