Skip to main content
Redhat Developers  Logo
  • Products

    Featured

    • Red Hat Enterprise Linux
      Red Hat Enterprise Linux Icon
    • Red Hat OpenShift AI
      Red Hat OpenShift AI
    • Red Hat Enterprise Linux AI
      Linux icon inside of a brain
    • Image mode for Red Hat Enterprise Linux
      RHEL image mode
    • Red Hat OpenShift
      Openshift icon
    • Red Hat Ansible Automation Platform
      Ansible icon
    • Red Hat Developer Hub
      Developer Hub
    • View All Red Hat Products
    • Linux

      • Red Hat Enterprise Linux
      • Image mode for Red Hat Enterprise Linux
      • Red Hat Universal Base Images (UBI)
    • Java runtimes & frameworks

      • JBoss Enterprise Application Platform
      • Red Hat build of OpenJDK
    • Kubernetes

      • Red Hat OpenShift
      • Microsoft Azure Red Hat OpenShift
      • Red Hat OpenShift Virtualization
      • Red Hat OpenShift Lightspeed
    • Integration & App Connectivity

      • Red Hat Build of Apache Camel
      • Red Hat Service Interconnect
      • Red Hat Connectivity Link
    • AI/ML

      • Red Hat OpenShift AI
      • Red Hat Enterprise Linux AI
    • Automation

      • Red Hat Ansible Automation Platform
      • Red Hat Ansible Lightspeed
    • Developer tools

      • Red Hat Trusted Software Supply Chain
      • Podman Desktop
      • Red Hat OpenShift Dev Spaces
    • Developer Sandbox

      Developer Sandbox
      Try Red Hat products and technologies without setup or configuration fees for 30 days with this shared Openshift and Kubernetes cluster.
    • Try at no cost
  • Technologies

    Featured

    • AI/ML
      AI/ML Icon
    • Linux
      Linux Icon
    • Kubernetes
      Cloud icon
    • Automation
      Automation Icon showing arrows moving in a circle around a gear
    • View All Technologies
    • Programming Languages & Frameworks

      • Java
      • Python
      • JavaScript
    • System Design & Architecture

      • Red Hat architecture and design patterns
      • Microservices
      • Event-Driven Architecture
      • Databases
    • Developer Productivity

      • Developer productivity
      • Developer Tools
      • GitOps
    • Secure Development & Architectures

      • Security
      • Secure coding
    • Platform Engineering

      • DevOps
      • DevSecOps
      • Ansible automation for applications and services
    • Automated Data Processing

      • AI/ML
      • Data Science
      • Apache Kafka on Kubernetes
      • View All Technologies
    • Start exploring in the Developer Sandbox for free

      sandbox graphic
      Try Red Hat's products and technologies without setup or configuration.
    • Try at no cost
  • Learn

    Featured

    • Kubernetes & Cloud Native
      Openshift icon
    • Linux
      Rhel icon
    • Automation
      Ansible cloud icon
    • Java
      Java icon
    • AI/ML
      AI/ML Icon
    • View All Learning Resources

    E-Books

    • GitOps Cookbook
    • Podman in Action
    • Kubernetes Operators
    • The Path to GitOps
    • View All E-books

    Cheat Sheets

    • Linux Commands
    • Bash Commands
    • Git
    • systemd Commands
    • View All Cheat Sheets

    Documentation

    • API Catalog
    • Product Documentation
    • Legacy Documentation
    • Red Hat Learning

      Learning image
      Boost your technical skills to expert-level with the help of interactive lessons offered by various Red Hat Learning programs.
    • Explore Red Hat Learning
  • Developer Sandbox

    Developer Sandbox

    • Access Red Hat’s products and technologies without setup or configuration, and start developing quicker than ever before with our new, no-cost sandbox environments.
    • Explore Developer Sandbox

    Featured Developer Sandbox activities

    • Get started with your Developer Sandbox
    • OpenShift virtualization and application modernization using the Developer Sandbox
    • Explore all Developer Sandbox activities

    Ready to start developing apps?

    • Try at no cost
  • Blog
  • Events
  • Videos

How to generate code using Fabric8 Kubernetes Client

January 24, 2023
Rohan Kumar
Related topics:
JavaKubernetes
Related products:
Red Hat Enterprise Linux

Share:

    Fabric8 Kubernetes Client provides two ways of interacting with CustomResources running in any Kubernetes cluster:

    • Typed API (covered in Part 2)
    • Typeless API (covered in Part 3)

    While typeless API provides a way to deal with CustomResources generically, it’s not always a preferable option for a strongly typed language like Java. Most developers want to use typed API to have complete and type-safe control over their CustomResources.

    However, there is one additional step involved in using typed API. It provides POJOs for Kubernetes CustomResource objects. This article showcases how you can automatically generate CustomResourceDefinition-related code using tools offered by the Fabric8 Kubernetes Client library.

    This is the fourth installment in the following series of articles:

    • Part 1: How to use Fabric8 Java Client with Kubernetes
    • Part 2: Programming Kubernetes custom resources in Java
    • Part 3: How to use Kubernetes dynamic client with Fabric8
    • Part 4: How to generate code using Fabric8 Kubernetes Client
    • Part 5: How to write tests with Fabric8 Kubernetes Client

    2 CRD generation options

    There are two possible approaches to generating code while using custom resources:

    1. Users coming from a Java background would have more confidence in writing Java classes than in writing CRD YAML, which is error-prone. They would prefer to generate CRD Yaml from the Java POJO they wrote.
    2. It is also possible that there is an existing CRD YAML file for which you can generate Java POJOs.

    Fabric8 Kubernetes Client provides tooling for both of these approaches via CRD Generator and Java Generator. 

    Let’s take an example of the Book CustomResource we used in part 2, Programming Kubernetes custom resources in Java, to see both approaches to generating Java POJOs from CRD YAML and vice versa.

    Generating CRD POJOs from CRD YAML

    Consider a scenario with only CRD YAML manifest for the Book CustomResource. We want to automatically generate Java POJOs for Book CustomResource. We’ll be using Fabric8 Java Generator to do this. We’ll be using its Java Generator Maven Plugin to generate Java POJOs from YAML during build time.

    Let’s start with a basic maven project and place our Book CustomResource YAML in our project’s resources folder. If you don’t have an existing project, you can clone this GitHub repository:

    fabric8-crd-java-generator-demo : $ tree src/main/resources/
    src/main/resources/
    └── crd
        └── book-crd.yaml
    

    In our project’s pom.xml let’s add Fabric8 Java Generator Maven Plugin configuration to generate Java POJOs for CRD YAML present in src/main/resources folder:

    <plugin>
        <groupId>io.fabric8</groupId>
        <artifactId>java-generator-maven-plugin</artifactId>
        <version>${fabric8.version}</version>
        <configuration>
            <!-- 1 -->
            <source>${project.basedir}/src/main/resources/crd/book-crd.yaml</source> 
             <!-- 2 -->
            <extraAnnotations>true</extraAnnotations>
        </configuration>
        <executions>
            <execution>
                <goals>
                    <goal>generate</goal>
                </goals>
            </execution>
        </executions>
    </plugin>
    

    By providing this plugin configuration, we’re instructing Java Generator Maven Plugin to do the following:

    • Pick book-crd.yaml file as a source file for generating CustomResource POJOs.
    • Add extra annotations to generated classes that can be processed by Sundrio to add additional helper builders and fluent classes. This would also require Sundrio and lombok dependencies added to the project.

    Compile the project as follows:

    fabric8-crd-java-generator-demo : $ mvn clean install

    Upon running mvn clean install, you can see that Book CustomResource POJOs are automatically generated intarget/generated-sources/java/. This is the default location of generated sources. If you want to generate these POJOs in some other directory, you can provide target in Java Generator Maven Plugin configuration section or via fabric8.java-generator.target property.

    Java Generator Maven Plugin also automatically adds these generated classes to maven source paths. So you don’t have to worry about adding extra configuration to add these generated classes to the maven source path.

    There are also some helper classes generated in target/generated-sources/java/:

    fabric8-crd-java-generator-demo : $ tree target/generated-sources/java/
    target/generated-sources/java/
    └── io
        └── fabric8
            └── demo
                └── generator
                    └── v1alpha1
                        ├── Book.java
                        ├── BookSpec.java
                        └── BookStatus.java
    
    5 directories, 3 files
    
    fabric8-crd-java-generator-demo : $ tree target/generated-sources/annotations/
    target/generated-sources/annotations/
    └── io
        └── fabric8
            └── demo
                └── generator
                    └── v1alpha1
                        ├── BookBuilder.java
                        ├── BookFluentImpl.java
                        ├── BookFluent.java
                        ├── BookSpecBuilder.java
                        ├── BookSpecFluentImpl.java
                        ├── BookSpecFluent.java
                        ├── BookStatusBuilder.java
                        ├── BookStatusFluentImpl.java
                        └── BookStatusFluent.java
    
    5 directories, 9 files
    

    You can go ahead and start writing code based on these generated Book POJOs. Java Generator Maven Plugin allows various configuration options to configure source generation. You can take a look here at the source code or documentation for more details.

    You can find the source code for this in this GitHub repository.

    Generating CRD Yaml from POJOs

    Now let’s take a look at the opposite scenario. We already have Java sources for the Book CustomResource but we want to generate CustomResourceDefinition YAML manifests.

    We have our POJOs in src/main/java folder as usual (see GitHub repository for source code).

    fabric8-java-crd-yaml-generator-demo : $ tree src/main/java/
    src/main/java/
    └── io
        └── fabric8
            └── demo
                └── crd
                    └── v1alpha1
                        ├── Book.java
                        ├── BookSpec.java
                        └── BookStatus.java
    
    5 directories, 3 files
    

    We’ll be using Fabric8 Crd Generator to generate CRD Yaml files for Book CustomResource. It’s available as a Java Annotation Processor, so you can simply add it as a dependency in your project, and you should be good to go.

    Add Fabric8 Crd Generator dependency to your pom.xml:

    <dependency>
        <groupId>io.fabric8</groupId>
        <artifactId>crd-generator-apt</artifactId>
        <version>${fabric8.version}</version>
    </dependency>
    

    Compile project:

    fabric8-java-crd-yaml-generator-demo : $ mvn clean install
    
    …
    
    [INFO] --- maven-compiler-plugin:3.8.1:compile (default-compile) @ fabric8-java-crd-yaml-generator-demo ---
    [INFO] Changes detected - recompiling the module!
    [INFO] Compiling 3 source files to /home/rokumar/work/repos/kubernetes-client-demo/fabric8-java-crd-yaml-generator-demo/target/classes
    [INFO] Generating CRD books.testing.fabric8.io:
    [INFO]   - v1beta1 -> /home/rokumar/work/repos/kubernetes-client-demo/fabric8-java-crd-yaml-generator-demo/target/classes/META-INF/fabric8/books.testing.fabric8.io-v1beta1.yml
    [INFO]   - v1 -> /home/rokumar/work/repos/kubernetes-client-demo/fabric8-java-crd-yaml-generator-demo/target/classes/META-INF/fabric8/books.testing.fabric8.io-v1.yml
    

    You will notice that during compilation, the Fabric8 Crd Annotation processor generated CustomResourceDefinition YAML files in target/classes/META-INF/fabric8 folder. It picks up all of the classes in the project, which extend io.fabric8.kubernetes.client.CustomResource and generate CustomResourceDefinition YAML files for each of them.

    fabric8-java-crd-yaml-generator-demo : $ ls target/classes/META-INF/fabric8/
    
    books.testing.fabric8.io-v1beta1.yml  books.testing.fabric8.io-v1.yml

    You will notice that there are two YAML files generated (one with v1 and one with v1beta1 suffix). The v1beta1 is kept for backward compatibility for older Kubernetes Clusters, which only supported apiextensions.k8s.io/v1beta1 CustomResourceDefinitions. For most cases, you would most likely be working with the v1 YAML file.

    You can go ahead and inspect the contents of generated CustomResourceDefinition YAML files and use them in your Kubernetes clusters.

    For more information about the different configuration options available, check out Fabric8 CRD Generator Documentation.

    You can find code for this example in this GitHub repository.

    Learn more about Fabric8 Kubernetes Client

    In this blog post, you learned about the code generation capabilities of Fabric8 Kubernetes Client’s tooling in form of Java Generator and CRD Generator. You can find the code in this GitHub repository. The next article in my series, How to write tests with Fabric8 Kubernetes Client, discusses Fabric8 Kubernetes Client testing libraries, Fabric8 Kubernetes Mock Server, and Fabric8 JUnit5 Extension.

    For more information, check out the Fabric8 Kubernetes Client GitHub page. Feel free to follow us on these channels:

    • StackOverflow
    • Fabric8 Kubernetes Client CHEATSHEET
    • Twitter
    • Gitter Chat

    Related Posts

    • How to use Fabric8 Java Client with Kubernetes

    • Programming Kubernetes custom resources in Java

    • How to use Kubernetes dynamic client with Fabric8

    • Configuring Kubernetes operands through custom resources

    Recent Posts

    • How Trilio secures OpenShift virtual machines and containers

    • How to implement observability with Node.js and Llama Stack

    • How to encrypt RHEL images for Azure confidential VMs

    • How to manage RHEL virtual machines with Podman Desktop

    • Speech-to-text with Whisper and Red Hat AI Inference Server

    What’s up next?

    Find out how you can move your legacy Java application into a container and deploy it to Kubernetes in minutes using the Developer Sandbox for Red Hat OpenShift.

    Try Java in the sandbox
    Red Hat Developers logo LinkedIn YouTube Twitter Facebook

    Products

    • Red Hat Enterprise Linux
    • Red Hat OpenShift
    • Red Hat Ansible Automation Platform

    Build

    • Developer Sandbox
    • Developer Tools
    • Interactive Tutorials
    • API Catalog

    Quicklinks

    • Learning Resources
    • E-books
    • Cheat Sheets
    • Blog
    • Events
    • Newsletter

    Communicate

    • About us
    • Contact sales
    • Find a partner
    • Report a website issue
    • Site Status Dashboard
    • Report a security problem

    RED HAT DEVELOPER

    Build here. Go anywhere.

    We serve the builders. The problem solvers who create careers with code.

    Join us if you’re a developer, software engineer, web designer, front-end designer, UX designer, computer scientist, architect, tester, product manager, project manager or team lead.

    Sign me up

    Red Hat legal and privacy links

    • About Red Hat
    • Jobs
    • Events
    • Locations
    • Contact Red Hat
    • Red Hat Blog
    • Inclusion at Red Hat
    • Cool Stuff Store
    • Red Hat Summit

    Red Hat legal and privacy links

    • Privacy statement
    • Terms of use
    • All policies and guidelines
    • Digital accessibility

    Report a website issue