|
| 1 | +package org.brapi.schematools.core.r.generator; |
| 2 | + |
| 3 | +import lombok.AllArgsConstructor; |
| 4 | +import lombok.extern.slf4j.Slf4j; |
| 5 | +import org.brapi.schematools.core.brapischema.BrAPISchemaReader; |
| 6 | +import org.brapi.schematools.core.model.BrAPIClass; |
| 7 | +import org.brapi.schematools.core.model.BrAPIObjectProperty; |
| 8 | +import org.brapi.schematools.core.model.BrAPIObjectType; |
| 9 | +import org.brapi.schematools.core.r.metadata.RGeneratorMetadata; |
| 10 | +import org.brapi.schematools.core.r.options.RGeneratorOptions; |
| 11 | +import org.brapi.schematools.core.response.Response; |
| 12 | +import org.brapi.schematools.core.utils.BrAPIClassCacheBuilder; |
| 13 | +import org.brapi.schematools.core.utils.StringUtils; |
| 14 | +import org.thymeleaf.TemplateEngine; |
| 15 | +import org.thymeleaf.context.Context; |
| 16 | +import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver; |
| 17 | + |
| 18 | +import java.io.IOException; |
| 19 | +import java.io.PrintWriter; |
| 20 | +import java.nio.charset.Charset; |
| 21 | +import java.nio.file.Files; |
| 22 | +import java.nio.file.Path; |
| 23 | +import java.util.ArrayList; |
| 24 | +import java.util.List; |
| 25 | + |
| 26 | +import static org.brapi.schematools.core.response.Response.fail; |
| 27 | +import static org.brapi.schematools.core.response.Response.success; |
| 28 | +/** |
| 29 | + * Generates R Client from a BrAPI JSON Schema. |
| 30 | + */ |
| 31 | +@Slf4j |
| 32 | +@AllArgsConstructor |
| 33 | +public class RGenerator { |
| 34 | + private final BrAPISchemaReader schemaReader ; |
| 35 | + private final RGeneratorOptions options ; |
| 36 | + private final Path outputPath ; |
| 37 | + private final String commentPrefix = "# " ; |
| 38 | + |
| 39 | + private final TemplateEngine templateEngine = createTemplateEngine(); |
| 40 | + |
| 41 | + /** |
| 42 | + * Creates a RGenerator using a default {@link BrAPISchemaReader} and |
| 43 | + * the default {@link RGeneratorOptions}. |
| 44 | + * @param outputPath the path of the output file or directory |
| 45 | + */ |
| 46 | + public RGenerator(Path outputPath) { |
| 47 | + this(new BrAPISchemaReader(), RGeneratorOptions.load(), outputPath) ; |
| 48 | + } |
| 49 | + |
| 50 | + /** |
| 51 | + * Creates a RGenerator using a default {@link BrAPISchemaReader} and |
| 52 | + * the provided {@link RGeneratorOptions}. |
| 53 | + * @param options The options to be used in the generation. |
| 54 | + * @param outputPath the path of the output file or directory |
| 55 | + */ |
| 56 | + public RGenerator(RGeneratorOptions options, Path outputPath) { |
| 57 | + this(new BrAPISchemaReader(), options, outputPath) ; |
| 58 | + } |
| 59 | + |
| 60 | + /** |
| 61 | + * Generates SQL files for type and their field descriptions |
| 62 | + * from the complete BrAPI Specification in |
| 63 | + * a directory contains a subdirectories for each module that contain |
| 64 | + * the BrAPI JSON schema and the additional subdirectories called 'Requests' |
| 65 | + * that contains the request schemas and BrAPI-Common that contains common schemas |
| 66 | + * for use across modules. |
| 67 | + * @param schemaDirectory the path to the complete BrAPI Specification |
| 68 | + * @return the paths of the Markdown files generated from the complete BrAPI Specification |
| 69 | + */ |
| 70 | + public Response<List<Path>> generate(Path schemaDirectory, RGeneratorMetadata metadata) { |
| 71 | + return schemaReader.readDirectories(schemaDirectory) |
| 72 | + .mapResultToResponse(brAPISchemas -> new Generator(brAPISchemas, metadata).generate()) ; |
| 73 | + } |
| 74 | + |
| 75 | + private class Generator { |
| 76 | + private final BrAPIClassCacheBuilder.BrAPIClassCache brAPIClassCache; |
| 77 | + private final RGeneratorMetadata metadata ; |
| 78 | + public Generator(List<BrAPIClass> brAPIClasses, RGeneratorMetadata metadata) { |
| 79 | + this.brAPIClassCache = BrAPIClassCacheBuilder.createCache(brAPIClasses) ; |
| 80 | + this.metadata = metadata ; |
| 81 | + } |
| 82 | + |
| 83 | + public Response<List<Path>> generate() { |
| 84 | + try { |
| 85 | + Files.createDirectories(outputPath) ; |
| 86 | + |
| 87 | + List<BrAPIClass> entityClasses = brAPIClassCache.getBrAPICClassesAsList() |
| 88 | + .stream() |
| 89 | + .filter(this::isGenerating).toList(); |
| 90 | + |
| 91 | + List<Path> paths = new ArrayList<>(); |
| 92 | + |
| 93 | + return createBrAPIClient(entityClasses) |
| 94 | + .onSuccessDoWithResult(paths::add) |
| 95 | + .map(() -> entityClasses |
| 96 | + .stream() |
| 97 | + .map(this::createR6ClassForModel) |
| 98 | + .collect(Response.mergeLists())) |
| 99 | + .onSuccessDoWithResult(paths::addAll) |
| 100 | + .map(() -> success(paths)); |
| 101 | + } catch (Exception e) { |
| 102 | + return fail(Response.ErrorType.VALIDATION, e.getMessage()) ; |
| 103 | + } |
| 104 | + } |
| 105 | + |
| 106 | + private boolean isGenerating(BrAPIClass brAPIClass) { |
| 107 | + return brAPIClass instanceof BrAPIObjectType && brAPIClass.getMetadata() != null && |
| 108 | + brAPIClass.getMetadata().isPrimaryModel() && options.isGeneratingFor(brAPIClass); |
| 109 | + } |
| 110 | + |
| 111 | + private Response<Path> createBrAPIClient(List<BrAPIClass> entityClasses) { |
| 112 | + Context context = new Context(); |
| 113 | + |
| 114 | + context.setVariable("classNames", entityClasses.stream().map(options::getPluralFor).toList()); |
| 115 | + context.setVariable("functionNames", entityClasses.stream().map(options::getPluralFor).map(StringUtils::toParameterCase).toList()); |
| 116 | + context.setVariable("entityNames", entityClasses.stream().map(BrAPIClass::getName).toList()); |
| 117 | + |
| 118 | + String text = templateEngine.process("BrAPIClient.txt", context) ; |
| 119 | + |
| 120 | + return writeToFile(outputPath.resolve(metadata.getFilePrefix() + "BrAPIClient.R"), "BrAPIClient", text) ; |
| 121 | + } |
| 122 | + |
| 123 | + private Response<List<Path>> createR6ClassForModel(BrAPIClass brAPIClass) { |
| 124 | + if (brAPIClass instanceof BrAPIObjectType brAPIObjectType) { |
| 125 | + Context context = new Context(); |
| 126 | + context.setVariable("className", options.getPluralFor(brAPIClass)); |
| 127 | + context.setVariable("entityPath", options.getPathItemNameFor(brAPIClass)); |
| 128 | + context.setVariable("searchPath", options.getSearchPathItemNameFor(brAPIClass)); |
| 129 | + context.setVariable("entityName", brAPIObjectType.getName()); |
| 130 | + context.setVariable("get-description", options.getSingleGet().getDescriptionFor(brAPIClass.getName())); |
| 131 | + context.setVariable("get", options.getSingleGet().isGeneratingFor(brAPIObjectType)); |
| 132 | + context.setVariable("getAll", options.getListGet().isGeneratingFor(brAPIObjectType)); |
| 133 | + context.setVariable("search", options.getSearch().isGeneratingFor(brAPIObjectType)); |
| 134 | + context.setVariable("create", options.getPost().isGeneratingFor(brAPIObjectType)); |
| 135 | + context.setVariable("update", options.getPut().isGeneratingFor(brAPIObjectType)); |
| 136 | + context.setVariable("delete", options.getDelete().isGeneratingFor(brAPIObjectType)); |
| 137 | + |
| 138 | + BrAPIClass requestSchema = brAPIClassCache.getBrAPIClass(String.format("%sRequest", brAPIObjectType.getName())); |
| 139 | + |
| 140 | + if (requestSchema instanceof BrAPIObjectType requestObjectType) { |
| 141 | + context.setVariable("requestArguments", requestObjectType.getProperties().stream().map(BrAPIObjectProperty::getName).toList()) ; |
| 142 | + context.setVariable("queryParameters", requestObjectType.getProperties().stream() |
| 143 | + .map(BrAPIObjectProperty::getName).map(options::getSingularForProperty).toList()) ; |
| 144 | + context.setVariable("argumentDescriptions", requestObjectType.getProperties().stream().map(this::getDescription).toList()) ; |
| 145 | + } |
| 146 | + |
| 147 | + String text = templateEngine.process("EntityClass.txt", context) ; |
| 148 | + |
| 149 | + return writeToFile(createPathForEntityClass(brAPIObjectType), brAPIObjectType.getName(), text) |
| 150 | + .mapResult(List::of) ; |
| 151 | + } else { |
| 152 | + return fail(Response.ErrorType.VALIDATION, brAPIClass.getName() + " is not a object class") ; |
| 153 | + } |
| 154 | + } |
| 155 | + |
| 156 | + private String getDescription(BrAPIObjectProperty brAPIObjectProperty) { |
| 157 | + return StringUtils.extractFirstLine(brAPIObjectProperty.getDescription()); |
| 158 | + } |
| 159 | + |
| 160 | + private Path createPathForEntityClass(BrAPIObjectType brAPIObjectType) { |
| 161 | + return outputPath.resolve(metadata.getFilePrefix() + brAPIObjectType.getName() + ".R"); |
| 162 | + } |
| 163 | + |
| 164 | + private Response<Path> writeToFile(Path path, String name, String text) { |
| 165 | + try { |
| 166 | + if (!options.isOverwritingExistingFiles() && Files.exists(path)) { |
| 167 | + log.warn("Output file '{}' already exists and was not overwritten", path); |
| 168 | + return Response.empty() ; |
| 169 | + } else { |
| 170 | + Files.createDirectories(path.getParent()) ; |
| 171 | + |
| 172 | + PrintWriter printWriter = new PrintWriter(Files.newBufferedWriter(path, Charset.defaultCharset())); |
| 173 | + |
| 174 | + printWriter.print(commentPrefix) ; |
| 175 | + printWriter.println(name); |
| 176 | + |
| 177 | + printWriter.println(text); |
| 178 | + |
| 179 | + if (options.isAddingGeneratorComments()) { |
| 180 | + printWriter.println(); |
| 181 | + printWriter.print(commentPrefix) ; |
| 182 | + printWriter.println("Generated by Schema Tools " + this.getClass().getSimpleName() + " Version: '" + options.getSchemaToolsVersion() +"'"); |
| 183 | + } |
| 184 | + |
| 185 | + printWriter.close(); |
| 186 | + return success(path) ; |
| 187 | + } |
| 188 | + } catch (IOException exception){ |
| 189 | + return fail(Response.ErrorType.VALIDATION, path, String.format("Can not write to file due to %s", exception.getMessage())) ; |
| 190 | + } |
| 191 | + } |
| 192 | + } |
| 193 | + |
| 194 | + private TemplateEngine createTemplateEngine() { |
| 195 | + ClassLoaderTemplateResolver resolver = new ClassLoaderTemplateResolver(); |
| 196 | + resolver.setPrefix("RTemplates/"); |
| 197 | + resolver.setSuffix(".txt"); |
| 198 | + resolver.setTemplateMode("TEXT"); |
| 199 | + resolver.setCharacterEncoding("UTF-8"); |
| 200 | + TemplateEngine engine = new TemplateEngine(); |
| 201 | + engine.setTemplateResolver(resolver); |
| 202 | + return engine; |
| 203 | + } |
| 204 | +} |
0 commit comments