Skip to content

Init #1

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Feb 18, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions .github/dependabot.yml
Original file line number Diff line number Diff line change
@@ -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"
23 changes: 23 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -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
54 changes: 54 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -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

1 change: 1 addition & 0 deletions .mvn/jvm.config
Original file line number Diff line number Diff line change
@@ -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
1 change: 1 addition & 0 deletions .mvn/wrapper/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
maven-wrapper.jar
18 changes: 18 additions & 0 deletions .mvn/wrapper/maven-wrapper.properties
Original file line number Diff line number Diff line change
@@ -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
73 changes: 72 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1 +1,72 @@
# json-schema-to-java-record
[![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
<dependencyManagement>
<dependencies>
<!-- ... -->
<dependency>
<groupId>com.cosium.json_schema_to_java_record</groupId>
<artifactId>json-schema-to-java-record-bom</artifactId>
<version>${json-schema-to-java-record.version}</version>
<scope>import</scope>
<type>pom</type>
</dependency>
<!-- ... -->
</dependencies>
</dependencyManagement>
```
2. Import the API:
```xml
<dependencies>
<!-- ... -->
<dependency>
<groupId>com.cosium.json_schema_to_java_record</groupId>
<artifactId>json-schema-to-java-record-api</artifactId>
</dependency>
<!-- ... -->
</dependencies>
```
3. Import the annotation processor:
```xml
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<annotationProcessorPaths>
<path>
<groupId>com.cosium.json_schema_to_java_record</groupId>
<artifactId>json-schema-to-java-record</artifactId>
</path>
</annotationProcessorPaths>
</configuration>
</plugin>
```
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
14 changes: 14 additions & 0 deletions api/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<parent>
<groupId>com.cosium.json_schema_to_java_record</groupId>
<artifactId>json-schema-to-java-record-parent</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>

<name>JSON schema to Java Record API</name>
<artifactId>json-schema-to-java-record-api</artifactId>

</project>
Original file line number Diff line number Diff line change
@@ -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 {};
}
Original file line number Diff line number Diff line change
@@ -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.
*
* <p>E.g. "com.aqme.Foo"
*/
String javaTypeQualifiedName() default "";

/**
* @return The interfaces that the generated record must implement.
*/
String[] javaInterfaceQualifiedNames() default {};
}
Original file line number Diff line number Diff line change
@@ -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"
*
* <p>Use empty string "" for the root package
*/
String moduleAndPackage();

/** e.g. "foo.schema.json" */
String relativeName();
}
31 changes: 31 additions & 0 deletions bom/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<parent>
<groupId>com.cosium.json_schema_to_java_record</groupId>
<artifactId>json-schema-to-java-record-parent</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>

<name>JSON schema to Java Record BOM</name>
<artifactId>json-schema-to-java-record-bom</artifactId>

<packaging>pom</packaging>

<dependencyManagement>
<dependencies>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>json-schema-to-java-record-api</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>json-schema-to-java-record</artifactId>
<version>${project.version}</version>
</dependency>
</dependencies>
</dependencyManagement>

</project>
48 changes: 48 additions & 0 deletions core/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<parent>
<groupId>com.cosium.json_schema_to_java_record</groupId>
<artifactId>json-schema-to-java-record-parent</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>

<name>JSON schema to Java Record</name>
<artifactId>json-schema-to-java-record</artifactId>

<dependencies>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>json-schema-to-java-record-api</artifactId>
<version>${project.version}</version>
</dependency>

<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>

<dependency>
<groupId>com.google.auto.service</groupId>
<artifactId>auto-service</artifactId>
<optional>true</optional>
</dependency>

<dependency>
<groupId>com.palantir.javapoet</groupId>
<artifactId>javapoet</artifactId>
</dependency>

<dependency>
<groupId>io.github.zenwave360</groupId>
<artifactId>json-schema-ref-parser-jvm</artifactId>
</dependency>

<dependency>
<groupId>com.cosium.logging</groupId>
<artifactId>annotation-processor-logger</artifactId>
</dependency>
</dependencies>

</project>
Original file line number Diff line number Diff line change
@@ -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);
}
}
}
Original file line number Diff line number Diff line change
@@ -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<Command> 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<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
if (roundEnv.processingOver() || annotations.isEmpty()) {
return ALLOW_OTHER_PROCESSORS_TO_CLAIM_ANNOTATIONS;
}

Set<Command> 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<String> getSupportedAnnotationTypes() {
return Set.of(GenerateRecordsFromJsonSchemas.class.getCanonicalName());
}

@Override
public SourceVersion getSupportedSourceVersion() {
return SourceVersion.latestSupported();
}
}
Original file line number Diff line number Diff line change
@@ -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 "";
}
}
Original file line number Diff line number Diff line change
@@ -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<String, JsonSchemaConfiguration> 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<JsonSchemaConfiguration> bySchemaId(String schemaId) {
return Optional.ofNullable(map.get(schemaId));
}
}
Original file line number Diff line number Diff line change
@@ -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);
}
}
}
Original file line number Diff line number Diff line change
@@ -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();
}
}
Original file line number Diff line number Diff line change
@@ -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<Object> enumeration,
Map<String, JsonSchemaContent> properties,
Set<String> 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<Object> enumeration,
@JsonProperty("properties") @Nullable Map<String, JsonSchemaContent> properties,
@JsonProperty("required") @Nullable Set<String> 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<String, JsonSchemaContent> 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());
}
}
}
Original file line number Diff line number Diff line change
@@ -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);
}
}
}
Original file line number Diff line number Diff line change
@@ -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);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
/**
* @author Réda Housni Alaoui
*/
@NullMarked
package com.cosium.json_schema_to_java_record;

import org.jspecify.annotations.NullMarked;
287 changes: 287 additions & 0 deletions mvnw
Original file line number Diff line number Diff line change
@@ -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 "$@"
187 changes: 187 additions & 0 deletions mvnw.cmd
Original file line number Diff line number Diff line change
@@ -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%
181 changes: 181 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,181 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<parent>
<groupId>com.cosium.maven_oss</groupId>
<artifactId>maven-oss</artifactId>
<version>1.5</version>
</parent>

<name>JSON schema to Java Record Parent</name>
<description>An annotation processor converting JSON schemas to java records</description>
<url>https://github.com/Cosium/json-schema-to-java-record</url>

<groupId>com.cosium.json_schema_to_java_record</groupId>
<artifactId>json-schema-to-java-record-parent</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>pom</packaging>

<modules>
<module>api</module>
<module>core</module>
<module>tests</module>
<module>bom</module>
</modules>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

<jackson.version>2.16.1</jackson.version>
<record-builder.version>44</record-builder.version>

<slf4j.version>2.0.16</slf4j.version>
<logback-classic.version>1.5.16</logback-classic.version>
<junit.version>5.11.4</junit.version>
<assertj.version>3.27.3</assertj.version>
<git-code-format-maven-plugin.version>5.3</git-code-format-maven-plugin.version>
</properties>

<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.fasterxml.jackson</groupId>
<artifactId>jackson-bom</artifactId>
<version>${jackson.version}</version>
<scope>import</scope>
<type>pom</type>
</dependency>

<dependency>
<groupId>org.junit</groupId>
<artifactId>junit-bom</artifactId>
<version>${junit.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>

<dependency>
<groupId>com.google.auto.service</groupId>
<artifactId>auto-service</artifactId>
<version>1.1.1</version>
</dependency>

<dependency>
<groupId>com.palantir.javapoet</groupId>
<artifactId>javapoet</artifactId>
<version>0.6.0</version>
</dependency>

<dependency>
<groupId>io.github.zenwave360</groupId>
<artifactId>json-schema-ref-parser-jvm</artifactId>
<version>0.8.7</version>
</dependency>

<dependency>
<groupId>com.cosium.logging</groupId>
<artifactId>annotation-processor-logger</artifactId>
<version>2.0</version>
</dependency>

<dependency>
<groupId>io.soabase.record-builder</groupId>
<artifactId>record-builder-core</artifactId>
<version>${record-builder.version}</version>
</dependency>
</dependencies>
</dependencyManagement>

<dependencies>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.jspecify</groupId>
<artifactId>jspecify</artifactId>
<version>1.0.0</version>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>

<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${logback-classic.version}</version>
<scope>test</scope>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>com.cosium.code</groupId>
<artifactId>git-code-format-maven-plugin</artifactId>
<version>${git-code-format-maven-plugin.version}</version>
<executions>
<!-- On commit, format the modified java files -->
<execution>
<id>install-formatter-hook</id>
<goals>
<goal>install-hooks</goal>
</goals>
</execution>
<!-- On Maven verify phase, fail if any file
(including unmodified) is badly formatted -->
<execution>
<id>validate-code-format</id>
<goals>
<goal>validate-code-format</goal>
</goals>
</execution>
</executions>
<dependencies>
<!-- Enable https://github.com/google/google-java-format -->
<dependency>
<groupId>com.cosium.code</groupId>
<artifactId>google-java-format</artifactId>
<version>${git-code-format-maven-plugin.version}</version>
</dependency>
</dependencies>
</plugin>

</plugins>
</build>

<scm>
<connection>scm:git:https://github.com/Cosium/json-schema-to-java-record</connection>
<developerConnection>scm:git:https://github.com/Cosium/json-schema-to-java-record</developerConnection>
<url>https://github.com/Cosium/json-schema-to-java-record</url>
<tag>HEAD</tag>
</scm>

<developers>
<developer>
<id>reda-alaoui</id>
<name>Réda Housni Alaoui</name>
<email>reda-alaoui@hey.com</email>
<url>https://github.com/reda-alaoui</url>
</developer>
</developers>

<licenses>
<license>
<name>MIT License</name>
<url>https://www.opensource.org/licenses/mit-license.php</url>
<distribution>repo</distribution>
</license>
</licenses>

</project>
2 changes: 2 additions & 0 deletions release.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
#!/usr/bin/env bash
./mvnw --batch-mode clean release:prepare release:perform && git push && git push --tags
63 changes: 63 additions & 0 deletions tests/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<parent>
<groupId>com.cosium.json_schema_to_java_record</groupId>
<artifactId>json-schema-to-java-record-parent</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>

<name>JSON schema to Java Record Tests</name>
<artifactId>json-schema-to-java-record-tests</artifactId>

<dependencies>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>json-schema-to-java-record-api</artifactId>
<version>${project.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.soabase.record-builder</groupId>
<artifactId>record-builder-core</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<annotationProcessorPaths>
<path>
<groupId>${project.groupId}</groupId>
<artifactId>json-schema-to-java-record</artifactId>
<version>${project.version}</version>
</path>
<path>
<groupId>io.soabase.record-builder</groupId>
<artifactId>record-builder-processor</artifactId>
<version>${record-builder.version}</version>
</path>
</annotationProcessorPaths>
<showWarnings>true</showWarnings>
</configuration>
<dependencies>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>json-schema-to-java-record</artifactId>
<version>${project.version}</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
</project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
package com.cosium.json_schema_to_java_record_tests.case1;

/**
* @author Réda Housni Alaoui
*/
public interface Location {}
Original file line number Diff line number Diff line change
@@ -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;
Original file line number Diff line number Diff line change
@@ -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" ]
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "country",
"enum": ["FRANCE", "MOROCCO"]
}
Original file line number Diff line number Diff line change
@@ -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" ]
}