Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

feat: add support of web socket protocol #369

Draft
wants to merge 6 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,13 @@ asyncapi generate fromTemplate <asyncapi.yaml> @asyncapi/java-spring-template

You can replace `<asyncapi.yaml>` with local path or URL pointing to [any AsyncAPI document](https://raw.githubusercontent.com/asyncapi/java-spring-template/master/tests/mocks/kafka.yml).

#### Supported protocols

- Kafka
- AMQP
- MQTT
- WebSocket

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

Expand Down
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,8 @@
"supportedProtocols": [
"kafka",
"amqp",
"mqtt"
"mqtt",
"ws"
],
"nonRenderableFiles": [
"**/*.jar"
Expand Down
49 changes: 49 additions & 0 deletions partials/WebSocketConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
{% macro wsConfig(asyncapi, params) %}

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;

import javax.annotation.processing.Generated;
import java.net.URI;
import java.net.URISyntaxException;

@Generated(value="com.asyncapi.generator.template.spring", date="{{''|currentTime }}")
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends WebSocketMessageBrokerConfigurer {

{% for serverName, server in asyncapi.servers() %}
@Value("${ws.server.{{serverName}}}")
private String {{serverName}}Url;
{% endfor %}

@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic");
config.setApplicationDestinationPrefixes("/app");
}

@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
{% for serverName, server in asyncapi.servers() %}
registry.addEndpoint(getPath({{serverName}}Url));
registry.addEndpoint(getPath({{serverName}}Url)).withSockJS();
{% endfor %}
}

private String getPath(String serverURL) {
String path;
try {URI uri = null;
uri = new URI(serverURL);
path = uri.getPath();
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
return path;
}
}
{% endmacro %}
31 changes: 31 additions & 0 deletions partials/WebSocketPublisher.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
{% macro wsPublisher(asyncapi, params) %}

{% for channelName, channel in asyncapi.channels() %}
{%- if channel.hasSubscribe() %}
{%- for message in channel.subscribe().messages() %}
import {{params['userJavaPackage']}}.model.{{message.payload().uid() | camelCase | upperFirst}};
{%- endfor -%}
{% endif -%}
{% endfor %}
import javax.annotation.processing.Generated;

@Generated(value="com.asyncapi.generator.template.spring", date="{{''|currentTime }}")
public interface PublisherService {

{% for channelName, channel in asyncapi.channels() %}
{%- if channel.hasSubscribe() %}
{%- set hasParameters = channel.hasParameters() %}
{%- if channel.subscribe().hasMultipleMessages() %}
{%- set varName = "object" %}
{%- else %}
{%- set varName = channel.subscribe().message().payload().uid() | camelCase %}
{%- endif %}
{% if channel.description() or channel.subscribe().description() %}/**{% for line in channel.description() | splitByLines %}
* {{line | safe}}{% endfor %}{% for line in channel.subscribe().description() | splitByLines %}
* {{line | safe}}{% endfor %}
*/{% endif %}
public void {{channel.subscribe().id() | camelCase}}(Integer key, {{varName | upperFirst}} {{varName}}{% if hasParameters %}{%for parameterName, parameter in channel.parameters() %}, {% if parameter.schema().type() === 'object'%}{{parameterName | camelCase | upperFirst}}{% else %}{{parameter.schema().type() | toJavaType(false)}}{% endif %} {{parameterName | camelCase}}{% endfor %}{% endif %});
{%- endif %}
{%- endfor %}
}
{% endmacro %}
36 changes: 36 additions & 0 deletions partials/WebSocketPublisherImpl.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
{% macro wsPublisherImpl(asyncapi, params) %}

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
{% for channelName, channel in asyncapi.channels() %}
{%- if channel.hasSubscribe() %}
{%- for message in channel.subscribe().messages() %}
import {{params['userJavaPackage']}}.model.{{message.payload().uid() | camelCase | upperFirst}};
{%- endfor -%}
{% endif -%}
{% endfor %}
import javax.annotation.processing.Generated;

@Generated(value="com.asyncapi.generator.template.spring", date="{{''|currentTime }}")
@Service
public class PublisherServiceImpl implements PublisherService {
{% for channelName, channel in asyncapi.channels() %}
{%- if channel.hasSubscribe() %}
{%- set hasParameters = channel.hasParameters() %}
{%- set methodName = channel.subscribe().id() | camelCase %}
{%- if channel.subscribe().hasMultipleMessages() %}
{%- set varName = "object" %}
{%- else %}
{%- set varName = channel.subscribe().message().payload().uid() | camelCase %}
{%- endif %}
{% if channel.description() or channel.subscribe().description() %}/**{% for line in channel.description() | splitByLines %}
* {{line | safe}}{% endfor %}{% for line in channel.subscribe().description() | splitByLines %}
* {{line | safe}}{% endfor %}
*/{% endif %}
public void {{methodName}}(Integer key, {{varName | upperFirst}} {{varName}}{% if hasParameters %}{%for parameterName, parameter in channel.parameters() %}, {% if parameter.schema().type() === 'object'%}{{parameterName | camelCase | upperFirst}}{% else %}{{parameter.schema().type() | toJavaType(false)}}{% endif %} {{parameterName | camelCase}}{% endfor %}{% endif %}) {

}
{%- endif %}
{% endfor %}
}
{% endmacro %}
4 changes: 4 additions & 0 deletions template/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@ dependencies {
{%- if asyncapi | isProtocol('mqtt') %}
implementation('org.springframework.integration:spring-integration-mqtt')
{% endif -%}
{%- if asyncapi | isProtocol('ws') %}
implementation('org.springframework:spring-websocket')
implementation('org.springframework:spring-messaging')
{% endif -%}
{%- if asyncapi | isProtocol('kafka') %}
{%- if params.springBoot2 %}
implementation('org.springframework.kafka:spring-kafka:2.9.12')
Expand Down
12 changes: 12 additions & 0 deletions template/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,18 @@
<scope>compile</scope>
</dependency>
{% endif -%}
{%- if asyncapi | isProtocol('ws') %}
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-websocket</artifactId>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-messaging</artifactId>
<scope>compile</scope>
</dependency>
{% endif -%}
{%- if asyncapi | isProtocol('kafka') %}
{%- if params.springBoot2 %}
<dependency>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
{%- from "partials/AmqpConfig.java" import amqpConfig -%}
{%- from "partials/MqttConfig.java" import mqttConfig -%}
{%- from "partials/KafkaConfig.java" import kafkaConfig -%}
{%- from "partials/WebSocketConfig.java" import wsConfig -%}

{%- if asyncapi | isProtocol('amqp') -%}
{{- amqpConfig(asyncapi, params) -}}
Expand All @@ -12,4 +13,7 @@
{%- endif -%}
{%- if (asyncapi | isProtocol('kafka')) or (asyncapi | isProtocol('kafka-secure')) -%}
{{- kafkaConfig(asyncapi, params) -}}
{%- endif -%}
{%- if asyncapi | isProtocol('ws') -%}
{{- wsConfig(asyncapi, params) -}}
{%- endif -%}
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@
import org.springframework.beans.factory.annotation.Value;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Service;
{%- if asyncapi | isProtocol('ws') and hasPublish %}
import org.springframework.messaging.handler.annotation.MessageMapping;
{%- endif %}
{%- if asyncapi | isProtocol('kafka') and hasPublish %}
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.support.KafkaHeaders;
Expand Down Expand Up @@ -115,6 +118,11 @@ public class MessageHandlerService {
// parametrized listener
}
{%- endif %}
{% elif asyncapi | isProtocol('ws') %}
@MessageMapping("/{{channelName}}")
public void handle{{methodName | upperFirst}}({{typeName}} payload) {
LOGGER.info("Message received from {{- channelName -}} : " + payload);
}
{%- else %}
{%- if hasParameters %}
@Value("${mqtt.topic.{{-methodName-}}}")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,13 @@
{%- from "partials/CommonPublisher.java" import commonPublisher -%}
{%- from "partials/KafkaPublisher.java" import kafkaPublisher -%}
{%- from "partials/AmqpPublisher.java" import amqpPublisher -%}
{%- from "partials/WebSocketPublisher.java" import wsPublisher -%}
{%- if asyncapi | isProtocol('kafka') -%}
{{- kafkaPublisher(asyncapi, params) -}}
{%- elif asyncapi | isProtocol('amqp') -%}
{{- amqpPublisher(asyncapi, params) -}}
{%- elif asyncapi | isProtocol('ws') -%}
{{- wsPublisher(asyncapi, params) -}}
{%- else -%}
{{- commonPublisher(asyncapi, params) -}}
{%- endif -%}
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,13 @@
{%- from "partials/CommonPublisherImpl.java" import commonPublisherImpl -%}
{%- from "partials/KafkaPublisherImpl.java" import kafkaPublisherImpl -%}
{%- from "partials/AmqpPublisherImpl.java" import amqpPublisherImpl -%}
{%- from "partials/WebSocketPublisherImpl.java" import wsPublisherImpl -%}
{%- if asyncapi | isProtocol('kafka') -%}
{{- kafkaPublisherImpl(asyncapi, params) -}}
{%- elif asyncapi | isProtocol('amqp') -%}
{{- amqpPublisherImpl(asyncapi, params) -}}
{%- elif asyncapi | isProtocol('ws') -%}
{{- wsPublisherImpl(asyncapi, params) -}}
{%- else -%}
{{- commonPublisherImpl(asyncapi, params) -}}
{%- endif -%}
6 changes: 6 additions & 0 deletions template/src/main/resources/application.yml
Original file line number Diff line number Diff line change
Expand Up @@ -70,4 +70,10 @@ spring:
poll-timeout: {{params.listenerPollTimeout}}
concurrency: {{params.listenerConcurrency}}
{% endif %}
{% endif %}

{%- if asyncapi | isProtocol('ws') %}
ws:
server: {% for serverName, server in asyncapi.servers() %}
{{serverName}}: {% if server.variable('port') %}{{server.url() | replace('{port}', server.variable('port').defaultValue())}}{% else %}{{server.url()}}{% endif %}{% endfor %}
{% endif %}
45 changes: 45 additions & 0 deletions tests/mocks/ws.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
asyncapi: '2.0.0'
info:
title: Chat Application
version: '1.0.0'
description: A simple chat application using WebSocket protocol
servers:
production:
url: 'ws://example.com/websocket'
protocol: ws
description: Endpoint address for connections
channels:
chat:
description: Channel for sending messages
subscribe:
operationId: sendMessage
summary: Send a message
message:
$ref: '#/components/messages/ChatMessage'
chatResponse:
description: Channel for receiving messages
publish:
operationId: receiveMessage
summary: Receive a message
message:
$ref: '#/components/messages/ChatMessage'
components:
messages:
ChatMessage:
summary: The message in a chat
payload:
$ref: "#/components/schemas/MessagePayload"
schemas:
MessagePayload:
type: object
properties:
username:
type: string
content:
type: string
sentAt:
$ref: "#/components/schemas/sentAt"
sentAt:
type: string
format: date-time
description: Date and time when the message was sent.
Loading