diff --git a/.gitignore b/.gitignore index 9a01d46..40a9601 100644 --- a/.gitignore +++ b/.gitignore @@ -17,3 +17,6 @@ buildNumber.properties .classpath node_modules +/java-to-zod-gradle-plugin/.gradle/ +/java-to-zod-gradle-plugin/build/ +/.idea/ diff --git a/java-to-zod-gradle-plugin/build.gradle.kts b/java-to-zod-gradle-plugin/build.gradle.kts new file mode 100644 index 0000000..6d40641 --- /dev/null +++ b/java-to-zod-gradle-plugin/build.gradle.kts @@ -0,0 +1,60 @@ +plugins { + id("java") + id("java-gradle-plugin") + id("maven-publish") +} + +group = "sh.ivan" +version = "0.7.0-SNAPSHOT" + +repositories { + mavenLocal() + mavenCentral() +} + +dependencies { + // https://mvnrepository.com/artifact/jakarta.validation/jakarta.validation-api + implementation("jakarta.validation:jakarta.validation-api:3.1.0") + implementation("sh.ivan:java-to-zod-core:0.7.0-SNAPSHOT") + // https://mvnrepository.com/artifact/org.apache.maven.plugin-tools/maven-plugin-annotations + compileOnly("org.apache.maven.plugin-tools:maven-plugin-annotations:3.15.0") + + + + // https://mvnrepository.com/artifact/org.projectlombok/lombok + implementation("org.projectlombok:lombok:1.18.34") + annotationProcessor("org.projectlombok:lombok:1.18.34") +// https://mvnrepository.com/artifact/com.google.guava/guava + implementation("com.google.guava:guava:33.3.1-jre") + + + implementation("cz.habarta.typescript-generator:typescript-generator-core:3.2.1263") + implementation(gradleApi()) + + testImplementation(platform("org.junit:junit-bom:5.10.2")) + testImplementation("org.junit.jupiter:junit-jupiter-api:5.10.3") + testImplementation("org.junit.jupiter:junit-jupiter-engine:5.8.1") + testImplementation("org.junit.jupiter:junit-jupiter") + testImplementation(gradleTestKit()) + +} + +tasks.test { + useJUnitPlatform() +} + +gradlePlugin { + plugins { + create("java-to-zod-gradle-plugin") { + id = "java-to-zod-gradle-plugin" + implementationClass = "sh.ivan.zod.JavaToZodPlugin" + } + } +} + +publishing { + + repositories { + mavenLocal() // Publish to the local Maven repository + } +} \ No newline at end of file diff --git a/java-to-zod-gradle-plugin/gradle/wrapper/gradle-wrapper.jar b/java-to-zod-gradle-plugin/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..249e583 Binary files /dev/null and b/java-to-zod-gradle-plugin/gradle/wrapper/gradle-wrapper.jar differ diff --git a/java-to-zod-gradle-plugin/gradle/wrapper/gradle-wrapper.properties b/java-to-zod-gradle-plugin/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..8cc0f79 --- /dev/null +++ b/java-to-zod-gradle-plugin/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Fri Sep 27 14:43:34 BST 2024 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.5-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/java-to-zod-gradle-plugin/gradlew b/java-to-zod-gradle-plugin/gradlew new file mode 100644 index 0000000..1b6c787 --- /dev/null +++ b/java-to-zod-gradle-plugin/gradlew @@ -0,0 +1,234 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed 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. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +APP_NAME="Gradle" +APP_BASE_NAME=${0##*/} + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +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 + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/java-to-zod-gradle-plugin/gradlew.bat b/java-to-zod-gradle-plugin/gradlew.bat new file mode 100644 index 0000000..107acd3 --- /dev/null +++ b/java-to-zod-gradle-plugin/gradlew.bat @@ -0,0 +1,89 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/java-to-zod-gradle-plugin/settings.gradle.kts b/java-to-zod-gradle-plugin/settings.gradle.kts new file mode 100644 index 0000000..c620ad8 --- /dev/null +++ b/java-to-zod-gradle-plugin/settings.gradle.kts @@ -0,0 +1,2 @@ +rootProject.name = "java-to-zod-gradle-plugin" + diff --git a/java-to-zod-gradle-plugin/src/main/java/sh/ivan/zod/GenerateZodSchemas.java b/java-to-zod-gradle-plugin/src/main/java/sh/ivan/zod/GenerateZodSchemas.java new file mode 100644 index 0000000..bccb12a --- /dev/null +++ b/java-to-zod-gradle-plugin/src/main/java/sh/ivan/zod/GenerateZodSchemas.java @@ -0,0 +1,97 @@ +package sh.ivan.zod; + +import cz.habarta.typescript.generator.Logger; +import cz.habarta.typescript.generator.TypeScriptGenerator; +import lombok.Setter; +import org.gradle.api.DefaultTask; +import org.gradle.api.tasks.Nested; +import org.gradle.api.tasks.OutputFile; +import org.gradle.api.tasks.TaskAction; +import org.jetbrains.annotations.NotNull; +import org.slf4j.LoggerFactory; + +import java.io.File; +import java.io.IOException; +import java.net.URL; +import java.net.URLClassLoader; +import java.util.ArrayList; +import java.util.List; + + +@Setter +public class GenerateZodSchemas extends DefaultTask { + + private static final org.slf4j.Logger log = LoggerFactory.getLogger(GenerateZodSchemas.class); + + // Path and name of generated file + private File outputFile = null; + + + @Nested + public PluginParameters getPluginParameters() { + return pluginParameters; + } + + private PluginParameters pluginParameters = new PluginParameters(); + + public GenerateZodSchemas() {} + + @TaskAction + public void runTask() { + try { + init(); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + public void init() throws IOException { + TypeScriptGenerator.setLogger(new Logger(pluginParameters.getLoggingLevel())); + TypeScriptGenerator.printVersion(); + if (pluginParameters.isSkip()) { + TypeScriptGenerator.getLogger().info("Skipping plugin execution"); + return; + } + + // class loader + List urls = new ArrayList<>(); + // Add the output directory for your compiled classes (this excludes dependencies) + File classesDir = new File(getBuildDirectoryAsFile(), "classes/java/main"); + + + // Check if the directory exists before adding it + if (classesDir.exists()) { + urls.add(classesDir.toURI().toURL()); + } + + // Create a class loader using URLs from the classpath + try (URLClassLoader classLoader = new URLClassLoader( + urls.toArray(new URL[0]), Thread.currentThread().getContextClassLoader())) { + + new JavaToZodConvertorWrapper(classLoader, pluginParameters, this::getOutputFile).run(); + + } catch (IOException e) { + log.error(e.getMessage()); + } + } + + @OutputFile + public File getOutputFile() { + + if (outputFile == null) { + // Set the default output file location based on the project directory + outputFile = + new File( + getBuildDirectoryAsFile(), "java-to-zod/" + getProject().getName() + "-schemas.js"); + + } + return outputFile; + } + + private @NotNull File getBuildDirectoryAsFile() { + return getProject().getLayout().getBuildDirectory().get().getAsFile(); + } + + + +} diff --git a/java-to-zod-gradle-plugin/src/main/java/sh/ivan/zod/JavaToZodConvertorWrapper.java b/java-to-zod-gradle-plugin/src/main/java/sh/ivan/zod/JavaToZodConvertorWrapper.java new file mode 100644 index 0000000..434de87 --- /dev/null +++ b/java-to-zod-gradle-plugin/src/main/java/sh/ivan/zod/JavaToZodConvertorWrapper.java @@ -0,0 +1,72 @@ +package sh.ivan.zod; + +import cz.habarta.typescript.generator.*; +import cz.habarta.typescript.generator.parser.Model; +import sh.ivan.zod.schema.ObjectSchema; + +import java.io.File; +import java.io.IOException; +import java.net.URLClassLoader; +import java.util.Map; +import java.util.function.Supplier; + +public class JavaToZodConvertorWrapper { + private final URLClassLoader classLoader; + private final PluginParameters pluginParameters; + private final Supplier getOutputFile; + + public JavaToZodConvertorWrapper(URLClassLoader classLoader, PluginParameters pluginParameters, Supplier getOutputFile) { + this.classLoader = classLoader; + this.pluginParameters = pluginParameters; + this.getOutputFile = getOutputFile; + } + + public void run() throws IOException { + Settings settings = from(classLoader, pluginParameters); + + cz.habarta.typescript.generator.Input.Parameters parameters = + new cz.habarta.typescript.generator.Input.Parameters(); + parameters.classNames = pluginParameters.getClasses(); + parameters.classNamePatterns = pluginParameters.getClassPatterns(); + parameters.classesWithAnnotations = pluginParameters.getClassesWithAnnotations(); + parameters.classesImplementingInterfaces = pluginParameters.getClassesImplementingInterfaces(); + parameters.classesExtendingClasses = pluginParameters.getClassesExtendingClasses(); + parameters.jaxrsApplicationClassName = pluginParameters.getClassesFromJaxrsApplication(); + parameters.automaticJaxrsApplication = pluginParameters.isClassesFromAutomaticJaxrsApplication(); + parameters.isClassNameExcluded = settings.getExcludeFilter(); + parameters.classLoader = classLoader; + parameters.scanningAcceptedPackages = pluginParameters.getScanningAcceptedPackages(); + parameters.debug = pluginParameters.getLoggingLevel() == Logger.Level.Debug; + + cz.habarta.typescript.generator.Input input = cz.habarta.typescript.generator.Input.from(parameters); + TypeScriptGenerator typeScriptGenerator = new TypeScriptGenerator(settings); + Model model = typeScriptGenerator.getModelParser().parseModel(input.getSourceTypes()); + Configuration configuration = Configuration.builder() + .schemaNamePrefix(pluginParameters.getSchemaNamePrefix()) + .schemaNameSuffix(pluginParameters.getSchemaNameSuffix()) + .build(); + JavaToZodConverter javaToZodConverter = + new JavaToZodConverter(typeScriptGenerator.getModelParser(), configuration); + Map beanSchemas = javaToZodConverter.getBeanSchemas(model); + SchemaFileWriter schemaFileWriter = new SchemaFileWriter(beanSchemas, getOutputFile.get()); + schemaFileWriter.write(); + } + + public Settings from(URLClassLoader classLoader, PluginParameters pluginParameters) { + Settings settings = new Settings(); + settings.setExcludeFilter(pluginParameters.getExcludeClasses(), pluginParameters.getExcludeClassPatterns()); + settings.jsonLibrary = pluginParameters.getJsonLibrary(); + settings.setJackson2Configuration(classLoader, pluginParameters.getJackson2Configuration()); + settings.gsonConfiguration = pluginParameters.getGsonConfiguration(); + settings.jsonbConfiguration = pluginParameters.getJsonbConfiguration(); + settings.scanSpringApplication = pluginParameters.isScanSpringApplication(); + settings.loadIncludePropertyAnnotations(classLoader, pluginParameters.getIncludePropertyAnnotations()); + settings.loadExcludePropertyAnnotations(classLoader, pluginParameters.getIncludePropertyAnnotations()); + settings.classLoader = classLoader; + settings.outputKind = TypeScriptOutputKind.global; // Unused, but required by settings validation + settings.outputFileType = TypeScriptFileType.implementationFile; + settings.loadOptionalAnnotations(classLoader, pluginParameters.getOptionalAnnotations()); + return settings; + } + +} diff --git a/java-to-zod-gradle-plugin/src/main/java/sh/ivan/zod/JavaToZodPlugin.java b/java-to-zod-gradle-plugin/src/main/java/sh/ivan/zod/JavaToZodPlugin.java new file mode 100644 index 0000000..4c65382 --- /dev/null +++ b/java-to-zod-gradle-plugin/src/main/java/sh/ivan/zod/JavaToZodPlugin.java @@ -0,0 +1,12 @@ +package sh.ivan.zod; + +import org.gradle.api.Plugin; +import org.gradle.api.Project; + +public class JavaToZodPlugin implements Plugin { + @Override + public void apply(Project project) { + // Register the custom task (PojoParser) + project.getTasks().create("generateZodSchemas", GenerateZodSchemas.class); + } +} \ No newline at end of file diff --git a/java-to-zod-gradle-plugin/src/main/java/sh/ivan/zod/PluginParameters.java b/java-to-zod-gradle-plugin/src/main/java/sh/ivan/zod/PluginParameters.java new file mode 100644 index 0000000..5ffd70d --- /dev/null +++ b/java-to-zod-gradle-plugin/src/main/java/sh/ivan/zod/PluginParameters.java @@ -0,0 +1,329 @@ +package sh.ivan.zod; + + +import cz.habarta.typescript.generator.*; +import lombok.Setter; +import org.apache.maven.plugins.annotations.Parameter; +import org.gradle.api.tasks.Input; +import org.gradle.api.tasks.Optional; + +import java.io.Serializable; +import java.util.Collections; +import java.util.List; + +@Setter +public class PluginParameters implements Serializable { + private static final long serialVersionUID = 1L; + + + /** + * Prefix added to generated schema names. + */ + @Parameter + private String schemaNamePrefix = ""; + + /** + * Suffix added to generated schema names. + */ + @Parameter(defaultValue = "Schema") + private String schemaNameSuffix = "Schema"; + + /** + * Classes to process. + */ + @Parameter + private List classes = Collections.emptyList(); + + /** + * Classes to process specified using glob patterns + * so it is possible to specify package or class name suffix. + * Glob patterns support two wildcards: + *
    + *
  • Single * wildcard matches any character except for . and $.
  • + *
  • Double ** wildcard matches any character.
  • + *
+ * For more information and examples see Class Names Glob Patterns Wiki page. + */ + @Parameter + private List classPatterns = Collections.emptyList(); + + /** + * Classes to process specified by annotations. + */ + @Parameter + private List classesWithAnnotations = Collections.emptyList(); + + /** + * Classes to process specified by implemented interface. + */ + @Parameter + private List classesImplementingInterfaces = Collections.emptyList(); + + /** + * Classes to process specified by extended superclasses. + */ + @Parameter + private List classesExtendingClasses = Collections.emptyList(); + + /** + * Scans specified JAX-RS {@link javax.ws.rs.core.Application} for classes to process. + * Parameter contains fully-qualified class name. + * It is possible to exclude particular REST resource classes using {@link #excludeClasses} parameter. + */ + @Parameter + private String classesFromJaxrsApplication; + + /** + * Scans JAX-RS resources for JSON classes to process. + * It is possible to exclude particular REST resource classes using {@link #excludeClasses} parameter. + */ + @Parameter + private boolean classesFromAutomaticJaxrsApplication = false; + + /** + * Allows to speed up classpath scanning by limiting scanning to specified packages. + * This optimization applies to following parameters: + *
    + *
  • classPatterns
  • + *
  • classesImplementingInterfaces
  • + *
  • classesExtendingClasses
  • + *
  • classesWithAnnotations
  • + *
  • classesFromAutomaticJaxrsApplication
  • + *
+ * This parameter is passed directly to underlying classpath scanning library (ClassGraph) without any validation or interpretation. + */ + @Parameter + private List scanningAcceptedPackages = Collections.emptyList(); + + /** + * List of classes excluded from processing. + */ + @Parameter + private List excludeClasses = Collections.emptyList(); + + /** + * Excluded classes specified using glob patterns. + * For more information and examples see Class Names Glob Patterns Wiki page. + */ + @Parameter + private List excludeClassPatterns = Collections.emptyList(); + + /** + * If this list is not empty then only properties with any of these annotations will be included. + */ + @Parameter + private List includePropertyAnnotations = Collections.emptyList(); + + /** + * Properties with any of these annotations will be excluded. + */ + @Parameter + private List excludePropertyAnnotations = Collections.emptyList(); + + /** + * Library used in JSON classes. + * Supported values are: + *
    + *
  • jackson2 - annotations from `com.fasterxml.jackson.annotation` package
  • + *
  • jaxb - annotations from `javax.xml.bind.annotation` package
  • + *
  • gson - annotations from `com.google.gson.annotations` package
  • + *
  • jsonb - annotations from `javax.json.bind.annotation` package
  • + *
+ * Required parameter, recommended value is jackson2. + */ + @Parameter(required = true) + private JsonLibrary jsonLibrary; + + /** + * Specifies Jackson 2 global configuration. + * Description of individual parameters is in + * Jackson2Configuration + * class on GitHub (latest version). + */ + @Parameter + private Jackson2Configuration jackson2Configuration; + + /** + * Specifies Gson global configuration. + * Description of individual parameters is in + * GsonConfiguration + * class on GitHub (latest version). + */ + @Parameter + private GsonConfiguration gsonConfiguration; + + /** + * Specifies JSON-B global configuration. + * Description of individual parameters is in + * Jackson2Configuration + * class on GitHub (latest version). + */ + @Parameter + private JsonbConfiguration jsonbConfiguration; + + /** + * If true Spring REST application will be loaded and scanned for classes to process. + * It is needed to specify application class using another parameter (for example {@link #classes}). + */ + @Parameter + private boolean scanSpringApplication = false; + + + /** + * Specifies level of logging output. + * Supported values are: + *
    + *
  • Debug
  • + *
  • Verbose
  • + *
  • Info
  • + *
  • Warning
  • + *
  • Error
  • + *
+ * Default value is Verbose. + */ + @Parameter + private Logger.Level loggingLevel = Logger.Level.Verbose; + + @Parameter(property = "java.to.zod.skip") + private boolean skip = false; + + + /** + * The presence of any annotation in this list on a JSON property will cause + * the typescript-generator to treat that property as optional when generating + * the corresponding TypeScript interface. + * Example optional annotation: javax.annotation.Nullable. + */ + private List optionalAnnotations = Collections.emptyList(); + + @Input + @Optional + public String getSchemaNamePrefix() { + return schemaNamePrefix; + } + + @Input + @Optional + public String getSchemaNameSuffix() { + return schemaNameSuffix; + } + + @Input + public List getClasses() { + return classes; + } + + @Input + @Optional + public List getClassPatterns() { + return classPatterns; + } + + @Input + @Optional + public List getClassesWithAnnotations() { + return classesWithAnnotations; + } + + @Input + @Optional + public List getClassesImplementingInterfaces() { + return classesImplementingInterfaces; + } + + @Input + @Optional + public List getClassesExtendingClasses() { + return classesExtendingClasses; + } + + @Input + @Optional + public String getClassesFromJaxrsApplication() { + return classesFromJaxrsApplication; + } + + @Input + public boolean isClassesFromAutomaticJaxrsApplication() { + return classesFromAutomaticJaxrsApplication; + } + + @Input + @Optional + public List getScanningAcceptedPackages() { + return scanningAcceptedPackages; + } + + @Input + @Optional + public List getExcludeClasses() { + return excludeClasses; + } + + @Input + @Optional + public List getExcludeClassPatterns() { + return excludeClassPatterns; + } + + @Input + @Optional + public List getIncludePropertyAnnotations() { + return includePropertyAnnotations; + } + + @Input + @Optional + public List getExcludePropertyAnnotations() { + return excludePropertyAnnotations; + } + + @Input + @Optional + public List getOptionalAnnotations() { + return optionalAnnotations; + } + + @Input + public JsonLibrary getJsonLibrary() { + return jsonLibrary; + } + + @Input + @Optional + public Jackson2Configuration getJackson2Configuration() { + return jackson2Configuration; + } + + @Input + @Optional + public GsonConfiguration getGsonConfiguration() { + return gsonConfiguration; + } + + @Input + @Optional + public JsonbConfiguration getJsonbConfiguration() { + return jsonbConfiguration; + } + + @Input + public boolean isScanSpringApplication() { + return scanSpringApplication; + } + + @Input + @Optional + public Logger.Level getLoggingLevel() { + return loggingLevel; + } + + @Input + public boolean isSkip() { + return skip; + } + + + +} + diff --git a/java-to-zod-gradle-plugin/src/test/java/sh/ivan/zod/GenerateZodSchemasTest.java b/java-to-zod-gradle-plugin/src/test/java/sh/ivan/zod/GenerateZodSchemasTest.java new file mode 100644 index 0000000..352de8a --- /dev/null +++ b/java-to-zod-gradle-plugin/src/test/java/sh/ivan/zod/GenerateZodSchemasTest.java @@ -0,0 +1,88 @@ +package sh.ivan.zod; + +import org.gradle.testkit.runner.BuildResult; +import org.gradle.testkit.runner.GradleRunner; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import java.io.File; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; +import java.util.Arrays; + +import static org.gradle.testkit.runner.TaskOutcome.SUCCESS; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +public class GenerateZodSchemasTest { + + @TempDir + File testProjectDir; + + @BeforeEach + public void setup() throws IOException { + // Copy the external build.gradle.kts file to the test project directory + Path buildFile = new File(testProjectDir, "build.gradle.kts").toPath(); + Path buildFileSource = Path.of("src/test/resources/build.gradle.kts"); + Files.copy(buildFileSource, buildFile, StandardCopyOption.REPLACE_EXISTING); + } + + @Test + public void testGenerateZodSchemasTask() throws IOException { + // Given: Add an actual Java test class to the test project directory + Path srcDir = Path.of(testProjectDir.getPath(), "src/main/java/sh/ivan/zod/resources"); + Files.createDirectories(srcDir); + + // Copy TestPersonClass.java from resources + Path testPersonClass = Path.of("src/test/java/sh/ivan/zod/resources/TestPersonClass.java"); + Files.copy(testPersonClass, srcDir.resolve("TestPersonClass.java"), StandardCopyOption.REPLACE_EXISTING); + + // Copy TestPersonRecord.java from resources + Path testPersonRecord = Path.of("src/test/java/sh/ivan/zod/resources/TestPersonRecord.java"); + Files.copy(testPersonRecord, srcDir.resolve("TestPersonRecord.java"), StandardCopyOption.REPLACE_EXISTING); + + // First: Build the Java class files + BuildResult buildResult = GradleRunner.create() + .withProjectDir(testProjectDir) + .withArguments("build") // or use 'compileJava' if you prefer + .withPluginClasspath() + .build(); + + // Ensure the build was successful + assertEquals(SUCCESS, buildResult.task(":build").getOutcome()); + + // When: Run the Gradle task to generate Zod schemas + BuildResult result = GradleRunner.create() + .withProjectDir(testProjectDir) + .withArguments("generateZodSchemas") + .withPluginClasspath() + .build(); + + // Then: Verify the task outcome and schema generation + assertEquals(SUCCESS, result.task(":generateZodSchemas").getOutcome()); + + File outputDir = new File(testProjectDir, "build/java-to-zod"); + System.out.println("Output directory contents: " + Arrays.toString(outputDir.listFiles())); + + + // Verify that the output file has been generated + File outputFile = new File(testProjectDir, "build/temp/generated-schemas/schemas.ts"); + assertTrue(outputFile.exists(), "Zod schema file should be generated"); + + // Verify + String outputContent = Files.readString(outputFile.toPath(), StandardCharsets.UTF_8); + + Path snapshotFilePath = Path.of("src/test/ts/src/schemas_snapshot.ts"); + String snapshotContent = Files.readString(snapshotFilePath, StandardCharsets.UTF_8); + assertEquals(normalizeLineEndings(outputContent), normalizeLineEndings(snapshotContent), "The generated Zod schemas do not match the snapshot content."); + + + } + public String normalizeLineEndings(String input) { + return input.replace("\r\n", "\n").trim(); + } +} diff --git a/java-to-zod-gradle-plugin/src/test/java/sh/ivan/zod/resources/TestPersonClass.java b/java-to-zod-gradle-plugin/src/test/java/sh/ivan/zod/resources/TestPersonClass.java new file mode 100644 index 0000000..0ad3346 --- /dev/null +++ b/java-to-zod-gradle-plugin/src/test/java/sh/ivan/zod/resources/TestPersonClass.java @@ -0,0 +1,89 @@ +package sh.ivan.zod.resources; + +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.Size; + +import java.util.Date; +import java.util.Objects; + +public final class TestPersonClass { + + private final Long id; + private final Date dateOfBirth; + private final String fName; + + @NotBlank(message = "Must not be blank") + @Size(min = 1, message = "Please supply a name.") + private final String lName; + + public TestPersonClass( + Long id, + Date dateOfBirth, + + String fName, + String lName + ) { + this.id = id; + this.dateOfBirth = dateOfBirth; + this.fName = fName; + this.lName = lName; + } + + /** + * Non-getter method shouldn't be in schema. + * */ + public TestPersonClass unWrapDto() { + return this; + } + + public String getlName() { + return lName; + } + + public Long getId() { + return id(); + } + + /** + * Non-getter method shouldn't be in schema. + * */ + public Long id() { + return id; + } + + public Date getDateOfBirth() { + return dateOfBirth; + } + + @NotBlank(message = "Must not be blank") + @Size(min = 1, message = "Please supply a name.") + public String getfName() { + return fName; + } + + @Override + public int hashCode() { + return Objects.hash(id, dateOfBirth, fName, lName); + } + + @Override + public boolean equals(Object obj) { + if (obj == this) return true; + if (obj == null || obj.getClass() != this.getClass()) return false; + var that = (TestPersonClass) obj; + return Objects.equals(this.id, that.id) && + Objects.equals(this.dateOfBirth, that.dateOfBirth) && + Objects.equals(this.fName, that.fName) && + Objects.equals(this.lName, that.lName); + } + + @Override + public String toString() { + return getClass().getSimpleName() + "(" + + "party_id = " + id + ", " + + "dateOfBirth = " + dateOfBirth + ", " + + "fName = " + fName + ", " + + "lName = " + lName + ")"; + } + +} \ No newline at end of file diff --git a/java-to-zod-gradle-plugin/src/test/java/sh/ivan/zod/resources/TestPersonRecord.java b/java-to-zod-gradle-plugin/src/test/java/sh/ivan/zod/resources/TestPersonRecord.java new file mode 100644 index 0000000..ee09748 --- /dev/null +++ b/java-to-zod-gradle-plugin/src/test/java/sh/ivan/zod/resources/TestPersonRecord.java @@ -0,0 +1,42 @@ +package sh.ivan.zod.resources; + +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.Size; + +import java.util.Date; + + +public record TestPersonRecord( + Long id, + Date dateOfBirth, + @NotBlank(message = "Must not be blank") + @Size(min = 1, message = "Please supply a name.") + String fName, + String lName +) { + + @Override + public String toString() { + return getClass().getSimpleName() + "(" + + "party_id = " + id + ", " + + "dateOfBirth = " + dateOfBirth + ", " + + "fName = " + fName + ", " + + "lName = " + lName + ")"; + } + + + public TestPersonRecord unWrapDto() { + return this; + } + + @NotBlank(message = "Must not be blank") + @Size(min = 1, message = "Please supply a name.") + @Override + public String lName() { + return lName; + } + + public Long getId() { + return id(); + } +} \ No newline at end of file diff --git a/java-to-zod-gradle-plugin/src/test/resources/build.gradle.kts b/java-to-zod-gradle-plugin/src/test/resources/build.gradle.kts new file mode 100644 index 0000000..3305c48 --- /dev/null +++ b/java-to-zod-gradle-plugin/src/test/resources/build.gradle.kts @@ -0,0 +1,62 @@ +import cz.habarta.typescript.generator.* + +plugins { + id("java") + id("cz.habarta.typescript-generator") version "3.2.1263" + id("java-to-zod-gradle-plugin") version "0.7.0-SNAPSHOT" + id("com.github.node-gradle.node") version "3.0.1" +} + +node { + version = "16.13.0" // Or the version you want to use + download = true // This ensures a local copy of Node.js is used +} + + +repositories { + mavenLocal() + mavenCentral() +} + +dependencies { + implementation("cz.habarta.typescript-generator:typescript-generator-core:3.2.1263") + implementation("jakarta.validation:jakarta.validation-api:3.1.0") +} + +java { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 +} + +tasks.withType { + val tempOutputDir = layout.buildDirectory.dir("temp/generated-schemas") + outputFile = tempOutputDir.map { it.file("schemas.ts") }.get().asFile + pluginParameters.jsonLibrary = JsonLibrary.jackson2 + pluginParameters.classes = mutableListOf("sh.ivan.zod.resources.TestPersonClass", "sh.ivan.zod.resources.TestPersonRecord") +} + +tasks.withType { + options.annotationProcessorPath = configurations["annotationProcessor"] +} + +tasks.register("runJestTests", Exec::class.java) { + group = "verification" + description = "Runs Jest tests to validate the generated Zod schemas." + + // Set working directory for Jest (e.g., the directory where the schema was generated) + workingDir = projectDir + + // Define the command to run Jest + commandLine = listOf("npm", "run", "test") + + // Ensure that Jest tests are run after the schemas are generated + dependsOn("generateZodSchemas") + + // Finalizer to clean the temp files after Jest has run + finalizedBy("cleanTemp") +} + +tasks.register("cleanTemp", Delete::class.java) { + delete(layout.buildDirectory.dir("temp")) +} + diff --git a/java-to-zod-gradle-plugin/src/test/ts/jest.config.js b/java-to-zod-gradle-plugin/src/test/ts/jest.config.js new file mode 100644 index 0000000..830c9a5 --- /dev/null +++ b/java-to-zod-gradle-plugin/src/test/ts/jest.config.js @@ -0,0 +1,5 @@ +module.exports = { + preset: 'ts-jest', + testEnvironment: 'node', + roots: ['/src'] +}; diff --git a/java-to-zod-gradle-plugin/src/test/ts/package.json b/java-to-zod-gradle-plugin/src/test/ts/package.json new file mode 100644 index 0000000..087a094 --- /dev/null +++ b/java-to-zod-gradle-plugin/src/test/ts/package.json @@ -0,0 +1,18 @@ +{ + "name": "java-to-zod-gradle-plugin-test", + "version": "0.7.0", + "main": "index.js", + "scripts": { + "test": "GENERATED_SCHEMA_PATH=build/temp/generated-schemas jest", + "clean": "rm -rf node_modules" + }, + "dependencies": { + "zod": "^3.22.4" + }, + "devDependencies": { + "@types/jest": "^29.5.13", + "jest": "^29.7.0", + "ts-jest": "^29.2.5", + "typescript": "^4.9.5" + } +} diff --git a/java-to-zod-gradle-plugin/src/test/ts/src/schemas_snapshot.ts b/java-to-zod-gradle-plugin/src/test/ts/src/schemas_snapshot.ts new file mode 100644 index 0000000..ebacf1d --- /dev/null +++ b/java-to-zod-gradle-plugin/src/test/ts/src/schemas_snapshot.ts @@ -0,0 +1,15 @@ +import { z as zod } from 'zod'; + +export const TestPersonClassSchema = zod.object({ + id: zod.number().int().optional().nullable(), + dateOfBirth: zod.date().optional().nullable(), + fName: zod.string().regex(/\S/, { message: 'Must not be blank' }).min(1, { message: 'Please supply a name.' }), + lName: zod.string().regex(/\S/, { message: 'Must not be blank' }).min(1, { message: 'Please supply a name.' }), +}); + +export const TestPersonRecordSchema = zod.object({ + id: zod.number().int().optional().nullable(), + dateOfBirth: zod.date().optional().nullable(), + fName: zod.string().regex(/\S/, { message: 'Must not be blank' }).min(1, { message: 'Please supply a name.' }), + lName: zod.string().regex(/\S/, { message: 'Must not be blank' }).min(1, { message: 'Please supply a name.' }), +}); diff --git a/java-to-zod-gradle-plugin/src/test/ts/src/test_literals.ts b/java-to-zod-gradle-plugin/src/test/ts/src/test_literals.ts new file mode 100644 index 0000000..c58b135 --- /dev/null +++ b/java-to-zod-gradle-plugin/src/test/ts/src/test_literals.ts @@ -0,0 +1,13 @@ +export const validTestPersonRecord = { + id: 123, // valid integer + dateOfBirth: new Date('1990-01-01'), // valid date + fName: 'John', // non-blank string + lName: 'Doe' // non-blank string +}; + +export const invalidTestPersonRecord = { + id: 'abc', // invalid, should be a number or null + dateOfBirth: 'not a date', // invalid, should be a Date object or null + fName: ' ', // invalid, blank string doesn't meet regex and min length + lName: '' // invalid, empty string doesn't meet regex and min length +}; diff --git a/java-to-zod-gradle-plugin/src/test/ts/src/validation.test.ts b/java-to-zod-gradle-plugin/src/test/ts/src/validation.test.ts new file mode 100644 index 0000000..ce34b3f --- /dev/null +++ b/java-to-zod-gradle-plugin/src/test/ts/src/validation.test.ts @@ -0,0 +1,29 @@ +import { validTestPersonRecord, invalidTestPersonRecord } from "./test_literals"; +import { TestPersonRecordSchema } from "./schemas_snapshot"; + +// Helper function to replace one field in the valid record with the invalid counterpart +function replaceField(obj: any, field: string, value: any) { + return { + ...obj, + [field]: value + }; +} + +describe('TestPersonRecordSchema', () => { + it('should validate a correct object', () => { + const result = TestPersonRecordSchema.safeParse(validTestPersonRecord); + expect(result.success).toBe(true); + }); + + it('should fail when any field from the invalid record is used', () => { + const fields = Object.keys(invalidTestPersonRecord); + + fields.forEach((field) => { + const testObject = replaceField(validTestPersonRecord, field, invalidTestPersonRecord[field as keyof typeof invalidTestPersonRecord]); + const result = TestPersonRecordSchema.safeParse(testObject); + + // Expect the validation to fail when an invalid field is substituted + expect(result.success).toBe(false); + }); + }); +}); diff --git a/java-to-zod-gradle-plugin/src/test/ts/tsconfig.json b/java-to-zod-gradle-plugin/src/test/ts/tsconfig.json new file mode 100644 index 0000000..be95560 --- /dev/null +++ b/java-to-zod-gradle-plugin/src/test/ts/tsconfig.json @@ -0,0 +1,10 @@ +{ + "compilerOptions": { + "target": "ES2020", + "module": "commonjs", + "strict": true, + "esModuleInterop": true, + "skipLibCheck": true + }, + "include": ["src/**/*"] +}