Skip to content

About

No description, website, or topics provided.

Resources

Stars

1 star

Watchers

1 watching

Forks

Latest commit

Β 

History

140 Commits

Folders and files

NameName
Last commit message
Last commit date
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

OpenAPI Model Generator Gradle Plugin

A comprehensive Gradle plugin for generating Java DTOs from multiple OpenAPI specifications with enterprise-grade features including template customization, incremental builds, performance optimizations, and automatic version detection.

πŸš€ Quick Start

1. Apply the Plugin

Important: You must apply the OpenAPI Generator plugin before applying this plugin:

plugins {
    id 'org.openapi.generator' version '7.26.0'  // Any version from 7.10.0 through 7.26.0 is tested
    id 'com.guidedbyte.openapi-modelgen' version '@version@'
}

2. Basic Configuration

openapiModelgen {
    specs {
        pets {
            inputSpec "src/main/resources/openapi-spec/pets.yaml"
            modelPackage "com.example.model.pets"
        }

        orders {
            inputSpec "src/main/resources/openapi-spec/orders.yaml"
            modelPackage "com.example.model.orders"
        }
    }
}

3. Generate Models

# Generate models for specific spec
./gradlew generatePets

# Generate models for all specs
./gradlew generateAllModels

# Get help
./gradlew generateHelp

4. Build Integration (Automatic)

No manual configuration required! The plugin automatically:

  • Registers each spec's generated src/main/java with the main sourceSet (generated tests and docs, when enabled, stay out of it)
  • Wires compileJava to depend on generateAllModels

Each spec generates to its own subdirectory for build cache isolation:

  • pets β†’ build/generated/sources/openapi/pets/src/main/java/
  • orders β†’ build/generated/sources/openapi/orders/src/main/java/

Just run ./gradlew build and everything works.

✨ Key Features

Core Functionality

  • Multi-spec support: Generate models from multiple OpenAPI specifications in a single project
  • Template customization system: YAML-based template modifications with comprehensive validation
  • Template precedence hierarchy: User templates > User YAML customizations > Plugin YAML > OpenAPI defaults
  • Template library support: Share and reuse templates/customizations via dependency JARs
  • Incremental build support: Only regenerates when inputs actually change
  • Lombok integration: Full annotation support with constructor conflict resolution

Performance & Enterprise Features

  • Multi-level caching system: 90% faster no-change builds, 70% faster incremental builds
  • Parallel multi-spec processing: Thread-safe concurrent generation
  • Cross-build performance optimization: Global cache persistence
  • Automatic version detection: Works with any OpenAPI Generator version from configuration plugins
  • Content-based change detection: SHA-256 hashing for reliable template change detection

Developer Experience

  • Command-line options: Override any configuration via CLI parameters
  • Comprehensive testing: 247+ test methods across 27 test classes (100% pass rate)
  • Method-call DSL: Type-safe configuration with validation and CLI overrides

πŸ“– Documentation

Configuration

Advanced Topics

  • Performance - Caching system, parallel processing, and optimization
  • Troubleshooting - Common issues, debug options, and known limitations
  • Development - Building, testing, and contributing

Release Information

  • CHANGELOG - Release notes and version history

πŸ’‘ Important: DSL Syntax

This plugin uses method-call syntax (no equals signs) for configuration:

// βœ… CORRECT - Method call syntax
openapiModelgen {
    defaults {
        outputDir "build/generated/sources/openapi"  // Calls outputDir(String value)
        validateSpec true                            // Calls validateSpec(Boolean value)
    }
    specs {
        pets {
            inputSpec "specs/pets.yaml"              // Calls inputSpec(String value)
            modelPackage "com.example.pets"          // Calls modelPackage(String value)
        }
    }
}

// ❌ INCORRECT - Assignment syntax (will cause compilation errors)
openapiModelgen {
    defaults {
        outputDir = "build/generated"                // Will fail
        validateSpec = true                          // Will fail
    }
}

This method-based approach enables type validation, CLI parameter overrides, and better error reporting.

πŸ”§ Configuration Defaults

The plugin comes pre-configured with sensible defaults for Spring Boot 3 + Jakarta EE + Lombok:

// These are the built-in defaults - you only need to override what you want to change
openapiModelgen {
    defaults {
        generatorName "spring"                               // OpenAPI Generator name
        outputDir "build/generated/sources/openapi"         // Generated code output
        modelNameSuffix "Dto"                               // Suffix for model classes
        validateSpec false                                   // Validate specs before generation
        applyPluginCustomizations true                       // Use built-in optimizations
        parallel true                                        // Enable parallel processing

        // Template variables available in all templates
        templateVariables([
            currentYear: "2025",                            // Dynamic
            generatedBy: "OpenAPI Model Generator Plugin",  // Plugin identification
            pluginVersion: "@version@"                      // Plugin version
        ])
    }
}

Minimal Configuration Required

You only need to specify the essential properties:

openapiModelgen {
    specs {
        mySpec {
            inputSpec "src/main/resources/openapi-spec/api.yaml"    // Required
            modelPackage "com.example.model"                       // Required
            // All other properties use sensible defaults
        }
    }
}

🎨 Template Customization Overview

The plugin provides multiple ways to customize generated code:

1. YAML-Based Customizations (Recommended)

Modify existing templates without replacing them entirely:

# src/main/resources/template-customizations/spring/pojo.mustache.yaml
insertions:
  - before: "{{#description}}"
    content: |
      /**
       * Generated by {{companyName}} on {{currentYear}}
       */

replacements:
  - pattern: "{{#deprecated}}"
    replacement: "{{#deprecated}}\n  // DEPRECATED - Use newer version"

2. Complete Template Override

Replace entire templates with your own:

src/main/resources/openapi-templates/
└── spring/
    β”œβ”€β”€ pojo.mustache       # Complete template override
    └── enumClass.mustache  # Complete template override

3. Template Libraries

Share templates across projects via JAR dependencies:

dependencies {
    openapiCustomizations 'com.company:api-templates:1.0.0'
}

openapiModelgen {
    defaults {
        useLibraryTemplates true
        useLibraryCustomizations true
    }
}

πŸ“– For complete template documentation, see Template System Guide

πŸ—οΈ Advanced Configuration Example

openapiModelgen {
    defaults {
        outputDir "build/generated/sources/openapi"
        userTemplateDir "src/main/resources/openapi-templates"
        userTemplateCustomizationsDir "src/main/resources/template-customizations"
        modelNameSuffix "Dto"
        validateSpec true
        parallel true

        // Template variables with nesting
        templateVariables([
            copyright: "Copyright Β© {{currentYear}} {{companyName}}",
            currentYear: "2025",
            companyName: "GuidedByte Technologies Inc."
        ])

        // OpenAPI Generator mappings
        importMappings([
            'UUID': 'java.util.UUID',
            'LocalDate': 'java.time.LocalDate'
        ])
        typeMappings([
            'string+uuid': 'UUID',
            'string+date': 'LocalDate'
        ])
        openapiNormalizer([
            'REFACTOR_ALLOF_WITH_PROPERTIES_ONLY': 'true',
            'SIMPLIFY_ONEOF_ANYOF': 'true'
        ])
    }

    specs {
        pets {
            inputSpec "src/main/resources/openapi-spec/pets.yaml"
            modelPackage "com.example.pets.model"
        }

        orders {
            inputSpec "src/main/resources/openapi-spec/orders.yaml"
            modelPackage "com.example.orders.model"
            modelNameSuffix "Entity"                     // Spec-specific override
            validateSpec false                           // Disable validation for this spec
        }
    }
}

πŸ“– For complete configuration documentation, see Configuration Guide

πŸš€ Generated Tasks

For each spec named {specName}, the plugin creates:

  • generate{SpecName} - Generate models for that specific spec (e.g., generatePets, generateOrders)
  • generateAllModels - Generate models for all specs
  • generateHelp - Display comprehensive plugin help and configuration options

Command Line Options

All configuration options can be overridden via command line:

# Generate with custom options
./gradlew generatePets --model-package=com.custom.model --validate-spec

# Generate all specs with custom output
./gradlew generateAllModels --output-dir=src/generated

# Override template settings
./gradlew generatePets --template-dir=custom-templates --model-name-suffix=Entity

🏒 Corporate Environment Support

The plugin automatically detects OpenAPI Generator versions from corporate plugins:

plugins {
    id 'com.company.java-standards'        // Provides OpenAPI Generator 8.2.0
    id 'com.guidedbyte.openapi-modelgen'   // Automatically detects and uses 8.2.0
}
// No additional configuration needed - respects corporate version management

πŸ“‹ Requirements

  • Java 17+
  • Gradle 8.0+
  • OpenAPI Generator 7.10.0 through 7.26.0 (must be provided by consumer project; see below)

OpenAPI Generator Compatibility

Every CI run tests the plugin against OpenAPI Generator 7.10.0, 7.14.0, 7.21.0 and 7.26.0, and any release in that range works. Newer releases usually work too; the plugin logs a warning at configuration time naming the tested range when you are outside it.

OpenAPI Generator 7.22.0 rewrote its Gradle task to the lazy configuration API (inputSpec, outputDir and templateDir became RegularFileProperty / DirectoryProperty) and now runs generation in a Gradle Worker with classloader isolation. The plugin adapts to either task API at runtime, so no configuration change is needed when you upgrade. What to expect on 7.22.0 and later:

  • One extra "Worker isolation" log line per generation task (7.23.0+).
  • Classes referenced by name in generator options (a custom normalizer or generator class) must be declared on the openApiGeneratorExtra configuration on 7.25.0+. See Custom generator classes on OpenAPI Generator 7.23+.
  • Generated DTOs differ cosmetically from 7.14.0 output (Jackson and Lombok annotation placement, collection defaults).
  • The plugin sets generateJsonIncludeAnnotations=false and generateJsonSetterNullsAnnotations=false as plugin defaults unless you set them, which silences two warnings per spec on 7.25.0+ without changing generated code.
  • Avoid 7.24.0 for the spring generator: that release emits @JsonInclude(NON_NULL) on every model property with no way to turn it off, so null properties vanish from serialized JSON regardless of your ObjectMapper. 7.25.0 restored the previous output.

🀝 Contributing

See Development Guide for detailed development guidelines and technical architecture documentation.

πŸ“„ License

SPDX-License-Identifier: Apache-2.0 OR 0BSD

This project is dual-licensed. Use it under either license, at your option:

  • Apache License 2.0 - includes an explicit patent grant; requires keeping the license and notice files when redistributing.
  • Zero-Clause BSD (0BSD) - no attribution, notice, or source-disclosure requirements of any kind.

The 0BSD option applies retroactively to every version of this project from the initial commit (2025-09-02) onward, including releases whose published metadata lists only Apache 2.0. See NOTICE for details.

Third-party dependencies remain under their own licenses.

πŸ†˜ Support


πŸ“– For detailed technical documentation, see the docs/ directory.

About

No description, website, or topics provided.

Resources

Stars

1 star

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages