Groovy client generation

This commit is contained in:
Victor Trakhtenberg 2013-07-18 13:27:22 +03:00
parent db68a3acbd
commit 8135cd65dc
5 changed files with 213 additions and 0 deletions

View File

@ -0,0 +1,49 @@
package {{invokerPackage}};
import groovyx.net.http.HTTPBuilder
import groovyx.net.http.Method
import static groovyx.net.http.ContentType.JSON
import static java.net.URI.create;
class ApiUtils {
def onSuccessPrintResult = {println "Successfully invoked API $it"}
def onFailurePrintError = {status, message -> println "Failed to invoke API $status $message"}
def invokeApi(onSuccess, onFailure, basePath, versionPath, resourcePath, queryParams, headerParams, method, container, type) {
def (url, uriPath) = buildUrlAndUriPath(basePath, versionPath, resourcePath)
println "url=$url uriPath=$uriPath"
def http = new HTTPBuilder(url)
http.request( Method.valueOf(method), JSON ) {
uri.path = uriPath
uri.query = queryParams
response.success = { resp, json ->
if (type != null) {
onSuccess(parse(json, container, type))
}
}
response.failure = { resp ->
onFailure(resp.status, resp.statusLine.reasonPhrase)
}
}
}
def buildUrlAndUriPath(basePath, versionPath, resourcePath) {
URI baseUri = create(basePath)
def pathOnly = baseUri.getPath()
[basePath-pathOnly, pathOnly+versionPath+resourcePath]
}
def parse(object, container, clazz) {
if (container == "List") {
return object.collect {parse(it, "", clazz)}
} else {
return clazz.newInstance(object)
}
}
}

View File

@ -0,0 +1,56 @@
package {{package}};
import groovyx.net.http.*
import static groovyx.net.http.ContentType.*
import static groovyx.net.http.Method.*
import {{invokerPackage}}.ApiUtils
//-------------
{{#imports}}import {{import}}
{{/imports}}
import java.util.*;
@Mixin(ApiUtils)
{{#operations}}
class {{classname}} {
String basePath = "{{basePath}}"
String versionPath = "/api/v1"
{{#operation}}
def {{nickname}} ({{#allParams}} {{{dataType}}} {{paramName}},{{/allParams}} Closure onSuccess, Closure onFailure) {
// create path and map variables
String resourcePath = "{{path}}"
// query params
def queryParams = [:]
def headerParams = [:]
{{#requiredParamCount}}
// verify required params are set
if({{/requiredParamCount}}{{#requiredParams}} {{paramName}} == null {{#hasMore}}|| {{/hasMore}}{{/requiredParams}}{{#requiredParamCount}}) {
throw new RuntimeException("missing required params")
}
{{/requiredParamCount}}
{{#queryParams}}if(!"null".equals(String.valueOf({{paramName}})))
queryParams.put("{{paramName}}", String.valueOf({{paramName}}))
{{/queryParams}}
{{#headerParams}}headerParams.put("{{paramName}}", {{paramName}})
{{/headerParams}}
invokeApi(onSuccess, onFailure, basePath, versionPath, resourcePath, queryParams, headerParams,
"{{httpMethod}}", "{{returnContainer}}",
{{#returnBaseType}}{{{returnBaseType}}}.class {{/returnBaseType}}{{^returnBaseType}}null {{/returnBaseType}})
}
{{/operation}}
}
{{/operations}}

View File

@ -0,0 +1,32 @@
apply plugin: 'groovy'
apply plugin: 'idea'
def artifactory = 'buildserver.supportspace.com'
group = 'com.supportspace'
archivesBaseName = 'swagger-gen-groovy'
version = '0.1'
buildscript {
repositories {
maven { url 'http://repo.jfrog.org/artifactory/gradle-plugins' }
}
dependencies {
classpath(group: 'org.jfrog.buildinfo', name: 'build-info-extractor-gradle', version: '2.0.16')
}
}
repositories {
mavenCentral()
mavenLocal()
mavenCentral(artifactUrls: ['http://maven.springframework.org/milestone'])
maven { url "http://$artifactory:8080/artifactory/repo" }
}
dependencies {
groovy "org.codehaus.groovy:groovy-all:2.0.5"
compile 'org.codehaus.groovy.modules.http-builder:http-builder:0.6'
}
task wrapper(type: Wrapper) { gradleVersion = '1.6' }

View File

@ -0,0 +1,21 @@
package {{package}};
import groovy.transform.Canonical
{{#imports}}import {{import}};
{{/imports}}
{{#models}}
{{#model}}
@Canonical
class {{classname}} {
{{#vars}}
{{#description}}/* {{{description}}} */
{{/description}}
{{{datatype}}} {{name}} = {{{defaultValue}}}
{{/vars}}
}
{{/model}}
{{/models}}

View File

@ -0,0 +1,55 @@
/**
* Copyright 2012 Wordnik, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file 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.
*/
package com.wordnik.swagger.codegen
import com.wordnik.swagger.codegen.BasicJavaGenerator
object BasicGroovyGenerator extends BasicGroovyGenerator {
def main(args: Array[String]) = generateClient(args)
}
class BasicGroovyGenerator extends BasicJavaGenerator {
// location of templates
override def templateDir = "Groovy"
// where to write generated code
override def destinationDir = "generated-code/groovy/src/main/groovy"
// template used for models
modelTemplateFiles += "model.mustache" -> ".groovy"
// template used for models
apiTemplateFiles += "api.mustache" -> ".groovy"
// package for models
override def modelPackage = Some("com.wordnik.client.model")
// package for api classes
override def apiPackage = Some("com.wordnik.client.api")
// file suffix
override def fileSuffix = ".groovy"
override def supportingFiles =
List(
("ApiUtils.mustache", destinationDir + java.io.File.separator + invokerPackage.get.replace(".", java.io.File.separator) + java.io.File.separator, "ApiUtils.groovy"),
("build.gradle.mustache", "generated-code/groovy", "build.gradle"))
}