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] format the Scala code style templete #6532

Merged
merged 5 commits into from Sep 29, 2017
Merged
Show file tree
Hide file tree
Changes from all 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
15 changes: 9 additions & 6 deletions modules/swagger-codegen/src/main/resources/scala/api.mustache
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,10 @@ import scala.concurrent.duration._
import scala.util.{Failure, Success, Try}

{{#operations}}
class {{classname}}(val defBasePath: String = "{{{basePath}}}",
defApiInvoker: ApiInvoker = ApiInvoker) {
class {{classname}}(
val defBasePath: String = "{{{basePath}}}",
defApiInvoker: ApiInvoker = ApiInvoker
) {

implicit val formats = new org.json4s.DefaultFormats {
override def dateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS+0000")
Expand All @@ -45,10 +47,12 @@ class {{classname}}(val defBasePath: String = "{{{basePath}}}",
implicit val stringWriter = RequestWriters.StringWriter
implicit val jsonWriter = JsonFormatsWriter

var basePath = defBasePath
var apiInvoker = defApiInvoker
var basePath: String = defBasePath
var apiInvoker: ApiInvoker = defApiInvoker

def addHeader(key: String, value: String) = apiInvoker.defaultHeaders += key -> value
def addHeader(key: String, value: String): mutable.HashMap[String, String] = {
apiInvoker.defaultHeaders += key -> value
}

val config = SwaggerConfig.forUrl(new URI(defBasePath))
val client = new RestClient(config)
Expand Down Expand Up @@ -79,7 +83,6 @@ class {{classname}}(val defBasePath: String = "{{{basePath}}}",
helper.{{operationId}}({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}})
}


{{/operation}}
}

Expand Down
154 changes: 83 additions & 71 deletions modules/swagger-codegen/src/main/resources/scala/apiInvoker.mustache
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import java.util.UUID
import javax.ws.rs.core.MediaType

import scala.collection.JavaConverters._
import scala.collection.mutable.HashMap
import scala.collection.mutable

import com.fasterxml.jackson.module.scala.DefaultScalaModule
import com.fasterxml.jackson.datatype.joda.JodaModule
Expand All @@ -30,8 +30,8 @@ object ScalaJsonUtil {
def getJsonMapper = {
val mapper = new ObjectMapper()
mapper.registerModule(new DefaultScalaModule())
mapper.registerModule(new JodaModule());
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
mapper.registerModule(new JodaModule())
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL)
mapper.setSerializationInclusion(JsonInclude.Include.NON_DEFAULT)
mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
Expand All @@ -41,13 +41,14 @@ object ScalaJsonUtil {
}

class ApiInvoker(val mapper: ObjectMapper = ScalaJsonUtil.getJsonMapper,
httpHeaders: HashMap[String, String] = HashMap(),
hostMap: HashMap[String, Client] = HashMap(),
asyncHttpClient: Boolean = false,
authScheme: String = "",
authPreemptive: Boolean = false) {
httpHeaders: mutable.HashMap[String, String] = mutable.HashMap(),
hostMap: mutable.HashMap[String, Client] = mutable.HashMap(),
asyncHttpClient: Boolean = false,
authScheme: String = "",
authPreemptive: Boolean = false
) {

var defaultHeaders: HashMap[String, String] = httpHeaders
var defaultHeaders: mutable.HashMap[String, String] = httpHeaders

def escape(value: String): String = {
URLEncoder.encode(value, "utf-8").replaceAll("\\+", "%20")
Expand All @@ -61,30 +62,29 @@ class ApiInvoker(val mapper: ObjectMapper = ScalaJsonUtil.getJsonMapper,
def deserialize(json: String, containerType: String, cls: Class[_]) = {
if (cls == classOf[String]) {
json match {
case s: String => {
if (s.startsWith("\"") && s.endsWith("\"") && s.length > 1) s.substring(1, s.length - 1)
else s
}
case s: String =>
if (s.startsWith("\"") && s.endsWith("\"") && s.length > 1) {
s.substring(1, s.length - 1)
} else {
s
}
case _ => null
}
} else {
containerType.toLowerCase match {
case "array" => {
val typeInfo = mapper.getTypeFactory().constructCollectionType(classOf[java.util.List[_]], cls)
case "array" =>
val typeInfo = mapper.getTypeFactory.constructCollectionType(classOf[java.util.List[_]], cls)
val response = mapper.readValue(json, typeInfo).asInstanceOf[java.util.List[_]]
response.asScala.toList
}
case "list" => {
val typeInfo = mapper.getTypeFactory().constructCollectionType(classOf[java.util.List[_]], cls)
case "list" =>
val typeInfo = mapper.getTypeFactory.constructCollectionType(classOf[java.util.List[_]], cls)
val response = mapper.readValue(json, typeInfo).asInstanceOf[java.util.List[_]]
response.asScala.toList
}
case _ => {
case _ =>
json match {
case e: String if ("\"\"" == e) => null
case e: String if "\"\"" == e => null
case _ => mapper.readValue(json, cls)
}
}
}
}
}
Expand All @@ -95,116 +95,128 @@ class ApiInvoker(val mapper: ObjectMapper = ScalaJsonUtil.getJsonMapper,
case e: List[_] => mapper.writeValueAsString(obj.asInstanceOf[List[_]].asJava)
case _ => mapper.writeValueAsString(obj)
}
} else null
} else {
null
}
}

def invokeApi(host: String, path: String, method: String, queryParams: Map[String, String], formParams: Map[String, String], body: AnyRef, headerParams: Map[String, String], contentType: String): String = {
def invokeApi(
host: String,
path: String,
method: String,
queryParams: Map[String, String],
formParams: Map[String, String],
body: AnyRef,
headerParams: Map[String, String],
contentType: String
): String = {
val client = getClient(host)

val querystring = queryParams.filter(k => k._2 != null).map(k => (escape(k._1) + "=" + escape(k._2))).mkString("?", "&", "")
val querystring = queryParams.filter(k => k._2 != null).map(k => escape(k._1) + "=" + escape(k._2)).mkString("?", "&", "")
val builder = client.resource(host + path + querystring).accept(contentType)
headerParams.map(p => builder.header(p._1, p._2))
defaultHeaders.map(p => {
defaultHeaders.foreach(p => {
headerParams.contains(p._1) match {
case true => // override default with supplied header
case false => if (p._2 != null) builder.header(p._1, p._2)
}
})
var formData: MultivaluedMapImpl = null
if(contentType == "application/x-www-form-urlencoded") {
if (contentType == "application/x-www-form-urlencoded") {
formData = new MultivaluedMapImpl()
formParams.map(p => formData.add(p._1, p._2))
formParams.foreach(p => formData.add(p._1, p._2))
}

val response: ClientResponse = method match {
case "GET" => {
builder.get(classOf[ClientResponse]).asInstanceOf[ClientResponse]
}
case "POST" => {
if(formData != null) builder.post(classOf[ClientResponse], formData)
else if(body != null && body.isInstanceOf[File]) {
case "GET" => builder.get(classOf[ClientResponse]).asInstanceOf[ClientResponse]
case "POST" =>
if (formData != null && formData.size() > 0) {
builder.post(classOf[ClientResponse], formData)
} else if (body != null && body.isInstanceOf[File]) {
val file = body.asInstanceOf[File]
val form = new FormDataMultiPart()
form.field("filename", file.getName())
form.field("filename", file.getName)
form.bodyPart(new FileDataBodyPart("file", file, MediaType.MULTIPART_FORM_DATA_TYPE))
builder.post(classOf[ClientResponse], form)
} else {
if (body == null) {
builder.post(classOf[ClientResponse], serialize(body))
} else {
builder.`type`(contentType).post(classOf[ClientResponse], serialize(body))
}
}
else {
if(body == null) builder.post(classOf[ClientResponse], serialize(body))
else builder.`type`(contentType).post(classOf[ClientResponse], serialize(body))
case "PUT" =>
if (formData != null) {
builder.post(classOf[ClientResponse], formData)
} else if (body == null) {
builder.put(classOf[ClientResponse], null)
} else {
builder.`type`(contentType).put(classOf[ClientResponse], serialize(body))
}
case "DELETE" => builder.delete(classOf[ClientResponse])
case "PATCH" =>
if(formData != null) {
builder.header("X-HTTP-Method-Override", "PATCH").post(classOf[ClientResponse], formData)
} else if(body == null) {
builder.header("X-HTTP-Method-Override", "PATCH").post(classOf[ClientResponse], null)
} else {
builder.header("X-HTTP-Method-Override", "PATCH").`type`(contentType).post(classOf[ClientResponse], serialize(body))
}
}
case "PUT" => {
if(formData != null) builder.post(classOf[ClientResponse], formData)
else if(body == null) builder.put(classOf[ClientResponse], null)
else builder.`type`(contentType).put(classOf[ClientResponse], serialize(body))
}
case "DELETE" => {
builder.delete(classOf[ClientResponse])
}
case "PATCH" => {
if(formData != null) builder.header("X-HTTP-Method-Override", "PATCH").post(classOf[ClientResponse], formData)
else if(body == null) builder.header("X-HTTP-Method-Override", "PATCH").post(classOf[ClientResponse], null)
else builder.header("X-HTTP-Method-Override", "PATCH").`type`(contentType).post(classOf[ClientResponse], serialize(body))
}
case _ => null
}
response.getStatusInfo().getStatusCode() match {
response.getStatusInfo.getStatusCode match {
case 204 => ""
case code: Int if (Range(200, 299).contains(code)) => {
response.hasEntity() match {
case code: Int if Range(200, 299).contains(code) =>
response.hasEntity match {
case true => response.getEntity(classOf[String])
case false => ""
}
}
case _ => {
val entity = response.hasEntity() match {
case _ =>
val entity = response.hasEntity match {
case true => response.getEntity(classOf[String])
case false => "no data"
}
throw new ApiException(
response.getStatusInfo().getStatusCode(),
entity)
}
throw new ApiException(response.getStatusInfo.getStatusCode, entity)
}
}

def getClient(host: String): Client = {
hostMap.contains(host) match {
case true => hostMap(host)
case false => {
case false =>
val client = newClient(host)
// client.addFilter(new LoggingFilter())
hostMap += host -> client
client
}
}
}

def newClient(host: String): Client = asyncHttpClient match {
case true => {
case true =>
import org.sonatype.spice.jersey.client.ahc.config.DefaultAhcConfig
import org.sonatype.spice.jersey.client.ahc.AhcHttpClient
import com.ning.http.client.Realm

val config: DefaultAhcConfig = new DefaultAhcConfig()
if (!authScheme.isEmpty) {
val authSchemeEnum = Realm.AuthScheme.valueOf(authScheme)
config.getAsyncHttpClientConfigBuilder
config
.getAsyncHttpClientConfigBuilder
.setRealm(new Realm.RealmBuilder().setScheme(authSchemeEnum)
.setUsePreemptiveAuth(authPreemptive).build)
}
AhcHttpClient.create(config)
}
case _ => Client.create()
}
}

object ApiInvoker extends ApiInvoker(mapper = ScalaJsonUtil.getJsonMapper,
httpHeaders = HashMap(),
hostMap = HashMap(),
object ApiInvoker extends ApiInvoker(
mapper = ScalaJsonUtil.getJsonMapper,
httpHeaders = mutable.HashMap(),
hostMap = mutable.HashMap(),
asyncHttpClient = {{asyncHttpClient}},
authScheme = "{{authScheme}}",
authPreemptive = {{authPreemptive}})
authPreemptive = {{authPreemptive}}
)

class ApiException(val code: Int, msg: String) extends RuntimeException(msg)
10 changes: 5 additions & 5 deletions modules/swagger-codegen/src/main/resources/scala/pom.mustache
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@
<dependencies>
<dependency>
<groupId>com.fasterxml.jackson.module</groupId>
<artifactId>jackson-module-scala_2.10</artifactId>
<artifactId>jackson-module-scala_2.11</artifactId>
<version>${jackson-version}</version>
</dependency>
<dependency>
Expand Down Expand Up @@ -189,7 +189,7 @@
</dependency>
<dependency>
<groupId>org.scalatest</groupId>
<artifactId>scalatest_2.10</artifactId>
<artifactId>scalatest_2.11</artifactId>
<version>${scala-test-version}</version>
<scope>test</scope>
</dependency>
Expand All @@ -211,16 +211,16 @@
</dependency>
<dependency>
<groupId>com.wordnik.swagger</groupId>
<artifactId>swagger-async-httpclient_2.10</artifactId>
<artifactId>swagger-async-httpclient_2.11</artifactId>
<version>${swagger-async-httpclient-version}</version>
</dependency>
</dependencies>
<properties>
<scala-version>2.10.4</scala-version>
<scala-version>2.11.11</scala-version>
<joda-version>1.2</joda-version>
<joda-time-version>2.2</joda-time-version>
<jersey-version>1.19</jersey-version>
<swagger-core-version>1.5.15</swagger-core-version>
<swagger-core-version>1.5.16</swagger-core-version>
<jersey-async-version>1.0.5</jersey-async-version>
<maven-plugin.version>1.0.0</maven-plugin.version>
<jackson-version>2.8.9</jackson-version>
Expand Down
Loading