Skip to content

Commit

Permalink
[scala] strip model class name for all scala generators (OpenAPITools…
Browse files Browse the repository at this point in the history
…#5439)

* stripped parameter enabled for all scala based generators

* scala samples updated

* docs generators updated

* fix scalatra. regenerated by openapi3 script.
manually removed enum default value from scalatra example due bug in schema extraction
  • Loading branch information
chameleon82 authored and MikailBag committed Mar 23, 2020
1 parent eb37060 commit b7ba8d1
Show file tree
Hide file tree
Showing 54 changed files with 205 additions and 168 deletions.
44 changes: 16 additions & 28 deletions docs/generators/scalatra.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,56 +67,44 @@ sidebar_label: scalatra

<ul class="column-ul">
<li>abstract</li>
<li>assert</li>
<li>boolean</li>
<li>break</li>
<li>byte</li>
<li>case</li>
<li>catch</li>
<li>char</li>
<li>class</li>
<li>const</li>
<li>continue</li>
<li>default</li>
<li>def</li>
<li>do</li>
<li>double</li>
<li>else</li>
<li>enum</li>
<li>extends</li>
<li>false</li>
<li>final</li>
<li>finally</li>
<li>float</li>
<li>for</li>
<li>goto</li>
<li>forSome</li>
<li>if</li>
<li>implements</li>
<li>implicit</li>
<li>import</li>
<li>instanceof</li>
<li>int</li>
<li>interface</li>
<li>long</li>
<li>native</li>
<li>lazy</li>
<li>match</li>
<li>new</li>
<li>null</li>
<li>object</li>
<li>override</li>
<li>package</li>
<li>private</li>
<li>protected</li>
<li>public</li>
<li>return</li>
<li>short</li>
<li>static</li>
<li>strictfp</li>
<li>sealed</li>
<li>super</li>
<li>switch</li>
<li>synchronized</li>
<li>this</li>
<li>throw</li>
<li>throws</li>
<li>transient</li>
<li>trait</li>
<li>true</li>
<li>try</li>
<li>type</li>
<li>void</li>
<li>volatile</li>
<li>val</li>
<li>var</li>
<li>while</li>
<li>with</li>
<li>yield</li>
</ul>

## FEATURE SET
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,7 @@ public AbstractScalaCodegen() {
cliOptions.add(new CliOption(CodegenConstants.MODEL_PACKAGE, CodegenConstants.MODEL_PACKAGE_DESC));
cliOptions.add(new CliOption(CodegenConstants.API_PACKAGE, CodegenConstants.API_PACKAGE_DESC));
cliOptions.add(new CliOption(CodegenConstants.SOURCE_FOLDER, CodegenConstants.SOURCE_FOLDER_DESC));

}

@Override
Expand Down Expand Up @@ -319,6 +320,31 @@ public Map<String, Object> postProcessModels(Map<String, Object> objs) {
return objs;
}

@Override
public String toModelName(final String name) {
final String sanitizedName = sanitizeName(modelNamePrefix + this.stripPackageName(name) + modelNameSuffix);

// camelize the model name
// phone_number => PhoneNumber
final String camelizedName = camelize(sanitizedName);

// model name cannot use reserved keyword, e.g. return
if (isReservedWord(camelizedName)) {
final String modelName = "Model" + camelizedName;
LOGGER.warn(camelizedName + " (reserved word) cannot be used as model name. Renamed to " + modelName);
return modelName;
}

// model name starts with number
if (name.matches("^\\d.*")) {
final String modelName = "Model" + camelizedName; // e.g. 200Response => Model200Response (after camelize)
LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + modelName);
return modelName;
}

return camelizedName;
}

@Override
public String toModelFilename(String name) {
// should be the same as the model name
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ public class ScalaAkkaClientCodegen extends AbstractScalaCodegen implements Code
protected boolean registerNonStandardStatusCodes = true;
protected boolean renderJavadoc = true;
protected boolean removeOAuthSecurities = true;
// protected boolean stripPackageName = false;


@SuppressWarnings("hiding")
Expand Down Expand Up @@ -304,11 +305,6 @@ public String toDefaultValue(Schema p) {
}
}

@Override
public String toModelName(final String name) {
return formatIdentifier(name, true);
}

private static abstract class CustomLambda implements Mustache.Lambda {
@Override
public void execute(Template.Fragment frag, Writer out) throws IOException {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,6 @@ public ScalaHttpClientCodegen() {
additionalProperties.put("authScheme", authScheme);
additionalProperties.put("authPreemptive", authPreemptive);
additionalProperties.put("clientName", clientName);
additionalProperties.put(CodegenConstants.STRIP_PACKAGE_NAME, stripPackageName);

supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml"));
supportingFiles.add(new SupportingFile("apiInvoker.mustache",
Expand Down Expand Up @@ -267,31 +266,6 @@ public String toOperationId(String operationId) {
return camelize(operationId, true);
}

@Override
public String toModelName(final String name) {
final String sanitizedName = sanitizeName(modelNamePrefix + this.stripPackageName(name) + modelNameSuffix);

// camelize the model name
// phone_number => PhoneNumber
final String camelizedName = camelize(sanitizedName);

// model name cannot use reserved keyword, e.g. return
if (isReservedWord(camelizedName)) {
final String modelName = "Model" + camelizedName;
LOGGER.warn(camelizedName + " (reserved word) cannot be used as model name. Renamed to " + modelName);
return modelName;
}

// model name starts with number
if (name.matches("^\\d.*")) {
final String modelName = "Model" + camelizedName; // e.g. 200Response => Model200Response (after camelize)
LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + modelName);
return modelName;
}

return camelizedName;
}

@Override
public String toEnumName(CodegenProperty property) {
return formatIdentifier(stripPackageName(property.baseName), true);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -229,35 +229,6 @@ public String toOperationId(String operationId) {
return camelize(operationId, true);
}

@Override
public String toModelName(final String name) {
final String sanitizedName = sanitizeName(modelNamePrefix + name + modelNameSuffix);

// camelize the model name
// phone_number => PhoneNumber
final String camelizedName = camelize(sanitizedName);

// model name cannot use reserved keyword, e.g. return
if (isReservedWord(camelizedName)) {
final String modelName = "Model" + camelizedName;
LOGGER.warn(
camelizedName + " (reserved word) cannot be used as model name. Renamed to " + modelName);
return modelName;
}

// model name starts with number
if (name.matches("^\\d.*")) {
final String modelName =
"Model" + camelizedName; // e.g. 200Response => Model200Response (after camelize)
LOGGER.warn(
name + " (model name starts with number) cannot be used as model name. Renamed to "
+ modelName);
return modelName;
}

return camelizedName;
}

@Override
public Map<String, Object> postProcessModelsEnum(Map<String, Object> objs) {
objs = super.postProcessModelsEnum(objs);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,17 +57,6 @@ public ScalatraServerCodegen() {
apiPackage = "org.openapitools.server.api";
modelPackage = "org.openapitools.server.model";

setReservedWordsLowerCase(
Arrays.asList(
"abstract", "continue", "for", "new", "switch", "assert",
"default", "if", "package", "synchronized", "boolean", "do", "goto", "private",
"this", "break", "double", "implements", "protected", "throw", "byte", "else",
"import", "public", "throws", "case", "enum", "instanceof", "return", "transient",
"catch", "extends", "int", "short", "try", "char", "final", "interface", "static",
"void", "class", "finally", "long", "strictfp", "volatile", "const", "float",
"native", "super", "while", "type")
);

defaultIncludes = new HashSet<String>(
Arrays.asList("double",
"Int",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -274,31 +274,6 @@ public String toOperationId(String operationId) {
return camelize(operationId, true);
}

@Override
public String toModelName(final String name) {
final String sanitizedName = sanitizeName(modelNamePrefix + this.stripPackageName(name) + modelNameSuffix);

// camelize the model name
// phone_number => PhoneNumber
final String camelizedName = camelize(sanitizedName);

// model name cannot use reserved keyword, e.g. return
if (isReservedWord(camelizedName)) {
final String modelName = "Model" + camelizedName;
LOGGER.warn(camelizedName + " (reserved word) cannot be used as model name. Renamed to " + modelName);
return modelName;
}

// model name starts with number
if (name.matches("^\\d.*")) {
final String modelName = "Model" + camelizedName; // e.g. 200Response => Model200Response (after camelize)
LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + modelName);
return modelName;
}

return camelizedName;
}

private static abstract class CustomLambda implements Mustache.Lambda {
@Override
public void execute(Template.Fragment frag, Writer out) throws IOException {
Expand Down
Original file line number Diff line number Diff line change
@@ -1 +1 @@
{{#allParams}}{{paramName}}: {{#required}}{{dataType}}{{/required}}{{^required}}{{#isContainer}}{{dataType}}{{/isContainer}}{{^isContainer}}Option[{{dataType}}]{{/isContainer}}{{/required}}{{^defaultValue}}{{^required}}{{^isContainer}} = None{{/isContainer}}{{/required}}{{/defaultValue}}{{#hasMore}}, {{/hasMore}}{{/allParams}}{{#authMethods.0}})(implicit {{#authMethods}}{{#isApiKey}}apiKey: ApiKeyValue{{/isApiKey}}{{#isBasic}}{{#isBasicBasic}}basicAuth: BasicCredentials{{/isBasicBasic}}{{#isBasicBearer}}bearerToken: BearerToken{{/isBasicBearer}}{{/isBasic}}{{#hasMore}}, {{/hasMore}}{{/authMethods}}{{/authMethods.0}}
{{#allParams}}{{paramName}}: {{#required}}{{dataType}}{{/required}}{{^required}}{{#isContainer}}{{dataType}}{{/isContainer}}{{^isContainer}}Option[{{dataType}}]{{/isContainer}}{{/required}}{{^defaultValue}}{{^required}}{{^isContainer}} = None{{/isContainer}}{{/required}}{{/defaultValue}}{{#hasMore}}, {{/hasMore}}{{/allParams}}{{#authMethods.0}})(implicit {{#authMethods}}{{#isApiKey}}apiKey: ApiKeyValue{{/isApiKey}}{{#isBasic}}{{#isBasicBasic}}basicAuth: BasicCredentials{{/isBasicBasic}}{{#isBasicBearer}}bearerToken: BearerToken{{/isBasicBearer}}{{/isBasic}}{{#hasMore}}, {{/hasMore}}{{/authMethods}}{{/authMethods.0}}
Original file line number Diff line number Diff line change
Expand Up @@ -363,4 +363,28 @@ public void codeGenerationTest() throws Exception {
generatedFiles.get(someObjFilename),
Resources.toString(Resources.getResource("codegen/scala/SomeObj.scala.txt"), StandardCharsets.UTF_8));
}

@Test(description = "strip model name")
public void stripModelNameTest() throws Exception {
final Schema model = new Schema()
.description("a map model");
final DefaultCodegen codegen = new ScalaAkkaClientCodegen();
OpenAPI openAPI = TestUtils.createOpenAPIWithOneSchema("sample", model);
codegen.setOpenAPI(openAPI);

final CodegenModel cms = codegen.fromModel("Stripped.ByDefault.ModelName", model);
Assert.assertEquals(cms.name, "Stripped.ByDefault.ModelName");
Assert.assertEquals(cms.classname, "ModelName");
Assert.assertEquals(cms.classFilename, "ModelName");

codegen.additionalProperties().put(CodegenConstants.STRIP_PACKAGE_NAME, "false");
codegen.processOpts();

final CodegenModel cm = codegen.fromModel("Non.Stripped.ModelName", model);

Assert.assertEquals(cm.name, "Non.Stripped.ModelName");
Assert.assertEquals(cm.classname, "NonStrippedModelName");
Assert.assertEquals(cm.classFilename, "NonStrippedModelName");

}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
openapi: 3.0.1
info:
version: 1.0.0
title: Example
license:
name: MIT
servers:
- url: http://api.example.xyz/v1
paths:
/deprecated-test:
x-swagger-router-controller: /deprecated-test
post:
requestBody:
content:
application/json:
schema:
$ref: '#/components/schemas/Non.Stripped.Request'
responses:
'200':
description: responses
content:
application/json:
schema:
$ref: '#/components/schemas/Response'
components:
schemas:
Non.Stripped.Request:
type: object
properties:
customerCode:
type: string
example: '0001'
firstName:
type: string
deprecated: true
example: 'first'
Response:
type: object
properties:
customerCode:
type: string
example: '0001'
firstName:
type: string
deprecated: true
example: 'first'
Original file line number Diff line number Diff line change
@@ -1 +1 @@
4.2.3-SNAPSHOT
4.3.0-SNAPSHOT
1 change: 1 addition & 0 deletions samples/client/petstore/scala-akka/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -118,3 +118,4 @@ Authentication schemes defined for the API:
## Author



Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,8 @@ class ApiInvoker(formats: Formats)(implicit system: ActorSystem) extends CustomC
req.withHeaders(Authorization(BasicHttpCredentials(login, password)))
case (req, ApiKeyCredentials(keyValue, keyName, ApiKeyLocations.HEADER)) =>
req.withHeaders(RawHeader(keyName, keyValue.value))
case (req, BearerToken(token)) =>
req.withHeaders(RawHeader("Authorization", s"Bearer $token"))
case (req, _) => req
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,8 @@ sealed trait Credentials {

sealed case class BasicCredentials(user: String, password: String) extends Credentials

sealed case class BearerToken(token: String) extends Credentials

sealed case class ApiKeyCredentials(key: ApiKeyValue, keyName: String, location: ApiKeyLocation) extends Credentials {
override def asQueryParam: Option[(String, String)] = location match {
case ApiKeyLocations.QUERY => Some((keyName, key.value))
Expand Down
Original file line number Diff line number Diff line change
@@ -1 +1 @@
4.2.3-SNAPSHOT
4.3.0-SNAPSHOT
2 changes: 1 addition & 1 deletion samples/client/petstore/scala-gatling/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ plugins {
}

repositories {
mavenCentral()
maven { url "https://repo1.maven.org/maven2" }
}

dependencies {
Expand Down
Original file line number Diff line number Diff line change
@@ -1 +1 @@
4.2.3-SNAPSHOT
4.3.0-SNAPSHOT
2 changes: 1 addition & 1 deletion samples/client/petstore/scala-httpclient/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ ext {

repositories {
mavenLocal()
mavenCentral()
maven { url "https://repo1.maven.org/maven2" }
}

dependencies {
Expand Down
Loading

0 comments on commit b7ba8d1

Please sign in to comment.