From be50955bbfa445b2b3ae69e05d21a8e00b63661a Mon Sep 17 00:00:00 2001 From: Jinkui Shi Date: Fri, 15 Dec 2017 00:47:10 +0800 Subject: [PATCH] [akka-scala] template upgrade dependency version and refactor #7171 (#7172) * [akka-scala] template upgrade dependency version and refactor #7171 * update sbt dependencies version and add enforce plugin * delete new to the case class --- .../resources/akka-scala/apiInvoker.mustache | 23 +- .../resources/akka-scala/apiRequest.mustache | 54 +- .../resources/akka-scala/apiSettings.mustache | 19 +- .../resources/akka-scala/build.sbt.mustache | 30 +- .../akka-scala/enumsSerializers.mustache | 9 +- .../main/resources/akka-scala/pom.mustache | 488 +++++++++--------- .../resources/akka-scala/requests.mustache | 48 +- 7 files changed, 345 insertions(+), 326 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/akka-scala/apiInvoker.mustache b/modules/swagger-codegen/src/main/resources/akka-scala/apiInvoker.mustache index 6267b425ba1..403765f20d4 100644 --- a/modules/swagger-codegen/src/main/resources/akka-scala/apiInvoker.mustache +++ b/modules/swagger-codegen/src/main/resources/akka-scala/apiInvoker.mustache @@ -49,8 +49,8 @@ object ApiInvoker { def addCustomStatusCode(code: CustomStatusCode): Unit = addCustomStatusCode(code.value, code.reason, code.isSuccess) - def addCustomStatusCode(code: Int, reason: String = "Application defined code", isSuccess: Boolean = true) = { - StatusCodes.getForKey(code) foreach { c => + def addCustomStatusCode(code: Int, reason: String = "Application defined code", isSuccess: Boolean = true): Unit = { + StatusCodes.getForKey(code) foreach { _ => StatusCodes.registerCustom(code, reason, reason, isSuccess, allowsEntity = true) } } @@ -97,16 +97,15 @@ class ApiInvoker(formats: Formats)(implicit system: ActorSystem) extends Untrust import io.swagger.client.core.ApiInvoker._ import io.swagger.client.core.ParametersMap._ - implicit val ec = system.dispatcher - implicit val jsonFormats = formats + implicit val ec: ExecutionContextExecutor = system.dispatcher + implicit val jsonFormats: Formats = formats def settings = ApiSettings(system) import spray.http.MessagePredicate._ - val CompressionFilter = MessagePredicate({ _ => settings.compressionEnabled}) && - Encoder.DefaultFilter && - minEntitySize(settings.compressionSizeThreshold) + val CompressionFilter: MessagePredicate= MessagePredicate({ _ => settings.compressionEnabled}) && + Encoder.DefaultFilter && minEntitySize(settings.compressionSizeThreshold) settings.customCodes.foreach(addCustomStatusCode) @@ -248,22 +247,22 @@ class ApiInvoker(formats: Formats)(implicit system: ActorSystem) extends Untrust case ResponseState.Success => ApiResponse(response.status.intValue, value, response.headers.map(header => (header.name, header.value)).toMap) case ResponseState.Error => - throw new ApiError(response.status.intValue, "Error response received", + throw ApiError(response.status.intValue, "Error response received", Some(value), headers = response.headers.map(header => (header.name, header.value)).toMap) } case Left(MalformedContent(error, Some(cause))) ⇒ - throw new ApiError(response.status.intValue, s"Unable to unmarshall content to [$manifest]", Some(response.entity.toString), cause) + throw ApiError(response.status.intValue, s"Unable to unmarshall content to [$manifest]", Some(response.entity.toString), cause) case Left(MalformedContent(error, None)) ⇒ - throw new ApiError(response.status.intValue, s"Unable to unmarshall content to [$manifest]", Some(response.entity.toString)) + throw ApiError(response.status.intValue, s"Unable to unmarshall content to [$manifest]", Some(response.entity.toString)) case Left(ContentExpected) ⇒ - throw new ApiError(response.status.intValue, s"Unable to unmarshall empty response to [$manifest]", Some(response.entity.toString)) + throw ApiError(response.status.intValue, s"Unable to unmarshall empty response to [$manifest]", Some(response.entity.toString)) } - case _ => throw new ApiError(response.status.intValue, "Unexpected response code", Some(response.entity.toString)) + case _ => throw ApiError(response.status.intValue, "Unexpected response code", Some(response.entity.toString)) } } diff --git a/modules/swagger-codegen/src/main/resources/akka-scala/apiRequest.mustache b/modules/swagger-codegen/src/main/resources/akka-scala/apiRequest.mustache index f516da6e10d..4481096bc2a 100644 --- a/modules/swagger-codegen/src/main/resources/akka-scala/apiRequest.mustache +++ b/modules/swagger-codegen/src/main/resources/akka-scala/apiRequest.mustache @@ -6,50 +6,54 @@ package {{invokerPackage}} sealed trait ResponseState + object ResponseState { + case object Success extends ResponseState + case object Error extends ResponseState + } case class ApiRequest[U]( - // required fields - method: ApiMethod, - basePath: String, - operationPath: String, - contentType: String, + // required fields + method: ApiMethod, + basePath: String, + operationPath: String, + contentType: String, - // optional fields - responses: Map[Int, (Manifest[_], ResponseState)] = Map.empty, - bodyParam: Option[Any] = None, - formParams: Map[String, Any] = Map.empty, - pathParams: Map[String, Any] = Map.empty, - queryParams: Map[String, Any] = Map.empty, - headerParams: Map[String, Any] = Map.empty, - credentials: Seq[Credentials] = List.empty) { + // optional fields + responses: Map[Int, (Manifest[_], ResponseState)] = Map.empty, + bodyParam: Option[Any] = None, + formParams: Map[String, Any] = Map.empty, + pathParams: Map[String, Any] = Map.empty, + queryParams: Map[String, Any] = Map.empty, + headerParams: Map[String, Any] = Map.empty, + credentials: Seq[Credentials] = List.empty) { - def withCredentials(cred: Credentials) = copy[U](credentials = credentials :+ cred) + def withCredentials(cred: Credentials): ApiRequest[U] = copy[U](credentials = credentials :+ cred) - def withApiKey(key: ApiKeyValue, keyName: String, location: ApiKeyLocation) = withCredentials(ApiKeyCredentials(key, keyName, location)) + def withApiKey(key: ApiKeyValue, keyName: String, location: ApiKeyLocation): ApiRequest[U] = withCredentials(ApiKeyCredentials(key, keyName, location)) - def withSuccessResponse[T](code: Int)(implicit m: Manifest[T]) = copy[U](responses = responses + (code -> (m, ResponseState.Success))) + def withSuccessResponse[T](code: Int)(implicit m: Manifest[T]): ApiRequest[U] = copy[U](responses = responses + (code -> (m, ResponseState.Success))) - def withErrorResponse[T](code: Int)(implicit m: Manifest[T]) = copy[U](responses = responses + (code -> (m, ResponseState.Error))) + def withErrorResponse[T](code: Int)(implicit m: Manifest[T]): ApiRequest[U] = copy[U](responses = responses + (code -> (m, ResponseState.Error))) - def withDefaultSuccessResponse[T](implicit m: Manifest[T]) = withSuccessResponse[T](0) + def withDefaultSuccessResponse[T](implicit m: Manifest[T]): ApiRequest[U] = withSuccessResponse[T](0) - def withDefaultErrorResponse[T](implicit m: Manifest[T]) = withErrorResponse[T](0) + def withDefaultErrorResponse[T](implicit m: Manifest[T]): ApiRequest[U] = withErrorResponse[T](0) def responseForCode(statusCode: Int): Option[(Manifest[_], ResponseState)] = responses.get(statusCode) orElse responses.get(0) - def withoutBody() = copy[U](bodyParam = None) + def withoutBody(): ApiRequest[U] = copy[U](bodyParam = None) - def withBody(body: Any) = copy[U](bodyParam = Some(body)) + def withBody(body: Any): ApiRequest[U] = copy[U](bodyParam = Some(body)) - def withFormParam(name: String, value: Any) = copy[U](formParams = formParams + (name -> value)) + def withFormParam(name: String, value: Any): ApiRequest[U] = copy[U](formParams = formParams + (name -> value)) - def withPathParam(name: String, value: Any) = copy[U](pathParams = pathParams + (name -> value)) + def withPathParam(name: String, value: Any): ApiRequest[U] = copy[U](pathParams = pathParams + (name -> value)) - def withQueryParam(name: String, value: Any) = copy[U](queryParams = queryParams + (name -> value)) + def withQueryParam(name: String, value: Any): ApiRequest[U] = copy[U](queryParams = queryParams + (name -> value)) - def withHeaderParam(name: String, value: Any) = copy[U](headerParams = headerParams + (name -> value)) + def withHeaderParam(name: String, value: Any): ApiRequest[U] = copy[U](headerParams = headerParams + (name -> value)) } diff --git a/modules/swagger-codegen/src/main/resources/akka-scala/apiSettings.mustache b/modules/swagger-codegen/src/main/resources/akka-scala/apiSettings.mustache index d101121c8c0..0d0d204cacd 100644 --- a/modules/swagger-codegen/src/main/resources/akka-scala/apiSettings.mustache +++ b/modules/swagger-codegen/src/main/resources/akka-scala/apiSettings.mustache @@ -20,18 +20,17 @@ class ApiSettings(config: Config) extends Extension { private def cfg = config.getConfig("io.swagger.client.apiRequest") - val alwaysTrustCertificates = cfg.getBoolean("trust-certificates") - val defaultHeaders = cfg.getConfig("default-headers").entrySet.toList.map(c => RawHeader(c.getKey, c.getValue.render)) + val alwaysTrustCertificates: Boolean = cfg.getBoolean("trust-certificates") + val defaultHeaders: List[RawHeader] = cfg.getConfig("default-headers").entrySet.toList.map(c => RawHeader(c.getKey, c.getValue.render)) val connectionTimeout = FiniteDuration(cfg.getDuration("connection-timeout", TimeUnit.MILLISECONDS), TimeUnit.MILLISECONDS) - val compressionEnabled = cfg.getBoolean("compression.enabled") - val compressionSizeThreshold = cfg.getBytes("compression.size-threshold").toInt - val customCodes = cfg.getConfigList("custom-codes").toList.map { c => CustomStatusCode( - c.getInt("code"), - c.getString("reason"), - c.getBoolean("success")) + val compressionEnabled: Boolean = cfg.getBoolean("compression.enabled") + val compressionSizeThreshold: Int = cfg.getBytes("compression.size-threshold").toInt + val customCodes: List[CustomStatusCode] = cfg.getConfigList("custom-codes").toList.map { c => + CustomStatusCode( + c.getInt("code"), + c.getString("reason"), + c.getBoolean("success")) } - - } object ApiSettings extends ExtensionKey[ApiSettings] diff --git a/modules/swagger-codegen/src/main/resources/akka-scala/build.sbt.mustache b/modules/swagger-codegen/src/main/resources/akka-scala/build.sbt.mustache index 6da2572974e..30510f4da30 100644 --- a/modules/swagger-codegen/src/main/resources/akka-scala/build.sbt.mustache +++ b/modules/swagger-codegen/src/main/resources/akka-scala/build.sbt.mustache @@ -1,26 +1,21 @@ -version := "{{artifactVersion}}" - -name := "{{artifactId}}" - -organization := "{{groupId}}" - -scalaVersion := "2.11.8" +version := "{{artifactVersion}}" +name := "{{artifactId}}" +organization := "{{groupId}}" +scalaVersion := "2.11.12" libraryDependencies ++= Seq( "io.swagger" % "swagger-core" % "1.5.15", - "com.typesafe" % "config" % "1.2.1", - "com.typesafe.akka" % "akka-actor_2.10" % "2.3.9", + "com.typesafe" % "config" % "1.3.2", + "com.typesafe.akka" %% "akka-actor" % "2.5.8", "io.spray" % "spray-client" % "1.3.1", - "joda-time" % "joda-time" % "2.2", - "org.joda" % "joda-convert" % "1.2", - "org.json4s" % "json4s-jackson_2.10" % "3.2.11", - "org.scalatest" %% "scalatest" % "2.2.4" % "test", - "junit" % "junit" % "4.8.1" % "test" + "joda-time" % "joda-time" % "2.9.9", + "org.joda" % "joda-convert" % "1.9.2", + "org.json4s" %% "json4s-jackson" % "3.5.3", + "org.scalatest" %% "scalatest" % "3.0.4" % "test", + "junit" % "junit" % "4.12" % "test" ) -resolvers ++= Seq( - Resolver.mavenLocal -) +resolvers ++= Seq(Resolver.mavenLocal) scalacOptions := Seq( "-unchecked", @@ -29,4 +24,3 @@ scalacOptions := Seq( ) publishArtifact in (Compile, packageDoc) := false - diff --git a/modules/swagger-codegen/src/main/resources/akka-scala/enumsSerializers.mustache b/modules/swagger-codegen/src/main/resources/akka-scala/enumsSerializers.mustache index 4577f59f969..3784981d3cb 100644 --- a/modules/swagger-codegen/src/main/resources/akka-scala/enumsSerializers.mustache +++ b/modules/swagger-codegen/src/main/resources/akka-scala/enumsSerializers.mustache @@ -11,27 +11,24 @@ import scala.reflect.ClassTag object EnumsSerializers { - def all = Seq[Serializer[_]](){{#models}}{{#model}}{{#hasEnums}}{{#vars}}{{#isEnum}} :+ + def all: Seq[Serializer[_]] = Seq[Serializer[_]](){{#models}}{{#model}}{{#hasEnums}}{{#vars}}{{#isEnum}} :+ new EnumNameSerializer({{classname}}Enums.{{datatypeWithEnum}}){{/isEnum}}{{/vars}}{{/hasEnums}}{{/model}}{{/models}} - - private class EnumNameSerializer[E <: Enumeration: ClassTag](enum: E) extends Serializer[E#Value] { import JsonDSL._ - val EnumerationClass = classOf[E#Value] + val EnumerationClass: Class[E#Value] = classOf[E#Value] def deserialize(implicit format: Formats): PartialFunction[(TypeInfo, JValue), E#Value] = { - case (t @ TypeInfo(EnumerationClass, _), json) if isValid(json) => { + case (t @ TypeInfo(EnumerationClass, _), json) if isValid(json) => json match { case JString(value) => enum.withName(value) case value => throw new MappingException(s"Can't convert $value to $EnumerationClass") } - } } private[this] def isValid(json: JValue) = json match { diff --git a/modules/swagger-codegen/src/main/resources/akka-scala/pom.mustache b/modules/swagger-codegen/src/main/resources/akka-scala/pom.mustache index 73066dfe256..da8f9d9043f 100644 --- a/modules/swagger-codegen/src/main/resources/akka-scala/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/akka-scala/pom.mustache @@ -1,246 +1,258 @@ - 4.0.0 - {{groupId}} - {{artifactId}} - jar - {{artifactId}} - {{artifactVersion}} + 4.0.0 - - - maven-mongodb-plugin-repo - maven mongodb plugin repository - http://maven-mongodb-plugin.googlecode.com/svn/maven/repo - default - - + {{artifactId}} - - - - org.apache.maven.plugins - maven-enforcer-plugin - 3.0.0-M1 - - - enforce-maven - - enforce - - - - - 2.2.0 - - - - - - - - org.apache.maven.plugins - maven-surefire-plugin - 2.12 - - - - loggerPath - conf/log4j.properties - - - -Xms512m -Xmx1500m - methods - pertest - - - - maven-dependency-plugin - - - package - - copy-dependencies - - - ${project.build.directory}/lib - - - - + {{groupId}} + {{artifactId}} + {{artifactVersion}} - - - org.apache.maven.plugins - maven-jar-plugin - 2.2 - - - - jar - test-jar - - - - - - + jar - - org.codehaus.mojo - build-helper-maven-plugin - 3.0.0 - - - add_sources - generate-sources - - add-source - - - - - src/main/java - - - - - add_test_sources - generate-test-sources - - add-test-source - - - - - src/test/java - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.6.1 - - - 1.7 - 1.7 - - - - net.alchim31.maven - scala-maven-plugin - ${scala-maven-plugin-version} - - - scala-compile-first - process-resources - - add-source - compile - - - - scala-test-compile - process-test-resources - - testCompile - - - - - - -feature - - - -Xms128m - -Xmx1500m - - - - - - - - - org.scala-tools - maven-scala-plugin - - ${scala-version} - - - - - - - org.scala-lang - scala-library - ${scala-version} - - - io.swagger - swagger-core - ${swagger-core-version} - - - org.scalatest - scalatest_2.10 - ${scala-test-version} - test - - - junit - junit - ${junit-version} - test - - - joda-time - joda-time - ${joda-time-version} - - - org.joda - joda-convert - ${joda-version} - - - com.typesafe - config - 1.2.1 - - - com.typesafe.akka - akka-actor_2.10 - ${akka-version} - - - io.spray - spray-client - ${spray-version} - - - org.json4s - json4s-jackson_2.10 - ${json4s-jackson-version} - - - - UTF-8 - 2.10.4 - 3.2.11 - 3.2.11 - 1.3.1 - 2.3.9 - 1.2 - 2.2 - 1.5.15 - 1.0.0 + + UTF-8 + UTF-8 + 1.8 + 2.11.12 + 3.5.3 + 3.2.11 + 1.3.1 + 2.5.8 + 1.9.2 + 2.9.9 + 1.5.15 + 1.0.0 - 4.8.1 - 3.1.5 - 2.2.0 - + 4.12 + 3.0.4 + + 3.3.1 + + + + + org.scala-lang + scala-library + ${scala-version} + + + io.swagger + swagger-core + ${swagger-core-version} + + + joda-time + joda-time + ${joda-time-version} + + + org.joda + joda-convert + ${joda-convert-version} + + + com.typesafe + config + 1.2.1 + + + com.typesafe.akka + akka-actor_2.11 + ${akka-version} + + + io.spray + spray-client + ${spray-version} + + + org.json4s + json4s-jackson_2.11 + ${json4s-jackson-version} + + + + org.scalatest + scalatest_2.11 + ${scala-test-version} + test + + + junit + junit + ${junit-version} + test + + + + + + maven-mongodb-plugin-repo + maven mongodb plugin repository + http://maven-mongodb-plugin.googlecode.com/svn/maven/repo + default + + + + + + + org.apache.maven.plugins + maven-enforcer-plugin + 3.0.0-M1 + + + enforce-maven + + enforce + + + + + 2.2.0 + + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.20.1 + + + + loggerPath + conf/log4j.properties + + + -Xms512m -Xmx1500m + methods + pertest + + + + org.apache.maven.plugins + maven-dependency-plugin + 3.0.2 + + + package + + copy-dependencies + + + ${project.build.directory}/lib + + + + + + + + org.apache.maven.plugins + maven-jar-plugin + 2.6 + + + + jar + test-jar + + + + + + + + + org.codehaus.mojo + build-helper-maven-plugin + 3.0.0 + + + add_sources + generate-sources + + add-source + + + + + src/main/java + + + + + + add_test_sources + generate-test-sources + + add-test-source + + + + + src/test/java + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.7.0 + + ${jdk.version} + ${jdk.version} + + + + net.alchim31.maven + scala-maven-plugin + ${scala-maven-plugin-version} + + + scala-compile-first + process-resources + + add-source + compile + + + + scala-test-compile + process-test-resources + + testCompile + + + + + + -feature + + + -Xms128m + -Xmx1500m + + + + + + + + + org.scala-tools + maven-scala-plugin + + ${scala-version} + + + + diff --git a/modules/swagger-codegen/src/main/resources/akka-scala/requests.mustache b/modules/swagger-codegen/src/main/resources/akka-scala/requests.mustache index 6680f84e09e..44a8208b9b5 100644 --- a/modules/swagger-codegen/src/main/resources/akka-scala/requests.mustache +++ b/modules/swagger-codegen/src/main/resources/akka-scala/requests.mustache @@ -7,20 +7,34 @@ package {{invokerPackage}} import java.io.File import java.net.URLEncoder + import scala.util.Try sealed trait ApiReturnWithHeaders { def headers: Map[String, String] + def header(name: String): Option[String] = headers.get(name) - def getStringHeader(name: String) = header(name) + + def getStringHeader(name: String): Option[String] = header(name) + // workaround: return date time header in string instead of datetime object - def getDateTimeHeader(name: String) = header(name) - def getIntHeader(name: String) = castedHeader(name, java.lang.Integer.parseInt) - def getLongHeader(name: String) = castedHeader(name, java.lang.Long.parseLong) - def getFloatHeader(name: String) = castedHeader(name, java.lang.Float.parseFloat) - def getDoubleHeader(name: String) = castedHeader(name, java.lang.Double.parseDouble) - def getBooleanHeader(name: String) = castedHeader(name, java.lang.Boolean.parseBoolean) - private def castedHeader[U](name: String, conversion: String => U): Option[U] = { Try { header(name).map( conversion ) }.get } + def getDateTimeHeader(name: String): Option[String] = header(name) + + def getIntHeader(name: String): Option[Int] = castedHeader(name, java.lang.Integer.parseInt) + + def getLongHeader(name: String): Option[Long] = castedHeader(name, java.lang.Long.parseLong) + + def getFloatHeader(name: String): Option[Float] = castedHeader(name, java.lang.Float.parseFloat) + + def getDoubleHeader(name: String): Option[Double] = castedHeader(name, java.lang.Double.parseDouble) + + def getBooleanHeader(name: String): Option[Boolean] = castedHeader(name, java.lang.Boolean.parseBoolean) + + private def castedHeader[U](name: String, conversion: String => U): Option[U] = { + Try { + header(name).map(conversion) + }.get + } } sealed case class ApiResponse[T](code: Int, content: T, headers: Map[String, String] = Map.empty) @@ -28,7 +42,7 @@ sealed case class ApiResponse[T](code: Int, content: T, headers: Map[String, Str sealed case class ApiError[T](code: Int, message: String, responseContent: Option[T], cause: Throwable = null, headers: Map[String, String] = Map.empty) extends Throwable(s"($code) $message.${responseContent.map(s => s" Content : $s").getOrElse("")}", cause) - with ApiReturnWithHeaders + with ApiReturnWithHeaders sealed case class ApiMethod(value: String) @@ -74,15 +88,17 @@ object ApiKeyLocations { case object QUERY extends ApiKeyLocation case object HEADER extends ApiKeyLocation + } /** * Case class used to unapply numeric values only in pattern matching + * * @param value the string representation of the numeric value */ sealed case class NumericValue(value: String) { - override def toString = value + override def toString: String = value } object NumericValue { @@ -144,9 +160,9 @@ object ParametersMap { */ implicit class ParametersMapImprovements(val m: Map[String, Any]) { - def asFormattedParamsList = m.toList.flatMap(formattedParams) + def asFormattedParamsList: List[(String, Any)] = m.toList.flatMap(formattedParams) - def asFormattedParams = m.flatMap(formattedParams) + def asFormattedParams: Map[String, Any] = m.flatMap(formattedParams) private def urlEncode(v: Any) = URLEncoder.encode(String.valueOf(v), "utf-8").replaceAll("\\+", "%20") @@ -159,15 +175,13 @@ object ParametersMap { case format: MergedArrayFormat => Seq((name, arr.values.mkString(format.separator))) } case None => Seq.empty - case Some(opt) => - formattedParams(name, opt) - case s: Seq[Any] => - formattedParams(name, ArrayValues(s)) + case Some(opt) => formattedParams(name, opt) + case s: Seq[Any] => formattedParams(name, ArrayValues(s)) case v: String => Seq((name, urlEncode(v))) case NumericValue(v) => Seq((name, urlEncode(v))) case f: File => Seq((name, f)) case m: ApiModel => Seq((name, m)) } - } + }