Giter VIP home page Giter VIP logo

java-spring-template's Introduction

AsyncAPI Java Spring Template

Java Spring template for the AsyncAPI Generator.


License npm All Contributors downloads


Attention, AsyncAPI v3 is not currently supported by this template


Usage

Install AsyncAPI CLI, for details follow the guide.

npm install -g @asyncapi/cli

Generate using CLI.

asyncapi generate fromTemplate <asyncapi.yaml> @asyncapi/java-spring-template

You can replace <asyncapi.yaml> with local path or URL pointing to any AsyncAPI document.

AsyncAPI definitions

To have correctly generated code, your AsyncAPI file MUST define operationId for every operation.

In order for the generator to know what names to use for some parameters AsyncAPI specification bindings SHOULD be used.

It is RECOMMENDED to not use anonymous objects in payload and components definition, if changing of data model is not possible, you MAY use $id to set name of element.

  • Complete example for Kafka is here. Notice information about binding.
    channels:
      event.lighting.measured:
        publish:
          bindings:
            kafka:
              groupId: my-group
          message:
            $ref: '#/components/messages/lightMeasured'
        subscribe:
          message:
            $ref: '#/components/messages/lightMeasured'
  • Complete example for MQTT is here.

Supported parameters

Name Description Required Default
disableEqualsHashCode Disable generation of equals and hashCode methods for model classes. No false
inverseOperations Generate an application that will publish messages to publish operation of channels and read messages from subscribe operation of channels. Literally this flag will simply swap publish and subscribe operations in the channels.
This flag will be useful when you want to generate a code of mock for your main application. Be aware, generation could be incomplete and manual changes will be required e.g. if bindings are defined only for case of main application.
No false
javaPackage The Java package of the generated classes. Alternatively you can set the specification extension info.x-java-package. If both extension and parameter are used, parameter has more priority. No com.asyncapi
springBoot2 Generate template files for the Spring Boot version 2. For kafka protocol it will also force to use spring-kafka 2.9.9 No false
maven Generate pom.xml Maven build file instead of Gradle build. No false
listenerPollTimeout Only for Kafka. Timeout in ms to use when polling the consumer. No 3000
listenerConcurrency Only for Kafka. Number of threads to run in the listener containers. No 3
addTypeInfoHeader Only for Kafka. Add type information to message header. No true
connectionTimeout Only for MQTT. This value, measured in seconds, defines the maximum time interval the client will wait for the network connection to the MQTT server to be established. The default timeout is 30 seconds. A value of 0 disables timeout processing meaning the client will wait until the network connection is made successfully or fails. No 30
disconnectionTimeout Only for MQTT. The completion timeout in milliseconds when disconnecting. The default disconnect completion timeout is 5000 milliseconds. No 5000
completionTimeout Only for MQTT. The completion timeout in milliseconds for operations. The default completion timeout is 30000 milliseconds. No 30000
mqttClientId Only for MQTT. Provides the client identifier for the MQTT server. This parameter overrides the value of the clientId if it's set in the AsyncAPI file.If both aren't provided, a default value is set. No
asyncapiFileDir Path where original AsyncAPI file will be stored. No src/main/resources/api/

Examples

The shortest possible syntax:

asyncapi generate fromTemplate asyncapi.yaml @asyncapi/java-spring-template

Specify where to put the result with -o option and define parameter of poll timeout with -p option:

asyncapi generate fromTemplate asyncapi.yaml @asyncapi/java-spring-template -o ./src -p listenerPollTimeout=5000

Run it

Go to the root folder of the generated code and run this command (you need the JDK 17):

./gradlew bootRun

Development

  1. Clone the repository:

    git clone https://github.com/asyncapi/java-spring-template
    cd java-spring-template
  2. Download all template dependencies:

    npm install
  3. Make required changes in the template.

  4. Run snapshot tests:

    npm test

    If there falling tests examine diff report and make an appropriate changes in template files or snapshots.

  5. Check output generation project. Install AsyncAPI Generator:

    npm install -g @asyncapi/cli
    
  6. Run generation (assuming you are in template folder):

    # for MQTT protocol test with below
    asyncapi generate fromTemplate tests/mocks/mqtt.yml ./ -o output
    # for Kafka protocol test with below
    asyncapi generate fromTemplate tests/mocks/kafka.yml ./ -o output
  7. Explore generated files in output directory. Generated project shouldn't contain syntax or compilation errors. Preferably generated tests should pass.

For local development, you need different variations of this command. First of all, you need to know about three important CLI flags:

  • --debug enables the debug mode.
  • --watch-template enables a watcher of changes that you make in the template. It regenerates your template whenever it detects a change.
  • --install enforces reinstallation of the template.

Missing features

See the list of features that are still missing in the component:

  • support of Kafka is done based on clear "spring-kafka" library without integration like for mqtt or amqp
  • generated code for protocol amqp could be out of date. Please have a look to application.yaml and AmqpConfig.java
  • tests for protocol amqp are not provided
  • parameters for topics are not supported
  • server variables are not entirely supported
  • security schemas are not supported
  • traits are not supported
  • Json serializer/deserializer is used always, without taking into account real content type
  • template generation of docker-compose depending on protocol of server, now the rabbitmq is hardcoded

If you want to help us develop them, feel free to contribute.

Contributors ✨

Thanks goes to these wonderful people (emoji key):


Semen

🚧📖 💻🐛👀⚠️

Francesco Nobilia

👀

Lukasz Gornicki

👀

Amrut Prabhu

💻

Vaishnavi Nandakumar

💻

taotao100

🐛

Jacopo Biscella

🐛

This project follows the all-contributors specification. Contributions of any kind welcome!

java-spring-template's People

Contributors

allcontributors[bot] avatar amrutprabhu avatar asyncapi-bot avatar codingtenshi avatar dalelane avatar dependabot[bot] avatar derberg avatar fmvilas avatar hutchhutchhutch avatar japudcret avatar khudadad414 avatar larshp avatar sihamtahi avatar tenischev avatar theeques avatar tuxburner avatar vaishnavinandakumar avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

java-spring-template's Issues

array with ref and Enumeration with dash Generation failed

Hello,
I am trying to generate a client from a yaml and i am getting the error below

something went wrong:
Template render error: (C:\Users\myUser\AppData\Roaming\npm\node_modules\@asyncapi\generator\node_modules\@asyncapi\java-spring-template\template\src\main\java\com\asyncapi\model\$$schema$$.java) [Line 21, Column 29]
  Error: Unable to call `the return value of (prop["items"])["format"]`, which is undefined or falsey
    at Object._prettifyError (C:\Users\myUser\AppData\Roaming\npm\node_modules\@asyncapi\generator\node_modules\nunjucks\src\lib.js:36:11)
    at C:\Users\myUser\AppData\Roaming\npm\node_modules\@asyncapi\generator\node_modules\nunjucks\src\environment.js:561:19
    at Template.root [as rootRenderFunc] (eval at _compile (C:\Users\myUser\AppData\Roaming\npm\node_modules\@asyncapi\generator\node_modules\nunjucks\src\environment.js:631:18), <anonymous>:1180:3)
    at Template.render (C:\Users\myUser\AppData\Roaming\npm\node_modules\@asyncapi\generator\node_modules\nunjucks\src\environment.js:550:10)
    at Environment.renderString (C:\Users\myUser\AppData\Roaming\npm\node_modules\@asyncapi\generator\node_modules\nunjucks\src\environment.js:378:17)
    at C:\Users\myUser\AppData\Roaming\npm\node_modules\@asyncapi\generator\lib\generator.js:595:21
    at new Promise (<anonymous>)
    at Generator.renderString (C:\Users\myUser\AppData\Roaming\npm\node_modules\@asyncapi\generator\lib\generator.js:594:12)
    at Generator.renderFile (C:\Users\myUser\AppData\Roaming\npm\node_modules\@asyncapi\generator\lib\generator.js:618:17)
    at async Generator.generateSeparateFile (C:\Users\myUser\AppData\Roaming\npm\node_modules\@asyncapi\generator\lib\generator.js:534:21)

After removing the
$ref: '#/components/schemas/iAmAnArrayWithRefThatWillNotLetYouGenerate'
and setting inline the object the generation was successfull.

Another issue is that after the generation if I have an enumeration with Dash '-' then it is not replaced with an underscore

Could you please investigate it when you have some time?

Ps i am attaching you the yaml file in a TXT format as it does not let me attach it as a yaml
failingExample.yaml.txt

Generation of the java model is not correct with an example of "anyOf"

Describe the bug

The model java class generated doesn't seem to be correct when I try to generate an example with some "anyOf" schema element. For example the "payload" variable is declared with AnonymousSchema1 class which doesn't exist.

This is the content of the TestMessages.java :

package be.test.model;

import java.util.Objects;


public class TestMessages {
    
    private AnonymousSchema1 payload;

    public AnonymousSchema1 getPayload() {
        return payload;
    }

    public void setPayload(AnonymousSchema1 payload) {
        this.payload = payload;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        TestMessages event = (TestMessages) o;
        return Objects.equals(this.payload, event.payload);
    }

    @Override
    public int hashCode() {
        return Objects.hash(payload);
    }

    @Override
    public String toString() {
        return "class TestMessages {\n" +
                "    payload: " + toIndentedString(payload) + "\n" +
                "}";
    }

    /**
     * Convert the given object to string with each line indented by 4 spaces (except the first line).
     */
    private String toIndentedString(Object o) {
        if (o == null) {
            return "null";
        }
        return o.toString().replace("\n", "\n    ");
    }
}

How to Reproduce

You can use this yaml example to run the generation : https://github.com/asyncapi/asyncapi/blob/master/examples/2.0.0/anyof.yml

Expected behavior

I expected to have a new class created for the payload part.

Thanks for your help on this

Error: Cannot find module 'graceful-fs' (GitBash / Win10)

Describe the bug

Following your README.md steps to use the java-spring-template, I got the below error :-(

Something went wrong:
Error: Cannot find module 'graceful-fs'

Using GitBash on Windows 10

How to Reproduce

$ ag asyncapi.yaml @asyncapi/java-spring-template -o ./src
npm http fetch GET 200 https://registry.npmjs.org/@asyncapi%2fjava-spring-template 3036ms
npm http fetch GET 200 https://registry.npmjs.org/@asyncapi/java-spring-template/-/java-spring-template-0.19.0.tgz 3056ms
npm http fetch GET 304 https://registry.npmjs.org/tmp 238ms (from cache)
npm http fetch GET 304 https://registry.npmjs.org/fs-extra 242ms (from cache)
npm http fetch GET 200 https://registry.npmjs.org/tmp/-/tmp-0.2.1.tgz 227ms
npm http fetch GET 200 https://registry.npmjs.org/fs-extra/-/fs-extra-9.0.1.tgz 258ms
npm http fetch GET 200 https://registry.npmjs.org/@asyncapi%2fgenerator-filters 1016ms
npm http fetch GET 200 https://registry.npmjs.org/@asyncapi/generator-filters/-/generator-filters-1.0.0.tgz 232ms
npm http fetch GET 200 https://registry.npmjs.org/@asyncapi%2fgenerator-hooks 1792ms
npm http fetch GET 200 https://registry.npmjs.org/@asyncapi/generator-hooks/-/generator-hooks-0.1.0.tgz 223ms
npm http fetch GET 304 https://registry.npmjs.org/markdown-it 215ms (from cache)
npm http fetch GET 200 https://registry.npmjs.org/openapi-sampler 268ms
npm http fetch GET 200 https://registry.npmjs.org/openapi-sampler/-/openapi-sampler-1.0.0-beta.16.tgz 236ms
npm http fetch GET 200 https://registry.npmjs.org/markdown-it/-/markdown-it-10.0.0.tgz 376ms
npm http fetch GET 304 https://registry.npmjs.org/entities 202ms (from cache)
npm http fetch GET 200 https://registry.npmjs.org/json-pointer 202ms
npm http fetch GET 200 https://registry.npmjs.org/json-pointer/-/json-pointer-0.6.0.tgz 209ms
npm http fetch GET 200 https://registry.npmjs.org/foreach 229ms
npm http fetch GET 200 https://registry.npmjs.org/foreach/-/foreach-2.0.5.tgz 205ms
npm http fetch GET 304 https://registry.npmjs.org/jsonfile 203ms (from cache)
npm http fetch GET 304 https://registry.npmjs.org/graceful-fs 212ms (from cache)
npm http fetch GET 200 https://registry.npmjs.org/at-least-node 219ms
npm http fetch GET 304 https://registry.npmjs.org/universalify 223ms (from cache)
npm http fetch GET 200 https://registry.npmjs.org/jsonfile/-/jsonfile-6.0.1.tgz 207ms
npm http fetch GET 200 https://registry.npmjs.org/at-least-node/-/at-least-node-1.0.0.tgz 222ms
npm http fetch GET 200 https://registry.npmjs.org/universalify/-/universalify-1.0.0.tgz 219ms
npm http fetch GET 304 https://registry.npmjs.org/rimraf 213ms (from cache)
npm http fetch GET 304 https://registry.npmjs.org/glob 203ms (from cache)
npm http fetch GET 304 https://registry.npmjs.org/inflight 225ms (from cache)
npm http fetch GET 304 https://registry.npmjs.org/inherits 228ms (from cache)
npm http fetch GET 304 https://registry.npmjs.org/fs.realpath 235ms (from cache)
npm http fetch GET 304 https://registry.npmjs.org/once 235ms (from cache)
npm http fetch GET 304 https://registry.npmjs.org/path-is-absolute 237ms (from cache)
npm http fetch GET 304 https://registry.npmjs.org/wrappy 192ms (from cache)
npm http fetch GET 304 https://registry.npmjs.org/fsevents 230ms (from cache)
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@~2.1.2 (node_modules\chokidar\node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})

+ @asyncapi/[email protected]
added 22 packages from 13 contributors in 12.328s

14 packages are looking for funding
  run `npm fund` for details

Something went wrong:
Error: Cannot find module 'graceful-fs'
Require stack:
- C:\Users\johndoe\AppData\Roaming\npm\node_modules\@asyncapi\generator\node_modules\@asyncapi\java-spring-template\node_modules\fs-extra\lib\fs\index.js
- C:\Users\johndoe\AppData\Roaming\npm\node_modules\@asyncapi\generator\node_modules\@asyncapi\java-spring-template\node_modules\fs-extra\lib\index.js
- C:\Users\johndoe\AppData\Roaming\npm\node_modules\@asyncapi\generator\node_modules\@asyncapi\java-spring-template\hooks\05_packageProcessor.js
- C:\Users\johndoe\AppData\Roaming\npm\node_modules\@asyncapi\generator\lib\hooksRegistry.js
- C:\Users\johndoe\AppData\Roaming\npm\node_modules\@asyncapi\generator\lib\generator.js
- C:\Users\johndoe\AppData\Roaming\npm\node_modules\@asyncapi\generator\cli.js
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:965:15)
    at Function.Module._load (internal/modules/cjs/loader.js:841:27)
    at Module.require (internal/modules/cjs/loader.js:1025:19)
    at require (internal/modules/cjs/helpers.js:72:18)
    at Object.<anonymous> (C:\Users\johndoe\AppData\Roaming\npm\node_modules\@asyncapi\generator\node_modules\@asyncapi\java-spring-template\node_modules\fs-extra\lib\fs\index.js:5:12)
    at Module._compile (internal/modules/cjs/loader.js:1137:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1157:10)
    at Module.load (internal/modules/cjs/loader.js:985:32)
    at Function.Module._load (internal/modules/cjs/loader.js:878:14)
    at Module.require (internal/modules/cjs/loader.js:1025:19)
    at require (internal/modules/cjs/helpers.js:72:18)
    at Object.<anonymous> (C:\Users\johndoe\AppData\Roaming\npm\node_modules\@asyncapi\generator\node_modules\@asyncapi\java-spring-template\node_modules\fs-extra\lib\index.js:5:6)
    at Module._compile (internal/modules/cjs/loader.js:1137:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1157:10)
    at Module.load (internal/modules/cjs/loader.js:985:32)
    at Function.Module._load (internal/modules/cjs/loader.js:878:14)

$ npm --version
6.14.6

Steps to reproduce the issue. Attach all resources that can help us understand the issue:

Expected behavior

I had to npm install -g graceful-fs to solve this

Did you forget to define this dependency ?

allOf produces AnonymousSchemaX

Describe the bug

I have just started to look into code generation for AsyncAPI. I can see from #90 that allOf was realized using aggregation, but it seems to me that java-spring-template creates classes named AnonymousSchema<X> for usages of allOf where the involved schema should better be given a name.

How to Reproduce

The following example is derived from the official spec (see "Models with Polymorphism Support") and validated against the playground.
Original example:
As per my analysis, the AnonymousSchema<X> is caused by the lines 36, 52.

asyncapi: 2.0.0
info:
  title: Pet Service
  version: 1.0.0
  description: This service is in charge of processing pet updates
channels:
  sample/pet/updated/v1:
    publish:
      operationId: petUpdated
      summary: Pet Update
      description: Notify about Pet Update that has taken place
      message:
        $ref: '#/components/messages/PetNotificationMessage'
components:
  messages:
    PetNotificationMessage:
      headers: {}
      payload:
        $ref: '#/components/schemas/Cat'
  schemas:
    Pet:
      type: object
      discriminator: petType
      properties:
        name:
          type: string
        petType:
          type: string
      required:
        - name
        - petType
    Cat:  ## "Cat" will be used as the discriminator value
      description: A representation of a cat
      allOf:
        - $ref: '#/components/schemas/Pet'
        - type: object
          properties:
            huntingSkill:
              type: string
              description: The measured skill for hunting
              enum:
                - clueless
                - lazy
                - adventurous
                - aggressive
          required:
            - huntingSkill
    Dog:  ## "Dog" will be used as the discriminator value
      description: A representation of a dog
      allOf:
        - $ref: '#/components/schemas/Pet'
        - type: object
          properties:
            packSize:
              type: integer
              format: int32
              description: the size of the pack the dog is from
              minimum: 0
          required:
            - packSize

Created with: ag .\Events-Pet.aas2.yml @asyncapi/java-spring-template -o ..\..\generated\asyncapi

Modified example:

As expected, the generator schema does not generate any AnonymousSchema<X> if I wrap the object into a separate schema, so the allOf only contains $refs to named schemas. However, the example in the official AsyncAPI spec apparently does not see any need for such wrappers in their example case of polymorphism – and I think that's nice, because the wrappers bloat the schema, right?

asyncapi: 2.0.0
info:
  title: Pet Service
  version: 1.0.0
  description: This service is in charge of processing pet updates
channels:
  sample/pet/updated/v1:
    publish:
      operationId: petUpdated
      summary: Pet Update
      description: Notify about Pet Update that has taken place
      message:
        $ref: '#/components/messages/PetNotificationMessage'
components:
  messages:
    PetNotificationMessage:
      headers: {}
      payload:
        $ref: '#/components/schemas/CatWrapper'
  schemas:
    Pet:
      type: object
      discriminator: petType
      properties:
        name:
          type: string
        petType:
          type: string
      required:
        - name
        - petType
    CatWrapper:
      description: A representation of a cat
      allOf:
        - $ref: '#/components/schemas/Pet'
        - $ref: '#/components/schemas/Cat'
    DogWrapper:
      description: A representation of a dog
      allOf:
        - $ref: '#/components/schemas/Pet'
        - $ref: '#/components/schemas/Dog'
    Cat:
      type: object
      properties:
        huntingSkill:
          type: string
          description: The measured skill for hunting
          enum:
            - clueless
            - lazy
            - adventurous
            - aggressive
      required:
        - huntingSkill
    Dog:
      type: object
      properties:
        packSize:
          type: integer
          format: int32
          description: the size of the pack the dog is from
          minimum: 0
      required:
        - packSize

Expected behavior (for original example)

  • The generate classes to be
    ** Cat
    ** Dog
    ** Pet
    ** PetNotificationMessage
  • Cat and Dog to contain the Pet properties

because the official spec mentions polymorphism.

In case you disagree: Is the "modified example" the recommended approach, or what would you recommend in such a case?
My goal is definitely to avoid AnonymousSchema<X> because it is too cumbersome to work with.

The automated release is failing 🚨

🚨 The automated release from the master branch failed. 🚨

I recommend you give this issue a high priority, so other packages depending on you could benefit from your bug fixes and new features.

You can find below the list of errors reported by semantic-release. Each one of them has to be resolved in order to automatically publish your package. I’m sure you can resolve this 💪.

Errors are usually caused by a misconfiguration or an authentication problem. With each error reported below you will find explanation and guidance to help you to resolve it.

Once all the errors are resolved, semantic-release will release your package the next time you push a commit to the master branch. You can also manually restart the failed CI job that runs semantic-release.

If you are not sure how to resolve this, here is some links that can help you:

If those don’t help, or if this issue is reporting something you think isn’t right, you can always ask the humans behind semantic-release.


Cannot push to the Git repository.

semantic-release cannot push the version tag to the branch master on the remote Git repository with URL https://x-access-token:[secure]@github.com/asyncapi/java-spring-template.git.

This can be caused by:


Good luck with your project ✨

Your semantic-release bot 📦🚀

"Error: Template parameter "server" has not been defined" while trying to generate Java Spring Boot

I'm not able to use Java Spring Boot generator, it throws an error. I've tried using the example, I've downloaded the file, I've used my own asyncapi file that properly renders in playgraound, I've tried the same with docker command and it always throws the same error.

npm version
{
  npm: '7.13.0',
  node: '16.2.0',
  v8: '9.0.257.25-node.16',
  uv: '1.41.0',
  zlib: '1.2.11',
  brotli: '1.0.9',
  ares: '1.17.1',
  modules: '93',
  nghttp2: '1.43.0',
  napi: '8',
  llhttp: '6.0.1',
  openssl: '1.1.1k',
  cldr: '39.0',
  icu: '69.1',
  tz: '2021a',
  unicode: '13.0'
}
npm list -g
/usr/local/lib
├── @asyncapi/[email protected]
├── @asyncapi/[email protected]
├── [email protected]
├── [email protected]
└── [email protected]
ag https://bit.ly/asyncapi @asyncapi/java-spring-template -p server=production -o example
Something went wrong:
Error: Template parameter "server" has not been defined in the package.json file under generator property. Please make sure it's listed there before you use it in your template.
    at Object.get [as server] (/usr/local/lib/node_modules/@asyncapi/generator/lib/generator.js:136:19)
    at module.exports.validateTemplateConfig (/usr/local/lib/node_modules/@asyncapi/generator/lib/templateConfigValidator.js:24:59)
    at Generator.generate (/usr/local/lib/node_modules/@asyncapi/generator/lib/generator.js:183:5)
    at /usr/local/lib/node_modules/@asyncapi/generator/cli.js:154:9

Provide an option to enable validation

Reason/Context

Currently only validation annotations are provided in generated model.
But validation itself is not enabled.
Provide an option to enable validation.

Description

Configuration class must be updated to set up validator.

Kafka Config: Type info mapping are not avaible in the header

I was creating a simple Kafka producer code and consumer code using the following API definition

asyncapi: 2.0.0
info:
  title: Banking backend events
  version: 1.0.0
servers:
  development:
    url: localhost:{port}
    protocol: kafka
    variables:
      port:
        default: '9092'
channels:
  banking.transaction.000:
    description: |-
      This contains events related to transactions.
    publish:
      operationId: consumeTransactionEvent
      message:
        $ref: '#/components/messages/transactionEvent'
      bindings:
        kafka:
          groupId: myGroupId

components:
  messages:
    transactionEvent:
      name: trasactionEvent
      contentType: 'application/json'
      payload:
        $ref: '#/components/schemas/TransactionEventPayload'
  schemas:
    TransactionEventPayload:
      type: object
      properties:
        transactionId:
          description: Transaction Id
          type: string
        amount:
          type: integer

When I was posting a message to Kafka using the producer code and then consuming it from the consumer code, I was getting the following error :

java.lang.IllegalStateException: No type information in headers and no default type provided

I searched around this problem and I figured out there is something wrong with the config created for the producer.

I see that at this location:

props.put(JsonSerializer.ADD_TYPE_INFO_HEADERS, false);

but setting this to false causes the next line in the code i.e

props.put(JsonSerializer.TYPE_MAPPINGS,

to not add mapping in the header and hence on the consumer side it fails, since it can't find any mapping in the header.

Expected behavior

I guess the value has to be set to true to allow the producer to add the mapping to the header.

Issue 2:

There is one more issue I saw, the headers that are set while sending the message using the Kafka template send method inside the PublisherService are also not populated in the headers section of the message.

Replace native array with List to generate arrays

Reason/Context

Currently template generates native arrays [] for the type: array. That's a bit old fashioned approach and could be replaced with List.
OpenAPI generators are using List to handle type: array.

Description

Update $$objectSchema$$.java file. Replace [] with List.

Update MQTT generation

Reason/Context

Currently generated java code for MQTT protocol in most cases is not compilable.
Current version of implementation was inherited from this template for 1.0 version of spec.
Normal complex channel path of MQTT like a/b/+/c leads to generation of not correct code.

Description

Description of the protocol https://mosquitto.org/man/mqtt-7.html
Description of spring mqtt integration https://docs.spring.io/spring-integration/reference/html/mqtt.html
Use operationId to avoid problems with channel names.
Provide tests to make sure the code works.

Add toString to model generation

Reason/Context

tiString is helpful when user want to log received message.

Description

Override toString in model classes, approach from OpenAPI generation could be used as an example

Doubts about code generated for streetlights.yaml

I have some doubts about code generated with streetlights.yaml. There are some classes that I misunderstand

LightMeasured is a class that never is used in the generated code

On the other hand, handleReceiveLightMeasurement method at MessageHandlerService has this contract public void handleReceiveLightMeasurement(Message<?> message)

shouldnt it be public void handleReceiveLightMeasurement(Message message) { ???

PubishService Interface has methods like turnOn, turnOff, dimlight whose arguments are String instead of playLoad generated (TurnOnOffPlayload, DimLightPlayload). Is it right?

Add supportedProtocols in package.json for java-spring

Reason/Context

Please try answering few of those questions

  • Why we need this improvement?.
    To maintain consistency across generators.

  • How will this change help?
    We can know what are the protocols supported on one sight.

  • What is the motivation?
    Some of the generators got the key (supportedProtocols) but not here.

https://github.com/asyncapi/java-spring-template/blob/master/package.json#L70
https://github.com/asyncapi/nodejs-ws-template/blob/master/package.json#L69

Description

Please try answering few of those questions

  • What changes have to be introduced?
    L1 change: We have to introduce supportedProtocols key in package.json for the first cut.
    L2 change: Next we may need to check the spec file and see only the listed protocols are there before generating.

  • Will this be a breaking change?

L1 change will be just for readbility.
L2 change will allow only the certain sets of spec files which the protocols are supported for.

  • How could it be implemented/designed?
    We have to start by adding supportedProtocols key and value in package.json under generator

Recursive model

Describe the bug

I want to create tree structure which each object has list of the same types.

How to Reproduce

This is my schemas components
image

It is recursive tree model
image

And this is error
image

Expected behavior

As a user I want to be able to create recursive model eg. trees graphs etc.

gradle build fails for java-spring-template generated code.

Describe the bug

The generated code fails to build.

How to Reproduce

The code generated by ..
ag streetlights.yaml @asyncapi/java-spring-template -o generated/java-spring --force-write

fails to build using ...

gradle build

with the following errors ...

> Task :compileJava FAILED
/Users/johncatlin/Documents/asyncapi/generator/api/generated/java-spring/src/main/java/com/asyncapi/model/SentAt.java:30: error: illegal start of expression
    }
    ^
/Users/johncatlin/Documents/asyncapi/generator/api/generated/java-spring/src/main/java/com/asyncapi/service/CommandLinePublisher.java:18: error: <identifier> expected
        publisherService.("Hello World from event.lighting.measured");
                         ^
/Users/johncatlin/Documents/asyncapi/generator/api/generated/java-spring/src/main/java/com/asyncapi/service/PublisherService.java:13: error: <identifier> expected
    void (String data);
        ^
/Users/johncatlin/Documents/asyncapi/generator/api/generated/java-spring/src/main/java/com/asyncapi/service/MessageHandlerService.java:16: error: '(' expected
    public void handleEvent.lighting.measured(Message<?> message) {
                           ^
/Users/johncatlin/Documents/asyncapi/generator/api/generated/java-spring/src/main/java/com/asyncapi/service/MessageHandlerService.java:16: error: <identifier> expected
    public void handleEvent.lighting.measured(Message<?> message) {
                                             ^
/Users/johncatlin/Documents/asyncapi/generator/api/generated/java-spring/src/main/java/com/asyncapi/infrastructure/Config.java:40: error: ';' expected
    private String event.lighting.measuredTopic;
                        ^
/Users/johncatlin/Documents/asyncapi/generator/api/generated/java-spring/src/main/java/com/asyncapi/infrastructure/Config.java:40: error: <identifier> expected
    private String event.lighting.measuredTopic;
                                               ^
7 errors

FAILURE: Build failed with an exception.

Expected behavior

It should build without errors?

Support for Pulsar

Reason/Context

It would be nice to have support for Apache Pulsar (Kafka successor).

Description

One could build uppon pulsar-java-spring-boot-starter for the templates.
I don't know your policies on external libraries, though...

api.yml would probably look like this:

servers:
  my-pulsar:
    url: {protocol}://my.pulsar.domain:{port}
    protocol: {protocol}
    description: my pulsar broker
    variables:
      port:
        default: '6650'
      protocol:
        default: 'pulsar'

Java Spring Boot code generator fails on oneOf property

Description

Java Spring Boot code generator fails if any channel.{operation}.[publish/subscribe].message contains oneOf property.
In the example below I've used the asyncapi file from the public samples: https://bit.ly/asyncapi and modified

      message:
        $ref: '#/components/messages/ixOtaResponse'

to

      message:
        oneOf:
          - $ref: '#/components/messages/ixOtaResponse'

Steps to Reproduce

Versions:

npm ls -g

/usr/local/lib
├── [email protected]
├── @asyncapi/[email protected]
├── @asyncapi/[email protected]

Command:

ag --debug -o asyncapi asyncapi.yml @asyncapi/java-spring-template --force-write

@asyncapi/java-spring-template not found in local dependencies but found it installed as a global package.
Template sources taken from /usr/local/lib/node_modules/@asyncapi/java-spring-template.
Version of used template is 0.23.3.
Something went wrong:
Error: Unable to call `the return value of (the return value of (channel["publish"])["message"])["payload"]`, which is undefined or falsey
    at Object.callWrap (/usr/local/lib/node_modules/@asyncapi/generator/node_modules/nunjucks/src/runtime.js:266:11)
    at Template.root [as rootRenderFunc] (eval at _compile (/usr/local/lib/node_modules/@asyncapi/generator/node_modules/nunjucks/src/environment.js:633:18), <anonymous>:229:215)
    at Template.render (/usr/local/lib/node_modules/@asyncapi/generator/node_modules/nunjucks/src/environment.js:552:10)
    at Environment.renderString (/usr/local/lib/node_modules/@asyncapi/generator/node_modules/nunjucks/src/environment.js:380:17)
    at /usr/local/lib/node_modules/@asyncapi/generator/lib/renderer/nunjucks.js:32:14
    at new Promise (<anonymous>)
    at nunjucksExport.renderNunjucks (/usr/local/lib/node_modules/@asyncapi/generator/lib/renderer/nunjucks.js:31:10)
    at Generator.renderFile (/usr/local/lib/node_modules/@asyncapi/generator/lib/generator.js:701:12)
    at Generator.renderAndWriteToFile (/usr/local/lib/node_modules/@asyncapi/generator/lib/generator.js:615:27)
    at Generator.generateFile (/usr/local/lib/node_modules/@asyncapi/generator/lib/generator.js:665:5)

full AsyncAPI file:

asyncapi: 2.0.0
info:
  title: OTA API
  version: '1.0.0'
  description: OTA API
 
defaultContentType: application/json
 
channels:
  'ic.ix.ota.request.env':
    description: The topic on which Metro Connect OTA events may be produced and consumed
    parameters:
      env:
        $ref: '#/components/parameters/env'
    publish:
      operationId: installInternetExchangePort
      message:
        $ref: '#/components/messages/ixOtaInstallRequest'
  'ic.ix.ota.response.env':
    description: The topic on which Internet Exchange OTA events may be produced and consumed
    parameters:
      env:
        $ref: '#/components/parameters/env'
    subscribe:
      operationId: receiveInternetExchangePortsStatus
      message:
        oneOf:
          - $ref: '#/components/messages/ixOtaResponse'
 
components:
  messages:
    ixOtaInstallRequest:
      name: ixOtaInstallRequest
      title: Internet Exchange OTA Request
      contentType: application/json
      traits:
        - $ref: '#/components/messageTraits/otaHeaders'
      payload:
        $ref: "#/components/schemas/ixOtaRequestPayload"
    ixOtaResponse:
      name: ixOtaResponse
      title: Internet Exchange OTA Response
      summary: Check Internet Exchange port status
      contentType: application/json
      traits:
        - $ref: '#/components/messageTraits/otaHeaders'
      payload:
        $ref: "#/components/schemas/ixOtaResponsePayload"
 
  schemas:
    uuid:
      type: string
      format: uuid
    timestamp:
      type: string
      format: date-time
      example: 2020-12-14T09:01:24.669Z
    actionType:
      type: string
      enum:
        - INSTALL
      description: Type of the action
    eventType:
      type: string
      enum:
        - STARTED
        - VALIDATED
        - IPV4_IPV6_ALLOCATED
        - RDNS_RECORDS_RESERVED
        - SVC_CREATED
        - MLPE_CONFIGURED
        - COMPLETED
        - FAILED
      description: Type of the event
      example: COMPLETED
    ixOtaRequestPayload:
      type: object
      required:
        - timestamp
        - actionType
        - uuid
        - data
      properties:
        uuid:
          $ref: '#/components/schemas/uuid'
          description: ID of the event
        timestamp:
          $ref: '#/components/schemas/timestamp'
          description: Timestamp of the event
        actionType:
          $ref: '#/components/schemas/actionType'
        data:
          $ref: '#/components/schemas/ixOtaInstallRequestData'
    ixOtaResponsePayload:
      type: object
      required:
        - timestamp
        - eventType
        - uuid
        - data
      properties:
        uuid:
          $ref: '#/components/schemas/uuid'
          description: ID of the event
        timestamp:
          $ref: '#/components/schemas/timestamp'
          description: Timestamp of the event
        eventType:
          $ref: '#/components/schemas/eventType'
        data:
          $ref: '#/components/schemas/ixOtaResponseData'
    ixOtaInstallRequestData:
      type: object
      description: Internet Exchange OTA Install data
      required:
        - gtId
        - activity
      properties:
        gtId:
          type: string
          example: TIBCO_TRANSACTION_ID
          description: ID of the Tibco transaction
        activity:
          $ref: '#/components/schemas/activity'
    ixOtaResponseData:
      type: object
      required:
        - gtId
        - activity
        - retryable
      properties:
        gtId:
          type: string
          example: TIBCO_TRANSACTION_ID
          description: ID of the Tibco transaction
        activity:
          required:
            - id
          properties:
            id:
              $ref: '#/components/schemas/activityId'
            retryable:
              type: boolean
              description: Determines whether can be retied
            order:
              $ref: '#/components/schemas/order'
            ipV4Address:
              type: string
              example: 208.115.136.169
              description: Allocated IPv4
            ipV6Address:
              type: string
              example: 2001:504:0:3:0:1:9008:1
              description: Allocated IPv6
            reverseDnsV4:
              type: string
              example: 19008-CH1-ix.equinix.com
              description: rDNS used - generared or provided in the request
            reverseDnsV6:
              type: string
              example: 19008-CH1-ix.equinix.com
              description: rDNS used - generared or provided in the request
            ipV4Subnet:
              type: string
              example: 208:115:136:0/23
              description: Subnet determined basing on IBX
            ipV6Subnet:
              type: string
              example: 2001:504:0:4::/64
              description: Subnet determined basing on IBX
            isSvcCreated:
              type: boolean
              description: Whether a new SVC has been created
            svcId:
              type: string
              example: 61242
              description: ID of the SVC that was either chosen or created
            svcName:
              type: string
              example: 606992-CH1-IX-01-208.115.136.169
              description: Name of the SVC that was either chosen or created
        discrepanciesIpV4:
          type: array
          items:
            $ref: '#/components/schemas/discrepancyIpV4'
          description: IPv4 addresses in use to be investigated. Only available for COMPLETED and FAILED eventTypes
        discrepanciesIpV6:
          type: array
          items:
            $ref: '#/components/schemas/discrepancyIpV6'
          description: IPv6 addresses in use to be investigated. Only available for COMPLETED and FAILED eventTypes
        errors:
          $ref: '#/components/schemas/errors'
    errors:
      type: array
      minItems: 1
      items:
        $ref: '#/components/schemas/error'
    discrepancyIpV4:
      type: object
      required:
        - address
        - failedValidations
      properties:
        addressIpV4:
          type: string
          example: 89.187.101.240
          description: IPv4 addres that was found to be in use.
        reverseDnsV4:
          type: string
          example: 8237-WA1-ix.equinix.com
          description: Reverse DNS the address has been labeled with by OL.
        failedValidations:
          type: array
          items:
            $ref: '#/components/schemas/failedValidation'
    discrepancyIpV6:
      type: object
      required:
        - address
        - failedValidations
      properties:
        addressIpV6:
          type: string
          example: 2001:7f8:c3::123:3
          description: IPv6 addres that was found to be in use.
        reverseDnsV6:
          type: string
          example: 3.0.0.0.3.2.1.0.0.0.0.0.0.0.0.0.0.0.0.0
          description: Reverse DNS the address has been labeled with by OL.
        failedValidations:
          type: array
          items:
            $ref: '#/components/schemas/failedValidation'
    failedValidation:
      type: object
      required:
        - validation
      properties:
        validation:
          type: string
          descrition: Identifies which validation failed while checking address availability
          enum:
            - PTR_RECORD
            - CLIENT_PEER_TABLE_NOCC
            - PORT_TABLE_NOCC
            - ROUTE_SERVER
            - IP_MAN_SEARCH
            - ALLOCATION_FAILED
        message:
          type: string
          description: Detailed reason why address is considered to be in use.
    activity:
      type: object
      required:
        - id
        - order
        - account
        - config
        - asn
        - reverseDnsV4
        - reverseDnsV6
        - location
        - physicalPorts
      properties:
        id:
          $ref: '#/components/schemas/activityId'
        type:
          $ref: '#/components/schemas/activityType'
        order:
          $ref: '#/components/schemas/order'
        account:
          $ref: '#/components/schemas/account'
        asn:
          $ref: '#/components/schemas/asn'
        reverseDnsV4:
          $ref: '#/components/schemas/dns'
        reverseDnsV6:
          $ref: '#/components/schemas/dns'
        location:
          $ref: '#/components/schemas/location'
        lag:
          $ref: '#/components/schemas/lag'
        encapsulation:
          $ref: '#/components/schemas/encapsulation'
        peering:
          $ref: '#/components/schemas/peering'
        physicalPorts:
          type: array
          items:
            $ref: '#/components/schemas/physicalPort'
        macs:
          type: array
          items:
            $ref: '#/components/schemas/mac'
    encapsulation:
      type: object
      required:
        - type
      properties:
        type:
          $ref: '#/components/schemas/encapsulationType'
    peering:
      type: object
      required:
        - type
        - state
      properties:
        type:
          $ref: '#/components/schemas/peeringType'
        state:
          $ref: '#/components/schemas/peeringState'
    lag:
      type: object
      required:
        - groupId
        - type
      properties:
        code:
          $ref: '#/components/schemas/lagGroupId'
        type:
          $ref: '#/components/schemas/lagType'
    location:
      type: object
      required:
        - code
        - type
      properties:
        code:
          $ref: '#/components/schemas/locationCode'
        type:
          $ref: '#/components/schemas/locationType'
    physicalPort:
      type: object
      required:
        - id
      properties:
        id:
          $ref: '#/components/schemas/portId'
        crossConnectId:
          $ref: '#/components/schemas/crossConnectId'
    crossConnectId:
      type: string
      example: 21440243-A
      description: Serial Cable ID
    account:
      type: object
      required:
        - number
      properties:
        number:
          $ref: '#/components/schemas/accountNumber'
    port:
      type: object
      required:
        - id
        - crossConnectId
      properties:
        id:
          $ref: '#/components/schemas/portId'
        crossConnectId:
          $ref: '#/components/schemas/crossConnectId'
    encapsulationType:
      type: string
      enum:
        - UNTAGGED
        - QINQ
        - DOT1Q
      example: UNTAGGED
      description: Encapsulation Type
    asn:
      type: integer
      description: >
        Autonomous System Number
    dns:
      type: string
      example: www.google.com
      description: Reverse DNS
    peeringType:
      type: string
      enum:
        - PRIVATE
        - PUBLIC
      example: PRIVATE
      description: Peering Type
    peeringState:
      type: string
      enum:
        - PRE-TURN-UP
        - TURN-UP
        - ACTIVE
      example: PRE-TURN-UP
      description: Peering Type
    lagGroupId:
      type: integer
      example: 123
      description: Ling Aggregation Group Identifier
    lagType:
      type: string
      enum:
        - LACP
        - OTHER
      example: LACP
      description: LAG Type
    locationCode:
      type: string
      example: WA1
      description: Code of the location dependent on its type
    locationType:
      type: string
      enum:
        - IBX
      example: IBX
      description: Location type
    accountNumber:
      type: string
      example: 201271
      description: Customer account number
    portId:
      type: integer
      example: 80751
      description: NOCC port ID
    activityId:
      type: string
      pattern: '^3-[1-9][0-9]*$'
      example: 3-198716093143
      description: ID of the order activity
    mac:
      type: string
      pattern: '^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$'
      example: 3D-F2-C9-A6-B3-4F
      description: Media Access Control Address
    activityType:
      type: string
      enum:
        - INSTALL
      default: INSTALL
      description: Type of the order activity
    order:
      type: object
      required:
        - number
      properties:
        number:
          $ref: '#/components/schemas/orderNumber'
    orderNumber:
      type: string
      pattern: '^1-[1-9][0-9]*$'
      example: 1-198656015405
      description: ID of the order
 
    error:
      type: object
      description: Error entity
      required:
        - code
        - message
        - details
      properties:
        code:
          type: string
          example: EQ-1
          description: Error Code
        message:
          type: string
          description: Error Message
        details:
          type: string
          description: Error Details
 
  parameters:
    env:
      description: Environment
      schema:
        type: string
        enum:
          - prod
          - dr
          - uat
          - uat2
          - qa1
          - qa2
 
  messageTraits:
    otaHeaders:
      headers:
        type: object
        required:
          - messageKey
          - CorrelationId
        properties:
          messageKey:
            $ref: '#/components/schemas/uuid'
            description: Message Key
          CorrelationId:
            $ref: '#/components/schemas/uuid'
            description: Correlation UUID
          Version:
            type: string
            enum:
              - v1
              - v2
            description: Version

Expected behavior

The code generation tool should work without error.

The automated release is failing 🚨

🚨 The automated release from the master branch failed. 🚨

I recommend you give this issue a high priority, so other packages depending on you could benefit from your bug fixes and new features.

You can find below the list of errors reported by semantic-release. Each one of them has to be resolved in order to automatically publish your package. I’m sure you can resolve this 💪.

Errors are usually caused by a misconfiguration or an authentication problem. With each error reported below you will find explanation and guidance to help you to resolve it.

Once all the errors are resolved, semantic-release will release your package the next time you push a commit to the master branch. You can also manually restart the failed CI job that runs semantic-release.

If you are not sure how to resolve this, here is some links that can help you:

If those don’t help, or if this issue is reporting something you think isn’t right, you can always ask the humans behind semantic-release.


Cannot push to the Git repository.

semantic-release cannot push the version tag to the branch master on the remote Git repository with URL https://x-access-token:[secure]@github.com/asyncapi/java-spring-template.git.

This can be caused by:


Good luck with your project ✨

Your semantic-release bot 📦🚀

Maven plugin to have the Java files generated automatically during build

Hi,
Is there a maven plugin for this project that we could use? It would be great if we could use this project in our maven based spring boot application and we would like to generate the classes during a maven build, not manually.

Reason/Context

Please try answering few of those questions

  • Why we need this improvement? To generate java files automatically during build, not manually.
  • How will this change help? It would make the generation faster and smoother.
  • What is the motivation? To be able to use a plugin that generates the files.

Description

Please try answering few of those questions

  • What changes have to be introduced? I am not entirely sure.
  • Will this be a breaking change? I don't think so.
  • How could it be implemented/designed?
  1. Creating plugin that does the npm install and ag commands
  2. Adding parameter options
  3. Uploading the plugin in a public place

Best regards,
Laszlo

Project build fails with Template Render Error

Describe the bug

Building this project produces the following error:

Something went wrong:
Template render error: (node_modules\@asyncapi\generator\node_modules\@asyncapi\java-spring-template\template\src\main\java\com\asyncapi\model\$$objectSchema$$.java) [Line 135, Column 90]
  ReferenceError: obj is not defined
    at Object._prettifyError (node_modules\nunjucks\src\lib.js:36:11)
    at node_modules\nunjucks\src\environment.js:561:19
    at Template.root [as rootRenderFunc] (eval at _compile (node_modules\@asyncapi\generator\node_modules\nunjucks\src\environment.js:631:18), <anonymous>:1532:3)
    at Template.render (node_modules\@asyncapi\generator\node_modules\nunjucks\src\environment.js:550:10)
    at Environment.renderString (node_modules\@asyncapi\generator\node_modules\nunjucks\src\environment.js:378:17)
    at node-v14.15.3-win-x64\node-v14.15.3-win-x64\node_modules\@asyncapi\generator\lib\renderer\nunjucks.js:32:14
    at new Promise (<anonymous>)
    at nunjucksExport.renderNunjucks (node_modules\@asyncapi\generator\lib\renderer\nunjucks.js:31:10)
    at Generator.renderFile (node_modules\@asyncapi\generator\lib\generator.js:678:12)
    at async Generator.renderAndWriteToFile (node_modules\@asyncapi\generator\lib\generator.js:593:28)
    at async Generator.generateSeparateFile (node_modules\@asyncapi\generator\lib\generator.js:580:5)
    at async Promise.all (index 0)
    at async Generator.filesGenerationHandler (node_modules\@asyncapi\generator\lib\generator.js:508:9)
    at async Walker.<anonymous> (node_modules\@asyncapi\generator\lib\generator.js:442:11)

unless java-spring-template is downgraded to version 0.20.1.

How to Reproduce

  1. Install AsyncAPI
  2. Clone this project
  3. Run npm install -g graceful-fs to bypass issue #80
  4. Run ag -o <dir> wpilib-ws-schema/schema/wpilib-ws.yaml @asyncapi/java-spring-template
  5. Run ag -o <dir> wpilib-ws-schema/schema/wpilib-ws.yaml @asyncapi/[email protected]

Expected behavior

The code should build without errors on the latest version of java-spring-template

Generalize Kafka properties

Reason/Context

In the potential feature #7 properties for kafka connect defined as custom properties with predefined values in application.yml. They are hardcoded and it's not clear whenever they should be changed or not. (Ofc if you know Kafka, it's evident for you)
Consider two improvement:

  1. Use spring-kafka library properties to configure consequent parameters.
    2.a) Define those properties as template parameters
    2.b) Move those properties to AsyncAPI spec, perhaps somewhere in server definition.

Description

For point one spring-kafka library docs could help.
For point two A:
https://github.com/asyncapi/generator/blob/master/docs/authoring.md#configuration-file
Example here - https://github.com/asyncapi/html-template#supported-parameters
For point two B:
Expand kafka binding for server https://github.com/asyncapi/bindings/tree/master/kafka#server or just define via extensions to use only in this template.

NPM certificate chain issue

Hi,

Describe the bug

I am trying to run the command to generate the files:
ag src/main/resource/asyncapi.yml -o target/asyncapi @asyncapi/java-spring-template

But I get this error:

Something went wrong:
FetchError: request to https://registry.npmjs.org/@asyncapi%2fjava-spring-template failed, reason: self signed certificate in certificate chain

I even tried to npm config set strict-ssl false before running the above command but I got the same results.

Do you have any suggestions?

Best regards,
Laszlo

Expected behavior

A clear and concise description of what you expected to happen.

Support of TLS for Kafka

Reason/Context

Currently TLS are totally ignored in the template.
Clients of Kafka communicate directly to the brokers and so, to support secure communication clients must configure it.

Description

Add parameter to enable security configuration into generated result.
Set of spring properties:

spring.kafka.ssl.key-password= # Password of the private key in the key store file.
spring.kafka.ssl.keystore-location= # Location of the key store file.
spring.kafka.ssl.keystore-password= # Store password for the key store file.
spring.kafka.ssl.keystore-type= # Type of the key store.
spring.kafka.ssl.protocol= # SSL protocol to use.
spring.kafka.ssl.truststore-location= # Location of the trust store file.
spring.kafka.ssl.truststore-password= # Store password for the trust store file.
spring.kafka.ssl.truststore-type= # Type of the trust store.

Add parameter to enable equals/hashCode generation in model

Reason/Context

OpenAPI by default generates equals and hashCode override for model classes.
Support the same function and add parameter to disable it.

Description

Use OpenAPI generation as an example.
Add param of template to disable

The automated release is failing 🚨

🚨 The automated release from the master branch failed. 🚨

I recommend you give this issue a high priority, so other packages depending on you could benefit from your bug fixes and new features.

You can find below the list of errors reported by semantic-release. Each one of them has to be resolved in order to automatically publish your package. I’m sure you can resolve this 💪.

Errors are usually caused by a misconfiguration or an authentication problem. With each error reported below you will find explanation and guidance to help you to resolve it.

Once all the errors are resolved, semantic-release will release your package the next time you push a commit to the master branch. You can also manually restart the failed CI job that runs semantic-release.

If you are not sure how to resolve this, here is some links that can help you:

If those don’t help, or if this issue is reporting something you think isn’t right, you can always ask the humans behind semantic-release.


Cannot push to the Git repository.

semantic-release cannot push the version tag to the branch master on the remote Git repository with URL https://x-access-token:[secure]@github.com/asyncapi/java-spring-template.git.

This can be caused by:


Good luck with your project ✨

Your semantic-release bot 📦🚀

Support of opposite side application generation

Reason/Context

As you know swagger allows to generate both server and client parts by one OpenAPI file. For sure, when we define "publish" and "subscribe" there is no clear "server" or "client". It is just about the application which could produce specified "subscribe" messages and consume specified "publish" messages.
Perhaps, generation of another side of communication makes sense. The application that could put messages to "publish" channel, so we could consume them, and read messages from "subscribe" channel.
At least this will be very fast way to create mock to test of main application.
Of course, there some obstacles e.g. for kafka the "groupId" binding is required to consume messages from topic. So, complete generation of "other" side could be not complete without modification of AsyncAPI spec file.

Description

The positive point, that in general to generate the opposite site application we should just switch "publish" to "subscribe" and vice-versa.
Enabling of this mode could be done by flag for generator.

Improve generation of docker-compose with brokers

Reason/Context

Currently template contains hardcoded docker-compose with rabbitmq.
It is not very convenient e.g. when you have kafka protocol.
Having a docker-compose with relevant protocol implementer could simply run of generated template.

Description

Add check for protocol in docker-compose.
Add relevant brokers for mqtt and kafka protocols

Validation check against ReadMe MUST requirements

Reason/Context

For the correct generation template require from AsynAPI to MUST have some parameters which is optional from spec point of view.
Currently the not-compilable code will be the result if user will ignore requirements from ReadMe.
See also #57

Description

Add hook generator:before to check for specific parameters in AsyncAPI file.
Produce error message for the user with description what should be added to AsyncAPI.

Ability to only generate model classes

Reason/Context

Please try answering few of those questions

  • Why we need this improvement?
    Currently, the generator only works for greenfield projects. If I already have a project and adding in a new AsyncAPI, I need to do this in another directory and manually copy files over.

  • How will this change help?
    Can make the generation of the model part of mvn and follow standard target/generated-sources flow

  • What is the motivation?
    I only need the model for my purposes. Most other spec -> generators support this flow (i.e.: swagger/openapi)

Description

Please try answering few of those questions

  • What changes have to be introduced?
    Only the model classes should be generated, everything else would be skipped.

  • Will this be a breaking change?
    I'd expect not, as it would be another param which controls the flow

  • How could it be implemented/designed?
    Not sure, I had a quick look but it seems the generators copy files over and then process them. would need the ability to control what is copied into the target directory.

Impossible to generate fields of wrapper type like java.lang.Integer, java.lang.Long in model classes

How to Reproduce

example.yaml

asyncapi: '2.0.0'
info:
  title: Streetlights API
  version: '1.0.0'
  description: |
    The Smartylighting Streetlights API allows you
    to remotely manage the city lights.
  license:
    name: Apache 2.0
    url: 'https://www.apache.org/licenses/LICENSE-2.0'

servers:
  production:
    url: kafka.bootstrap:{port}
    protocol: kafka
    variables:
      port:
        default: '9092'
        enum:
          - '9092'
          - '9093'

channels:
  event.lighting.measured:
    publish:
      bindings:
        kafka:
          groupId: my-group
      operationId: readLightMeasurement
      message:
        $ref: '#/components/messages/lightMeasured'
    subscribe:
      operationId: updateLightMeasurement
      message:
        $ref: '#/components/messages/lightMeasured'
components:
  messages:
    lightMeasured:
      summary: Inform about environmental lighting conditions for a particular streetlight.
      payload:
        $ref: "#/components/schemas/lightMeasuredPayload"
  schemas:
    lightMeasuredPayload:
      type: object
      properties:
        lumens:
          type: integer
          minimum: 0
          description: Light intensity measured in lumens.
        sentAt:
          $ref: "#/components/schemas/sentAt"
    sentAt:
      type: string
      format: date-time
      description: Date and time when the message was sent.

Result model

public class LightMeasuredPayload {
    
    private @Valid int lumens;
    
    private @Valid java.time.OffsetDateTime sentAt;
    
    //Getters, setters, etc.
}

Property lumens is not mandatory, that's why there should be possibility to use for it type "java.lang.Integer" in order to be able to assign null when it doesn't present.

Expected behavior

Possibility to generate code that use wrapper types like java.lang.Integer, java.lang.Long, java.lang.Double, etc.

No source code generated when generation ran with a packageName starting with "com."

Nothing is generated under src/main/java when I run the code generation with javaPackage starting with "com"

for example this generate nothing :
ag -o testGeneration2 -p javaPackage=com.test ./src/main/resources/transaction-asyncapi.yaml @asyncapi/java-spring-template --force-write

but these 2 run are working :
ag -o testGeneration2 -p javaPackage=com2.test ./src/main/resources/transaction-asyncapi.yaml @asyncapi/java-spring-template --force-write

ag -o testGeneration2 -p javaPackage=com2.com.test ./src/main/resources/transaction-asyncapi.yaml @asyncapi/java-spring-template --force-write

Add support of allOf

Reason/Context

Add support of allOf keyword for model generation.

Description

Aggregation pattern is mostly suitable to present allOf relation in Java

Add generation of enums to the model

Reason/Context

OpenAPI supports generation of java enum in case of type: string of property.
At least this level of support should be reached.
Perhaps, enum generation could be also implimented for type: integer

Description

Use inner enum class in model class file.
OpenAPI generation could be a good example.

Cleanup GitHub Actions workflows

Context

  1. We want to make sure we have healthy community and people respec each other in GitHub. We want to monitor all comments in every repository and analyze sentiments to identify negative ones and get proper notification. Idea is to use GitHub Actions for it, to check sentiments with Google Natural Language API and post negative comments to Slack for review.

  2. We manage community files in global .github repo, and we have GitHub Funding config file there too. As a result we need to cleanup all the repos to remove .github/FUNDING.yml

  3. Start supporting new GitHub pull request event that allows gives access to GITHUB_TOKEN with write access. Fix welcome contributors workflow is needed.

  4. We want to automatically merge Pull Requests that are submitted by Dependanbot. New workflow needs to be added, or if already existins it needs to be modified

Description

  1. Add this workflow file called sentiment-analysis.yml to .github/workflows (create it if it doesn't exist yet) directory: https://gist.github.com/derberg/ab362e4b37f542e7e1813e67b7cb11ee
    Proper secrets are already added to GitHub organization so it is as simple as adding above file to workflows dir.
  2. Remove .github/FUNDING.yml if it exists
  3. If not done already rename pull_request from line 4 to pull_request_target in .github/workflows/welcome-first-time-contrib.yml file
  4. Create new file called automerge.yml with the following content: https://gist.github.com/derberg/024814a26959d54f683e7bd68d68f007
    If the repository already has a file called automerge-release-pr-bump.yml than rename it and adjust if statements to check github.actor == 'asyncapi-bot' || github.actor == 'dependabot[bot]' || github.actor == 'dependabot-preview[bot]' instead of github.actor == 'asyncapi-bot'

Generated project does not compile

Hi! First of all thanks for working on developing a tooling around AsyncAPI 😃

The following report is almost identical of the one I've just opened here: asyncapi/java-spring-cloud-stream-template#58

Describe the bug

When using the example reference AsyncAPI definition (https://bit.ly/asyncapi) which is using camelCase for schemas, the generated project is not Java compliant and hence does not build.

The generated model classes (the schemas) are in a file named in camelCase.java whilst the class definition itself is in PascalCase.
The above example results in:

  • File name: dimLightPayload.java
  • Class definition: public class DimLightPayload

Here is the console output:

$ gradle compileJava

> Task :compileJava
.../src/main/java/com/asyncapi/model/dimLight.java:6: error: class DimLight is public, should be declared in a file named DimLight.java
public class DimLight {
       ^
.../src/main/java/com/asyncapi/model/dimLightPayload.java:14: error: class DimLightPayload is public, should be declared in a file named DimLightPayload.java
public class DimLightPayload {
       ^
.../src/main/java/com/asyncapi/model/lightMeasured.java:6: 
error: class LightMeasured is public, should be declared in a file named LightMeasured.java
public class LightMeasured {
       ^
.../src/main/java/com/asyncapi/model/lightMeasuredPayload.java:14: error: class LightMeasuredPayload is public, should be declared in a file named LightMeasuredPayload.java
public class LightMeasuredPayload {
       ^
.../src/main/java/com/asyncapi/model/turnOnOff.java:6: error: class TurnOnOff is public, should be declared in a file named TurnOnOff.java
public class TurnOnOff {
       ^
.../src/main/java/com/asyncapi/model/turnOnOffPayload.java:14: error: class TurnOnOffPayload is public, should be declared in a file named TurnOnOffPayload.java
public class TurnOnOffPayload {
       ^
6 errors

> Task :compileJava FAILED

So the file name should be always switched to PascalCase as its being done with the class name itself (following Java conventions).

I've also find the problem in the section of messages:

  messages:
    LightMeasured:
      name: lightMeasured

where the name: of the message is in camelCase and also generates files and classes in the same incorrect way.

One should argue that the definition of the official sample API could be updated to turn schema names into PascalCase to help align conventions. In my personal guideline I always define schemas in PascalCase and parameters in camelCase, which semantically maps to classes (or data models) and arguments of a function respectively (I guess in Java and probably many other languages). What do you think @fmvilas ?

But giving the above thought aside, the Java/Spring generator should handle the casing properly 😁

How to Reproduce

npm install -g @asyncapi/generator
ag https://bit.ly/asyncapi @asyncapi/java-spring-template
gradle compileJava

Expected behavior

Let the generated code to compile out-of-the-box.

Thanks! 🙏 😃

Payload don't generated with avro schema

Hi,

When I try to generate code with asyncapi specification with avro schema , payload class is not being generated.

I got classes references with names like AnonymousSchema5. Further, this class is not being generated

I have used 1.0.0-rc.7 generator version.

Attach the asyncapi specification used
asyncapi_kafka_avro.zip

Please provide documentation

when i run:
ag -o foo --force-write spec.yaml java-spring

I get following error:
Error: 404 Not Found - GET https://registry.npmjs.org/java-spring - Not found

As work around i cloned this directory and changed the generator.js to:

      //const { name: templatePkgName, path: templatePkgPath } = await this.installTemplate(this.install);
      this.templateDir = this.templateName;
      this.templateName = this.templateName;

This results in an empty template.
Can some one please provide a tutorial.

Wrong parser API usage for mqtt and amqp

Describe the bug

Due to following errors in API usage generation falls down:
.bindings('amqp') instead of .binding('amqp')
.bindings('mqtt') instead of .binding('mqtt')
variables(port) instead of variable('port')

How to Reproduce

Run with

servers:
  production:
    url: api.streetlights.smartylighting.com:{port}
    protocol: mqtt
    description: Test broker
    variables:
      port:
        description: Secure connection (TLS) is available through port 8883.
        default: '1883'
        enum:
          - '1883'
          - '8883'

Expected behavior

Template generates without errors

invalid render regexp value for `javax.validation.constraints.@Pattern` annotation of models

How to Reproduce

example.yaml

asyncapi: 2.0.0
info:
  title: Example spec
  version: 1.0.0
channels:
  some/channel:
    subscribe:
      message:
        $ref: '#/components/messages/ExampleMessage'
components:
  messages:
    ExampleMessage:
      payload:
        $ref: '#/components/schemas/ExamplePayload'
  schemas:
    ExamplePayload:
      type: object
      properties:
        p1:
          type: boolean
        p2:
          type: string
          pattern: ^\w{1,64}$

result model

public class ExamplePayload {
    
    private @Valid boolean p1;
    
    private @Valid String p2;
  
    @JsonProperty("p1")
    public boolean getP1() {
        return p1;
    }

    public void setP1(boolean p1) {
        this.p1 = p1;
    }
    
    @JsonProperty("p2")@Pattern(regexp="^\w{1,64}$") // <-- invalid regexp value, must be @Pattern(regexp="^\\w{1,64}$")
    public String getP2() {
        return p2;
    }

Expected behavior

The backslash character ('\') serves to introduce escaped constructs, as defined in the table above, as well as to quote characters that otherwise would be interpreted as unescaped constructs. Thus the expression \\ matches a single backslash and \{ matches a left brace.

https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html

Command line example does not work with option -p

Describe the bug

While using the Command Line example for the Template in order to generate Java code I've found a bug that does not let the generator create the required schemas described in the .yml file.

How to Reproduce

After Installing the required generator with the following command:
npm install -g @asyncapi/generator
I've tried using the following command as described in the example:
ag -o ./bob -p javaPackage=test.testing asyncapi.yml @asyncapi/java-spring-template
The result is the creation of the folder bob in the desired location but then the class that should have been generated are not visible and are not generated, in other words the folder bob/src/main/java/test/testing/ is empty and does not contain any desired class.
While debugging I've tried removing the -p option and the relative parameter javaPackage, therefore using the following command:
ag -o ./bob asyncapi.yml @asyncapi/java-spring-template
With these line I've been able to make the generator create all the desired java class in the specified folder, the problem is that I am not able to specify using the option -p the desired Java Package.

Expected behavior

As described above I'd like to have the option to generate java class starting from my .yml specification file in the desired output directory and with the specified javaPackage using the -p option.

Cannot read property 'startsWith' of undefined : generation example of oneOf

Describe the bug

An error occur during the generation of an example of "oneOf". Details of the error si below.
I dont know if this asyncapi example can be used like this or not.

Something went wrong:

Template render error: (/usr/local/lib/node_modules/@asyncapi/generator/node_modules/@asyncapi/java-spring-template/template/src/test/java/com/asyncapi/SimpleKafkaTest.java) [Line 13, Column 64]
  TypeError: Cannot read property 'startsWith' of undefined
    at Object._prettifyError (/usr/local/lib/node_modules/@asyncapi/generator/node_modules/nunjucks/src/lib.js:36:11)
    at /usr/local/lib/node_modules/@asyncapi/generator/node_modules/nunjucks/src/environment.js:561:19
    at Template.root [as rootRenderFunc] (eval at _compile (/usr/local/lib/node_modules/@asyncapi/generator/node_modules/nunjucks/src/environment.js:631:18), <anonymous>:649:3)
    at Template.render (/usr/local/lib/node_modules/@asyncapi/generator/node_modules/nunjucks/src/environment.js:550:10)
    at Environment.renderString (/usr/local/lib/node_modules/@asyncapi/generator/node_modules/nunjucks/src/environment.js:378:17)
    at /usr/local/lib/node_modules/@asyncapi/generator/lib/generator.js:616:21
    at new Promise (<anonymous>)
    at Generator.renderString (/usr/local/lib/node_modules/@asyncapi/generator/lib/generator.js:615:12)
    at Generator.renderFile (/usr/local/lib/node_modules/@asyncapi/generator/lib/generator.js:639:17)
    at async Generator.generateFile (/usr/local/lib/node_modules/@asyncapi/generator/lib/generator.js:580:27)

How to Reproduce

I tried to run the generation with the example below and I got the error.
https://github.com/asyncapi/asyncapi/blob/master/examples/2.0.0/oneof.yml

Add more descriptions as javadocs

Reason/Context

Improve plainness of generated code by adding descriptions from elements as javadocs.

Description

Channel or operation description for publish/subscribe methods, server description for addresses in application.yml

Add support of Kafka

Current template is outdated (doesn't support api spec 2.0.0) and doesn't contain logic for Kafka generation.
It would be good to have a template for Kafka on Java based on AsyncAPI.
Also, perhaps supportedProtocols should be documented in configuration.

Generating code from streetlights sample results in error

Description:
I am new to asyncapi and I tried to play around with generating code from a yaml spec.
After trying to get started with generating code using the java-spring-template I came across an obstacle.
Using the streetlights sample (and other samples) generating code results in the error below:

Something went wrong:
Template render error: 
(/home/osboxes/bin/nodejs/node-v12.18.3-linux-x64/lib/node_modules/@asyncapi/generator/node_modules/@asyncapi/java-spring-template/template/src/test/java/com/asyncapi/SimpleKafkaTest.java) [Line 13, Column 64]
  Error: Unable to call `the return value of (the return value of (channel["subscribe"])["message"])["payload"]`, which is undefined or falsey
    at Object._prettifyError (/home/osboxes/bin/nodejs/node-v12.18.3-linux-x64/lib/node_modules/@asyncapi/generator/node_modules/nunjucks/src/lib.js:36:11)
    at /home/osboxes/bin/nodejs/node-v12.18.3-linux-x64/lib/node_modules/@asyncapi/generator/node_modules/nunjucks/src/environment.js:561:19
    at Template.root [as rootRenderFunc] (eval at _compile (/home/osboxes/bin/nodejs/node-v12.18.3-linux-x64/lib/node_modules/@asyncapi/generator/node_modules/nunjucks/src/environment.js:631:18), <anonymous>:649:3)
    at Template.render (/home/osboxes/bin/nodejs/node-v12.18.3-linux-x64/lib/node_modules/@asyncapi/generator/node_modules/nunjucks/src/environment.js:550:10)
    at Environment.renderString (/home/osboxes/bin/nodejs/node-v12.18.3-linux-x64/lib/node_modules/@asyncapi/generator/node_modules/nunjucks/src/environment.js:378:17)
    at /home/osboxes/bin/nodejs/node-v12.18.3-linux-x64/lib/node_modules/@asyncapi/generator/lib/generator.js:610:21
    at new Promise (<anonymous>)
    at Generator.renderString (/home/osboxes/bin/nodejs/node-v12.18.3-linux-x64/lib/node_modules/@asyncapi/generator/lib/generator.js:609:12)
    at Generator.renderFile (/home/osboxes/bin/nodejs/node-v12.18.3-linux-x64/lib/node_modules/@asyncapi/generator/lib/generator.js:633:17)
    at async Generator.generateFile (/home/osboxes/bin/nodejs/node-v12.18.3-linux-x64/lib/node_modules/@asyncapi/generator/lib/generator.js:574:27)

Steps to reproduce the issue:

  • Using OS: CentOS 7
  • Using asyncapi generator (1.0.0-rc.5)
  • Use streetlights.yml
  • Run cmd: ag streetlights.yml @asyncapi/java-spring-template

Expectation:
A clarification/solution as to what is wrong.
Honestly, I used streetlights as an example, but I expect java-spring-template to create working java code for all samples out of the box in 2.0.0 examples.

Improve integration of code generation into CI process

Reason/Context

Continuous integration (CI) and continuous delivery (CD) is a set of operating principles that enable application development teams to deliver code changes more frequently and reliably.
The technical goal of CI is to establish a consistent and automated way to build, package, and test applications.
If project\company takes also the "API-first" approach that also means that generation of software artifacts based on API must be included into CI process.

Current version of template contains a bit bootstrap code which will never used in real productive operation systems which is not allow to use template generation as is without changes in CI process.

Description

  • At first mechanism to disable CommandLinePublisher.java generation should be introduced, it's good to have as an example of usage and check that code is work, but useless in real system.
  • Consider shift of MessageHandler and Publisher to interface-implementation approach with possibility to disable implementation generation.
  • Consider providing gradle/maven plugin. So users could easily integrate generation into the build process.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.