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

[scala][templates] java 8 dates support #5291

Merged
merged 21 commits into from
Mar 17, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
d64f2c9
[scala][akka-http-client] java8 dates support
chameleon82 Feb 11, 2020
5e99613
scala-akka readme doc updated
chameleon82 Feb 13, 2020
74cb8ec
Merge branch 'master' into scala-akka-java-time
chameleon82 Feb 29, 2020
368e311
DateSerializers renamed
chameleon82 Feb 29, 2020
e0376dd
Merge branch 'master' into scala-akka-java-time
chameleon82 Feb 29, 2020
bc4b30f
rename serializers
chameleon82 Feb 29, 2020
d45139a
move date-library option to abstractScala
chameleon82 Feb 29, 2020
04da6d4
generators docs updated
chameleon82 Mar 1, 2020
94f6473
enum defined for date libraries
chameleon82 Mar 2, 2020
f737a9d
Merge branch 'master' into scala-akka-java-time
chameleon82 Mar 2, 2020
786c979
Backport to scala-http-client
chameleon82 Mar 2, 2020
ee8376f
fix scala-akka-client date serializers
chameleon82 Mar 2, 2020
ee4183d
fix typo in docs
chameleon82 Mar 2, 2020
b839b0d
switch scala templates to java8 (jsr-310) date library by default
chameleon82 Mar 4, 2020
a44a757
Merge branch 'master' into scala-akka-java-time
chameleon82 Mar 4, 2020
b2c6c0f
update scala samples with java8 date library
chameleon82 Mar 4, 2020
213e390
update scala generators docs with java8 default date library
chameleon82 Mar 4, 2020
4cfade8
fix scala-play-server generator cli options as only java8 dateLibrary…
chameleon82 Mar 4, 2020
f130f04
fix scalaz DateTimeCodecs template to support java8
chameleon82 Mar 5, 2020
5ea9005
scalaz ci test againt java7 removed as it generate scala 2.11.8 clien…
chameleon82 Mar 6, 2020
c7c7b91
Merge branch 'master' into scala-akka-java-time
chameleon82 Mar 11, 2020
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: 2 additions & 1 deletion docs/generators/scala-akka.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ sidebar_label: scala-akka
| ------ | ----------- | ------ | ------- |
|allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false|
|apiPackage|package for generated api classes| |null|
|dateLibrary|Option. Date library to use|<dl><dt>**joda**</dt><dd>Joda (for legacy app)</dd><dt>**java8**</dt><dd>Java 8 native JSR310 (prefered for JDK 1.8+)</dd></dl>|java8|
|ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true|
|mainPackage|Top-level package name, which defines 'apiPackage', 'modelPackage', 'invokerPackage'| |org.openapitools.client|
|modelPackage|package for generated models| |null|
Expand All @@ -23,7 +24,7 @@ sidebar_label: scala-akka
|Array|java.util.List|
|ArrayList|java.util.ArrayList|
|Date|java.util.Date|
|DateTime|org.joda.time.DateTime|
|DateTime|org.joda.time.*|
|File|java.io.File|
|HashMap|java.util.HashMap|
|ListBuffer|scala.collection.mutable.ListBuffer|
Expand Down
1 change: 1 addition & 0 deletions docs/generators/scala-gatling.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ sidebar_label: scala-gatling
| ------ | ----------- | ------ | ------- |
|allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false|
|apiPackage|package for generated api classes| |null|
|dateLibrary|Option. Date library to use|<dl><dt>**joda**</dt><dd>Joda (for legacy app)</dd><dt>**java8**</dt><dd>Java 8 native JSR310 (prefered for JDK 1.8+)</dd></dl>|java8|
|ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true|
|modelPackage|package for generated models| |null|
|modelPropertyNaming|Naming convention for the property: 'camelCase', 'PascalCase', 'snake_case' and 'original', which keeps the original name| |camelCase|
Expand Down
1 change: 1 addition & 0 deletions docs/generators/scala-httpclient-deprecated.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ sidebar_label: scala-httpclient-deprecated
| ------ | ----------- | ------ | ------- |
|allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false|
|apiPackage|package for generated api classes| |null|
|dateLibrary|Option. Date library to use|<dl><dt>**joda**</dt><dd>Joda (for legacy app)</dd><dt>**java8**</dt><dd>Java 8 native JSR310 (prefered for JDK 1.8+)</dd></dl>|java8|
|ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true|
|modelPackage|package for generated models| |null|
|modelPropertyNaming|Naming convention for the property: 'camelCase', 'PascalCase', 'snake_case' and 'original', which keeps the original name| |camelCase|
Expand Down
1 change: 1 addition & 0 deletions docs/generators/scala-lagom-server.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ sidebar_label: scala-lagom-server
| ------ | ----------- | ------ | ------- |
|allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false|
|apiPackage|package for generated api classes| |null|
|dateLibrary|Option. Date library to use|<dl><dt>**joda**</dt><dd>Joda (for legacy app)</dd><dt>**java8**</dt><dd>Java 8 native JSR310 (prefered for JDK 1.8+)</dd></dl>|java8|
|ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true|
|modelPackage|package for generated models| |null|
|modelPropertyNaming|Naming convention for the property: 'camelCase', 'PascalCase', 'snake_case' and 'original', which keeps the original name| |camelCase|
Expand Down
3 changes: 2 additions & 1 deletion docs/generators/scala-sttp.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ sidebar_label: scala-sttp
| ------ | ----------- | ------ | ------- |
|allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false|
|apiPackage|package for generated api classes| |null|
|dateLibrary|Option. Date library to use|<dl><dt>**joda**</dt><dd>Joda (for legacy app)</dd><dt>**java8**</dt><dd>Java 8 native JSR310 (prefered for JDK 1.8+)</dd></dl>|java8|
|ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true|
|mainPackage|Top-level package name, which defines 'apiPackage', 'modelPackage', 'invokerPackage'| |org.openapitools.client|
|modelPackage|package for generated models| |null|
Expand All @@ -23,7 +24,7 @@ sidebar_label: scala-sttp
|Array|java.util.List|
|ArrayList|java.util.ArrayList|
|Date|java.util.Date|
|DateTime|org.joda.time.DateTime|
|DateTime|org.joda.time.*|
|File|java.io.File|
|HashMap|java.util.HashMap|
|ListBuffer|scala.collection.mutable.ListBuffer|
Expand Down
1 change: 1 addition & 0 deletions docs/generators/scalatra.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ sidebar_label: scalatra
| ------ | ----------- | ------ | ------- |
|allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false|
|apiPackage|package for generated api classes| |null|
|dateLibrary|Option. Date library to use|<dl><dt>**joda**</dt><dd>Joda (for legacy app)</dd><dt>**java8**</dt><dd>Java 8 native JSR310 (prefered for JDK 1.8+)</dd></dl>|java8|
|ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true|
|modelPackage|package for generated models| |null|
|modelPropertyNaming|Naming convention for the property: 'camelCase', 'PascalCase', 'snake_case' and 'original', which keeps the original name| |camelCase|
Expand Down
1 change: 1 addition & 0 deletions docs/generators/scalaz.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ sidebar_label: scalaz
| ------ | ----------- | ------ | ------- |
|allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false|
|apiPackage|package for generated api classes| |null|
|dateLibrary|Option. Date library to use|<dl><dt>**joda**</dt><dd>Joda (for legacy app)</dd><dt>**java8**</dt><dd>Java 8 native JSR310 (prefered for JDK 1.8+)</dd></dl>|java8|
|ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true|
|modelPackage|package for generated models| |null|
|modelPropertyNaming|Naming convention for the property: 'camelCase', 'PascalCase', 'snake_case' and 'original', which keeps the original name| |camelCase|
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
import java.io.File;
import java.util.*;

import static org.openapitools.codegen.languages.AbstractJavaCodegen.DATE_LIBRARY;
import static org.openapitools.codegen.utils.StringUtils.camelize;
import static org.openapitools.codegen.utils.StringUtils.underscore;

Expand All @@ -41,6 +42,19 @@ public abstract class AbstractScalaCodegen extends DefaultCodegen {
protected String invokerPackage = "org.openapitools.client";
protected String sourceFolder = "src/main/scala";
protected boolean stripPackageName = true;
protected String dateLibrary = DateLibraries.java8.name();

protected enum DateLibraries {
java8("Java 8 native JSR310 (prefered for JDK 1.8+)"),
joda( "Joda (for legacy app)"),
legacy( "Backport to http-client (deprecated)");

private final String description;

DateLibraries(String description) {
this.description = description;
}
}

public AbstractScalaCodegen() {
super();
Expand Down Expand Up @@ -131,6 +145,13 @@ public AbstractScalaCodegen() {
cliOptions.add(new CliOption(CodegenConstants.SOURCE_FOLDER, CodegenConstants.SOURCE_FOLDER_DESC));
cliOptions.add(new CliOption(CodegenConstants.MODEL_PROPERTY_NAMING, CodegenConstants.MODEL_PROPERTY_NAMING_DESC).defaultValue(modelPropertyNaming));

CliOption dateLibrary = new CliOption(DATE_LIBRARY, "Option. Date library to use").defaultValue(this.dateLibrary);
Map<String, String> dateOptions = new HashMap<>();
dateOptions.put(DateLibraries.java8.name(), DateLibraries.java8.description);
dateOptions.put(DateLibraries.joda.name(), DateLibraries.joda.description);
dateLibrary.setEnum(dateOptions);
cliOptions.add(dateLibrary);

}

@Override
Expand All @@ -156,6 +177,43 @@ public void processOpts() {
setModelPropertyNaming(
(String) additionalProperties.get(CodegenConstants.MODEL_PROPERTY_NAMING));
}

if (additionalProperties.containsKey(DATE_LIBRARY)) {
this.setDateLibrary(additionalProperties.get(DATE_LIBRARY).toString(), false);
}
if (DateLibraries.java8.name().equals(dateLibrary)) {
this.importMapping.put("LocalDate", "java.time.LocalDate");
this.importMapping.put("OffsetDateTime", "java.time.OffsetDateTime");
this.typeMapping.put("date", "LocalDate");
this.typeMapping.put("DateTime", "OffsetDateTime");
additionalProperties.put("java8", "true");
} else if (DateLibraries.joda.name().equals(dateLibrary)) {
this.importMapping.put("LocalDate", "org.joda.time.LocalDate");
this.importMapping.put("DateTime", "org.joda.time.DateTime");
this.importMapping.put("LocalDateTime", "org.joda.time.LocalDateTime");
this.importMapping.put("LocalTime", "org.joda.time.LocalTime");
this.typeMapping.put("date", "LocalDate");
this.typeMapping.put("DateTime", "DateTime");
additionalProperties.put("joda", "true");
}
}

public void setDateLibrary(String dateLibrary, boolean withLegacy) {
if (withLegacy && dateLibrary.equals(DateLibraries.legacy.name())) {
this.dateLibrary = dateLibrary;
return;
}
for ( DateLibraries dateLib : DateLibraries.values()) {
if (dateLib.name().equals(dateLibrary)) {
this.dateLibrary = dateLibrary;
return;
}
}
throw new IllegalArgumentException("Invalid dateLibrary. Must be 'java8' or 'joda'");
}

public String getDateLibrary() {
return this.dateLibrary;
}

public void setModelPropertyNaming(String naming) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
import java.io.Writer;
import java.util.*;

import static org.openapitools.codegen.languages.AbstractJavaCodegen.DATE_LIBRARY;
import static org.openapitools.codegen.utils.StringUtils.camelize;

public class ScalaAkkaClientCodegen extends AbstractScalaCodegen implements CodegenConfig {
Expand All @@ -49,8 +50,6 @@ 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")
protected Logger LOGGER = LoggerFactory.getLogger(ScalaAkkaClientCodegen.class);
Expand Down Expand Up @@ -121,8 +120,6 @@ public ScalaAkkaClientCodegen() {
importMapping.remove("Set");
importMapping.remove("Map");

importMapping.put("DateTime", "org.joda.time.DateTime");

typeMapping = new HashMap<>();
typeMapping.put("array", "Seq");
typeMapping.put("set", "Set");
Expand Down Expand Up @@ -172,6 +169,7 @@ public void processOpts() {
supportingFiles.add(new SupportingFile("apiSettings.mustache", invokerFolder, "ApiSettings.scala"));
final String apiFolder = (sourceFolder + File.separator + apiPackage).replace(".", File.separator);
supportingFiles.add(new SupportingFile("enumsSerializers.mustache", apiFolder, "EnumsSerializers.scala"));
supportingFiles.add(new SupportingFile("serializers.mustache", invokerFolder, "Serializers.scala"));
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,7 @@ public ScalaHttpClientCodegen() {
importMapping.remove("Set");
importMapping.remove("Map");

setDateLibrary("legacy",true);
importMapping.put("Date", "java.util.Date");

typeMapping = new HashMap<String, String>();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
import java.util.stream.Collectors;

import static org.apache.commons.lang3.StringUtils.rightPad;
import static org.openapitools.codegen.languages.AbstractJavaCodegen.DATE_LIBRARY;
import static org.openapitools.codegen.utils.OnceLogger.once;
import static org.openapitools.codegen.utils.StringUtils.camelize;

Expand Down Expand Up @@ -102,6 +103,7 @@ public ScalaPlayFrameworkServerCodegen() {
importMapping.remove("BigDecimal");
importMapping.put("TemporaryFile", "play.api.libs.Files.TemporaryFile");

cliOptions.removeIf(opt -> DATE_LIBRARY.equals(opt.getOpt()));
cliOptions.add(new CliOption(ROUTES_FILE_NAME, "Name of the routes file to generate.").defaultValue(routesFileName));
cliOptions.add(new CliOption(BASE_PACKAGE, "Base package in which supporting classes are generated.").defaultValue(basePackage));

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,10 +53,6 @@ public void processOpts() {
additionalProperties.put("modelPackage", modelPackage);
}

if (!additionalProperties.containsKey("java8")) {
additionalProperties.put("joda", "true");
}

supportingFiles.clear();
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
supportingFiles.add(new SupportingFile("build.sbt.mustache", "", "build.sbt"));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,6 @@ import akka.stream.ActorMaterializer
import akka.stream.scaladsl.Source
import akka.util.{ ByteString, Timeout }
import de.heikoseeberger.akkahttpjson4s.Json4sSupport
import org.joda.time.DateTime
import org.joda.time.format.ISODateTimeFormat
import org.json4s.JsonAST.JString
import org.json4s._
import org.json4s.jackson.JsonMethods._
import org.json4s.jackson.Serialization
Expand All @@ -29,10 +26,10 @@ import scala.reflect.ClassTag
object ApiInvoker {

def apply()(implicit system: ActorSystem): ApiInvoker =
apply(DefaultFormats + DateTimeSerializer)
apply(DefaultFormats ++ Serializers.all)

def apply(serializers: Iterable[Serializer[_]])(implicit system: ActorSystem): ApiInvoker =
apply(DefaultFormats + DateTimeSerializer ++ serializers)
apply(DefaultFormats ++ Serializers.all ++ serializers)

def apply(formats: Formats)(implicit system: ActorSystem): ApiInvoker = new ApiInvoker(formats)

Expand Down Expand Up @@ -67,15 +64,6 @@ object ApiInvoker {
def toAkkaHttpMethod: HttpMethod = HttpMethods.getForKey(method.value).getOrElse(HttpMethods.GET)
}

case object DateTimeSerializer extends CustomSerializer[DateTime](_ => ( {
case JString(s) =>
ISODateTimeFormat.dateOptionalTimeParser().parseDateTime(s)
}, {
case d: DateTime =>
JString(ISODateTimeFormat.dateTime().print(d))
})
)

}

trait UnitJSONSupport {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@ libraryDependencies ++= Seq(
"com.typesafe.akka" %% "akka-actor" % "2.5.21",
"com.typesafe.akka" %% "akka-stream" % "2.5.21",
"com.typesafe.akka" %% "akka-http" % "10.1.7",
{{#joda}}
"joda-time" % "joda-time" % "2.10.1",
{{/joda}}
"org.json4s" %% "json4s-jackson" % "3.6.5",
"org.json4s" %% "json4s-ext" % "3.6.5",
"de.heikoseeberger" %% "akka-http-json4s" % "1.25.2",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,9 @@
<json4s.ext.version>3.2.11</json4s.ext.version>
<akka.version>2.5.21</akka.version>
<akka.http.version>10.1.7</akka.http.version>
{{#joda}}
<joda.time.version>2.10.1</joda.time.version>
{{/joda}}
<typesafeconfig.version>1.3.3</typesafeconfig.version>
<akka.http.json4s.version>1.25.2</akka.http.json4s.version>
<junit.version>4.13</junit.version>
Expand All @@ -36,11 +38,13 @@
<version>${scala.version}</version>
<scope>provided</scope>
</dependency>
{{#joda}}
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>${joda.time.version}</version>
</dependency>
{{/joda}}
<dependency>
<groupId>com.typesafe</groupId>
<artifactId>config</artifactId>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package {{invokerPackage}}

{{#java8}}
import java.time.{LocalDate, LocalDateTime, OffsetDateTime, ZoneId}
import java.time.format.DateTimeFormatter
{{/java8}}
{{#joda}}
import org.joda.time.format.ISODateTimeFormat
import org.joda.time.{LocalDate, DateTime}
{{/joda}}
import org.json4s.{Serializer, CustomSerializer, JNull}
import org.json4s.JsonAST.JString

import scala.util.Try

object Serializers {

{{#java8}}
case object DateTimeSerializer extends CustomSerializer[OffsetDateTime]( _ => ( {
case JString(s) =>
Try(OffsetDateTime.parse(s, DateTimeFormatter.ISO_OFFSET_DATE_TIME)) orElse
Try(LocalDateTime.parse(s).atZone(ZoneId.systemDefault()).toOffsetDateTime) getOrElse null
}, {
case d: OffsetDateTime =>
JString(d.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME))
}))

case object LocalDateSerializer extends CustomSerializer[LocalDate]( _ => ( {
case JString(s) => LocalDate.parse(s)
}, {
JString(d.format(DateTimeFormatter.ISO_LOCAL_DATE))
}))
{{/java8}}
{{#joda}}
case object DateTimeSerializer extends CustomSerializer[DateTime](_ => ( {
case JString(s) =>
ISODateTimeFormat.dateOptionalTimeParser().parseDateTime(s)
}, {
case d: DateTime => JString(ISODateTimeFormat.dateTime().print(d))
}))

case object LocalDateSerializer extends CustomSerializer[LocalDate]( _ => ( {
case JString(s) => ISODateTimeFormat.localDateParser().parseLocalDate(s)
}, {
case d: LocalDate => JString(ISODateTimeFormat.date().print(d))
}))
{{/joda}}

def all: Seq[Serializer[_]] = Seq[Serializer[_]]() :+ DateTimeSerializer :+ LocalDateSerializer

}
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,26 @@ import argonaut.DecodeJson._
import org.http4s._
import org.http4s.{EntityDecoder, EntityEncoder}
import org.http4s.argonaut._

{{#joda}}
import org.joda.time.DateTime
{{/joda}}
{{#java8}}
import java.time.OffsetDateTime
{{/java8}}

object DateTimeCodecs {
{{#joda}}
implicit def dateTimeEncodeJson: EncodeJson[DateTime] =
EncodeJson[DateTime](dt => StringEncodeJson(dt.toString))

implicit def dateTimeDecodeJson: DecodeJson[DateTime] =
DecodeJson.of[String].map(DateTime.parse(_)) setName "org.joda.time.DateTime"
{{/joda}}
{{#java8}}
implicit def dateTimeEncodeJson: EncodeJson[OffsetDateTime] =
EncodeJson[OffsetDateTime](dt => StringEncodeJson(dt.toString))

implicit def dateTimeDecodeJson: DecodeJson[OffsetDateTime] =
DecodeJson.of[String].map(OffsetDateTime.parse(_)) setName "java.time.OffsetDateTime"
{{/java8}}
}
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ public class ScalaAkkaClientOptionsProvider implements OptionsProvider {
public static final String PREPEND_FORM_OR_BODY_PARAMETERS_VALUE = "true";
public static final String MAIN_PACKAGE_VALUE = "net.test";
public static final String MODEL_PROPERTY_NAMING = "camelCase";
public static final String DATE_LIBRARY = "joda";


@Override
Expand All @@ -53,6 +54,7 @@ public Map<String, String> createOptions() {
.put(CodegenConstants.PREPEND_FORM_OR_BODY_PARAMETERS, PREPEND_FORM_OR_BODY_PARAMETERS_VALUE)
.put("mainPackage", MAIN_PACKAGE_VALUE)
.put(CodegenConstants.MODEL_PROPERTY_NAMING, MODEL_PROPERTY_NAMING)
.put("dateLibrary", DATE_LIBRARY)
.build();
}

Expand Down
Loading