diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..d4cd657 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,11 @@ +# To get started with Dependabot version updates, you'll need to specify which +# package ecosystems to update and where the package manifests are located. +# Please see the documentation for all configuration options: +# https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates + +version: 2 +updates: + - package-ecosystem: "maven" # See documentation for possible values + directory: "/" # Location of package manifests + schedule: + interval: "weekly" diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..acf7261 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,23 @@ +name: CI + +on: + push: + branches: + - '**' + pull_request: + branches: + - '**' + +jobs: + build: + runs-on: ubuntu-latest + if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name != github.event.pull_request.base.repo.full_name + steps: + - uses: actions/checkout@v2 + - name: Set up JDK 17 + uses: actions/setup-java@v2 + with: + java-version: '17' + distribution: 'temurin' + - name: Build with Maven + run: ./mvnw --batch-mode clean verify diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..e7d1631 --- /dev/null +++ b/.gitignore @@ -0,0 +1,54 @@ +# Created by .ignore support plugin (hsz.mobi) +### JetBrains template +# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and Webstorm +# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 + +# User-specific stuff: +.idea + +# Sensitive or high-churn files: +.idea/dataSources.ids +.idea/dataSources.xml +.idea/dataSources.local.xml +.idea/sqlDataSources.xml +.idea/dynamic.xml +.idea/uiDesigner.xml + +# Gradle: +.idea/gradle.xml +.idea/libraries + +# Mongo Explorer plugin: +.idea/mongoSettings.xml + +## File-based project format: +*.iws +*.iml + +## Plugin-specific files: + +# IntelliJ +/out/ + +# mpeltonen/sbt-idea plugin +.idea_modules/ + +# JIRA plugin +atlassian-ide-plugin.xml + +# Crashlytics plugin (for Android Studio and IntelliJ) +com_crashlytics_export_strings.xml +crashlytics.properties +crashlytics-build.properties +fabric.properties +### Maven template +target/ +pom.xml.tag +pom.xml.releaseBackup +pom.xml.versionsBackup +pom.xml.next +release.properties +dependency-reduced-pom.xml +buildNumber.properties +.mvn/timing.properties + diff --git a/.mvn/jvm.config b/.mvn/jvm.config new file mode 100644 index 0000000..7cafa1e --- /dev/null +++ b/.mvn/jvm.config @@ -0,0 +1 @@ +--add-exports jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED --add-exports jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED --add-exports jdk.compiler/com.sun.tools.javac.parser=ALL-UNNAMED --add-exports jdk.compiler/com.sun.tools.javac.tree=ALL-UNNAMED --add-exports jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED --add-opens=java.base/java.util=ALL-UNNAMED --add-opens=java.base/java.lang.reflect=ALL-UNNAMED --add-opens=java.base/java.text=ALL-UNNAMED --add-opens=java.desktop/java.awt.font=ALL-UNNAMED diff --git a/.mvn/wrapper/.gitignore b/.mvn/wrapper/.gitignore new file mode 100644 index 0000000..e72f5e8 --- /dev/null +++ b/.mvn/wrapper/.gitignore @@ -0,0 +1 @@ +maven-wrapper.jar diff --git a/.mvn/wrapper/maven-wrapper.properties b/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000..70e554c --- /dev/null +++ b/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,18 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.8.1/apache-maven-3.8.1-bin.zip +wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.1/maven-wrapper-3.1.1.jar diff --git a/README.md b/README.md index 8ddd85e..1e37c23 100644 --- a/README.md +++ b/README.md @@ -1 +1,72 @@ -# json-schema-to-java-record \ No newline at end of file +[![Build Status](https://github.com/Cosium/json-schema-to-java-record/actions/workflows/ci.yml/badge.svg)](https://github.com/Cosium/json-schema-to-java-record/actions/workflows/ci.yml) +[![Maven Central Version](https://img.shields.io/maven-central/v/com.cosium.json_schema_to_java_record/json-schema-to-java-record)](https://central.sonatype.com/artifact/com.cosium.json_schema_to_java_record/json-schema-to-java-record) + +# JSON Schema To Java Record + +An annotation processor converting JSON schemas to java records. + +# Quick start + +1. Import the BOM: + ```xml + + + + + com.cosium.json_schema_to_java_record + json-schema-to-java-record-bom + ${json-schema-to-java-record.version} + import + pom + + + + + ``` +2. Import the API: + ```xml + + + + com.cosium.json_schema_to_java_record + json-schema-to-java-record-api + + + + ``` +3. Import the annotation processor: + ```xml + + org.apache.maven.plugins + maven-compiler-plugin + + + + com.cosium.json_schema_to_java_record + json-schema-to-java-record + + + + + ``` +4. Add your JSON schema files to the class path: + ``` + src/main/resources/com/aqme + └── foo.schema.json + ``` +5. Annotate a `package-info.java` file like this: + ```java + @GenerateRecordsFromJsonSchemas( + schemaRootFileLocations = + @JsonSchemaFileLocation( + moduleAndPackage = "com.aqme", + relativeName = "foo.schema.json" + ) + ) + package com.aqme; + + import com.cosium.json_schema_to_java_record_api.GenerateRecordsFromJsonSchemas; + import com.cosium.json_schema_to_java_record_api.JsonSchemaConfiguration; + import com.cosium.json_schema_to_java_record_api.JsonSchemaFileLocation; + ``` +6. Compile to generate the java files \ No newline at end of file diff --git a/api/pom.xml b/api/pom.xml new file mode 100644 index 0000000..cb4c579 --- /dev/null +++ b/api/pom.xml @@ -0,0 +1,14 @@ + + + 4.0.0 + + + com.cosium.json_schema_to_java_record + json-schema-to-java-record-parent + 1.0-SNAPSHOT + + + JSON schema to Java Record API + json-schema-to-java-record-api + + diff --git a/api/src/main/java/com/cosium/json_schema_to_java_record_api/GenerateRecordsFromJsonSchemas.java b/api/src/main/java/com/cosium/json_schema_to_java_record_api/GenerateRecordsFromJsonSchemas.java new file mode 100644 index 0000000..602fed8 --- /dev/null +++ b/api/src/main/java/com/cosium/json_schema_to_java_record_api/GenerateRecordsFromJsonSchemas.java @@ -0,0 +1,15 @@ +package com.cosium.json_schema_to_java_record_api; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Target; + +/** + * @author Réda Housni Alaoui + */ +@Target({ElementType.PACKAGE}) +public @interface GenerateRecordsFromJsonSchemas { + + JsonSchemaFileLocation[] schemaRootFileLocations(); + + JsonSchemaConfiguration[] schemaConfigurations() default {}; +} diff --git a/api/src/main/java/com/cosium/json_schema_to_java_record_api/JsonSchemaConfiguration.java b/api/src/main/java/com/cosium/json_schema_to_java_record_api/JsonSchemaConfiguration.java new file mode 100644 index 0000000..d827f67 --- /dev/null +++ b/api/src/main/java/com/cosium/json_schema_to_java_record_api/JsonSchemaConfiguration.java @@ -0,0 +1,25 @@ +package com.cosium.json_schema_to_java_record_api; + +/** + * @author Réda Housni Alaoui + */ +public @interface JsonSchemaConfiguration { + + /** + * @return A value that should match the JSON schema $id attribute. + */ + String schemaId(); + + /** + * Allows forcing the java type qualified name of the schema. If the type already exists, it will + * be used as is. + * + *

E.g. "com.aqme.Foo" + */ + String javaTypeQualifiedName() default ""; + + /** + * @return The interfaces that the generated record must implement. + */ + String[] javaInterfaceQualifiedNames() default {}; +} diff --git a/api/src/main/java/com/cosium/json_schema_to_java_record_api/JsonSchemaFileLocation.java b/api/src/main/java/com/cosium/json_schema_to_java_record_api/JsonSchemaFileLocation.java new file mode 100644 index 0000000..2dae4d9 --- /dev/null +++ b/api/src/main/java/com/cosium/json_schema_to_java_record_api/JsonSchemaFileLocation.java @@ -0,0 +1,16 @@ +package com.cosium.json_schema_to_java_record_api; + +/** + * @author Réda Housni Alaoui + */ +public @interface JsonSchemaFileLocation { + /** + * e.g. "com.aqme" + * + *

Use empty string "" for the root package + */ + String moduleAndPackage(); + + /** e.g. "foo.schema.json" */ + String relativeName(); +} diff --git a/bom/pom.xml b/bom/pom.xml new file mode 100644 index 0000000..d809d12 --- /dev/null +++ b/bom/pom.xml @@ -0,0 +1,31 @@ + + + 4.0.0 + + + com.cosium.json_schema_to_java_record + json-schema-to-java-record-parent + 1.0-SNAPSHOT + + + JSON schema to Java Record BOM + json-schema-to-java-record-bom + + pom + + + + + ${project.groupId} + json-schema-to-java-record-api + ${project.version} + + + ${project.groupId} + json-schema-to-java-record + ${project.version} + + + + + diff --git a/core/pom.xml b/core/pom.xml new file mode 100644 index 0000000..69c9804 --- /dev/null +++ b/core/pom.xml @@ -0,0 +1,48 @@ + + + 4.0.0 + + + com.cosium.json_schema_to_java_record + json-schema-to-java-record-parent + 1.0-SNAPSHOT + + + JSON schema to Java Record + json-schema-to-java-record + + + + ${project.groupId} + json-schema-to-java-record-api + ${project.version} + + + + com.fasterxml.jackson.core + jackson-databind + + + + com.google.auto.service + auto-service + true + + + + com.palantir.javapoet + javapoet + + + + io.github.zenwave360 + json-schema-ref-parser-jvm + + + + com.cosium.logging + annotation-processor-logger + + + + diff --git a/core/src/main/java/com/cosium/json_schema_to_java_record/$RefClasspathResolver.java b/core/src/main/java/com/cosium/json_schema_to_java_record/$RefClasspathResolver.java new file mode 100644 index 0000000..74a7db1 --- /dev/null +++ b/core/src/main/java/com/cosium/json_schema_to_java_record/$RefClasspathResolver.java @@ -0,0 +1,47 @@ +package com.cosium.json_schema_to_java_record; + +import static java.util.Objects.requireNonNull; + +import io.zenwave360.jsonrefparser.$Ref; +import io.zenwave360.jsonrefparser.resolver.Resolver; +import java.io.InputStream; +import java.net.URI; +import java.nio.charset.StandardCharsets; + +/** + * @author Réda Housni Alaoui + */ +class $RefClasspathResolver implements Resolver { + + private final ReadonlyClassPathResources classPathResources; + + $RefClasspathResolver(ReadonlyClassPathResources classPathResources) { + this.classPathResources = requireNonNull(classPathResources); + } + + @Override + public String resolve($Ref $ref) { + try { + URI uri = $ref.getURI(); + if (uri.toString().startsWith("classpath:") && !uri.toString().startsWith("classpath:/")) { + // gracefully handle classpath: without the slash + uri = URI.create(uri.toString().replace("classpath:", "classpath:/")); + } + + String uriPath = uri.getPath().replaceFirst("^/", ""); + int lastIndexOfSlash = uriPath.lastIndexOf("/"); + + String packageName = uriPath.substring(0, lastIndexOfSlash).replace("/", "."); + String relativeName = uriPath.substring(lastIndexOfSlash + 1); + try (InputStream inputStream = + classPathResources.openInputStream(packageName, relativeName)) { + return new String(inputStream.readAllBytes(), StandardCharsets.UTF_8); + } + + } catch (MissingResourceException missingResourceException) { + throw missingResourceException; + } catch (Exception e) { + throw new RuntimeException(e); + } + } +} diff --git a/core/src/main/java/com/cosium/json_schema_to_java_record/AnnotationProcessor.java b/core/src/main/java/com/cosium/json_schema_to_java_record/AnnotationProcessor.java new file mode 100644 index 0000000..6b6a003 --- /dev/null +++ b/core/src/main/java/com/cosium/json_schema_to_java_record/AnnotationProcessor.java @@ -0,0 +1,74 @@ +package com.cosium.json_schema_to_java_record; + +import com.cosium.json_schema_to_java_record_api.GenerateRecordsFromJsonSchemas; +import com.cosium.logging.annotation_processor.AbstractLoggingProcessor; +import com.google.auto.service.AutoService; +import java.util.Set; +import java.util.concurrent.CopyOnWriteArraySet; +import java.util.function.Predicate; +import java.util.stream.Collectors; +import javax.annotation.processing.ProcessingEnvironment; +import javax.annotation.processing.Processor; +import javax.annotation.processing.RoundEnvironment; +import javax.lang.model.SourceVersion; +import javax.lang.model.element.TypeElement; +import org.jspecify.annotations.Nullable; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * @author Réda Housni Alaoui + */ +@AutoService(Processor.class) +public class AnnotationProcessor extends AbstractLoggingProcessor { + + private static final Logger LOGGER = LoggerFactory.getLogger(AnnotationProcessor.class); + + private static final Boolean ALLOW_OTHER_PROCESSORS_TO_CLAIM_ANNOTATIONS = false; + + private final Set processedCommands = new CopyOnWriteArraySet<>(); + + @Nullable private JavaTypes javaTypes; + @Nullable private JsonSchemas jsonSchemas; + + @Override + public synchronized void init(ProcessingEnvironment processingEnv) { + super.init(processingEnv); + this.javaTypes = new JavaTypes(processingEnv.getFiler()); + jsonSchemas = new JsonSchemas(new ReadonlyClassPathResources(processingEnv.getFiler())); + } + + @Override + protected boolean doProcess(Set annotations, RoundEnvironment roundEnv) { + if (roundEnv.processingOver() || annotations.isEmpty()) { + return ALLOW_OTHER_PROCESSORS_TO_CLAIM_ANNOTATIONS; + } + + Set commands = + roundEnv.getElementsAnnotatedWith(GenerateRecordsFromJsonSchemas.class).stream() + .map( + element -> + new Command( + element, element.getAnnotation(GenerateRecordsFromJsonSchemas.class))) + .filter(Predicate.not(processedCommands::contains)) + .collect(Collectors.toUnmodifiableSet()); + + commands.stream() + .peek(command -> LOGGER.debug("Executing {}", command)) + .forEach(command -> command.execute(javaTypes, jsonSchemas)); + + processedCommands.addAll(commands); + + return ALLOW_OTHER_PROCESSORS_TO_CLAIM_ANNOTATIONS; + } + + @Override + public Set getSupportedAnnotationTypes() { + return Set.of(GenerateRecordsFromJsonSchemas.class.getCanonicalName()); + } + + @Override + public SourceVersion getSupportedSourceVersion() { + return SourceVersion.latestSupported(); + } +} diff --git a/core/src/main/java/com/cosium/json_schema_to_java_record/Command.java b/core/src/main/java/com/cosium/json_schema_to_java_record/Command.java new file mode 100644 index 0000000..2680d92 --- /dev/null +++ b/core/src/main/java/com/cosium/json_schema_to_java_record/Command.java @@ -0,0 +1,39 @@ +package com.cosium.json_schema_to_java_record; + +import static java.util.Objects.requireNonNull; + +import com.cosium.json_schema_to_java_record_api.GenerateRecordsFromJsonSchemas; +import java.util.Arrays; +import javax.lang.model.element.Element; +import javax.lang.model.element.PackageElement; + +/** + * @author Réda Housni Alaoui + */ +record Command(Element annotatedElement, GenerateRecordsFromJsonSchemas annotation) { + + public Command { + requireNonNull(annotatedElement); + requireNonNull(annotation); + } + + public void execute(JavaTypes javaTypes, JsonSchemas jsonSchemas) { + Configuration configuration = new Configuration(annotatedElementPackageName(), annotation); + + Arrays.stream(annotation.schemaRootFileLocations()) + .map(jsonSchemas::parse) + .forEach(jsonSchema -> jsonSchema.writeJavaType(javaTypes, configuration)); + } + + private String annotatedElementPackageName() { + + Element visitedElement = annotatedElement; + while (visitedElement != null) { + if (visitedElement instanceof PackageElement packageElement) { + return packageElement.getQualifiedName().toString(); + } + visitedElement = visitedElement.getEnclosingElement(); + } + return ""; + } +} diff --git a/core/src/main/java/com/cosium/json_schema_to_java_record/Configuration.java b/core/src/main/java/com/cosium/json_schema_to_java_record/Configuration.java new file mode 100644 index 0000000..1ef152e --- /dev/null +++ b/core/src/main/java/com/cosium/json_schema_to_java_record/Configuration.java @@ -0,0 +1,35 @@ +package com.cosium.json_schema_to_java_record; + +import static java.util.Objects.requireNonNull; + +import com.cosium.json_schema_to_java_record_api.GenerateRecordsFromJsonSchemas; +import com.cosium.json_schema_to_java_record_api.JsonSchemaConfiguration; +import java.util.Arrays; +import java.util.Map; +import java.util.Optional; +import java.util.function.Function; +import java.util.stream.Collectors; + +/** + * @author Réda Housni Alaoui + */ +class Configuration { + + private final String rootPackage; + private final Map map; + + public Configuration(String rootPackage, GenerateRecordsFromJsonSchemas annotation) { + this.rootPackage = requireNonNull(rootPackage); + map = + Arrays.stream(annotation.schemaConfigurations()) + .collect(Collectors.toMap(JsonSchemaConfiguration::schemaId, Function.identity())); + } + + public String rootPackage() { + return rootPackage; + } + + public Optional bySchemaId(String schemaId) { + return Optional.ofNullable(map.get(schemaId)); + } +} diff --git a/core/src/main/java/com/cosium/json_schema_to_java_record/JavaTypes.java b/core/src/main/java/com/cosium/json_schema_to_java_record/JavaTypes.java new file mode 100644 index 0000000..6055748 --- /dev/null +++ b/core/src/main/java/com/cosium/json_schema_to_java_record/JavaTypes.java @@ -0,0 +1,64 @@ +package com.cosium.json_schema_to_java_record; + +import static java.util.Objects.requireNonNull; + +import com.cosium.json_schema_to_java_record_api.GenerateRecordsFromJsonSchemas; +import com.palantir.javapoet.AnnotationSpec; +import com.palantir.javapoet.ClassName; +import com.palantir.javapoet.JavaFile; +import com.palantir.javapoet.TypeSpec; +import java.io.IOException; +import java.io.UncheckedIOException; +import javax.annotation.processing.Filer; +import javax.annotation.processing.FilerException; +import javax.annotation.processing.Generated; +import javax.tools.StandardLocation; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * @author Réda Housni Alaoui + */ +class JavaTypes { + + private static final Logger LOGGER = LoggerFactory.getLogger(JavaTypes.class); + + private final Filer filer; + + JavaTypes(Filer filer) { + this.filer = requireNonNull(filer); + } + + public boolean existsOnClassPath(ClassName className) { + try { + filer.getResource( + StandardLocation.CLASS_PATH, className.packageName(), className.simpleName() + ".class"); + return true; + } catch (IOException | IllegalArgumentException e) { + return false; + } + } + + public void write(String packageName, TypeSpec.Builder typeSpecBuilder) { + typeSpecBuilder.addAnnotation( + AnnotationSpec.builder(Generated.class) + .addMember("value", "$S", GenerateRecordsFromJsonSchemas.class.getName()) + .build()); + write(JavaFile.builder(packageName, typeSpecBuilder.build()).build()); + } + + private void write(JavaFile javaFile) { + LOGGER.debug("Writing {}", javaFile); + try { + javaFile.writeTo(filer); + } catch (FilerException e) { + if (e.getMessage().contains("Attempt to recreate a file")) { + LOGGER.debug("{} already exists. Skipping write.", javaFile); + return; + } + throw new UncheckedIOException(e); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } +} diff --git a/core/src/main/java/com/cosium/json_schema_to_java_record/JsonSchema.java b/core/src/main/java/com/cosium/json_schema_to_java_record/JsonSchema.java new file mode 100644 index 0000000..9523f71 --- /dev/null +++ b/core/src/main/java/com/cosium/json_schema_to_java_record/JsonSchema.java @@ -0,0 +1,41 @@ +package com.cosium.json_schema_to_java_record; + +import static java.util.Objects.requireNonNull; + +import com.palantir.javapoet.ClassName; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * @author Réda Housni Alaoui + */ +record JsonSchema(String fileRelativeName, JsonSchemaContent content) { + + private static final Logger LOGGER = LoggerFactory.getLogger(JsonSchema.class); + + JsonSchema { + requireNonNull(fileRelativeName); + requireNonNull(content); + } + + public void writeJavaType(JavaTypes javaTypes, Configuration configuration) { + LOGGER.debug("Writing java types of {}", this); + content.writeJavaType( + javaTypes, configuration, createDefaultJavaClassName(configuration), false); + } + + private ClassName createDefaultJavaClassName(Configuration configuration) { + + return ClassName.get( + configuration.rootPackage(), + Stream.of(fileRelativeName.split("\\.")[0].split("-")) + .map(this::capitalize) + .collect(Collectors.joining(""))); + } + + private String capitalize(String text) { + return text.substring(0, 1).toUpperCase() + text.substring(1).toLowerCase(); + } +} diff --git a/core/src/main/java/com/cosium/json_schema_to_java_record/JsonSchemaContent.java b/core/src/main/java/com/cosium/json_schema_to_java_record/JsonSchemaContent.java new file mode 100644 index 0000000..7704318 --- /dev/null +++ b/core/src/main/java/com/cosium/json_schema_to_java_record/JsonSchemaContent.java @@ -0,0 +1,238 @@ +package com.cosium.json_schema_to_java_record; + +import com.cosium.json_schema_to_java_record_api.JsonSchemaConfiguration; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.palantir.javapoet.AnnotationSpec; +import com.palantir.javapoet.ClassName; +import com.palantir.javapoet.MethodSpec; +import com.palantir.javapoet.ParameterSpec; +import com.palantir.javapoet.ParameterizedTypeName; +import com.palantir.javapoet.TypeName; +import com.palantir.javapoet.TypeSpec; +import java.net.URI; +import java.time.ZonedDateTime; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import javax.lang.model.element.Modifier; +import org.jspecify.annotations.NonNull; +import org.jspecify.annotations.Nullable; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * @author Réda Housni Alaoui + */ +record JsonSchemaContent( + @Nullable String $schema, + @Nullable String $id, + Type type, + @Nullable String format, + @Nullable JsonSchemaContent items, + @Nullable Set enumeration, + Map properties, + Set required) { + + private static final Logger LOGGER = LoggerFactory.getLogger(JsonSchemaContent.class); + + @JsonCreator + JsonSchemaContent( + @JsonProperty("$schema") @Nullable String $schema, + @JsonProperty("$id") @Nullable String $id, + @JsonProperty("type") @Nullable String type, + @JsonProperty("format") @Nullable String format, + @JsonProperty("items") @Nullable JsonSchemaContent items, + @JsonProperty("enum") @Nullable Set enumeration, + @JsonProperty("properties") @Nullable Map properties, + @JsonProperty("required") @Nullable Set required) { + this( + $schema, + $id, + Type.parseRawValue(type), + format, + items, + enumeration, + Optional.ofNullable(properties).orElseGet(Map::of), + Optional.ofNullable(required).orElseGet(Set::of)); + } + + public TypeName writeJavaType( + JavaTypes javaTypes, + Configuration configuration, + ClassName fallbackClassName, + boolean preferPrimitive) { + + final TypeName processedTypeName = + switch (type()) { + case STRING -> { + if ("date-time".equals(format)) { + yield ClassName.get(ZonedDateTime.class); + } + if ("uri".equals(format)) { + yield ClassName.get(URI.class); + } + yield ClassName.get(String.class); + } + case ARRAY -> + ParameterizedTypeName.get( + ClassName.get(List.class), + items.writeJavaType(javaTypes, configuration, fallbackClassName, false)); + case NUMBER -> { + if (preferPrimitive) { + yield TypeName.DOUBLE; + } + yield ClassName.get(Double.class); + } + case INTEGER -> { + if (preferPrimitive) { + yield TypeName.INT; + } + yield ClassName.get(Integer.class); + } + case BOOLEAN -> { + if (preferPrimitive) { + yield TypeName.BOOLEAN; + } + yield ClassName.get(Boolean.class); + } + case NULL -> ClassName.get(Void.class); + case OBJECT -> null; + }; + if (processedTypeName != null) { + LOGGER.debug("{} already processed. Skipping.", processedTypeName); + return processedTypeName; + } + + JsonSchemaConfiguration schemaConfiguration = + Optional.ofNullable($id()).flatMap(configuration::bySchemaId).orElse(null); + + ClassName className = + Optional.ofNullable(schemaConfiguration) + .map(JsonSchemaConfiguration::javaTypeQualifiedName) + .map(ClassName::bestGuess) + .orElse(fallbackClassName); + + if (javaTypes.existsOnClassPath(className)) { + LOGGER.info("{} already exists on the class path. Skipping.", className); + return className; + } + + TypeSpec.Builder typeBuilder; + if (enumeration() != null) { + typeBuilder = TypeSpec.enumBuilder(className).addModifiers(Modifier.PUBLIC); + enumeration().stream().map(String::valueOf).forEach(typeBuilder::addEnumConstant); + } else { + typeBuilder = TypeSpec.recordBuilder(className).addModifiers(Modifier.PUBLIC); + + MethodSpec.Builder recordConstructorBuilder = MethodSpec.constructorBuilder(); + + for (Map.Entry property : properties().entrySet()) { + + String propertyName = property.getKey(); + JsonSchemaContent propertySchema = property.getValue(); + + TypeName propertyType = + propertySchema.writeJavaType( + javaTypes, + configuration, + createClassNameFromPropertyName(configuration, propertyName), + required.contains(propertyName)); + + ParameterSpec.Builder parameterSpecBuilder = + ParameterSpec.builder(propertyType, propertyName); + + addJsonRelatedAnnotations(parameterSpecBuilder, propertyName); + + if (!propertyType.isPrimitive()) { + addNullRelatedAnnotations(javaTypes, parameterSpecBuilder, propertyName); + } + + ParameterSpec parameterSpec = parameterSpecBuilder.build(); + + recordConstructorBuilder.addParameter(parameterSpec); + typeBuilder.recordConstructor(recordConstructorBuilder.build()); + } + addRecordBuilderRelatedAnnotations(javaTypes, typeBuilder); + addJsonRelatedAnnotations(typeBuilder); + } + + Optional.ofNullable(schemaConfiguration) + .map(JsonSchemaConfiguration::javaInterfaceQualifiedNames) + .map(Set::of) + .orElseGet(Set::of) + .stream() + .map(ClassName::bestGuess) + .forEach(typeBuilder::addSuperinterface); + + javaTypes.write(className.packageName(), typeBuilder); + + return className; + } + + private void addJsonRelatedAnnotations( + ParameterSpec.Builder parameterBuilder, String propertyName) { + + parameterBuilder.addAnnotation( + AnnotationSpec.builder(JsonProperty.class).addMember("value", "$S", propertyName).build()); + } + + private void addJsonRelatedAnnotations(TypeSpec.Builder typeBuilder) { + + typeBuilder.addAnnotation( + AnnotationSpec.builder(JsonInclude.class) + .addMember( + "value", "$T.$L", JsonInclude.Include.class, JsonInclude.Include.NON_NULL.name()) + .build()); + } + + private void addNullRelatedAnnotations( + JavaTypes javaTypes, ParameterSpec.Builder parameterBuilder, String propertyName) { + + boolean notNull = required.contains(propertyName); + + if (notNull && javaTypes.existsOnClassPath(ClassName.get(NonNull.class))) { + parameterBuilder.addAnnotation(NonNull.class); + } else if (!notNull && javaTypes.existsOnClassPath(ClassName.get(Nullable.class))) { + parameterBuilder.addAnnotation(Nullable.class); + } + } + + private void addRecordBuilderRelatedAnnotations( + JavaTypes javaTypes, TypeSpec.Builder typeBuilder) { + + ClassName recordBuilderClassName = + ClassName.get("io.soabase.recordbuilder.core", "RecordBuilder"); + if (!javaTypes.existsOnClassPath(recordBuilderClassName)) { + return; + } + typeBuilder.addAnnotation(recordBuilderClassName); + } + + private ClassName createClassNameFromPropertyName( + Configuration configuration, String propertyName) { + + return ClassName.get( + configuration.rootPackage(), + propertyName.substring(0, 1).toUpperCase() + propertyName.substring(1)); + } + + public enum Type { + STRING, + NUMBER, + INTEGER, + OBJECT, + ARRAY, + BOOLEAN, + NULL; + + public static Type parseRawValue(@Nullable String type) { + if (type == null) { + return OBJECT; + } + return valueOf(type.toUpperCase()); + } + } +} diff --git a/core/src/main/java/com/cosium/json_schema_to_java_record/JsonSchemas.java b/core/src/main/java/com/cosium/json_schema_to_java_record/JsonSchemas.java new file mode 100644 index 0000000..3666fa4 --- /dev/null +++ b/core/src/main/java/com/cosium/json_schema_to_java_record/JsonSchemas.java @@ -0,0 +1,50 @@ +package com.cosium.json_schema_to_java_record; + +import static java.util.Objects.requireNonNull; + +import com.cosium.json_schema_to_java_record_api.JsonSchemaFileLocation; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.zenwave360.jsonrefparser.$RefParser; +import io.zenwave360.jsonrefparser.resolver.RefFormat; +import io.zenwave360.jsonrefparser.resolver.Resolver; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; + +/** + * @author Réda Housni Alaoui + */ +class JsonSchemas { + + private final ReadonlyClassPathResources classPathResources; + private final Resolver resolver; + private final ObjectMapper objectMapper = + new ObjectMapper().disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); + + public JsonSchemas(ReadonlyClassPathResources classPathResources) { + this.classPathResources = requireNonNull(classPathResources); + resolver = new $RefClasspathResolver(classPathResources); + } + + public JsonSchema parse(JsonSchemaFileLocation fileLocation) { + try (InputStream inputStream = + classPathResources.openInputStream( + fileLocation.moduleAndPackage(), fileLocation.relativeName())) { + + JsonSchemaContent jsonSchemaContent = + objectMapper.convertValue( + objectMapper.valueToTree( + new $RefParser(new String(inputStream.readAllBytes(), StandardCharsets.UTF_8)) + .withResolver(RefFormat.CLASSPATH, resolver) + .parse() + .dereference() + .getRefs() + .schema()), + JsonSchemaContent.class); + return new JsonSchema(fileLocation.relativeName(), jsonSchemaContent); + } catch (IOException e) { + throw new RuntimeException(e); + } + } +} diff --git a/core/src/main/java/com/cosium/json_schema_to_java_record/ReadonlyClassPathResources.java b/core/src/main/java/com/cosium/json_schema_to_java_record/ReadonlyClassPathResources.java new file mode 100644 index 0000000..0cce561 --- /dev/null +++ b/core/src/main/java/com/cosium/json_schema_to_java_record/ReadonlyClassPathResources.java @@ -0,0 +1,30 @@ +package com.cosium.json_schema_to_java_record; + +import static java.util.Objects.requireNonNull; + +import java.io.IOException; +import java.io.InputStream; +import javax.annotation.processing.Filer; +import javax.tools.StandardLocation; + +/** + * @author Réda Housni Alaoui + */ +class ReadonlyClassPathResources { + + private final Filer filer; + + ReadonlyClassPathResources(Filer filer) { + this.filer = requireNonNull(filer); + } + + public InputStream openInputStream(String moduleAndPackageLocation, String relativeNameLocation) { + try { + return filer + .getResource(StandardLocation.CLASS_PATH, moduleAndPackageLocation, relativeNameLocation) + .openInputStream(); + } catch (IOException e) { + throw new RuntimeException(e); + } + } +} diff --git a/core/src/main/java/com/cosium/json_schema_to_java_record/package-info.java b/core/src/main/java/com/cosium/json_schema_to_java_record/package-info.java new file mode 100644 index 0000000..31587f1 --- /dev/null +++ b/core/src/main/java/com/cosium/json_schema_to_java_record/package-info.java @@ -0,0 +1,7 @@ +/** + * @author Réda Housni Alaoui + */ +@NullMarked +package com.cosium.json_schema_to_java_record; + +import org.jspecify.annotations.NullMarked; diff --git a/mvnw b/mvnw new file mode 100755 index 0000000..b7f0646 --- /dev/null +++ b/mvnw @@ -0,0 +1,287 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Apache Maven Wrapper startup batch script, version 3.1.1 +# +# Required ENV vars: +# ------------------ +# JAVA_HOME - location of a JDK home dir +# +# Optional ENV vars +# ----------------- +# MAVEN_OPTS - parameters passed to the Java VM when running Maven +# e.g. to debug Maven itself, use +# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +# MAVEN_SKIP_RC - flag to disable loading of mavenrc files +# ---------------------------------------------------------------------------- + +if [ -z "$MAVEN_SKIP_RC" ] ; then + + if [ -f /usr/local/etc/mavenrc ] ; then + . /usr/local/etc/mavenrc + fi + + if [ -f /etc/mavenrc ] ; then + . /etc/mavenrc + fi + + if [ -f "$HOME/.mavenrc" ] ; then + . "$HOME/.mavenrc" + fi + +fi + +# OS specific support. $var _must_ be set to either true or false. +cygwin=false; +darwin=false; +mingw=false +case "`uname`" in + CYGWIN*) cygwin=true ;; + MINGW*) mingw=true;; + Darwin*) darwin=true + # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home + # See https://developer.apple.com/library/mac/qa/qa1170/_index.html + if [ -z "$JAVA_HOME" ]; then + if [ -x "/usr/libexec/java_home" ]; then + JAVA_HOME="`/usr/libexec/java_home`"; export JAVA_HOME + else + JAVA_HOME="/Library/Java/Home"; export JAVA_HOME + fi + fi + ;; +esac + +if [ -z "$JAVA_HOME" ] ; then + if [ -r /etc/gentoo-release ] ; then + JAVA_HOME=`java-config --jre-home` + fi +fi + +# For Cygwin, ensure paths are in UNIX format before anything is touched +if $cygwin ; then + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --unix "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --unix "$CLASSPATH"` +fi + +# For Mingw, ensure paths are in UNIX format before anything is touched +if $mingw ; then + [ -n "$JAVA_HOME" ] && + JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" +fi + +if [ -z "$JAVA_HOME" ]; then + javaExecutable="`which javac`" + if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then + # readlink(1) is not available as standard on Solaris 10. + readLink=`which readlink` + if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then + if $darwin ; then + javaHome="`dirname \"$javaExecutable\"`" + javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" + else + javaExecutable="`readlink -f \"$javaExecutable\"`" + fi + javaHome="`dirname \"$javaExecutable\"`" + javaHome=`expr "$javaHome" : '\(.*\)/bin'` + JAVA_HOME="$javaHome" + export JAVA_HOME + fi + fi +fi + +if [ -z "$JAVACMD" ] ; then + if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + else + JAVACMD="`\\unset -f command; \\command -v java`" + fi +fi + +if [ ! -x "$JAVACMD" ] ; then + echo "Error: JAVA_HOME is not defined correctly." >&2 + echo " We cannot execute $JAVACMD" >&2 + exit 1 +fi + +if [ -z "$JAVA_HOME" ] ; then + echo "Warning: JAVA_HOME environment variable is not set." +fi + +# traverses directory structure from process work directory to filesystem root +# first directory with .mvn subdirectory is considered project base directory +find_maven_basedir() { + if [ -z "$1" ] + then + echo "Path not specified to find_maven_basedir" + return 1 + fi + + basedir="$1" + wdir="$1" + while [ "$wdir" != '/' ] ; do + if [ -d "$wdir"/.mvn ] ; then + basedir=$wdir + break + fi + # workaround for JBEAP-8937 (on Solaris 10/Sparc) + if [ -d "${wdir}" ]; then + wdir=`cd "$wdir/.."; pwd` + fi + # end of workaround + done + printf '%s' "$(cd "$basedir"; pwd)" +} + +# concatenates all lines of a file +concat_lines() { + if [ -f "$1" ]; then + echo "$(tr -s '\n' ' ' < "$1")" + fi +} + +BASE_DIR=$(find_maven_basedir "$(dirname $0)") +if [ -z "$BASE_DIR" ]; then + exit 1; +fi + +MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}; export MAVEN_PROJECTBASEDIR +if [ "$MVNW_VERBOSE" = true ]; then + echo $MAVEN_PROJECTBASEDIR +fi + +########################################################################################## +# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +# This allows using the maven wrapper in projects that prohibit checking in binary data. +########################################################################################## +if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found .mvn/wrapper/maven-wrapper.jar" + fi +else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." + fi + if [ -n "$MVNW_REPOURL" ]; then + wrapperUrl="$MVNW_REPOURL/org/apache/maven/wrapper/maven-wrapper/3.1.1/maven-wrapper-3.1.1.jar" + else + wrapperUrl="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.1/maven-wrapper-3.1.1.jar" + fi + while IFS="=" read key value; do + case "$key" in (wrapperUrl) wrapperUrl="$value"; break ;; + esac + done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" + if [ "$MVNW_VERBOSE" = true ]; then + echo "Downloading from: $wrapperUrl" + fi + wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" + if $cygwin; then + wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"` + fi + + if command -v wget > /dev/null; then + QUIET="--quiet" + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found wget ... using wget" + QUIET="" + fi + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + wget $QUIET "$wrapperUrl" -O "$wrapperJarPath" + else + wget $QUIET --http-user="$MVNW_USERNAME" --http-password="$MVNW_PASSWORD" "$wrapperUrl" -O "$wrapperJarPath" + fi + [ $? -eq 0 ] || rm -f "$wrapperJarPath" + elif command -v curl > /dev/null; then + QUIET="--silent" + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found curl ... using curl" + QUIET="" + fi + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + curl $QUIET -o "$wrapperJarPath" "$wrapperUrl" -f -L + else + curl $QUIET --user "$MVNW_USERNAME:$MVNW_PASSWORD" -o "$wrapperJarPath" "$wrapperUrl" -f -L + fi + [ $? -eq 0 ] || rm -f "$wrapperJarPath" + else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Falling back to using Java to download" + fi + javaSource="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" + javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" + # For Cygwin, switch paths to Windows format before running javac + if $cygwin; then + javaSource=`cygpath --path --windows "$javaSource"` + javaClass=`cygpath --path --windows "$javaClass"` + fi + if [ -e "$javaSource" ]; then + if [ ! -e "$javaClass" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Compiling MavenWrapperDownloader.java ..." + fi + # Compiling the Java class + ("$JAVA_HOME/bin/javac" "$javaSource") + fi + if [ -e "$javaClass" ]; then + # Running the downloader + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Running MavenWrapperDownloader.java ..." + fi + ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") + fi + fi + fi +fi +########################################################################################## +# End of extension +########################################################################################## + +MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" + +# For Cygwin, switch paths to Windows format before running java +if $cygwin; then + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --windows "$CLASSPATH"` + [ -n "$MAVEN_PROJECTBASEDIR" ] && + MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` +fi + +# Provide a "standardized" way to retrieve the CLI args that will +# work with both Windows and non-Windows executions. +MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" +export MAVEN_CMD_LINE_ARGS + +WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +exec "$JAVACMD" \ + $MAVEN_OPTS \ + $MAVEN_DEBUG_OPTS \ + -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ + "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ + ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" diff --git a/mvnw.cmd b/mvnw.cmd new file mode 100644 index 0000000..474c9d6 --- /dev/null +++ b/mvnw.cmd @@ -0,0 +1,187 @@ +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM http://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Apache Maven Wrapper startup batch script, version 3.1.1 +@REM +@REM Required ENV vars: +@REM JAVA_HOME - location of a JDK home dir +@REM +@REM Optional ENV vars +@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands +@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending +@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven +@REM e.g. to debug Maven itself, use +@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files +@REM ---------------------------------------------------------------------------- + +@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' +@echo off +@REM set title of command window +title %0 +@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on' +@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% + +@REM set %HOME% to equivalent of $HOME +if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") + +@REM Execute a user defined script before this one +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre +@REM check for pre script, once with legacy .bat ending and once with .cmd ending +if exist "%USERPROFILE%\mavenrc_pre.bat" call "%USERPROFILE%\mavenrc_pre.bat" %* +if exist "%USERPROFILE%\mavenrc_pre.cmd" call "%USERPROFILE%\mavenrc_pre.cmd" %* +:skipRcPre + +@setlocal + +set ERROR_CODE=0 + +@REM To isolate internal variables from possible post scripts, we use another setlocal +@setlocal + +@REM ==== START VALIDATION ==== +if not "%JAVA_HOME%" == "" goto OkJHome + +echo. +echo Error: JAVA_HOME not found in your environment. >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +:OkJHome +if exist "%JAVA_HOME%\bin\java.exe" goto init + +echo. +echo Error: JAVA_HOME is set to an invalid directory. >&2 +echo JAVA_HOME = "%JAVA_HOME%" >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +@REM ==== END VALIDATION ==== + +:init + +@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". +@REM Fallback to current working directory if not found. + +set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% +IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir + +set EXEC_DIR=%CD% +set WDIR=%EXEC_DIR% +:findBaseDir +IF EXIST "%WDIR%"\.mvn goto baseDirFound +cd .. +IF "%WDIR%"=="%CD%" goto baseDirNotFound +set WDIR=%CD% +goto findBaseDir + +:baseDirFound +set MAVEN_PROJECTBASEDIR=%WDIR% +cd "%EXEC_DIR%" +goto endDetectBaseDir + +:baseDirNotFound +set MAVEN_PROJECTBASEDIR=%EXEC_DIR% +cd "%EXEC_DIR%" + +:endDetectBaseDir + +IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig + +@setlocal EnableExtensions EnableDelayedExpansion +for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a +@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% + +:endReadAdditionalConfig + +SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" +set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" +set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +set WRAPPER_URL="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.1/maven-wrapper-3.1.1.jar" + +FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( + IF "%%A"=="wrapperUrl" SET WRAPPER_URL=%%B +) + +@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +@REM This allows using the maven wrapper in projects that prohibit checking in binary data. +if exist %WRAPPER_JAR% ( + if "%MVNW_VERBOSE%" == "true" ( + echo Found %WRAPPER_JAR% + ) +) else ( + if not "%MVNW_REPOURL%" == "" ( + SET WRAPPER_URL="%MVNW_REPOURL%/org/apache/maven/wrapper/maven-wrapper/3.1.1/maven-wrapper-3.1.1.jar" + ) + if "%MVNW_VERBOSE%" == "true" ( + echo Couldn't find %WRAPPER_JAR%, downloading it ... + echo Downloading from: %WRAPPER_URL% + ) + + powershell -Command "&{"^ + "$webclient = new-object System.Net.WebClient;"^ + "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ + "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ + "}"^ + "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%WRAPPER_URL%', '%WRAPPER_JAR%')"^ + "}" + if "%MVNW_VERBOSE%" == "true" ( + echo Finished downloading %WRAPPER_JAR% + ) +) +@REM End of extension + +@REM Provide a "standardized" way to retrieve the CLI args that will +@REM work with both Windows and non-Windows executions. +set MAVEN_CMD_LINE_ARGS=%* + +%MAVEN_JAVA_EXE% ^ + %JVM_CONFIG_MAVEN_PROPS% ^ + %MAVEN_OPTS% ^ + %MAVEN_DEBUG_OPTS% ^ + -classpath %WRAPPER_JAR% ^ + "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" ^ + %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* +if ERRORLEVEL 1 goto error +goto end + +:error +set ERROR_CODE=1 + +:end +@endlocal & set ERROR_CODE=%ERROR_CODE% + +if not "%MAVEN_SKIP_RC%"=="" goto skipRcPost +@REM check for post script, once with legacy .bat ending and once with .cmd ending +if exist "%USERPROFILE%\mavenrc_post.bat" call "%USERPROFILE%\mavenrc_post.bat" +if exist "%USERPROFILE%\mavenrc_post.cmd" call "%USERPROFILE%\mavenrc_post.cmd" +:skipRcPost + +@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' +if "%MAVEN_BATCH_PAUSE%"=="on" pause + +if "%MAVEN_TERMINATE_CMD%"=="on" exit %ERROR_CODE% + +cmd /C exit /B %ERROR_CODE% diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..a8b89ca --- /dev/null +++ b/pom.xml @@ -0,0 +1,181 @@ + + + 4.0.0 + + + com.cosium.maven_oss + maven-oss + 1.5 + + + JSON schema to Java Record Parent + An annotation processor converting JSON schemas to java records + https://github.com/Cosium/json-schema-to-java-record + + com.cosium.json_schema_to_java_record + json-schema-to-java-record-parent + 1.0-SNAPSHOT + pom + + + api + core + tests + bom + + + + UTF-8 + + 2.16.1 + 44 + + 2.0.16 + 1.5.16 + 5.11.4 + 3.27.3 + 5.3 + + + + + + com.fasterxml.jackson + jackson-bom + ${jackson.version} + import + pom + + + + org.junit + junit-bom + ${junit.version} + pom + import + + + + com.google.auto.service + auto-service + 1.1.1 + + + + com.palantir.javapoet + javapoet + 0.6.0 + + + + io.github.zenwave360 + json-schema-ref-parser-jvm + 0.8.7 + + + + com.cosium.logging + annotation-processor-logger + 2.0 + + + + io.soabase.record-builder + record-builder-core + ${record-builder.version} + + + + + + + org.slf4j + slf4j-api + ${slf4j.version} + + + org.jspecify + jspecify + 1.0.0 + + + org.assertj + assertj-core + ${assertj.version} + test + + + + org.junit.jupiter + junit-jupiter + test + + + ch.qos.logback + logback-classic + ${logback-classic.version} + test + + + + + + + com.cosium.code + git-code-format-maven-plugin + ${git-code-format-maven-plugin.version} + + + + install-formatter-hook + + install-hooks + + + + + validate-code-format + + validate-code-format + + + + + + + com.cosium.code + google-java-format + ${git-code-format-maven-plugin.version} + + + + + + + + + scm:git:https://github.com/Cosium/json-schema-to-java-record + scm:git:https://github.com/Cosium/json-schema-to-java-record + https://github.com/Cosium/json-schema-to-java-record + HEAD + + + + + reda-alaoui + Réda Housni Alaoui + reda-alaoui@hey.com + https://github.com/reda-alaoui + + + + + + MIT License + https://www.opensource.org/licenses/mit-license.php + repo + + + + diff --git a/release.sh b/release.sh new file mode 100755 index 0000000..c19e275 --- /dev/null +++ b/release.sh @@ -0,0 +1,2 @@ +#!/usr/bin/env bash +./mvnw --batch-mode clean release:prepare release:perform && git push && git push --tags diff --git a/tests/pom.xml b/tests/pom.xml new file mode 100644 index 0000000..6e43cbd --- /dev/null +++ b/tests/pom.xml @@ -0,0 +1,63 @@ + + + 4.0.0 + + + com.cosium.json_schema_to_java_record + json-schema-to-java-record-parent + 1.0-SNAPSHOT + + + JSON schema to Java Record Tests + json-schema-to-java-record-tests + + + + ${project.groupId} + json-schema-to-java-record-api + ${project.version} + test + + + com.fasterxml.jackson.core + jackson-annotations + test + + + io.soabase.record-builder + record-builder-core + provided + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + + + ${project.groupId} + json-schema-to-java-record + ${project.version} + + + io.soabase.record-builder + record-builder-processor + ${record-builder.version} + + + true + + + + ${project.groupId} + json-schema-to-java-record + ${project.version} + + + + + + diff --git a/tests/src/test/java/com/cosium/json_schema_to_java_record_tests/case1/Location.java b/tests/src/test/java/com/cosium/json_schema_to_java_record_tests/case1/Location.java new file mode 100644 index 0000000..4bddcea --- /dev/null +++ b/tests/src/test/java/com/cosium/json_schema_to_java_record_tests/case1/Location.java @@ -0,0 +1,6 @@ +package com.cosium.json_schema_to_java_record_tests.case1; + +/** + * @author Réda Housni Alaoui + */ +public interface Location {} diff --git a/tests/src/test/java/com/cosium/json_schema_to_java_record_tests/case1/package-info.java b/tests/src/test/java/com/cosium/json_schema_to_java_record_tests/case1/package-info.java new file mode 100644 index 0000000..2a12f3f --- /dev/null +++ b/tests/src/test/java/com/cosium/json_schema_to_java_record_tests/case1/package-info.java @@ -0,0 +1,26 @@ +/** + * @author Réda Housni Alaoui + */ +@GenerateRecordsFromJsonSchemas( + schemaRootFileLocations = + @JsonSchemaFileLocation( + moduleAndPackage = "com.cosium.json_schema_to_java_record_tests.case1", + relativeName = "customer.json"), + schemaConfigurations = { + @JsonSchemaConfiguration( + schemaId = "customer", + javaTypeQualifiedName = "com.cosium.json_schema_to_java_record_tests.case1.Customer"), + @JsonSchemaConfiguration( + schemaId = "address", + javaTypeQualifiedName = "com.cosium.json_schema_to_java_record_tests.case1.Address"), + @JsonSchemaConfiguration( + schemaId = "country", + javaTypeQualifiedName = "com.cosium.json_schema_to_java_record_tests.case1.Country", + javaInterfaceQualifiedNames = + "com.cosium.json_schema_to_java_record_tests.case1.Location"), + }) +package com.cosium.json_schema_to_java_record_tests.case1; + +import com.cosium.json_schema_to_java_record_api.GenerateRecordsFromJsonSchemas; +import com.cosium.json_schema_to_java_record_api.JsonSchemaConfiguration; +import com.cosium.json_schema_to_java_record_api.JsonSchemaFileLocation; diff --git a/tests/src/test/resources/com/cosium/json_schema_to_java_record_tests/case1/address.json b/tests/src/test/resources/com/cosium/json_schema_to_java_record_tests/case1/address.json new file mode 100644 index 0000000..e67e1b3 --- /dev/null +++ b/tests/src/test/resources/com/cosium/json_schema_to_java_record_tests/case1/address.json @@ -0,0 +1,17 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "address", + "type": "object", + "properties": { + "streetNumber": { + "type": "integer" + }, + "streetName": { + "type": "string" + }, + "country": { + "$ref": "classpath:/com/cosium/json_schema_to_java_record_tests/case1/country.json" + } + }, + "required": [ "streetNumber", "streetName" ] +} \ No newline at end of file diff --git a/tests/src/test/resources/com/cosium/json_schema_to_java_record_tests/case1/country.json b/tests/src/test/resources/com/cosium/json_schema_to_java_record_tests/case1/country.json new file mode 100644 index 0000000..538df08 --- /dev/null +++ b/tests/src/test/resources/com/cosium/json_schema_to_java_record_tests/case1/country.json @@ -0,0 +1,5 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "country", + "enum": ["FRANCE", "MOROCCO"] +} \ No newline at end of file diff --git a/tests/src/test/resources/com/cosium/json_schema_to_java_record_tests/case1/customer.json b/tests/src/test/resources/com/cosium/json_schema_to_java_record_tests/case1/customer.json new file mode 100644 index 0000000..5d45363 --- /dev/null +++ b/tests/src/test/resources/com/cosium/json_schema_to_java_record_tests/case1/customer.json @@ -0,0 +1,17 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "customer", + "type": "object", + "properties": { + "firstName": { + "type": "string" + }, + "lastName": { + "type": "string" + }, + "address": { + "$ref": "classpath:/com/cosium/json_schema_to_java_record_tests/case1/address.json" + } + }, + "required": [ "firstName", "lastName" ] +} \ No newline at end of file