001/*
002 * SPDX-FileCopyrightText: none
003 * SPDX-License-Identifier: CC0-1.0
004 */
005
006package dev.metaschema.databind;
007
008import dev.metaschema.core.model.IModule;
009import dev.metaschema.core.model.MetaschemaException;
010import dev.metaschema.databind.codegen.IModuleBindingGenerator;
011import dev.metaschema.databind.model.IBoundModule;
012import edu.umd.cs.findbugs.annotations.NonNull;
013
014/**
015 * A simple module loader strategy that supports optional dynamic code
016 * generation.
017 * <p>
018 * By default, dynamic compilation is disabled. To enable dynamic compilation of
019 * Metaschema modules into bound Java classes, provide an
020 * {@link IModuleBindingGenerator} implementation to the constructor.
021 *
022 * @since 2.0.0
023 */
024public class SimpleModuleLoaderStrategy
025    extends AbstractModuleLoaderStrategy {
026  @NonNull
027  private static final IModuleBindingGenerator COMPILATION_DISABLED_GENERATOR = module -> {
028    throw new UnsupportedOperationException(
029        "Dynamic compilation of Metaschema modules is not enabled by default." +
030            " Configure a different IModuleBindingGenerator with the IModuleLoaderStrategy" +
031            " used with the IBindignContext.");
032  };
033
034  @NonNull
035  private final IModuleBindingGenerator generator;
036
037  /**
038   * Construct a new simple module loader strategy with dynamic compilation
039   * disabled.
040   */
041  public SimpleModuleLoaderStrategy() {
042    this(COMPILATION_DISABLED_GENERATOR);
043  }
044
045  /**
046   * Construct a new simple module loader strategy with the provided binding
047   * generator.
048   *
049   * @param generator
050   *          the generator to use for dynamic module compilation
051   */
052  public SimpleModuleLoaderStrategy(@NonNull IModuleBindingGenerator generator) {
053    this.generator = generator;
054  }
055
056  @Override
057  protected Class<? extends IBoundModule> handleUnboundModule(IModule module) throws MetaschemaException {
058    return generator.generate(module);
059  }
060}