adding Vert.X Codegen

Adding the possibility to generate java Vert.X servers.
It uses Vertx-Swagger-Router project.
It can generate an Async callback version or a Rx version.
This commit is contained in:
Florent Chamfroy
2017-07-08 16:10:07 +02:00
parent 7ae4146a2b
commit d044498de4
69 changed files with 5891 additions and 0 deletions

View File

@@ -0,0 +1,18 @@
service.{{operationId}}({{#hasParams}}{{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{^hasMore}}, {{/hasMore}}{{/allParams}}{{/hasParams}}result -> {
if (result.succeeded())
{{#returnType}}
{{#isListContainer}}
message.reply(new JsonArray(Json.encode(result.result())).encodePrettily());
{{/isListContainer}}
{{^isListContainer}}
message.reply(new JsonObject(Json.encode(result.result())).encodePrettily());
{{/isListContainer}}
{{/returnType}}
{{^returnType}}
message.reply(null);
{{/returnType}}
else {
Throwable cause = result.cause();
manageError(message, cause, "{{#vendorExtensions}}{{x-serviceid}}{{/vendorExtensions}}");
}
});

View File

@@ -0,0 +1 @@
void {{operationId}}({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{^hasMore}}, {{/hasMore}}{{/allParams}}Handler<AsyncResult<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}>> handler);

View File

@@ -0,0 +1,22 @@
package {{rootPackage}};
public class MainApiException extends Exception {
private int statusCode;
private String statusMessage;
public MainApiException(int statusCode, String statusMessage) {
super();
this.statusCode = statusCode;
this.statusMessage = statusMessage;
}
public int getStatusCode() {
return statusCode;
}
public String getStatusMessage() {
return statusMessage;
}
public static final MainApiException INTERNAL_SERVER_ERROR = new MainApiException(500, "Internal Server Error");
}

View File

@@ -0,0 +1,57 @@
package {{rootPackage}};
import java.nio.charset.Charset;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.github.phiz71.vertx.swagger.router.OperationIdServiceIdResolver;
import com.github.phiz71.vertx.swagger.router.SwaggerRouter;
import io.swagger.models.Swagger;
import io.swagger.parser.SwaggerParser;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.Future;
import io.vertx.core.file.FileSystem;
import io.vertx.core.json.Json;
import io.vertx.core.logging.Logger;
import io.vertx.core.logging.LoggerFactory;
import io.vertx.ext.web.Router;
public class MainApiVerticle extends AbstractVerticle {
final static Logger LOGGER = LoggerFactory.getLogger(MainApiVerticle.class);
final Router router = Router.router(vertx);
@Override
public void start(Future<Void> startFuture) throws Exception {
Json.mapper.registerModule(new JavaTimeModule());
FileSystem vertxFileSystem = vertx.fileSystem();
vertxFileSystem.readFile("swagger.json", readFile -> {
if (readFile.succeeded()) {
Swagger swagger = new SwaggerParser().parse(readFile.result().toString(Charset.forName("utf-8")));
Router swaggerRouter = SwaggerRouter.swaggerRouter(Router.router(vertx), swagger, vertx.eventBus(), new OperationIdServiceIdResolver());
deployVerticles(startFuture);
vertx.createHttpServer()
.requestHandler(swaggerRouter::accept)
.listen({{serverPort}});
startFuture.complete();
} else {
startFuture.fail(readFile.cause());
}
});
}
public void deployVerticles(Future<Void> startFuture) {
{{#apiInfo}}{{#apis}}
vertx.deployVerticle("{{apiPackage}}.{{classname}}Verticle", res -> {
if (res.succeeded()) {
LOGGER.info("{{classname}}Verticle : Deployed");
} else {
startFuture.fail(res.cause());
LOGGER.error("{{classname}}Verticle : Deployement failed");
}
});
{{/apis}}{{/apiInfo}}
}
}

View File

@@ -0,0 +1 @@
Project generated on : {{generatedDate}}

View File

@@ -0,0 +1,18 @@
service.{{operationId}}({{#hasParams}}{{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}{{/hasParams}}).subscribe(
{{#returnType}}
result -> {
{{#isListContainer}}
message.reply(new JsonArray(Json.encode(result)).encodePrettily());
{{/isListContainer}}
{{^isListContainer}}
message.reply(new JsonObject(Json.encode(result)).encodePrettily());
{{/isListContainer}}
{{/returnType}}
{{^returnType}}
() -> {
message.reply(null);
{{/returnType}}
},
error -> {
manageError(message, error, "{{#vendorExtensions}}{{x-serviceid}}{{/vendorExtensions}}");
});

View File

@@ -0,0 +1 @@
public {{#returnType}}Single<{{{returnType}}}>{{/returnType}}{{^returnType}}Completable{{/returnType}} {{operationId}}({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}},{{/hasMore}}{{/allParams}});

View File

@@ -0,0 +1,31 @@
package {{package}};
{{#imports}}import {{import}};
{{/imports}}
{{#rxInterface}}
import rx.Completable;
import rx.Single;
{{/rxInterface}}
{{^rxInterface}}
import io.vertx.core.AsyncResult;
import io.vertx.core.Handler;
{{/rxInterface}}
import java.util.List;
import java.util.Map;
public interface {{classname}} {
{{#operations}}
{{#operation}}
//{{#vendorExtensions}}{{x-serviceid}}{{/vendorExtensions}}
{{#rxInterface}}
{{>RxMethod}}
{{/rxInterface}}
{{^rxInterface}}
{{>AsyncMethod}}
{{/rxInterface}}
{{/operation}}
{{/operations}}
}

View File

@@ -0,0 +1,14 @@
package {{package}};
{{#imports}}import {{import}};
{{/imports}}
public final class {{classname}}Exception extends MainApiException {
public {{classname}}Exception(int statusCode, String statusMessage) {
super(statusCode, statusMessage);
}
{{#operations}}{{#operation}}{{#responses}}{{^isDefault}}public static final {{classname}}Exception {{baseName}}_{{{operationId}}}_{{{code}}}_Exception = new {{classname}}Exception({{{code}}}, "{{{message}}}");
{{/isDefault}}{{/responses}}{{/operation}}{{/operations}}
}

View File

@@ -0,0 +1,82 @@
package {{package}};
import io.vertx.core.AbstractVerticle;
import io.vertx.core.eventbus.Message;
import io.vertx.core.json.Json;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.core.logging.Logger;
import io.vertx.core.logging.LoggerFactory;
{{#imports}}import {{import}};
{{/imports}}
import java.util.List;
import java.util.Map;
public class {{classname}}Verticle extends AbstractVerticle {
final static Logger LOGGER = LoggerFactory.getLogger({{classname}}Verticle.class);
{{#operations}}{{#operation}}{{#vendorExtensions}}final static String {{x-serviceid-varname}} = "{{x-serviceid}}";
{{/vendorExtensions}}{{/operation}}{{/operations}}
//TODO : create Implementation
{{classname}} service = new {{classname}}Impl();
@Override
public void start() throws Exception {
{{#operations}}{{#operation}}
//Consumer for {{#vendorExtensions}}{{x-serviceid}}{{/vendorExtensions}}
vertx.eventBus().<JsonObject> consumer({{#vendorExtensions}}{{x-serviceid-varname}}{{/vendorExtensions}}).handler(message -> {
try {
{{#hasParams}}
{{#allParams}}
{{#isListContainer}}
{{{dataType}}} {{paramName}} = Json.mapper.readValue(message.body().getJsonArray("{{baseName}}").encode(),
Json.mapper.getTypeFactory().constructCollectionType(List.class, {{{baseType}}}.class));
{{/isListContainer}}
{{^isListContainer}}
{{#isPrimitiveType}}
{{#isString}}
{{{dataType}}} {{paramName}} = message.body().getString("{{baseName}}");
{{/isString}}
{{^isString}}
{{{dataType}}} {{paramName}} = Json.mapper.readValue(message.body().getString("{{baseName}}"), {{{dataType}}}.class);
{{/isString}}
{{/isPrimitiveType}}
{{^isPrimitiveType}}
{{{dataType}}} {{paramName}} = Json.mapper.readValue(message.body().getJsonObject("{{baseName}}").encode(), {{{dataType}}}.class);
{{/isPrimitiveType}}
{{/isListContainer}}
{{/allParams}}
{{/hasParams}}
{{#rxInterface}}
{{>RxCall}}
{{/rxInterface}}
{{^rxInterface}}
{{>AsyncCall}}
{{/rxInterface}}
} catch (Exception e) {
logUnexpectedError("{{#vendorExtensions}}{{x-serviceid}}{{/vendorExtensions}}", e);
message.fail(MainApiException.INTERNAL_SERVER_ERROR.getStatusCode(), MainApiException.INTERNAL_SERVER_ERROR.getStatusMessage());
}
});
{{/operation}}{{/operations}}
}
private void manageError(Message<JsonObject> message, Throwable cause, String serviceName) {
int code = MainApiException.INTERNAL_SERVER_ERROR.getStatusCode();
String statusMessage = MainApiException.INTERNAL_SERVER_ERROR.getStatusMessage();
if (cause instanceof MainApiException) {
code = ((MainApiException)cause).getStatusCode();
statusMessage = ((MainApiException)cause).getStatusMessage();
} else {
logUnexpectedError(serviceName, cause);
}
message.fail(code, statusMessage);
}
private void logUnexpectedError(String serviceName, Throwable cause) {
LOGGER.error("Unexpected error in "+ serviceName, cause);
}
}

View File

@@ -0,0 +1,17 @@
public enum {{{datatypeWithEnum}}} {
{{#allowableValues}}{{#enumVars}}{{{name}}}({{{value}}}){{^-last}},
{{/-last}}{{#-last}};{{/-last}}{{/enumVars}}{{/allowableValues}}
private String value;
{{{datatypeWithEnum}}}(String value) {
this.value = value;
}
@Override
@JsonValue
public String toString() {
return value;
}
}

View File

@@ -0,0 +1,3 @@
public enum {{classname}} {
{{#allowableValues}}{{.}}{{^-last}}, {{/-last}}{{/allowableValues}}
}

View File

@@ -0,0 +1,12 @@
package {{package}};
import java.util.Objects;
{{#imports}}import {{import}};
{{/imports}}
{{#serializableModel}}import java.io.Serializable;
{{/serializableModel}}{{#models}}{{#model}}{{#description}}
/**
* {{description}}
**/
{{/description}}{{^description}}
{{/description}}{{#isEnum}}{{>enumOuterClass}}{{/isEnum}}{{^isEnum}}{{>pojo}}{{/isEnum}}{{/model}}{{/models}}

View File

@@ -0,0 +1,71 @@
@JsonInclude(JsonInclude.Include.NON_NULL)
public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#serializableModel}}implements Serializable{{/serializableModel}} {
{{#vars}}{{#isEnum}}
{{>enumClass}}{{/isEnum}}{{#items.isEnum}}{{#items}}
{{>enumClass}}{{/items}}{{/items.isEnum}}
private {{{datatypeWithEnum}}} {{name}} = {{{defaultValue}}};{{/vars}}
public {{classname}} () {
}
public {{classname}} ({{#vars}}{{{datatypeWithEnum}}} {{name}}{{#hasMore}}, {{/hasMore}}{{/vars}}) {
{{#vars}}
this.{{name}} = {{name}};
{{/vars}}
}
{{#vars}}
{{#vendorExtensions.extraAnnotation}}{{vendorExtensions.extraAnnotation}}{{/vendorExtensions.extraAnnotation}}
@JsonProperty("{{baseName}}")
public {{{datatypeWithEnum}}} {{getter}}() {
return {{name}};
}
public void {{setter}}({{{datatypeWithEnum}}} {{name}}) {
this.{{name}} = {{name}};
}
{{/vars}}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
{{classname}} {{classVarName}} = ({{classname}}) o;{{#hasVars}}
return {{#vars}}Objects.equals({{name}}, {{classVarName}}.{{name}}){{#hasMore}} &&
{{/hasMore}}{{^hasMore}};{{/hasMore}}{{/vars}}{{/hasVars}}{{^hasVars}}
return true;{{/hasVars}}
}
@Override
public int hashCode() {
return Objects.hash({{#vars}}{{name}}{{#hasMore}}, {{/hasMore}}{{/vars}});
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class {{classname}} {\n");
{{#parent}}sb.append(" ").append(toIndentedString(super.toString())).append("\n");{{/parent}}
{{#vars}}sb.append(" {{name}}: ").append(toIndentedString({{name}})).append("\n");
{{/vars}}sb.append("}");
return sb.toString();
}
/**
* 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 ");
}
}

View File

@@ -0,0 +1,91 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>{{groupId}}</groupId>
<artifactId>{{artifactId}}</artifactId>
<version>{{artifactVersion}}</version>
<packaging>jar</packaging>
<name>{{appName}}</name>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
<junit.version>4.12</junit.version>
<vertx.version>3.4.1</vertx.version>
<maven-compiler-plugin.version>3.3</maven-compiler-plugin.version>
<vertx-swagger-router.version>{{vertxSwaggerRouterVersion}}</vertx-swagger-router.version>
<maven-shade-plugin.version>2.3</maven-shade-plugin.version>
<jackson-datatype-jsr310.version>2.7.4</jackson-datatype-jsr310.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.vertx</groupId>
<artifactId>vertx-unit</artifactId>
<version>${vertx.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.github.phiz71</groupId>
<artifactId>vertx-swagger-router</artifactId>
<version>${vertx-swagger-router.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>${jackson-datatype-jsr310.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>${maven-shade-plugin.version}</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<transformers>
<transformer
implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<manifestEntries>
<Main-Class>io.vertx.core.Starter</Main-Class>
<Main-Verticle>{{rootPackage}}.MainApiVerticle</Main-Verticle>
</manifestEntries>
</transformer>
</transformers>
<artifactSet />
<outputFile>${project.build.directory}/${project.artifactId}-${project.version}-fat.jar</outputFile>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

View File

@@ -0,0 +1 @@
{{{fullSwagger}}}

View File

@@ -0,0 +1,30 @@
#
# Copyright 2014 Red Hat, Inc.
#
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Eclipse Public License v1.0
# and Apache License v2.0 which accompanies this distribution.
#
# The Eclipse Public License is available at
# http://www.eclipse.org/legal/epl-v10.html
#
# The Apache License v2.0 is available at
# http://www.opensource.org/licenses/apache2.0.php
#
# You may elect to redistribute this code under either of these licenses.
#
handlers=java.util.logging.ConsoleHandler,java.util.logging.FileHandler
java.util.logging.SimpleFormatter.format=%5$s %6$s\n
java.util.logging.ConsoleHandler.formatter=java.util.logging.SimpleFormatter
java.util.logging.ConsoleHandler.level=FINEST
java.util.logging.FileHandler.level=INFO
java.util.logging.FileHandler.formatter=io.vertx.core.logging.VertxLoggerFormatter
# Put the log in the system temporary directory
java.util.logging.FileHandler.pattern=vertx.log
.level=INFO
io.vertx.ext.web.level=FINEST
io.vertx.level=INFO
com.hazelcast.level=INFO
io.netty.util.internal.PlatformDependent.level=SEVERE