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

Add new generator: Java Play Framework Server Generator #4943

Merged
merged 7 commits into from
Mar 10, 2017
Merged
Show file tree
Hide file tree
Changes from 3 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
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -909,6 +909,7 @@ Here are some companies/projects using Swagger Codegen in production. To add you
- [snapCX](https://snapcx.io)
- [SPINEN](http://www.spinen.com)
- [SRC](https://www.src.si/)
- [Stingray](http://www.stingray.com)
- [StyleRecipe](http://stylerecipe.co.jp)
- [Svenska Spel AB](https://www.svenskaspel.se/)
- [TaskData](http://www.taskdata.com/)
Expand Down Expand Up @@ -961,6 +962,7 @@ Swagger Codegen core team members are contributors who have been making signific
| Java Spring Boot | @cbornet (2016/07/19) |
| Java Spring MVC | @kolyjjj (2016/05/01) @cbornet (2016/07/19) |
| Java JAX-RS | |
| Java Play Framework | |
| NancyFX | |
| NodeJS | @kolyjjj (2016/05/01) |
| PHP Lumen | @abcsum (2016/05/01) |
Expand Down Expand Up @@ -1008,6 +1010,7 @@ Here is a list of template creators:
* Java MSF4J: @sanjeewa-malalgoda
* Java Spring Boot: @diyfr
* Java Undertow: @stevehu
* Java Play Framework: @JFCote
* JAX-RS RestEasy: @chameleon82
* JAX-RS CXF: @hiveship
* JAX-RS CXF (CDI): @nickcmaynard
Expand Down
31 changes: 31 additions & 0 deletions bin/java-play-framework-petstore-server.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
#!/bin/sh

SCRIPT="$0"

while [ -h "$SCRIPT" ] ; do
ls=`ls -ld "$SCRIPT"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
SCRIPT="$link"
else
SCRIPT=`dirname "$SCRIPT"`/"$link"
fi
done

if [ ! -d "${APP_DIR}" ]; then
APP_DIR=`dirname "$SCRIPT"`/..
APP_DIR=`cd "${APP_DIR}"; pwd`
fi

executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar"

if [ ! -f "$executable" ]
then
mvn clean package
fi

# if you've executed sbt assembly previously it will use that instead.
export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="$@ generate -t modules/swagger-codegen/src/main/resources/JavaPlayFramework -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l java-play-framework -o samples/server/petstore/java-play-framework -DhideGenerationTimestamp=true"

java $JAVA_OPTS -jar $executable $ags
10 changes: 10 additions & 0 deletions bin/windows/java-play-framework-petstore-server.bat
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
set executable=.\modules\swagger-codegen-cli\target\swagger-codegen-cli.jar

If Not Exist %executable% (
mvn clean package
)

REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M
set ags=generate -i modules\swagger-codegen\src\test\resources\2_0\petstore.json -l java-play-framework -o samples\server\petstore\java-play-framework

java %JAVA_OPTS% -jar %executable% %ags%
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,10 @@ public class CodegenParameter {
secondaryParam, isCollectionFormatMulti, isPrimitiveType;
public String baseName, paramName, dataType, datatypeWithEnum, dataFormat,
collectionFormat, description, unescapedDescription, baseType, defaultValue, enumName;

//This was added for javaPlayFramework specifically to get around a bug in swagger-play. See generator for more info on the bug.
public String dataTypeForImplicitParam;

public String example; // example value (x-example)
public String jsonSchema;
public boolean isString, isInteger, isLong, isFloat, isDouble, isByteArray, isBinary, isBoolean, isDate, isDateTime;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,248 @@
package io.swagger.codegen.languages;

import io.swagger.codegen.*;
import io.swagger.codegen.languages.features.BeanValidationFeatures;

import java.io.File;
import java.util.List;
import java.util.Map;

public class JavaPlayFrameworkCodegen extends AbstractJavaCodegen implements BeanValidationFeatures {

public static final String TITLE = "title";
public static final String CONFIG_PACKAGE = "configPackage";
public static final String BASE_PACKAGE = "basePackage";
public static final String CONTROLLER_ONLY = "controllerOnly";
public static final String SINGLE_CONTENT_TYPES = "singleContentTypes";
public static final String RESPONSE_WRAPPER = "responseWrapper";
public static final String USE_TAGS = "useTags";

protected String title = "swagger-petstore";
protected String configPackage = "io.swagger.configuration";
protected String basePackage = "io.swagger";
protected boolean controllerOnly = false;
protected boolean singleContentTypes = false;
protected String responseWrapper = "";
protected boolean useTags = false;
protected boolean useBeanValidation = true;

public JavaPlayFrameworkCodegen() {
super();
outputFolder = "generated-code/javaPlayFramework";
apiTestTemplateFiles.clear();
embeddedTemplateDir = templateDir = "JavaPlayFramework";
apiPackage = "controllers";
modelPackage = "apimodels";
invokerPackage = "io.swagger.api";
artifactId = "swagger-java-playframework";

projectFolder = "";
sourceFolder = projectFolder + File.separator + "app";
projectTestFolder = projectFolder + File.separator + "test";
testFolder = projectTestFolder;

additionalProperties.put(CONFIG_PACKAGE, configPackage);
additionalProperties.put(BASE_PACKAGE, basePackage);

additionalProperties.put("jackson", "true");
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Putting something in the additionalProperties will allow you to use it in the mustache templates. For this case, one can do the following:

{{#jackson}}
// do something for jackson here
{{/jackson}}

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Will keep it there so it use jackson by default. Will remove the TODO


cliOptions.add(new CliOption(TITLE, "server title name or client service name"));
cliOptions.add(new CliOption(CONFIG_PACKAGE, "configuration package for generated code"));
cliOptions.add(new CliOption(BASE_PACKAGE, "base package for generated code"));
cliOptions.add(CliOption.newBoolean(CONTROLLER_ONLY, "Whether to generate only API interface stubs without the server files."));
cliOptions.add(CliOption.newBoolean(SINGLE_CONTENT_TYPES, "Whether to select only one produces/consumes content-type by operation."));
cliOptions.add(new CliOption(RESPONSE_WRAPPER, "wrap the responses in given type (Future,Callable,CompletableFuture,ListenableFuture,DeferredResult,HystrixCommand,RxObservable,RxSingle or fully qualified type)"));
cliOptions.add(CliOption.newBoolean(USE_TAGS, "use tags for creating interface and controller classnames"));
cliOptions.add(CliOption.newBoolean(USE_BEANVALIDATION, "Use BeanValidation API annotations"));
}

@Override
public CodegenType getTag() {
return CodegenType.SERVER;
}

@Override
public String getName() {
return "java-play-framework";
}

@Override
public String getHelp() {
return "Generates a Java Play Framework Server application.";
}

@Override
public void processOpts() {
super.processOpts();

// clear model and api doc template as this codegen
// does not support auto-generated markdown doc at the moment
//TODO: add doc templates
modelDocTemplateFiles.remove("model_doc.mustache");
apiDocTemplateFiles.remove("api_doc.mustache");

if (additionalProperties.containsKey(TITLE)) {
this.setTitle((String) additionalProperties.get(TITLE));
}

if (additionalProperties.containsKey(CONFIG_PACKAGE)) {
this.setConfigPackage((String) additionalProperties.get(CONFIG_PACKAGE));
}

if (additionalProperties.containsKey(BASE_PACKAGE)) {
this.setBasePackage((String) additionalProperties.get(BASE_PACKAGE));
}

if (additionalProperties.containsKey(CONTROLLER_ONLY)) {
this.setControllerOnly(Boolean.valueOf(additionalProperties.get(CONTROLLER_ONLY).toString()));
}

if (additionalProperties.containsKey(SINGLE_CONTENT_TYPES)) {
this.setSingleContentTypes(Boolean.valueOf(additionalProperties.get(SINGLE_CONTENT_TYPES).toString()));
}

if (additionalProperties.containsKey(RESPONSE_WRAPPER)) {
this.setResponseWrapper((String) additionalProperties.get(RESPONSE_WRAPPER));
}

if (additionalProperties.containsKey(USE_TAGS)) {
this.setUseTags(Boolean.valueOf(additionalProperties.get(USE_TAGS).toString()));
}

if (additionalProperties.containsKey(USE_BEANVALIDATION)) {
this.setUseBeanValidation(convertPropertyToBoolean(USE_BEANVALIDATION));
}

if (useBeanValidation) {
writePropertyBack(USE_BEANVALIDATION, useBeanValidation);
}

//Root folder
supportingFiles.add(new SupportingFile("README.mustache", "", "README"));
supportingFiles.add(new SupportingFile("LICENSE.mustache", "", "LICENSE"));
supportingFiles.add(new SupportingFile("build.mustache", "", "build.sbt"));

//Project folder
supportingFiles.add(new SupportingFile("buildproperties.mustache", "project", "build.properties"));
supportingFiles.add(new SupportingFile("plugins.mustache", "project", "plugins.sbt"));

//Conf folder
supportingFiles.add(new SupportingFile("logback.mustache", "conf", "logback.xml"));
supportingFiles.add(new SupportingFile("application.mustache", "conf", "application.conf"));
supportingFiles.add(new SupportingFile("routes.mustache", "conf", "routes"));

//App/Utils folder
supportingFiles.add(new SupportingFile("swaggerUtils.mustache", "app/swagger", "SwaggerUtils.java"));

//App/Controllers
supportingFiles.add(new SupportingFile("apiDocController.mustache", "app/controllers", "ApiDocController.java"));

//We remove the default api.mustache that is used
apiTemplateFiles.remove("api.mustache");
apiTemplateFiles.put("newApiController.mustache", "Controller.java");
if (!this.controllerOnly) {
apiTemplateFiles.put("newApi.mustache", "ControllerImp.java");
}

additionalProperties.put("javaVersion", "1.8");
additionalProperties.put("jdk8", "true");
typeMapping.put("date", "LocalDate");
typeMapping.put("DateTime", "OffsetDateTime");
importMapping.put("LocalDate", "java.time.LocalDate");
importMapping.put("OffsetDateTime", "java.time.OffsetDateTime");

// Some well-known Spring or Spring-Cloud response wrappers
switch (this.responseWrapper) {
case "Future":
case "Callable":
case "CompletableFuture":
additionalProperties.put(RESPONSE_WRAPPER, "java.util.concurrent" + this.responseWrapper);
break;
default:
break;
}
}

public void setTitle(String title) {
this.title = title;
}

public void setConfigPackage(String configPackage) {
this.configPackage = configPackage;
}

public void setBasePackage(String configPackage) {
this.basePackage = configPackage;
}

public void setControllerOnly(boolean controllerOnly) { this.controllerOnly = controllerOnly; }

public void setSingleContentTypes(boolean singleContentTypes) {
this.singleContentTypes = singleContentTypes;
}

public void setResponseWrapper(String responseWrapper) { this.responseWrapper = responseWrapper; }

public void setUseTags(boolean useTags) {
this.useTags = useTags;
}

@Override
public Map<String, Object> postProcessOperations(Map<String, Object> objs) {
Map<String, Object> operations = (Map<String, Object>) objs.get("operations");
if (operations != null) {
List<CodegenOperation> ops = (List<CodegenOperation>) operations.get("operation");
for (CodegenOperation operation : ops) {

//This is to fix this bug in the swagger-play project: https://github.com/swagger-api/swagger-play/issues/131
//We need to explicitly add the model package name in front of the dataType because if we don't, the
//implicitParam is not valid and show error when loading the documentation
//This can be removed safely after the bug has been fixed
for (CodegenParameter param : operation.allParams) {
if (!param.isPathParam ) {
if (!param.isPrimitiveType) {
param.dataTypeForImplicitParam = String.format("%s.%s", modelPackage, param.dataType);
} else {
param.dataTypeForImplicitParam = param.dataType;
}
}
}

if (operation.path.contains("{")) {
operation.path = operation.path.replace("{", ":").replace("}", "");
}

if (operation.returnType != null) {
if (operation.returnType.startsWith("List")) {
String rt = operation.returnType;
int end = rt.lastIndexOf(">");
if (end > 0) {
operation.returnType = rt.substring("List<".length(), end).trim();
operation.returnContainer = "List";
}
} else if (operation.returnType.startsWith("Map")) {
String rt = operation.returnType;
int end = rt.lastIndexOf(">");
if (end > 0) {
operation.returnType = rt.substring("Map<".length(), end).split(",")[1].trim();
operation.returnContainer = "Map";
}
} else if (operation.returnType.startsWith("Set")) {
String rt = operation.returnType;
int end = rt.lastIndexOf(">");
if (end > 0) {
operation.returnType = rt.substring("Set<".length(), end).trim();
operation.returnContainer = "Set";
}
}
}
}
}

return objs;
}

public void setUseBeanValidation(boolean useBeanValidation) {
this.useBeanValidation = useBeanValidation;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
This software is licensed under the Apache 2 license, quoted below.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We might later need to empty this file as there's a discussion about not setting any license to the auto-generated code and let the users to decide which license (e.g. MIT, GNU, Apache2, etc) to use.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

no problem. I was just mimicking the output of a brand new Play Framework project.


Licensed under the Apache License, Version 2.0 (the "License"); you may not use this project except in compliance with
the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific
language governing permissions and limitations under the License.
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
This is your new Play application
=================================

This file will be packaged with your application when using `activator dist`.
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package controllers;

import javax.inject.*;
import play.mvc.*;

public class ApiDocController extends Controller {

@Inject
private ApiDocController() {
}

public Result api() {
return redirect(String.format("/assets/lib/swagger-ui/index.html?/url=%s/api-docs", ""));
}
}
Loading