diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..2af7cef
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,24 @@
+target/
+!.mvn/wrapper/maven-wrapper.jar
+
+### STS ###
+.apt_generated
+.classpath
+.factorypath
+.project
+.settings
+.springBeans
+
+### IntelliJ IDEA ###
+.idea
+*.iws
+*.iml
+*.ipr
+
+### NetBeans ###
+nbproject/private/
+build/
+nbbuild/
+dist/
+nbdist/
+.nb-gradle/
\ No newline at end of file
diff --git a/.mvn/wrapper/maven-wrapper.jar b/.mvn/wrapper/maven-wrapper.jar
new file mode 100644
index 0000000..9cc84ea
Binary files /dev/null and b/.mvn/wrapper/maven-wrapper.jar differ
diff --git a/.mvn/wrapper/maven-wrapper.properties b/.mvn/wrapper/maven-wrapper.properties
new file mode 100644
index 0000000..9dda3b6
--- /dev/null
+++ b/.mvn/wrapper/maven-wrapper.properties
@@ -0,0 +1 @@
+distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.5.2/apache-maven-3.5.2-bin.zip
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..514f6db
--- /dev/null
+++ b/README.md
@@ -0,0 +1,357 @@
+# Swagger 示例
+- [OpenAPI 和 Swagger](#OpenAPI-和-Swagger)
+ * [OpenAPI](#OpenAPI)
+ * [Swagger](#Swagger)
+ * [为什么要使用OpenAPI](#为什么要使用OpenAPI)
+- [Swagger规范介绍](#Swagger规范介绍)
+ * [基本结构](#基本结构)
+ * [元数据](#元数据)
+ * [基本URL](#基本URL)
+ * [消费和生产](#消费和生产)
+ * [路径](#路径)
+ * [参数](#参数)
+ * [响应](#响应)
+ * [输入和输出模型](#输入和输出模型)
+ * [认证](#认证)
+- [Swagger工具箱](#Swagger工具箱)
+ * [Swagger Editor](#Swagger-Editor)
+ * [Swagger UI](#Swagger-UI)
+ * [Swagger Codegen](#Swagger-Codegen)
+ * [asciidoctor](#asciidoctor)
+- [如何开始](#如何开始)
+
+
+## OpenAPI 和 Swagger
+### OpenAPI
+OpenAPI规范(以前叫Swagger规范)是Linux基金会的一个项目,试图通过定义一种用来描述API格式或API定义的语言,来规范RESTful服务开发过程。OpenAPI规范帮助我们描述一个API的全部信息,比如:
+
+* 可用路径(```/users```)和每个路径上的可用操作(```GET /users```, ```POST /users```)
+* 每个操作的输入/输出参数
+* 安全认证方法
+* 联系信息、许可证、使用条款和其他信息
+
+我们可以选择使用JSON或者YAML的语言格式来编写API文档, 这两种格式对人和机器都是可读的
+
+### Swagger
+
+Swagger是围绕OpenAPI规范建立的一系列工具,可以帮我们设计、构建、编写文档和消费REST APIs
+
+主要工具包括:
+* Swagger Editor – 基于浏览器的编写OpenAPI文档的工具
+* Swagger UI – 把OpenAPI文档转换成交互式文档的工具
+* Swagger Codegen – 从OpenAPI文档生成服务器和客户端代码
+
+### 为什么要使用OpenAPI
+API描述自己结构的能力是OpenAPI中所有卓越功能的根源。一旦写好OpenAPI文档,OpenAPI规范和Swagger工具可以通过各种方式进一步驱动API开发:
+
+* 对于先有设计的用户:使用Swagger Codegen为API来生成服务器存根。唯一剩下的就是实现服务器逻辑 - API已经准备好了!
+* 使用Swagger Codegen,可以为40多种语言的API 生成客户端。
+* 使用Swagger UI生成交互式API文档,让用户直接在浏览器中尝试API调用。
+* 使用OpenAPI规范文档将API相关工具连接到API。例如,将规范导入到SoapUI中,为API创建自动测试。
+
+-----
+-----
+
+## Swagger规范介绍
+
+### **基本结构**
+Swagger可以用JSON或YAML编写。在本例中,我们只使用YAML示例,但JSON工作效果一样好。
+
+用YAML编写的Swagger示例示例如下所示:
+```yaml
+swagger: "2.0"
+info:
+ title: Sample API
+ description: API description in Markdown.
+ version: 1.0.0
+
+host: api.example.com
+basePath: /v1
+schemes:
+ - https
+
+paths:
+ /users:
+ get:
+ summary: Returns a list of users.
+ description: Optional extended description in Markdown.
+ produces:
+ - application/json
+ responses:
+ 200:
+ description: OK
+```
+
+
+### **元数据**
+每个Swagger规范文档以Swagger版本开始,2.0是最新版本。Swagger版本定义了API规范的整体结构 - 可以记录什么以及如何记录它。
+
+```yaml
+swagger: "2.0"
+```
+
+然后,需要指定```API info```,```title```(```description```可选),```version```(API的版本,而不是文件版本或Swagger版本)。
+
+```yaml
+info:
+ title: Sample API
+ description: API description in Markdown.
+ version: 1.0.0
+```
+
+```version``` 可以是一个任意字符串。可以使用major.minor.patch(如语义化版本控制规范),或任意格式,如1.0-beta或2016.11.15。
+
+```description``` 支持多行和GitHub Flavored Markdown,用于丰富的文本表示。
+
+```info``` 还支持其他字段, 比如联系信息,许可证和其他详细信息。
+
+
+### **基本URL**
+所有API调用的基本URL由```schemes```,```host```和```basePath```定义:
+
+```yaml
+host: api.example.com
+basePath: /v1
+schemes:
+ - https
+```
+
+所有API路径都是相对于基本URL。例如,/ users实际上是指*https://api.example.com/v1/users*。
+
+
+### **消费和生产**
+
+```consumes``` 与 ```produces``` 部分定义API所支持的MIME类型。根级别定义可以在各个操作中被覆盖。
+
+```yaml
+consumes:
+ - application/json
+ - application/xml
+produces:
+ - application/json
+ - application/xml
+```
+
+
+### **路径**
+该```paths```部分定义了API中的各个端点(路径)以及这些端点支持的HTTP方法(操作)。例如,```GET /users```可以描述为:
+```yaml
+paths:
+ /users:
+ get:
+ summary: Returns a list of users.
+ description: Optional extended description in Markdown.
+ produces:
+ - application/json
+ responses:
+ 200:
+ description: OK
+
+```
+
+
+### **参数**
+操作可以包含参数,可以通过URL path(```/users/{userId}```),query string(```/users?role=admin```),headers(```X-CustomHeader:
+Value```)和请求体传递的参数。可以定义参数类型,格式,是否需要或可选,以及其他详细信息:
+```yaml
+paths:
+ /users/{userId}:
+ get:
+ summary: Returns a user by ID.
+ parameters:
+ - in: path
+ name: userId
+ required: true
+ type: integer
+ minimum: 1
+ description: Parameter description in Markdown.
+ responses:
+ 200:
+ description: OK
+```
+
+
+### **响应**
+对于每个操作,可以定义可能的状态代码,例如200 OK或404 Not Found,以及```schema```响应内容。响应内容可以通过内联定义或从外部定义引用```$ref```。还可以为不同的内容类型提供示例响应。
+```yaml
+paths:
+ /users/{userId}:
+ get:
+ summary: Returns a user by ID.
+ parameters:
+ - in: path
+ name: userId
+ required: true
+ type: integer
+ minimum: 1
+ description: The ID of the user to return.
+ responses:
+ 200:
+ description: A User object.
+ schema:
+ type: object
+ properties:
+ id:
+ type: integer
+ example: 4
+ name:
+ type: string
+ example: Arthur Dent
+ 400:
+ description: The specified user ID is invalid (e.g. not a number).
+ 404:
+ description: A user with the specified ID was not found.
+ default:
+ description: Unexpected error
+```
+
+
+### **输入和输出模型**
+全局```definitions```部分允许定义API中使用的公共数据结构。每当```schema```需要时,可以使用```$ref```引用它们,无论是请求体和响应体。
+
+例如,这个JSON对象:
+```json
+{
+ "id": 4,
+ "name": "Arthur Dent"
+}
+```
+可以表示为:
+```yaml
+definitions:
+ User:
+ properties:
+ id:
+ type: integer
+ name:
+ type: string
+ # Both properties are required
+ required:
+ - id
+ - name
+
+```
+
+然后在request body和response body中引用如下:
+
+```yaml
+paths:
+ /users/{userId}:
+ get:
+ summary: Returns a user by ID.
+ parameters:
+ - in: path
+ name: userId
+ required: true
+ type: integer
+ responses:
+ 200:
+ description: OK
+ schema:
+ $ref: '#/definitions/User'
+ /users:
+ post:
+ summary: Creates a new user.
+ parameters:
+ - in: body
+ name: user
+ schema:
+ $ref: '#/definitions/User'
+ responses:
+ 200:
+ description: OK
+```
+
+
+### **认证**
+
+```securityDefinitions``` 和 ```security``` 关键字用于描述API中使用的身份认证方式。
+
+```yaml
+securityDefinitions:
+ BasicAuth:
+ type: basic
+
+security:
+ - BasicAuth: []
+```
+
+
+支持的认证方法有:
+
+* Basic authentication
+* API key (as a header or query parameter)
+* OAuth 2 common flows (implicit, password, application and access code)
+
+
+## Swagger工具箱
+### **Swagger Editor**
+Swagger Editor是第一个开源的专注于Swagger-based APIs的编辑器,
+可以设计、描述、记录API。Swagger编辑器非常适合快速入门Swagger规范。它清爽,高效,并具有许多功能,可帮助设计和记录RESTful接口,开箱即用。
+
+Swagger Editor允许在浏览器内的YAML中编辑Swagger API规范,并实时预览文档。然后可以使用完整的Swagger工具(代码生成,文档等)。
+
+* 在任何地方运行: 编辑器可以工作在任何开发环境中,无论是在本地还是在网络中
+* 智能反馈:输入时有简明反馈和错误提示以及验证Swagger-compliance的语法
+* 即时可视化:当你还在定义API文档时就直观地呈现,同时与API进行交互
+* 智能自动完成:通过智能自动完成来更快编写
+* 完全可定制:轻松配置和自定义任何东西,从行间距到主题
+* 关于构建:为API生成每种流行语言的服务器端和客户端
+
+### **Swagger UI**
+Swagger UI允许任何人,无论是开发团队还是最终消费者,都可以可视化地与API资源进行交互,而无需有任何实现逻辑。它是从Swagger规范自动生成的,可视化文档使后端实现和客户端消费变得容易。
+
+* 依赖关系:在任何环境中托管Swagger UI
+* 人性化:允许客户端开发人员轻松交互,并尝试API暴露的每个操作,以方便消费
+* 易于导航:通过整齐分类的文档快速查找和使用资源和端点
+* 所有浏览器支持:Swagger UI可以在所有主流浏览器中运行
+* 完全可定制:代码完全开源,可以个性化定制和调整Swagger UI
+
+### **Swagger Codegen**
+使用Swagger Codegen,对于每种流行语言,可以更快地构建和改善基于Swagger定义的API。Swagger
+Codegen可以从Swagger规范生成服务器端和客户端SDK来简化构建过程,因此团队可以更好地关注API的实现和适配。
+
+* 生成服务器:通过生成超过20种不同语言的样板服务器代码来消除繁琐的调整和配置
+* 改善API消费:生成超过40种不同语言的客户端SDK,使客户端开发人员轻松与API集成
+* 持续改进:Swagger Codegen始终使用编程世界中最新和最好的改进进行更新
+
+### **asciidoctor**
+* asciidoc
+* asciidoctor
+
+Asciidoctor是一种用于将AsciiDoc内容转换为HTML5,DocBook 5(或4.5)和其他格式的快速文本处理器和发布工具链。Asciidoctor是用Ruby编写的,封装成RubyGem并发布到RubyGems
+.org。该Gem还包含在几个Linux发行版中,包括Fedora,Debian和Ubuntu。Asciidoctor是开源的,托管在GitHub上,并根据MIT许可证发布。
+
+## 如何开始
+
+1.install: git clone 之后, 在根目录执行:
+
+```
+swagger-server/bin/install.sh
+```
+
+会生成几种客户端SDK、服务器端stub和asciidoc、html文档,目录结构如下:
+
+```
++---asciidoc //asciidoc文档
++---client //自动生成的客户端
+| +---go //--go语言客户端
+| +---html2 //--html文档
+| \---java //--java客户端
++---docs //html文档
+| swagger-example.html
++---server //自动生成的服务器端stub
+| +---jaxrs-resteasy //--使用resteasy生成jaxrs的服务器端stub
+| \---spring //--spring服务器端stub
+\---swagger-server //一个server的例子, 可以生成swagger.json
+```
+
+2.运行swagger-server:
+
+```
+java -jar swagger-server/target/swagger-server-${version}.jar
+```
+
+swagger.json: `http://127.0.0.1:8080/v2/api-docs`
+
+swagger-ui: `http://127.0.0.1:8080/swagger-ui.html`
\ No newline at end of file
diff --git a/asciidoc/swagger-example.adoc b/asciidoc/swagger-example.adoc
new file mode 100644
index 0000000..fdbbd95
--- /dev/null
+++ b/asciidoc/swagger-example.adoc
@@ -0,0 +1,331 @@
+= Swagger Demo
+
+
+[[_overview]]
+== Overview
+Swagger的简单示例, 包括swagger-codegen, swagger2markup 和 asciidoctor.
+
+
+=== Version information
+[%hardbreaks]
+__Version__ : v1
+
+
+=== Contact information
+[%hardbreaks]
+__Contact__ : Damon
+__Contact Email__ : damon.q@iv66.net
+
+
+=== License information
+[%hardbreaks]
+__License__ : Apache License
+__License URL__ : http://www.apache.org/licenses/LICENSE-2.0.html
+__Terms of service__ : http://www.apache.org/licenses/LICENSE-2.0.html
+
+
+=== URI scheme
+[%hardbreaks]
+__Host__ : localhost:8080
+__BasePath__ : /
+__Schemes__ : HTTP, HTTPS
+
+
+=== Tags
+
+* book-api : Book Api
+* category-api : Category Api
+
+
+
+
+[[_paths]]
+== Paths
+
+[[_getbooksbycategoryusingget]]
+=== 根据分类获取书籍
+....
+GET /v1/book/getByCategoryId
+....
+
+
+==== Parameters
+
+[options="header", cols=".^2,.^3,.^9,.^4"]
+|===
+|Type|Name|Description|Schema
+|**Query**|**id** +
+__required__|id|integer (int32)
+|===
+
+
+==== Responses
+
+[options="header", cols=".^2,.^14,.^4"]
+|===
+|HTTP Code|Description|Schema
+|**200**|OK|< <<_book,Book>> > array
+|**401**|Unauthorized|No Content
+|**403**|Forbidden|No Content
+|**404**|Not Found|No Content
+|===
+
+
+==== Consumes
+
+* `application/json`
+
+
+==== Produces
+
+* `*/*`
+
+
+==== Tags
+
+* book-api
+
+
+==== Security
+
+[options="header", cols=".^3,.^4"]
+|===
+|Type|Name
+|**apiKey**|**<<_api_key,api_key>>**
+|===
+
+
+[[_updateusingpost]]
+=== 更新书籍
+....
+POST /v1/book/update
+....
+
+
+==== Parameters
+
+[options="header", cols=".^2,.^3,.^9,.^4"]
+|===
+|Type|Name|Description|Schema
+|**Body**|**id** +
+__optional__|id|integer (int32)
+|===
+
+
+==== Responses
+
+[options="header", cols=".^2,.^14,.^4"]
+|===
+|HTTP Code|Description|Schema
+|**200**|OK|boolean
+|**201**|Created|No Content
+|**401**|Unauthorized|No Content
+|**403**|Forbidden|No Content
+|**404**|Not Found|No Content
+|===
+
+
+==== Consumes
+
+* `application/json`
+
+
+==== Produces
+
+* `*/*`
+
+
+==== Tags
+
+* book-api
+
+
+==== Security
+
+[options="header", cols=".^3,.^4"]
+|===
+|Type|Name
+|**apiKey**|**<<_api_key,api_key>>**
+|===
+
+
+[[_getbookbyidusingget]]
+=== 根据ID获取书籍
+....
+GET /v1/book/{id}
+....
+
+
+==== Parameters
+
+[options="header", cols=".^2,.^3,.^9,.^4"]
+|===
+|Type|Name|Description|Schema
+|**Path**|**id** +
+__required__|id|integer (int32)
+|===
+
+
+==== Responses
+
+[options="header", cols=".^2,.^14,.^4"]
+|===
+|HTTP Code|Description|Schema
+|**200**|OK|<<_book,Book>>
+|**401**|Unauthorized|No Content
+|**403**|Forbidden|No Content
+|**404**|Not Found|No Content
+|===
+
+
+==== Consumes
+
+* `application/json`
+
+
+==== Produces
+
+* `*/*`
+
+
+==== Tags
+
+* book-api
+
+
+==== Security
+
+[options="header", cols=".^3,.^4"]
+|===
+|Type|Name
+|**apiKey**|**<<_api_key,api_key>>**
+|===
+
+
+[[_getallusingget]]
+=== 获取全部分类
+....
+GET /v1/category/
+....
+
+
+==== Responses
+
+[options="header", cols=".^2,.^14,.^4"]
+|===
+|HTTP Code|Description|Schema
+|**200**|OK|< <<_category,Category>> > array
+|**401**|Unauthorized|No Content
+|**403**|Forbidden|No Content
+|**404**|Not Found|No Content
+|===
+
+
+==== Consumes
+
+* `application/json`
+
+
+==== Produces
+
+* `*/*`
+
+
+==== Tags
+
+* category-api
+
+
+[[_getusingget]]
+=== 根据ID获取分类
+....
+GET /v1/category/{id}
+....
+
+
+==== Parameters
+
+[options="header", cols=".^2,.^3,.^9,.^4"]
+|===
+|Type|Name|Description|Schema
+|**Path**|**id** +
+__required__|id|integer (int32)
+|===
+
+
+==== Responses
+
+[options="header", cols=".^2,.^14,.^4"]
+|===
+|HTTP Code|Description|Schema
+|**200**|OK|<<_category,Category>>
+|**401**|Unauthorized|No Content
+|**403**|Forbidden|No Content
+|**404**|Not Found|No Content
+|===
+
+
+==== Consumes
+
+* `application/json`
+
+
+==== Produces
+
+* `*/*`
+
+
+==== Tags
+
+* category-api
+
+
+
+
+[[_definitions]]
+== Definitions
+
+[[_book]]
+=== Book
+
+[options="header", cols=".^3,.^11,.^4"]
+|===
+|Name|Description|Schema
+|**author** +
+__optional__|作者|string
+|**categoryId** +
+__optional__||integer (int32)
+|**id** +
+__optional__||integer (int32)
+|**name** +
+__optional__|书名|string
+|===
+
+
+[[_category]]
+=== Category
+
+[options="header", cols=".^3,.^4"]
+|===
+|Name|Schema
+|**id** +
+__optional__|integer (int32)
+|**name** +
+__optional__|string
+|===
+
+
+
+
+[[_securityscheme]]
+== Security
+
+[[_api_key]]
+=== api_key
+[%hardbreaks]
+__Type__ : apiKey
+__Name__ : api_key
+__In__ : HEADER
+
+
+
diff --git a/client/go/.gitignore b/client/go/.gitignore
new file mode 100644
index 0000000..daf913b
--- /dev/null
+++ b/client/go/.gitignore
@@ -0,0 +1,24 @@
+# Compiled Object files, Static and Dynamic libs (Shared Objects)
+*.o
+*.a
+*.so
+
+# Folders
+_obj
+_test
+
+# Architecture specific extensions/prefixes
+*.[568vq]
+[568vq].out
+
+*.cgo1.go
+*.cgo2.c
+_cgo_defun.c
+_cgo_gotypes.go
+_cgo_export.*
+
+_testmain.go
+
+*.exe
+*.test
+*.prof
diff --git a/client/go/.swagger-codegen-ignore b/client/go/.swagger-codegen-ignore
new file mode 100644
index 0000000..c5fa491
--- /dev/null
+++ b/client/go/.swagger-codegen-ignore
@@ -0,0 +1,23 @@
+# Swagger Codegen Ignore
+# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen
+
+# Use this file to prevent files from being overwritten by the generator.
+# The patterns follow closely to .gitignore or .dockerignore.
+
+# As an example, the C# client generator defines ApiClient.cs.
+# You can make changes and tell Swagger Codgen to ignore just this file by uncommenting the following line:
+#ApiClient.cs
+
+# You can match any string of characters against a directory, file or extension with a single asterisk (*):
+#foo/*/qux
+# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux
+
+# You can recursively match patterns against a directory, file or extension with a double asterisk (**):
+#foo/**/qux
+# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux
+
+# You can also negate patterns with an exclamation (!).
+# For example, you can ignore all files in a docs folder with the file extension .md:
+#docs/*.md
+# Then explicitly reverse the ignore rule for a single file:
+#!docs/README.md
diff --git a/client/go/.swagger-codegen/VERSION b/client/go/.swagger-codegen/VERSION
new file mode 100644
index 0000000..717311e
--- /dev/null
+++ b/client/go/.swagger-codegen/VERSION
@@ -0,0 +1 @@
+unset
\ No newline at end of file
diff --git a/client/go/.travis.yml b/client/go/.travis.yml
new file mode 100644
index 0000000..f5cb2ce
--- /dev/null
+++ b/client/go/.travis.yml
@@ -0,0 +1,8 @@
+language: go
+
+install:
+ - go get -d -v .
+
+script:
+ - go build -v ./
+
diff --git a/client/go/README.md b/client/go/README.md
new file mode 100644
index 0000000..bfb0b4d
--- /dev/null
+++ b/client/go/README.md
@@ -0,0 +1,51 @@
+# Go API client for swagger
+
+Swagger的简单示例, 包括swagger-codegen, swagger2markup 和 asciidoctor.
+
+## Overview
+This API client was generated by the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project. By using the [swagger-spec](https://github.com/swagger-api/swagger-spec) from a remote server, you can easily generate an API client.
+
+- API version: v1
+- Package version: 1.0.0
+- Build package: io.swagger.codegen.languages.GoClientCodegen
+For more information, please visit [http://www.google.com](http://www.google.com)
+
+## Installation
+Put the package under your project folder and add the following in import:
+```
+ "./swagger"
+```
+
+## Documentation for API Endpoints
+
+All URIs are relative to *http://localhost:8080*
+
+Class | Method | HTTP request | Description
+------------ | ------------- | ------------- | -------------
+*BookapiApi* | [**GetBookByIdUsingGET**](docs/BookapiApi.md#getbookbyidusingget) | **Get** /v1/book/{id} | 根据ID获取书籍
+*BookapiApi* | [**GetBooksByCategoryUsingGET**](docs/BookapiApi.md#getbooksbycategoryusingget) | **Get** /v1/book/getByCategoryId | 根据分类获取书籍
+*BookapiApi* | [**UpdateUsingPOST**](docs/BookapiApi.md#updateusingpost) | **Post** /v1/book/update | 更新书籍
+*CategoryapiApi* | [**GetAllUsingGET**](docs/CategoryapiApi.md#getallusingget) | **Get** /v1/category/ | 获取全部分类
+*CategoryapiApi* | [**GetUsingGET**](docs/CategoryapiApi.md#getusingget) | **Get** /v1/category/{id} | 根据ID获取分类
+
+
+## Documentation For Models
+
+ - [Book](docs/Book.md)
+ - [Category](docs/Category.md)
+
+
+## Documentation For Authorization
+
+
+## api_key
+
+- **Type**: API key
+- **API key parameter name**: api_key
+- **Location**: HTTP header
+
+
+## Author
+
+damon.q@iv66.net
+
diff --git a/client/go/api_client.go b/client/go/api_client.go
new file mode 100644
index 0000000..f198bf8
--- /dev/null
+++ b/client/go/api_client.go
@@ -0,0 +1,164 @@
+/*
+ * Swagger Demo
+ *
+ * Swagger的简单示例, 包括swagger-codegen, swagger2markup 和 asciidoctor.
+ *
+ * OpenAPI spec version: v1
+ * Contact: damon.q@iv66.net
+ * Generated by: https://github.com/swagger-api/swagger-codegen.git
+ */
+
+package swagger
+
+import (
+ "bytes"
+ "fmt"
+ "path/filepath"
+ "reflect"
+ "strings"
+ "net/url"
+ "io/ioutil"
+ "gopkg.in/go-resty/resty.v0"
+)
+
+type APIClient struct {
+ config *Configuration
+}
+
+func (c *APIClient) SelectHeaderContentType(contentTypes []string) string {
+
+ if len(contentTypes) == 0 {
+ return ""
+ }
+ if contains(contentTypes, "application/json") {
+ return "application/json"
+ }
+ return contentTypes[0] // use the first content type specified in 'consumes'
+}
+
+func (c *APIClient) SelectHeaderAccept(accepts []string) string {
+
+ if len(accepts) == 0 {
+ return ""
+ }
+ if contains(accepts, "application/json") {
+ return "application/json"
+ }
+ return strings.Join(accepts, ",")
+}
+
+func contains(haystack []string, needle string) bool {
+ for _, a := range haystack {
+ if strings.ToLower(a) == strings.ToLower(needle) {
+ return true
+ }
+ }
+ return false
+}
+
+func (c *APIClient) CallAPI(path string, method string,
+ postBody interface{},
+ headerParams map[string]string,
+ queryParams url.Values,
+ formParams map[string]string,
+ fileName string,
+ fileBytes []byte) (*resty.Response, error) {
+
+ rClient := c.prepareClient()
+ request := c.prepareRequest(rClient, postBody, headerParams, queryParams, formParams, fileName, fileBytes)
+
+ switch strings.ToUpper(method) {
+ case "GET":
+ response, err := request.Get(path)
+ return response, err
+ case "POST":
+ response, err := request.Post(path)
+ return response, err
+ case "PUT":
+ response, err := request.Put(path)
+ return response, err
+ case "PATCH":
+ response, err := request.Patch(path)
+ return response, err
+ case "DELETE":
+ response, err := request.Delete(path)
+ return response, err
+ }
+
+ return nil, fmt.Errorf("invalid method %v", method)
+}
+
+func (c *APIClient) ParameterToString(obj interface{}, collectionFormat string) string {
+ delimiter := ""
+ switch collectionFormat {
+ case "pipes":
+ delimiter = "|"
+ case "ssv":
+ delimiter = " "
+ case "tsv":
+ delimiter = "\t"
+ case "csv":
+ delimiter = ","
+ }
+
+ if reflect.TypeOf(obj).Kind() == reflect.Slice {
+ return strings.Trim(strings.Replace(fmt.Sprint(obj), " ", delimiter, -1), "[]")
+ }
+
+ return fmt.Sprintf("%v", obj)
+}
+
+func (c *APIClient) prepareClient() *resty.Client {
+
+ rClient := resty.New()
+
+ rClient.SetDebug(c.config.Debug)
+ if c.config.Transport != nil {
+ rClient.SetTransport(c.config.Transport)
+ }
+
+ if c.config.Timeout != nil {
+ rClient.SetTimeout(*c.config.Timeout)
+ }
+ rClient.SetLogger(ioutil.Discard)
+ return rClient
+}
+
+func (c *APIClient) prepareRequest(
+ rClient *resty.Client,
+ postBody interface{},
+ headerParams map[string]string,
+ queryParams url.Values,
+ formParams map[string]string,
+ fileName string,
+ fileBytes []byte) *resty.Request {
+
+
+ request := rClient.R()
+ request.SetBody(postBody)
+
+ if c.config.UserAgent != "" {
+ request.SetHeader("User-Agent", c.config.UserAgent)
+ }
+
+ // add header parameter, if any
+ if len(headerParams) > 0 {
+ request.SetHeaders(headerParams)
+ }
+
+ // add query parameter, if any
+ if len(queryParams) > 0 {
+ request.SetMultiValueQueryParams(queryParams)
+ }
+
+ // add form parameter, if any
+ if len(formParams) > 0 {
+ request.SetFormData(formParams)
+ }
+
+ if len(fileBytes) > 0 && fileName != "" {
+ _, fileNm := filepath.Split(fileName)
+ request.SetFileReader("file", fileNm, bytes.NewReader(fileBytes))
+ }
+ return request
+}
diff --git a/client/go/api_response.go b/client/go/api_response.go
new file mode 100644
index 0000000..d7ea559
--- /dev/null
+++ b/client/go/api_response.go
@@ -0,0 +1,44 @@
+/*
+ * Swagger Demo
+ *
+ * Swagger的简单示例, 包括swagger-codegen, swagger2markup 和 asciidoctor.
+ *
+ * OpenAPI spec version: v1
+ * Contact: damon.q@iv66.net
+ * Generated by: https://github.com/swagger-api/swagger-codegen.git
+ */
+
+package swagger
+
+import (
+ "net/http"
+)
+
+type APIResponse struct {
+ *http.Response `json:"-"`
+ Message string `json:"message,omitempty"`
+ // Operation is the name of the swagger operation.
+ Operation string `json:"operation,omitempty"`
+ // RequestURL is the request URL. This value is always available, even if the
+ // embedded *http.Response is nil.
+ RequestURL string `json:"url,omitempty"`
+ // Method is the HTTP method used for the request. This value is always
+ // available, even if the embedded *http.Response is nil.
+ Method string `json:"method,omitempty"`
+ // Payload holds the contents of the response body (which may be nil or empty).
+ // This is provided here as the raw response.Body() reader will have already
+ // been drained.
+ Payload []byte `json:"-"`
+}
+
+func NewAPIResponse(r *http.Response) *APIResponse {
+
+ response := &APIResponse{Response: r}
+ return response
+}
+
+func NewAPIResponseWithError(errorMessage string) *APIResponse {
+
+ response := &APIResponse{Message: errorMessage}
+ return response
+}
diff --git a/client/go/book.go b/client/go/book.go
new file mode 100644
index 0000000..aada531
--- /dev/null
+++ b/client/go/book.go
@@ -0,0 +1,24 @@
+/*
+ * Swagger Demo
+ *
+ * Swagger的简单示例, 包括swagger-codegen, swagger2markup 和 asciidoctor.
+ *
+ * OpenAPI spec version: v1
+ * Contact: damon.q@iv66.net
+ * Generated by: https://github.com/swagger-api/swagger-codegen.git
+ */
+
+package swagger
+
+type Book struct {
+
+ // 作者
+ Author string `json:"author,omitempty"`
+
+ CategoryId int32 `json:"categoryId,omitempty"`
+
+ Id int32 `json:"id,omitempty"`
+
+ // 书名
+ Name string `json:"name,omitempty"`
+}
diff --git a/client/go/bookapi_api.go b/client/go/bookapi_api.go
new file mode 100644
index 0000000..f7049d8
--- /dev/null
+++ b/client/go/bookapi_api.go
@@ -0,0 +1,229 @@
+/*
+ * Swagger Demo
+ *
+ * Swagger的简单示例, 包括swagger-codegen, swagger2markup 和 asciidoctor.
+ *
+ * OpenAPI spec version: v1
+ * Contact: damon.q@iv66.net
+ * Generated by: https://github.com/swagger-api/swagger-codegen.git
+ */
+
+package swagger
+
+import (
+ "net/url"
+ "strings"
+ "encoding/json"
+ "fmt"
+)
+
+type BookapiApi struct {
+ Configuration *Configuration
+}
+
+func NewBookapiApi() *BookapiApi {
+ configuration := NewConfiguration()
+ return &BookapiApi{
+ Configuration: configuration,
+ }
+}
+
+func NewBookapiApiWithBasePath(basePath string) *BookapiApi {
+ configuration := NewConfiguration()
+ configuration.BasePath = basePath
+
+ return &BookapiApi{
+ Configuration: configuration,
+ }
+}
+
+/**
+ * 根据ID获取书籍
+ *
+ * @param id id
+ * @return *Book
+ */
+func (a BookapiApi) GetBookByIdUsingGET(id int32) (*Book, *APIResponse, error) {
+
+ var localVarHttpMethod = strings.ToUpper("Get")
+ // create path and map variables
+ localVarPath := a.Configuration.BasePath + "/v1/book/{id}"
+ localVarPath = strings.Replace(localVarPath, "{"+"id"+"}", fmt.Sprintf("%v", id), -1)
+
+ localVarHeaderParams := make(map[string]string)
+ localVarQueryParams := url.Values{}
+ localVarFormParams := make(map[string]string)
+ var localVarPostBody interface{}
+ var localVarFileName string
+ var localVarFileBytes []byte
+ // authentication '(api_key)' required
+ // set key with prefix in header
+ localVarHeaderParams["api_key"] = a.Configuration.GetAPIKeyWithPrefix("api_key")
+ // add default headers if any
+ for key := range a.Configuration.DefaultHeader {
+ localVarHeaderParams[key] = a.Configuration.DefaultHeader[key]
+ }
+
+ // to determine the Content-Type header
+ localVarHttpContentTypes := []string{ "application/json", }
+
+ // set Content-Type header
+ localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes)
+ if localVarHttpContentType != "" {
+ localVarHeaderParams["Content-Type"] = localVarHttpContentType
+ }
+ // to determine the Accept header
+ localVarHttpHeaderAccepts := []string{
+ "*/*",
+ }
+
+ // set Accept header
+ localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts)
+ if localVarHttpHeaderAccept != "" {
+ localVarHeaderParams["Accept"] = localVarHttpHeaderAccept
+ }
+ var successPayload = new(Book)
+ localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)
+
+ var localVarURL, _ = url.Parse(localVarPath)
+ localVarURL.RawQuery = localVarQueryParams.Encode()
+ var localVarAPIResponse = &APIResponse{Operation: "GetBookByIdUsingGET", Method: localVarHttpMethod, RequestURL: localVarURL.String()}
+ if localVarHttpResponse != nil {
+ localVarAPIResponse.Response = localVarHttpResponse.RawResponse
+ localVarAPIResponse.Payload = localVarHttpResponse.Body()
+ }
+
+ if err != nil {
+ return successPayload, localVarAPIResponse, err
+ }
+ err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload)
+ return successPayload, localVarAPIResponse, err
+}
+
+/**
+ * 根据分类获取书籍
+ *
+ * @param id id
+ * @return []Book
+ */
+func (a BookapiApi) GetBooksByCategoryUsingGET(id int32) ([]Book, *APIResponse, error) {
+
+ var localVarHttpMethod = strings.ToUpper("Get")
+ // create path and map variables
+ localVarPath := a.Configuration.BasePath + "/v1/book/getByCategoryId"
+
+ localVarHeaderParams := make(map[string]string)
+ localVarQueryParams := url.Values{}
+ localVarFormParams := make(map[string]string)
+ var localVarPostBody interface{}
+ var localVarFileName string
+ var localVarFileBytes []byte
+ // authentication '(api_key)' required
+ // set key with prefix in header
+ localVarHeaderParams["api_key"] = a.Configuration.GetAPIKeyWithPrefix("api_key")
+ // add default headers if any
+ for key := range a.Configuration.DefaultHeader {
+ localVarHeaderParams[key] = a.Configuration.DefaultHeader[key]
+ }
+ localVarQueryParams.Add("id", a.Configuration.APIClient.ParameterToString(id, ""))
+
+ // to determine the Content-Type header
+ localVarHttpContentTypes := []string{ "application/json", }
+
+ // set Content-Type header
+ localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes)
+ if localVarHttpContentType != "" {
+ localVarHeaderParams["Content-Type"] = localVarHttpContentType
+ }
+ // to determine the Accept header
+ localVarHttpHeaderAccepts := []string{
+ "*/*",
+ }
+
+ // set Accept header
+ localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts)
+ if localVarHttpHeaderAccept != "" {
+ localVarHeaderParams["Accept"] = localVarHttpHeaderAccept
+ }
+ var successPayload = new([]Book)
+ localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)
+
+ var localVarURL, _ = url.Parse(localVarPath)
+ localVarURL.RawQuery = localVarQueryParams.Encode()
+ var localVarAPIResponse = &APIResponse{Operation: "GetBooksByCategoryUsingGET", Method: localVarHttpMethod, RequestURL: localVarURL.String()}
+ if localVarHttpResponse != nil {
+ localVarAPIResponse.Response = localVarHttpResponse.RawResponse
+ localVarAPIResponse.Payload = localVarHttpResponse.Body()
+ }
+
+ if err != nil {
+ return *successPayload, localVarAPIResponse, err
+ }
+ err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload)
+ return *successPayload, localVarAPIResponse, err
+}
+
+/**
+ * 更新书籍
+ *
+ * @param id id
+ * @return *bool
+ */
+func (a BookapiApi) UpdateUsingPOST(id int32) (*bool, *APIResponse, error) {
+
+ var localVarHttpMethod = strings.ToUpper("Post")
+ // create path and map variables
+ localVarPath := a.Configuration.BasePath + "/v1/book/update"
+
+ localVarHeaderParams := make(map[string]string)
+ localVarQueryParams := url.Values{}
+ localVarFormParams := make(map[string]string)
+ var localVarPostBody interface{}
+ var localVarFileName string
+ var localVarFileBytes []byte
+ // authentication '(api_key)' required
+ // set key with prefix in header
+ localVarHeaderParams["api_key"] = a.Configuration.GetAPIKeyWithPrefix("api_key")
+ // add default headers if any
+ for key := range a.Configuration.DefaultHeader {
+ localVarHeaderParams[key] = a.Configuration.DefaultHeader[key]
+ }
+
+ // to determine the Content-Type header
+ localVarHttpContentTypes := []string{ "application/json", }
+
+ // set Content-Type header
+ localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes)
+ if localVarHttpContentType != "" {
+ localVarHeaderParams["Content-Type"] = localVarHttpContentType
+ }
+ // to determine the Accept header
+ localVarHttpHeaderAccepts := []string{
+ "*/*",
+ }
+
+ // set Accept header
+ localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts)
+ if localVarHttpHeaderAccept != "" {
+ localVarHeaderParams["Accept"] = localVarHttpHeaderAccept
+ }
+ // body params
+ localVarPostBody = &id
+ var successPayload = new(bool)
+ localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)
+
+ var localVarURL, _ = url.Parse(localVarPath)
+ localVarURL.RawQuery = localVarQueryParams.Encode()
+ var localVarAPIResponse = &APIResponse{Operation: "UpdateUsingPOST", Method: localVarHttpMethod, RequestURL: localVarURL.String()}
+ if localVarHttpResponse != nil {
+ localVarAPIResponse.Response = localVarHttpResponse.RawResponse
+ localVarAPIResponse.Payload = localVarHttpResponse.Body()
+ }
+
+ if err != nil {
+ return successPayload, localVarAPIResponse, err
+ }
+ err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload)
+ return successPayload, localVarAPIResponse, err
+}
+
diff --git a/client/go/category.go b/client/go/category.go
new file mode 100644
index 0000000..189503f
--- /dev/null
+++ b/client/go/category.go
@@ -0,0 +1,18 @@
+/*
+ * Swagger Demo
+ *
+ * Swagger的简单示例, 包括swagger-codegen, swagger2markup 和 asciidoctor.
+ *
+ * OpenAPI spec version: v1
+ * Contact: damon.q@iv66.net
+ * Generated by: https://github.com/swagger-api/swagger-codegen.git
+ */
+
+package swagger
+
+type Category struct {
+
+ Id int32 `json:"id,omitempty"`
+
+ Name string `json:"name,omitempty"`
+}
diff --git a/client/go/categoryapi_api.go b/client/go/categoryapi_api.go
new file mode 100644
index 0000000..98ae37b
--- /dev/null
+++ b/client/go/categoryapi_api.go
@@ -0,0 +1,157 @@
+/*
+ * Swagger Demo
+ *
+ * Swagger的简单示例, 包括swagger-codegen, swagger2markup 和 asciidoctor.
+ *
+ * OpenAPI spec version: v1
+ * Contact: damon.q@iv66.net
+ * Generated by: https://github.com/swagger-api/swagger-codegen.git
+ */
+
+package swagger
+
+import (
+ "net/url"
+ "strings"
+ "encoding/json"
+ "fmt"
+)
+
+type CategoryapiApi struct {
+ Configuration *Configuration
+}
+
+func NewCategoryapiApi() *CategoryapiApi {
+ configuration := NewConfiguration()
+ return &CategoryapiApi{
+ Configuration: configuration,
+ }
+}
+
+func NewCategoryapiApiWithBasePath(basePath string) *CategoryapiApi {
+ configuration := NewConfiguration()
+ configuration.BasePath = basePath
+
+ return &CategoryapiApi{
+ Configuration: configuration,
+ }
+}
+
+/**
+ * 获取全部分类
+ *
+ * @return []Category
+ */
+func (a CategoryapiApi) GetAllUsingGET() ([]Category, *APIResponse, error) {
+
+ var localVarHttpMethod = strings.ToUpper("Get")
+ // create path and map variables
+ localVarPath := a.Configuration.BasePath + "/v1/category/"
+
+ localVarHeaderParams := make(map[string]string)
+ localVarQueryParams := url.Values{}
+ localVarFormParams := make(map[string]string)
+ var localVarPostBody interface{}
+ var localVarFileName string
+ var localVarFileBytes []byte
+ // add default headers if any
+ for key := range a.Configuration.DefaultHeader {
+ localVarHeaderParams[key] = a.Configuration.DefaultHeader[key]
+ }
+
+ // to determine the Content-Type header
+ localVarHttpContentTypes := []string{ "application/json", }
+
+ // set Content-Type header
+ localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes)
+ if localVarHttpContentType != "" {
+ localVarHeaderParams["Content-Type"] = localVarHttpContentType
+ }
+ // to determine the Accept header
+ localVarHttpHeaderAccepts := []string{
+ "*/*",
+ }
+
+ // set Accept header
+ localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts)
+ if localVarHttpHeaderAccept != "" {
+ localVarHeaderParams["Accept"] = localVarHttpHeaderAccept
+ }
+ var successPayload = new([]Category)
+ localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)
+
+ var localVarURL, _ = url.Parse(localVarPath)
+ localVarURL.RawQuery = localVarQueryParams.Encode()
+ var localVarAPIResponse = &APIResponse{Operation: "GetAllUsingGET", Method: localVarHttpMethod, RequestURL: localVarURL.String()}
+ if localVarHttpResponse != nil {
+ localVarAPIResponse.Response = localVarHttpResponse.RawResponse
+ localVarAPIResponse.Payload = localVarHttpResponse.Body()
+ }
+
+ if err != nil {
+ return *successPayload, localVarAPIResponse, err
+ }
+ err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload)
+ return *successPayload, localVarAPIResponse, err
+}
+
+/**
+ * 根据ID获取分类
+ *
+ * @param id id
+ * @return *Category
+ */
+func (a CategoryapiApi) GetUsingGET(id int32) (*Category, *APIResponse, error) {
+
+ var localVarHttpMethod = strings.ToUpper("Get")
+ // create path and map variables
+ localVarPath := a.Configuration.BasePath + "/v1/category/{id}"
+ localVarPath = strings.Replace(localVarPath, "{"+"id"+"}", fmt.Sprintf("%v", id), -1)
+
+ localVarHeaderParams := make(map[string]string)
+ localVarQueryParams := url.Values{}
+ localVarFormParams := make(map[string]string)
+ var localVarPostBody interface{}
+ var localVarFileName string
+ var localVarFileBytes []byte
+ // add default headers if any
+ for key := range a.Configuration.DefaultHeader {
+ localVarHeaderParams[key] = a.Configuration.DefaultHeader[key]
+ }
+
+ // to determine the Content-Type header
+ localVarHttpContentTypes := []string{ "application/json", }
+
+ // set Content-Type header
+ localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes)
+ if localVarHttpContentType != "" {
+ localVarHeaderParams["Content-Type"] = localVarHttpContentType
+ }
+ // to determine the Accept header
+ localVarHttpHeaderAccepts := []string{
+ "*/*",
+ }
+
+ // set Accept header
+ localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts)
+ if localVarHttpHeaderAccept != "" {
+ localVarHeaderParams["Accept"] = localVarHttpHeaderAccept
+ }
+ var successPayload = new(Category)
+ localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)
+
+ var localVarURL, _ = url.Parse(localVarPath)
+ localVarURL.RawQuery = localVarQueryParams.Encode()
+ var localVarAPIResponse = &APIResponse{Operation: "GetUsingGET", Method: localVarHttpMethod, RequestURL: localVarURL.String()}
+ if localVarHttpResponse != nil {
+ localVarAPIResponse.Response = localVarHttpResponse.RawResponse
+ localVarAPIResponse.Payload = localVarHttpResponse.Body()
+ }
+
+ if err != nil {
+ return successPayload, localVarAPIResponse, err
+ }
+ err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload)
+ return successPayload, localVarAPIResponse, err
+}
+
diff --git a/client/go/configuration.go b/client/go/configuration.go
new file mode 100644
index 0000000..a4f6feb
--- /dev/null
+++ b/client/go/configuration.go
@@ -0,0 +1,67 @@
+/*
+ * Swagger Demo
+ *
+ * Swagger的简单示例, 包括swagger-codegen, swagger2markup 和 asciidoctor.
+ *
+ * OpenAPI spec version: v1
+ * Contact: damon.q@iv66.net
+ * Generated by: https://github.com/swagger-api/swagger-codegen.git
+ */
+
+package swagger
+
+import (
+ "encoding/base64"
+ "net/http"
+ "time"
+)
+
+
+type Configuration struct {
+ Username string `json:"userName,omitempty"`
+ Password string `json:"password,omitempty"`
+ APIKeyPrefix map[string]string `json:"APIKeyPrefix,omitempty"`
+ APIKey map[string]string `json:"APIKey,omitempty"`
+ Debug bool `json:"debug,omitempty"`
+ DebugFile string `json:"debugFile,omitempty"`
+ OAuthToken string `json:"oAuthToken,omitempty"`
+ BasePath string `json:"basePath,omitempty"`
+ Host string `json:"host,omitempty"`
+ Scheme string `json:"scheme,omitempty"`
+ AccessToken string `json:"accessToken,omitempty"`
+ DefaultHeader map[string]string `json:"defaultHeader,omitempty"`
+ UserAgent string `json:"userAgent,omitempty"`
+ APIClient *APIClient
+ Transport *http.Transport
+ Timeout *time.Duration `json:"timeout,omitempty"`
+}
+
+func NewConfiguration() *Configuration {
+ cfg := &Configuration{
+ BasePath: "http://localhost:8080",
+ DefaultHeader: make(map[string]string),
+ APIKey: make(map[string]string),
+ APIKeyPrefix: make(map[string]string),
+ UserAgent: "Swagger-Codegen/1.0.0/go",
+ APIClient: &APIClient{},
+ }
+
+ cfg.APIClient.config = cfg
+ return cfg
+}
+
+func (c *Configuration) GetBasicAuthEncodedString() string {
+ return base64.StdEncoding.EncodeToString([]byte(c.Username + ":" + c.Password))
+}
+
+func (c *Configuration) AddDefaultHeader(key string, value string) {
+ c.DefaultHeader[key] = value
+}
+
+func (c *Configuration) GetAPIKeyWithPrefix(APIKeyIdentifier string) string {
+ if c.APIKeyPrefix[APIKeyIdentifier] != "" {
+ return c.APIKeyPrefix[APIKeyIdentifier] + " " + c.APIKey[APIKeyIdentifier]
+ }
+
+ return c.APIKey[APIKeyIdentifier]
+}
diff --git a/client/go/docs/Book.md b/client/go/docs/Book.md
new file mode 100644
index 0000000..d4e63f2
--- /dev/null
+++ b/client/go/docs/Book.md
@@ -0,0 +1,13 @@
+# Book
+
+## Properties
+Name | Type | Description | Notes
+------------ | ------------- | ------------- | -------------
+**Author** | **string** | 作者 | [optional] [default to null]
+**CategoryId** | **int32** | | [optional] [default to null]
+**Id** | **int32** | | [optional] [default to null]
+**Name** | **string** | 书名 | [optional] [default to null]
+
+[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)
+
+
diff --git a/client/go/docs/BookapiApi.md b/client/go/docs/BookapiApi.md
new file mode 100644
index 0000000..49e1446
--- /dev/null
+++ b/client/go/docs/BookapiApi.md
@@ -0,0 +1,92 @@
+# \BookapiApi
+
+All URIs are relative to *http://localhost:8080*
+
+Method | HTTP request | Description
+------------- | ------------- | -------------
+[**GetBookByIdUsingGET**](BookapiApi.md#GetBookByIdUsingGET) | **Get** /v1/book/{id} | 根据ID获取书籍
+[**GetBooksByCategoryUsingGET**](BookapiApi.md#GetBooksByCategoryUsingGET) | **Get** /v1/book/getByCategoryId | 根据分类获取书籍
+[**UpdateUsingPOST**](BookapiApi.md#UpdateUsingPOST) | **Post** /v1/book/update | 更新书籍
+
+
+# **GetBookByIdUsingGET**
+> Book GetBookByIdUsingGET($id)
+
+根据ID获取书籍
+
+
+### Parameters
+
+Name | Type | Description | Notes
+------------- | ------------- | ------------- | -------------
+ **id** | **int32**| id |
+
+### Return type
+
+[**Book**](Book.md)
+
+### Authorization
+
+[api_key](../README.md#api_key)
+
+### HTTP request headers
+
+ - **Content-Type**: application/json
+ - **Accept**: */*
+
+[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
+
+# **GetBooksByCategoryUsingGET**
+> []Book GetBooksByCategoryUsingGET($id)
+
+根据分类获取书籍
+
+
+### Parameters
+
+Name | Type | Description | Notes
+------------- | ------------- | ------------- | -------------
+ **id** | **int32**| id |
+
+### Return type
+
+[**[]Book**](Book.md)
+
+### Authorization
+
+[api_key](../README.md#api_key)
+
+### HTTP request headers
+
+ - **Content-Type**: application/json
+ - **Accept**: */*
+
+[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
+
+# **UpdateUsingPOST**
+> bool UpdateUsingPOST($id)
+
+更新书籍
+
+
+### Parameters
+
+Name | Type | Description | Notes
+------------- | ------------- | ------------- | -------------
+ **id** | **int32**| id | [optional]
+
+### Return type
+
+**bool**
+
+### Authorization
+
+[api_key](../README.md#api_key)
+
+### HTTP request headers
+
+ - **Content-Type**: application/json
+ - **Accept**: */*
+
+[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
+
diff --git a/client/go/docs/Category.md b/client/go/docs/Category.md
new file mode 100644
index 0000000..355d5ea
--- /dev/null
+++ b/client/go/docs/Category.md
@@ -0,0 +1,11 @@
+# Category
+
+## Properties
+Name | Type | Description | Notes
+------------ | ------------- | ------------- | -------------
+**Id** | **int32** | | [optional] [default to null]
+**Name** | **string** | | [optional] [default to null]
+
+[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)
+
+
diff --git a/client/go/docs/CategoryapiApi.md b/client/go/docs/CategoryapiApi.md
new file mode 100644
index 0000000..0672f03
--- /dev/null
+++ b/client/go/docs/CategoryapiApi.md
@@ -0,0 +1,61 @@
+# \CategoryapiApi
+
+All URIs are relative to *http://localhost:8080*
+
+Method | HTTP request | Description
+------------- | ------------- | -------------
+[**GetAllUsingGET**](CategoryapiApi.md#GetAllUsingGET) | **Get** /v1/category/ | 获取全部分类
+[**GetUsingGET**](CategoryapiApi.md#GetUsingGET) | **Get** /v1/category/{id} | 根据ID获取分类
+
+
+# **GetAllUsingGET**
+> []Category GetAllUsingGET()
+
+获取全部分类
+
+
+### Parameters
+This endpoint does not need any parameter.
+
+### Return type
+
+[**[]Category**](Category.md)
+
+### Authorization
+
+No authorization required
+
+### HTTP request headers
+
+ - **Content-Type**: application/json
+ - **Accept**: */*
+
+[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
+
+# **GetUsingGET**
+> Category GetUsingGET($id)
+
+根据ID获取分类
+
+
+### Parameters
+
+Name | Type | Description | Notes
+------------- | ------------- | ------------- | -------------
+ **id** | **int32**| id |
+
+### Return type
+
+[**Category**](Category.md)
+
+### Authorization
+
+No authorization required
+
+### HTTP request headers
+
+ - **Content-Type**: application/json
+ - **Accept**: */*
+
+[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
+
diff --git a/client/go/git_push.sh b/client/go/git_push.sh
new file mode 100644
index 0000000..ed37461
--- /dev/null
+++ b/client/go/git_push.sh
@@ -0,0 +1,52 @@
+#!/bin/sh
+# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/
+#
+# Usage example: /bin/sh ./git_push.sh wing328 swagger-petstore-perl "minor update"
+
+git_user_id=$1
+git_repo_id=$2
+release_note=$3
+
+if [ "$git_user_id" = "" ]; then
+ git_user_id="GIT_USER_ID"
+ echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id"
+fi
+
+if [ "$git_repo_id" = "" ]; then
+ git_repo_id="GIT_REPO_ID"
+ echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id"
+fi
+
+if [ "$release_note" = "" ]; then
+ release_note="Minor update"
+ echo "[INFO] No command line input provided. Set \$release_note to $release_note"
+fi
+
+# Initialize the local directory as a Git repository
+git init
+
+# Adds the files in the local repository and stages them for commit.
+git add .
+
+# Commits the tracked changes and prepares them to be pushed to a remote repository.
+git commit -m "$release_note"
+
+# Sets the new remote
+git_remote=`git remote`
+if [ "$git_remote" = "" ]; then # git remote not defined
+
+ if [ "$GIT_TOKEN" = "" ]; then
+ echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git crediential in your environment."
+ git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git
+ else
+ git remote add origin https://${git_user_id}:${GIT_TOKEN}@github.com/${git_user_id}/${git_repo_id}.git
+ fi
+
+fi
+
+git pull origin master
+
+# Pushes (Forces) the changes in the local repository up to the remote repository
+echo "Git pushing to https://github.com/${git_user_id}/${git_repo_id}.git"
+git push origin master 2>&1 | grep -v 'To https'
+
diff --git a/client/html2/.swagger-codegen-ignore b/client/html2/.swagger-codegen-ignore
new file mode 100644
index 0000000..c5fa491
--- /dev/null
+++ b/client/html2/.swagger-codegen-ignore
@@ -0,0 +1,23 @@
+# Swagger Codegen Ignore
+# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen
+
+# Use this file to prevent files from being overwritten by the generator.
+# The patterns follow closely to .gitignore or .dockerignore.
+
+# As an example, the C# client generator defines ApiClient.cs.
+# You can make changes and tell Swagger Codgen to ignore just this file by uncommenting the following line:
+#ApiClient.cs
+
+# You can match any string of characters against a directory, file or extension with a single asterisk (*):
+#foo/*/qux
+# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux
+
+# You can recursively match patterns against a directory, file or extension with a double asterisk (**):
+#foo/**/qux
+# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux
+
+# You can also negate patterns with an exclamation (!).
+# For example, you can ignore all files in a docs folder with the file extension .md:
+#docs/*.md
+# Then explicitly reverse the ignore rule for a single file:
+#!docs/README.md
diff --git a/client/html2/.swagger-codegen/VERSION b/client/html2/.swagger-codegen/VERSION
new file mode 100644
index 0000000..717311e
--- /dev/null
+++ b/client/html2/.swagger-codegen/VERSION
@@ -0,0 +1 @@
+unset
\ No newline at end of file
diff --git a/client/html2/index.html b/client/html2/index.html
new file mode 100644
index 0000000..0dea4ab
--- /dev/null
+++ b/client/html2/index.html
@@ -0,0 +1,4242 @@
+
+
+
+
+ Swagger Demo
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Bookapi
+
+
+
+
getBookByIdUsingGET
+
根据ID获取书籍
+
+
+
+
+
+
+
+ /v1/book/{id}
+
+
Usage and SDK Samples
+
+
+
+
+
+
curl -X GET -H "api_key: [[apiKey]]" "http://localhost:8080/v1/book/{id}"
+
+
+
import io.swagger.client.*;
+import io.swagger.client.auth.*;
+import io.swagger.client.model.*;
+import io.swagger.client.api.BookapiApi;
+
+import java.io.File;
+import java.util.*;
+
+public class BookapiApiExample {
+
+ public static void main(String[] args) {
+ ApiClient defaultClient = Configuration.getDefaultApiClient();
+
+ // Configure API key authorization: api_key
+ ApiKeyAuth api_key = (ApiKeyAuth) defaultClient.getAuthentication("api_key");
+ api_key.setApiKey("YOUR API KEY");
+ // Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)
+ //api_key.setApiKeyPrefix("Token");
+
+ BookapiApi apiInstance = new BookapiApi();
+ Integer id = 56; // Integer | id
+ try {
+ Book result = apiInstance.getBookByIdUsingGET(id);
+ System.out.println(result);
+ } catch (ApiException e) {
+ System.err.println("Exception when calling BookapiApi#getBookByIdUsingGET");
+ e.printStackTrace();
+ }
+ }
+}
+
+
+
+
import io.swagger.client.api.BookapiApi;
+
+public class BookapiApiExample {
+
+ public static void main(String[] args) {
+ BookapiApi apiInstance = new BookapiApi();
+ Integer id = 56; // Integer | id
+ try {
+ Book result = apiInstance.getBookByIdUsingGET(id);
+ System.out.println(result);
+ } catch (ApiException e) {
+ System.err.println("Exception when calling BookapiApi#getBookByIdUsingGET");
+ e.printStackTrace();
+ }
+ }
+}
+
+
+
+
Configuration *apiConfig = [Configuration sharedConfig];
+
+// Configure API key authorization: (authentication scheme: api_key)
+[apiConfig setApiKey:@"YOUR_API_KEY" forApiKeyIdentifier:@"api_key"];
+// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
+//[apiConfig setApiKeyPrefix:@"Bearer" forApiKeyIdentifier:@"api_key"];
+
+Integer *id = 56; // id
+
+BookapiApi *apiInstance = [[BookapiApi alloc] init];
+
+// 根据ID获取书籍
+[apiInstance getBookByIdUsingGETWith:id
+ completionHandler: ^(Book output, NSError* error) {
+ if (output) {
+ NSLog(@"%@", output);
+ }
+ if (error) {
+ NSLog(@"Error: %@", error);
+ }
+ }];
+
+
+
+
+
var SwaggerDemo = require('swagger_demo');
+var defaultClient = SwaggerDemo.ApiClient.instance;
+
+// Configure API key authorization: api_key
+var api_key = defaultClient.authentications['api_key'];
+api_key.apiKey = "YOUR API KEY"
+// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)
+//api_key.apiKeyPrefix['api_key'] = "Token"
+
+var api = new SwaggerDemo.BookapiApi()
+
+var id = 56; // {Integer} id
+
+
+var callback = function(error, data, response) {
+ if (error) {
+ console.error(error);
+ } else {
+ console.log('API called successfully. Returned data: ' + data);
+ }
+};
+api.getBookByIdUsingGET(id, callback);
+
+
+
+
+
+
using System;
+using System.Diagnostics;
+using IO.Swagger.Api;
+using IO.Swagger.Client;
+using IO.Swagger.Model;
+
+namespace Example
+{
+ public class getBookByIdUsingGETExample
+ {
+ public void main()
+ {
+
+ // Configure API key authorization: api_key
+ Configuration.Default.ApiKey.Add("api_key", "YOUR_API_KEY");
+ // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
+ // Configuration.Default.ApiKeyPrefix.Add("api_key", "Bearer");
+
+ var apiInstance = new BookapiApi();
+ var id = 56; // Integer | id
+
+ try
+ {
+ // 根据ID获取书籍
+ Book result = apiInstance.getBookByIdUsingGET(id);
+ Debug.WriteLine(result);
+ }
+ catch (Exception e)
+ {
+ Debug.Print("Exception when calling BookapiApi.getBookByIdUsingGET: " + e.Message );
+ }
+ }
+ }
+}
+
+
+
+
+
<?php
+require_once(__DIR__ . '/vendor/autoload.php');
+
+// Configure API key authorization: api_key
+Swagger\Client\Configuration::getDefaultConfiguration()->setApiKey('api_key', 'YOUR_API_KEY');
+// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
+// Swagger\Client\Configuration::getDefaultConfiguration()->setApiKeyPrefix('api_key', 'Bearer');
+
+$api_instance = new Swagger\Client\Api\BookapiApi();
+$id = 56; // Integer | id
+
+try {
+ $result = $api_instance->getBookByIdUsingGET($id);
+ print_r($result);
+} catch (Exception $e) {
+ echo 'Exception when calling BookapiApi->getBookByIdUsingGET: ', $e->getMessage(), PHP_EOL;
+}
+?>
+
+
+
+
use Data::Dumper;
+use WWW::SwaggerClient::Configuration;
+use WWW::SwaggerClient::BookapiApi;
+
+# Configure API key authorization: api_key
+$WWW::SwaggerClient::Configuration::api_key->{'api_key'} = 'YOUR_API_KEY';
+# uncomment below to setup prefix (e.g. Bearer) for API key, if needed
+#$WWW::SwaggerClient::Configuration::api_key_prefix->{'api_key'} = "Bearer";
+
+my $api_instance = WWW::SwaggerClient::BookapiApi->new();
+my $id = 56; # Integer | id
+
+eval {
+ my $result = $api_instance->getBookByIdUsingGET(id => $id);
+ print Dumper($result);
+};
+if ($@) {
+ warn "Exception when calling BookapiApi->getBookByIdUsingGET: $@\n";
+}
+
+
+
+
from __future__ import print_statement
+import time
+import swagger_client
+from swagger_client.rest import ApiException
+from pprint import pprint
+
+# Configure API key authorization: api_key
+swagger_client.configuration.api_key['api_key'] = 'YOUR_API_KEY'
+# Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
+# swagger_client.configuration.api_key_prefix['api_key'] = 'Bearer'
+
+# create an instance of the API class
+api_instance = swagger_client.BookapiApi()
+id = 56 # Integer | id
+
+try:
+ # 根据ID获取书籍
+ api_response = api_instance.get_book_by_id_using_get(id)
+ pprint(api_response)
+except ApiException as e:
+ print("Exception when calling BookapiApi->getBookByIdUsingGET: %s\n" % e)
+
+
+
+ Parameters
+
+ Path parameters
+
+
+ Name
+ Description
+
+ id*
+
+
+
+
+
+
+
+ Integer
+
+
+ (int32)
+
+
+
+ id
+
+
+
+ Required
+
+
+
+
+
+
+
+
+
+
+
+
+ Responses
+ Status: 200 - OK
+
+
+
+
+
+ Status: 401 - Unauthorized
+
+
+
+
+
+
+ Status: 403 - Forbidden
+
+
+
+
+
+
+ Status: 404 - Not Found
+
+
+
+
+
+
+
+
+
+
+
+
+
getBooksByCategoryUsingGET
+
根据分类获取书籍
+
+
+
+
+
+
+
+ /v1/book/getByCategoryId
+
+
Usage and SDK Samples
+
+
+
+
+
+
curl -X GET -H "api_key: [[apiKey]]" "http://localhost:8080/v1/book/getByCategoryId?id="
+
+
+
import io.swagger.client.*;
+import io.swagger.client.auth.*;
+import io.swagger.client.model.*;
+import io.swagger.client.api.BookapiApi;
+
+import java.io.File;
+import java.util.*;
+
+public class BookapiApiExample {
+
+ public static void main(String[] args) {
+ ApiClient defaultClient = Configuration.getDefaultApiClient();
+
+ // Configure API key authorization: api_key
+ ApiKeyAuth api_key = (ApiKeyAuth) defaultClient.getAuthentication("api_key");
+ api_key.setApiKey("YOUR API KEY");
+ // Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)
+ //api_key.setApiKeyPrefix("Token");
+
+ BookapiApi apiInstance = new BookapiApi();
+ Integer id = 56; // Integer | id
+ try {
+ array[Book] result = apiInstance.getBooksByCategoryUsingGET(id);
+ System.out.println(result);
+ } catch (ApiException e) {
+ System.err.println("Exception when calling BookapiApi#getBooksByCategoryUsingGET");
+ e.printStackTrace();
+ }
+ }
+}
+
+
+
+
import io.swagger.client.api.BookapiApi;
+
+public class BookapiApiExample {
+
+ public static void main(String[] args) {
+ BookapiApi apiInstance = new BookapiApi();
+ Integer id = 56; // Integer | id
+ try {
+ array[Book] result = apiInstance.getBooksByCategoryUsingGET(id);
+ System.out.println(result);
+ } catch (ApiException e) {
+ System.err.println("Exception when calling BookapiApi#getBooksByCategoryUsingGET");
+ e.printStackTrace();
+ }
+ }
+}
+
+
+
+
Configuration *apiConfig = [Configuration sharedConfig];
+
+// Configure API key authorization: (authentication scheme: api_key)
+[apiConfig setApiKey:@"YOUR_API_KEY" forApiKeyIdentifier:@"api_key"];
+// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
+//[apiConfig setApiKeyPrefix:@"Bearer" forApiKeyIdentifier:@"api_key"];
+
+Integer *id = 56; // id
+
+BookapiApi *apiInstance = [[BookapiApi alloc] init];
+
+// 根据分类获取书籍
+[apiInstance getBooksByCategoryUsingGETWith:id
+ completionHandler: ^(array[Book] output, NSError* error) {
+ if (output) {
+ NSLog(@"%@", output);
+ }
+ if (error) {
+ NSLog(@"Error: %@", error);
+ }
+ }];
+
+
+
+
+
var SwaggerDemo = require('swagger_demo');
+var defaultClient = SwaggerDemo.ApiClient.instance;
+
+// Configure API key authorization: api_key
+var api_key = defaultClient.authentications['api_key'];
+api_key.apiKey = "YOUR API KEY"
+// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)
+//api_key.apiKeyPrefix['api_key'] = "Token"
+
+var api = new SwaggerDemo.BookapiApi()
+
+var id = 56; // {Integer} id
+
+
+var callback = function(error, data, response) {
+ if (error) {
+ console.error(error);
+ } else {
+ console.log('API called successfully. Returned data: ' + data);
+ }
+};
+api.getBooksByCategoryUsingGET(id, callback);
+
+
+
+
+
+
using System;
+using System.Diagnostics;
+using IO.Swagger.Api;
+using IO.Swagger.Client;
+using IO.Swagger.Model;
+
+namespace Example
+{
+ public class getBooksByCategoryUsingGETExample
+ {
+ public void main()
+ {
+
+ // Configure API key authorization: api_key
+ Configuration.Default.ApiKey.Add("api_key", "YOUR_API_KEY");
+ // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
+ // Configuration.Default.ApiKeyPrefix.Add("api_key", "Bearer");
+
+ var apiInstance = new BookapiApi();
+ var id = 56; // Integer | id
+
+ try
+ {
+ // 根据分类获取书籍
+ array[Book] result = apiInstance.getBooksByCategoryUsingGET(id);
+ Debug.WriteLine(result);
+ }
+ catch (Exception e)
+ {
+ Debug.Print("Exception when calling BookapiApi.getBooksByCategoryUsingGET: " + e.Message );
+ }
+ }
+ }
+}
+
+
+
+
+
<?php
+require_once(__DIR__ . '/vendor/autoload.php');
+
+// Configure API key authorization: api_key
+Swagger\Client\Configuration::getDefaultConfiguration()->setApiKey('api_key', 'YOUR_API_KEY');
+// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
+// Swagger\Client\Configuration::getDefaultConfiguration()->setApiKeyPrefix('api_key', 'Bearer');
+
+$api_instance = new Swagger\Client\Api\BookapiApi();
+$id = 56; // Integer | id
+
+try {
+ $result = $api_instance->getBooksByCategoryUsingGET($id);
+ print_r($result);
+} catch (Exception $e) {
+ echo 'Exception when calling BookapiApi->getBooksByCategoryUsingGET: ', $e->getMessage(), PHP_EOL;
+}
+?>
+
+
+
+
use Data::Dumper;
+use WWW::SwaggerClient::Configuration;
+use WWW::SwaggerClient::BookapiApi;
+
+# Configure API key authorization: api_key
+$WWW::SwaggerClient::Configuration::api_key->{'api_key'} = 'YOUR_API_KEY';
+# uncomment below to setup prefix (e.g. Bearer) for API key, if needed
+#$WWW::SwaggerClient::Configuration::api_key_prefix->{'api_key'} = "Bearer";
+
+my $api_instance = WWW::SwaggerClient::BookapiApi->new();
+my $id = 56; # Integer | id
+
+eval {
+ my $result = $api_instance->getBooksByCategoryUsingGET(id => $id);
+ print Dumper($result);
+};
+if ($@) {
+ warn "Exception when calling BookapiApi->getBooksByCategoryUsingGET: $@\n";
+}
+
+
+
+
from __future__ import print_statement
+import time
+import swagger_client
+from swagger_client.rest import ApiException
+from pprint import pprint
+
+# Configure API key authorization: api_key
+swagger_client.configuration.api_key['api_key'] = 'YOUR_API_KEY'
+# Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
+# swagger_client.configuration.api_key_prefix['api_key'] = 'Bearer'
+
+# create an instance of the API class
+api_instance = swagger_client.BookapiApi()
+id = 56 # Integer | id
+
+try:
+ # 根据分类获取书籍
+ api_response = api_instance.get_books_by_category_using_get(id)
+ pprint(api_response)
+except ApiException as e:
+ print("Exception when calling BookapiApi->getBooksByCategoryUsingGET: %s\n" % e)
+
+
+
+ Parameters
+
+
+
+
+
+ Query parameters
+
+
+ Name
+ Description
+
+ id*
+
+
+
+
+
+
+
+ Integer
+
+
+ (int32)
+
+
+
+ id
+
+
+
+ Required
+
+
+
+
+
+
+
+
+ Responses
+ Status: 200 - OK
+
+
+
+
+
+ Status: 401 - Unauthorized
+
+
+
+
+
+
+ Status: 403 - Forbidden
+
+
+
+
+
+
+ Status: 404 - Not Found
+
+
+
+
+
+
+
+
+
+
+
+
+
updateUsingPOST
+
更新书籍
+
+
+
+
+
+
+
+ /v1/book/update
+
+
Usage and SDK Samples
+
+
+
+
+
+
curl -X POST -H "api_key: [[apiKey]]" "http://localhost:8080/v1/book/update"
+
+
+
import io.swagger.client.*;
+import io.swagger.client.auth.*;
+import io.swagger.client.model.*;
+import io.swagger.client.api.BookapiApi;
+
+import java.io.File;
+import java.util.*;
+
+public class BookapiApiExample {
+
+ public static void main(String[] args) {
+ ApiClient defaultClient = Configuration.getDefaultApiClient();
+
+ // Configure API key authorization: api_key
+ ApiKeyAuth api_key = (ApiKeyAuth) defaultClient.getAuthentication("api_key");
+ api_key.setApiKey("YOUR API KEY");
+ // Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)
+ //api_key.setApiKeyPrefix("Token");
+
+ BookapiApi apiInstance = new BookapiApi();
+ Integer id = 56; // Integer | id
+ try {
+ 'Boolean' result = apiInstance.updateUsingPOST(id);
+ System.out.println(result);
+ } catch (ApiException e) {
+ System.err.println("Exception when calling BookapiApi#updateUsingPOST");
+ e.printStackTrace();
+ }
+ }
+}
+
+
+
+
import io.swagger.client.api.BookapiApi;
+
+public class BookapiApiExample {
+
+ public static void main(String[] args) {
+ BookapiApi apiInstance = new BookapiApi();
+ Integer id = 56; // Integer | id
+ try {
+ 'Boolean' result = apiInstance.updateUsingPOST(id);
+ System.out.println(result);
+ } catch (ApiException e) {
+ System.err.println("Exception when calling BookapiApi#updateUsingPOST");
+ e.printStackTrace();
+ }
+ }
+}
+
+
+
+
Configuration *apiConfig = [Configuration sharedConfig];
+
+// Configure API key authorization: (authentication scheme: api_key)
+[apiConfig setApiKey:@"YOUR_API_KEY" forApiKeyIdentifier:@"api_key"];
+// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
+//[apiConfig setApiKeyPrefix:@"Bearer" forApiKeyIdentifier:@"api_key"];
+
+Integer *id = 56; // id (optional)
+
+BookapiApi *apiInstance = [[BookapiApi alloc] init];
+
+// 更新书籍
+[apiInstance updateUsingPOSTWith:id
+ completionHandler: ^('Boolean' output, NSError* error) {
+ if (output) {
+ NSLog(@"%@", output);
+ }
+ if (error) {
+ NSLog(@"Error: %@", error);
+ }
+ }];
+
+
+
+
+
var SwaggerDemo = require('swagger_demo');
+var defaultClient = SwaggerDemo.ApiClient.instance;
+
+// Configure API key authorization: api_key
+var api_key = defaultClient.authentications['api_key'];
+api_key.apiKey = "YOUR API KEY"
+// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)
+//api_key.apiKeyPrefix['api_key'] = "Token"
+
+var api = new SwaggerDemo.BookapiApi()
+
+var opts = {
+ 'id': 56 // {Integer} id
+};
+
+var callback = function(error, data, response) {
+ if (error) {
+ console.error(error);
+ } else {
+ console.log('API called successfully. Returned data: ' + data);
+ }
+};
+api.updateUsingPOST(opts, callback);
+
+
+
+
+
+
using System;
+using System.Diagnostics;
+using IO.Swagger.Api;
+using IO.Swagger.Client;
+using IO.Swagger.Model;
+
+namespace Example
+{
+ public class updateUsingPOSTExample
+ {
+ public void main()
+ {
+
+ // Configure API key authorization: api_key
+ Configuration.Default.ApiKey.Add("api_key", "YOUR_API_KEY");
+ // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
+ // Configuration.Default.ApiKeyPrefix.Add("api_key", "Bearer");
+
+ var apiInstance = new BookapiApi();
+ var id = 56; // Integer | id (optional)
+
+ try
+ {
+ // 更新书籍
+ 'Boolean' result = apiInstance.updateUsingPOST(id);
+ Debug.WriteLine(result);
+ }
+ catch (Exception e)
+ {
+ Debug.Print("Exception when calling BookapiApi.updateUsingPOST: " + e.Message );
+ }
+ }
+ }
+}
+
+
+
+
+
<?php
+require_once(__DIR__ . '/vendor/autoload.php');
+
+// Configure API key authorization: api_key
+Swagger\Client\Configuration::getDefaultConfiguration()->setApiKey('api_key', 'YOUR_API_KEY');
+// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
+// Swagger\Client\Configuration::getDefaultConfiguration()->setApiKeyPrefix('api_key', 'Bearer');
+
+$api_instance = new Swagger\Client\Api\BookapiApi();
+$id = 56; // Integer | id
+
+try {
+ $result = $api_instance->updateUsingPOST($id);
+ print_r($result);
+} catch (Exception $e) {
+ echo 'Exception when calling BookapiApi->updateUsingPOST: ', $e->getMessage(), PHP_EOL;
+}
+?>
+
+
+
+
use Data::Dumper;
+use WWW::SwaggerClient::Configuration;
+use WWW::SwaggerClient::BookapiApi;
+
+# Configure API key authorization: api_key
+$WWW::SwaggerClient::Configuration::api_key->{'api_key'} = 'YOUR_API_KEY';
+# uncomment below to setup prefix (e.g. Bearer) for API key, if needed
+#$WWW::SwaggerClient::Configuration::api_key_prefix->{'api_key'} = "Bearer";
+
+my $api_instance = WWW::SwaggerClient::BookapiApi->new();
+my $id = WWW::SwaggerClient::Object::Integer->new(); # Integer | id
+
+eval {
+ my $result = $api_instance->updateUsingPOST(id => $id);
+ print Dumper($result);
+};
+if ($@) {
+ warn "Exception when calling BookapiApi->updateUsingPOST: $@\n";
+}
+
+
+
+
from __future__ import print_statement
+import time
+import swagger_client
+from swagger_client.rest import ApiException
+from pprint import pprint
+
+# Configure API key authorization: api_key
+swagger_client.configuration.api_key['api_key'] = 'YOUR_API_KEY'
+# Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
+# swagger_client.configuration.api_key_prefix['api_key'] = 'Bearer'
+
+# create an instance of the API class
+api_instance = swagger_client.BookapiApi()
+id = 56 # Integer | id (optional)
+
+try:
+ # 更新书籍
+ api_response = api_instance.update_using_post(id=id)
+ pprint(api_response)
+except ApiException as e:
+ print("Exception when calling BookapiApi->updateUsingPOST: %s\n" % e)
+
+
+
+ Parameters
+
+
+
+ Body parameters
+
+
+ Name
+ Description
+
+ id
+
+
+
+
+
+
+
+
+
+
+
+
+ Responses
+ Status: 200 - OK
+
+
+
+
+
+ Status: 201 - Created
+
+
+
+
+
+
+ Status: 401 - Unauthorized
+
+
+
+
+
+
+ Status: 403 - Forbidden
+
+
+
+
+
+
+ Status: 404 - Not Found
+
+
+
+
+
+
+
+
+
+
+
+ Categoryapi
+
+
+
+
getAllUsingGET
+
获取全部分类
+
+
+
+
+
+
+
+ /v1/category/
+
+
Usage and SDK Samples
+
+
+
+
+
+
curl -X GET "http://localhost:8080/v1/category/"
+
+
+
import io.swagger.client.*;
+import io.swagger.client.auth.*;
+import io.swagger.client.model.*;
+import io.swagger.client.api.CategoryapiApi;
+
+import java.io.File;
+import java.util.*;
+
+public class CategoryapiApiExample {
+
+ public static void main(String[] args) {
+
+ CategoryapiApi apiInstance = new CategoryapiApi();
+ try {
+ array[Category] result = apiInstance.getAllUsingGET();
+ System.out.println(result);
+ } catch (ApiException e) {
+ System.err.println("Exception when calling CategoryapiApi#getAllUsingGET");
+ e.printStackTrace();
+ }
+ }
+}
+
+
+
+
import io.swagger.client.api.CategoryapiApi;
+
+public class CategoryapiApiExample {
+
+ public static void main(String[] args) {
+ CategoryapiApi apiInstance = new CategoryapiApi();
+ try {
+ array[Category] result = apiInstance.getAllUsingGET();
+ System.out.println(result);
+ } catch (ApiException e) {
+ System.err.println("Exception when calling CategoryapiApi#getAllUsingGET");
+ e.printStackTrace();
+ }
+ }
+}
+
+
+
+
+CategoryapiApi *apiInstance = [[CategoryapiApi alloc] init];
+
+// 获取全部分类
+[apiInstance getAllUsingGETWithCompletionHandler:
+ ^(array[Category] output, NSError* error) {
+ if (output) {
+ NSLog(@"%@", output);
+ }
+ if (error) {
+ NSLog(@"Error: %@", error);
+ }
+ }];
+
+
+
+
+
var SwaggerDemo = require('swagger_demo');
+
+var api = new SwaggerDemo.CategoryapiApi()
+
+var callback = function(error, data, response) {
+ if (error) {
+ console.error(error);
+ } else {
+ console.log('API called successfully. Returned data: ' + data);
+ }
+};
+api.getAllUsingGET(callback);
+
+
+
+
+
+
using System;
+using System.Diagnostics;
+using IO.Swagger.Api;
+using IO.Swagger.Client;
+using IO.Swagger.Model;
+
+namespace Example
+{
+ public class getAllUsingGETExample
+ {
+ public void main()
+ {
+
+ var apiInstance = new CategoryapiApi();
+
+ try
+ {
+ // 获取全部分类
+ array[Category] result = apiInstance.getAllUsingGET();
+ Debug.WriteLine(result);
+ }
+ catch (Exception e)
+ {
+ Debug.Print("Exception when calling CategoryapiApi.getAllUsingGET: " + e.Message );
+ }
+ }
+ }
+}
+
+
+
+
+
<?php
+require_once(__DIR__ . '/vendor/autoload.php');
+
+$api_instance = new Swagger\Client\Api\CategoryapiApi();
+
+try {
+ $result = $api_instance->getAllUsingGET();
+ print_r($result);
+} catch (Exception $e) {
+ echo 'Exception when calling CategoryapiApi->getAllUsingGET: ', $e->getMessage(), PHP_EOL;
+}
+?>
+
+
+
+
use Data::Dumper;
+use WWW::SwaggerClient::Configuration;
+use WWW::SwaggerClient::CategoryapiApi;
+
+my $api_instance = WWW::SwaggerClient::CategoryapiApi->new();
+
+eval {
+ my $result = $api_instance->getAllUsingGET();
+ print Dumper($result);
+};
+if ($@) {
+ warn "Exception when calling CategoryapiApi->getAllUsingGET: $@\n";
+}
+
+
+
+
from __future__ import print_statement
+import time
+import swagger_client
+from swagger_client.rest import ApiException
+from pprint import pprint
+
+# create an instance of the API class
+api_instance = swagger_client.CategoryapiApi()
+
+try:
+ # 获取全部分类
+ api_response = api_instance.get_all_using_get()
+ pprint(api_response)
+except ApiException as e:
+ print("Exception when calling CategoryapiApi->getAllUsingGET: %s\n" % e)
+
+
+
+ Parameters
+
+
+
+
+
+
+ Responses
+ Status: 200 - OK
+
+
+
+
+
+ Status: 401 - Unauthorized
+
+
+
+
+
+
+ Status: 403 - Forbidden
+
+
+
+
+
+
+ Status: 404 - Not Found
+
+
+
+
+
+
+
+
+
+
+
+
+
getUsingGET
+
根据ID获取分类
+
+
+
+
+
+
+
+ /v1/category/{id}
+
+
Usage and SDK Samples
+
+
+
+
+
+
curl -X GET "http://localhost:8080/v1/category/{id}"
+
+
+
import io.swagger.client.*;
+import io.swagger.client.auth.*;
+import io.swagger.client.model.*;
+import io.swagger.client.api.CategoryapiApi;
+
+import java.io.File;
+import java.util.*;
+
+public class CategoryapiApiExample {
+
+ public static void main(String[] args) {
+
+ CategoryapiApi apiInstance = new CategoryapiApi();
+ Integer id = 56; // Integer | id
+ try {
+ Category result = apiInstance.getUsingGET(id);
+ System.out.println(result);
+ } catch (ApiException e) {
+ System.err.println("Exception when calling CategoryapiApi#getUsingGET");
+ e.printStackTrace();
+ }
+ }
+}
+
+
+
+
import io.swagger.client.api.CategoryapiApi;
+
+public class CategoryapiApiExample {
+
+ public static void main(String[] args) {
+ CategoryapiApi apiInstance = new CategoryapiApi();
+ Integer id = 56; // Integer | id
+ try {
+ Category result = apiInstance.getUsingGET(id);
+ System.out.println(result);
+ } catch (ApiException e) {
+ System.err.println("Exception when calling CategoryapiApi#getUsingGET");
+ e.printStackTrace();
+ }
+ }
+}
+
+
+
+
Integer *id = 56; // id
+
+CategoryapiApi *apiInstance = [[CategoryapiApi alloc] init];
+
+// 根据ID获取分类
+[apiInstance getUsingGETWith:id
+ completionHandler: ^(Category output, NSError* error) {
+ if (output) {
+ NSLog(@"%@", output);
+ }
+ if (error) {
+ NSLog(@"Error: %@", error);
+ }
+ }];
+
+
+
+
+
var SwaggerDemo = require('swagger_demo');
+
+var api = new SwaggerDemo.CategoryapiApi()
+
+var id = 56; // {Integer} id
+
+
+var callback = function(error, data, response) {
+ if (error) {
+ console.error(error);
+ } else {
+ console.log('API called successfully. Returned data: ' + data);
+ }
+};
+api.getUsingGET(id, callback);
+
+
+
+
+
+
using System;
+using System.Diagnostics;
+using IO.Swagger.Api;
+using IO.Swagger.Client;
+using IO.Swagger.Model;
+
+namespace Example
+{
+ public class getUsingGETExample
+ {
+ public void main()
+ {
+
+ var apiInstance = new CategoryapiApi();
+ var id = 56; // Integer | id
+
+ try
+ {
+ // 根据ID获取分类
+ Category result = apiInstance.getUsingGET(id);
+ Debug.WriteLine(result);
+ }
+ catch (Exception e)
+ {
+ Debug.Print("Exception when calling CategoryapiApi.getUsingGET: " + e.Message );
+ }
+ }
+ }
+}
+
+
+
+
+
<?php
+require_once(__DIR__ . '/vendor/autoload.php');
+
+$api_instance = new Swagger\Client\Api\CategoryapiApi();
+$id = 56; // Integer | id
+
+try {
+ $result = $api_instance->getUsingGET($id);
+ print_r($result);
+} catch (Exception $e) {
+ echo 'Exception when calling CategoryapiApi->getUsingGET: ', $e->getMessage(), PHP_EOL;
+}
+?>
+
+
+
+
use Data::Dumper;
+use WWW::SwaggerClient::Configuration;
+use WWW::SwaggerClient::CategoryapiApi;
+
+my $api_instance = WWW::SwaggerClient::CategoryapiApi->new();
+my $id = 56; # Integer | id
+
+eval {
+ my $result = $api_instance->getUsingGET(id => $id);
+ print Dumper($result);
+};
+if ($@) {
+ warn "Exception when calling CategoryapiApi->getUsingGET: $@\n";
+}
+
+
+
+
from __future__ import print_statement
+import time
+import swagger_client
+from swagger_client.rest import ApiException
+from pprint import pprint
+
+# create an instance of the API class
+api_instance = swagger_client.CategoryapiApi()
+id = 56 # Integer | id
+
+try:
+ # 根据ID获取分类
+ api_response = api_instance.get_using_get(id)
+ pprint(api_response)
+except ApiException as e:
+ print("Exception when calling CategoryapiApi->getUsingGET: %s\n" % e)
+
+
+
+ Parameters
+
+ Path parameters
+
+
+ Name
+ Description
+
+ id*
+
+
+
+
+
+
+
+ Integer
+
+
+ (int32)
+
+
+
+ id
+
+
+
+ Required
+
+
+
+
+
+
+
+
+
+
+
+
+ Responses
+ Status: 200 - OK
+
+
+
+
+
+ Status: 401 - Unauthorized
+
+
+
+
+
+
+ Status: 403 - Forbidden
+
+
+
+
+
+
+ Status: 404 - Not Found
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Generated 2017-11-09T10:58:40.435+08:00
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/client/java/.gitignore b/client/java/.gitignore
new file mode 100644
index 0000000..a530464
--- /dev/null
+++ b/client/java/.gitignore
@@ -0,0 +1,21 @@
+*.class
+
+# Mobile Tools for Java (J2ME)
+.mtj.tmp/
+
+# Package Files #
+*.jar
+*.war
+*.ear
+
+# exclude jar for gradle wrapper
+!gradle/wrapper/*.jar
+
+# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
+hs_err_pid*
+
+# build files
+**/target
+target
+.gradle
+build
diff --git a/client/java/.swagger-codegen-ignore b/client/java/.swagger-codegen-ignore
new file mode 100644
index 0000000..c5fa491
--- /dev/null
+++ b/client/java/.swagger-codegen-ignore
@@ -0,0 +1,23 @@
+# Swagger Codegen Ignore
+# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen
+
+# Use this file to prevent files from being overwritten by the generator.
+# The patterns follow closely to .gitignore or .dockerignore.
+
+# As an example, the C# client generator defines ApiClient.cs.
+# You can make changes and tell Swagger Codgen to ignore just this file by uncommenting the following line:
+#ApiClient.cs
+
+# You can match any string of characters against a directory, file or extension with a single asterisk (*):
+#foo/*/qux
+# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux
+
+# You can recursively match patterns against a directory, file or extension with a double asterisk (**):
+#foo/**/qux
+# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux
+
+# You can also negate patterns with an exclamation (!).
+# For example, you can ignore all files in a docs folder with the file extension .md:
+#docs/*.md
+# Then explicitly reverse the ignore rule for a single file:
+#!docs/README.md
diff --git a/client/java/.swagger-codegen/VERSION b/client/java/.swagger-codegen/VERSION
new file mode 100644
index 0000000..717311e
--- /dev/null
+++ b/client/java/.swagger-codegen/VERSION
@@ -0,0 +1 @@
+unset
\ No newline at end of file
diff --git a/client/java/.travis.yml b/client/java/.travis.yml
new file mode 100644
index 0000000..70cb81a
--- /dev/null
+++ b/client/java/.travis.yml
@@ -0,0 +1,17 @@
+#
+# Generated by: https://github.com/swagger-api/swagger-codegen.git
+#
+language: java
+jdk:
+ - oraclejdk8
+ - oraclejdk7
+before_install:
+ # ensure gradlew has proper permission
+ - chmod a+x ./gradlew
+script:
+ # test using maven
+ - mvn test
+ # uncomment below to test using gradle
+ # - gradle test
+ # uncomment below to test using sbt
+ # - sbt test
diff --git a/client/java/README.md b/client/java/README.md
new file mode 100644
index 0000000..135475f
--- /dev/null
+++ b/client/java/README.md
@@ -0,0 +1,130 @@
+# swagger-client-java
+
+## Requirements
+
+Building the API client library requires [Maven](https://maven.apache.org/) to be installed.
+
+## Installation
+
+To install the API client library to your local Maven repository, simply execute:
+
+```shell
+mvn install
+```
+
+To deploy it to a remote Maven repository instead, configure the settings of the repository and execute:
+
+```shell
+mvn deploy
+```
+
+Refer to the [official documentation](https://maven.apache.org/plugins/maven-deploy-plugin/usage.html) for more information.
+
+### Maven users
+
+Add this dependency to your project's POM:
+
+```xml
+
+ com.example
+ swagger-client-java
+ 1.0.0
+ compile
+
+```
+
+### Gradle users
+
+Add this dependency to your project's build file:
+
+```groovy
+compile "com.example:swagger-client-java:1.0.0"
+```
+
+### Others
+
+At first generate the JAR by executing:
+
+ mvn package
+
+Then manually install the following JARs:
+
+* target/swagger-client-java-1.0.0.jar
+* target/lib/*.jar
+
+## Getting Started
+
+Please follow the [installation](#installation) instruction and execute the following Java code:
+
+```java
+
+import io.swagger.client.*;
+import io.swagger.client.auth.*;
+import io.swagger.client.model.*;
+import io.swagger.client.api.BookApiApi;
+
+import java.io.File;
+import java.util.*;
+
+public class BookApiApiExample {
+
+ public static void main(String[] args) {
+ ApiClient defaultClient = Configuration.getDefaultApiClient();
+
+ // Configure API key authorization: api_key
+ ApiKeyAuth api_key = (ApiKeyAuth) defaultClient.getAuthentication("api_key");
+ api_key.setApiKey("YOUR API KEY");
+ // Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)
+ //api_key.setApiKeyPrefix("Token");
+
+ BookApiApi apiInstance = new BookApiApi();
+ Integer id = 56; // Integer | id
+ try {
+ Book result = apiInstance.getBookByIdUsingGET(id);
+ System.out.println(result);
+ } catch (ApiException e) {
+ System.err.println("Exception when calling BookApiApi#getBookByIdUsingGET");
+ e.printStackTrace();
+ }
+ }
+}
+
+```
+
+## Documentation for API Endpoints
+
+All URIs are relative to *http://localhost:8080*
+
+Class | Method | HTTP request | Description
+------------ | ------------- | ------------- | -------------
+*BookApiApi* | [**getBookByIdUsingGET**](docs/BookApiApi.md#getBookByIdUsingGET) | **GET** /v1/book/{id} | 根据ID获取书籍
+*BookApiApi* | [**getBooksByCategoryUsingGET**](docs/BookApiApi.md#getBooksByCategoryUsingGET) | **GET** /v1/book/getByCategoryId | 根据分类获取书籍
+*BookApiApi* | [**updateUsingPOST**](docs/BookApiApi.md#updateUsingPOST) | **POST** /v1/book/update | 更新书籍
+*CategoryApiApi* | [**getAllUsingGET**](docs/CategoryApiApi.md#getAllUsingGET) | **GET** /v1/category/ | 获取全部分类
+*CategoryApiApi* | [**getUsingGET**](docs/CategoryApiApi.md#getUsingGET) | **GET** /v1/category/{id} | 根据ID获取分类
+
+
+## Documentation for Models
+
+ - [Book](docs/Book.md)
+ - [Category](docs/Category.md)
+
+
+## Documentation for Authorization
+
+Authentication schemes defined for the API:
+### api_key
+
+- **Type**: API key
+- **API key parameter name**: api_key
+- **Location**: HTTP header
+
+
+## Recommendation
+
+It's recommended to create an instance of `ApiClient` per thread in a multithreaded environment to avoid any potential issues.
+
+## Author
+
+damon.q@iv66.net
+
diff --git a/client/java/build.gradle b/client/java/build.gradle
new file mode 100644
index 0000000..b74b036
--- /dev/null
+++ b/client/java/build.gradle
@@ -0,0 +1,102 @@
+apply plugin: 'idea'
+apply plugin: 'eclipse'
+
+group = 'com.example'
+version = '1.0.0'
+
+buildscript {
+ repositories {
+ jcenter()
+ }
+ dependencies {
+ classpath 'com.android.tools.build:gradle:2.3.+'
+ classpath 'com.github.dcendents:android-maven-gradle-plugin:1.5'
+ }
+}
+
+repositories {
+ jcenter()
+}
+
+
+if(hasProperty('target') && target == 'android') {
+
+ apply plugin: 'com.android.library'
+ apply plugin: 'com.github.dcendents.android-maven'
+
+ android {
+ compileSdkVersion 25
+ buildToolsVersion '25.0.2'
+ defaultConfig {
+ minSdkVersion 14
+ targetSdkVersion 25
+ }
+ compileOptions {
+ sourceCompatibility JavaVersion.VERSION_1_8
+ targetCompatibility JavaVersion.VERSION_1_8
+ }
+
+ // Rename the aar correctly
+ libraryVariants.all { variant ->
+ variant.outputs.each { output ->
+ def outputFile = output.outputFile
+ if (outputFile != null && outputFile.name.endsWith('.aar')) {
+ def fileName = "${project.name}-${variant.baseName}-${version}.aar"
+ output.outputFile = new File(outputFile.parent, fileName)
+ }
+ }
+ }
+
+ dependencies {
+ provided 'javax.annotation:jsr250-api:1.0'
+ }
+ }
+
+ afterEvaluate {
+ android.libraryVariants.all { variant ->
+ def task = project.tasks.create "jar${variant.name.capitalize()}", Jar
+ task.description = "Create jar artifact for ${variant.name}"
+ task.dependsOn variant.javaCompile
+ task.from variant.javaCompile.destinationDir
+ task.destinationDir = project.file("${project.buildDir}/outputs/jar")
+ task.archiveName = "${project.name}-${variant.baseName}-${version}.jar"
+ artifacts.add('archives', task);
+ }
+ }
+
+ task sourcesJar(type: Jar) {
+ from android.sourceSets.main.java.srcDirs
+ classifier = 'sources'
+ }
+
+ artifacts {
+ archives sourcesJar
+ }
+
+} else {
+
+ apply plugin: 'java'
+ apply plugin: 'maven'
+
+ sourceCompatibility = JavaVersion.VERSION_1_8
+ targetCompatibility = JavaVersion.VERSION_1_8
+
+ install {
+ repositories.mavenInstaller {
+ pom.artifactId = 'swagger-client-java'
+ }
+ }
+
+ task execute(type:JavaExec) {
+ main = System.getProperty('mainClass')
+ classpath = sourceSets.main.runtimeClasspath
+ }
+}
+
+dependencies {
+ compile 'io.swagger:swagger-annotations:1.5.15'
+ compile 'com.squareup.okhttp:okhttp:2.7.5'
+ compile 'com.squareup.okhttp:logging-interceptor:2.7.5'
+ compile 'com.google.code.gson:gson:2.8.1'
+ testCompile 'junit:junit:4.12'
+}
diff --git a/client/java/build.sbt b/client/java/build.sbt
new file mode 100644
index 0000000..1a063fa
--- /dev/null
+++ b/client/java/build.sbt
@@ -0,0 +1,19 @@
+lazy val root = (project in file(".")).
+ settings(
+ organization := "com.example",
+ name := "swagger-client-java",
+ version := "1.0.0",
+ scalaVersion := "2.11.4",
+ scalacOptions ++= Seq("-feature"),
+ javacOptions in compile ++= Seq("-Xlint:deprecation"),
+ publishArtifact in (Compile, packageDoc) := false,
+ resolvers += Resolver.mavenLocal,
+ libraryDependencies ++= Seq(
+ "io.swagger" % "swagger-annotations" % "1.5.15",
+ "com.squareup.okhttp" % "okhttp" % "2.7.5",
+ "com.squareup.okhttp" % "logging-interceptor" % "2.7.5",
+ "com.google.code.gson" % "gson" % "2.8.1",
+ "junit" % "junit" % "4.12" % "test",
+ "com.novocode" % "junit-interface" % "0.10" % "test"
+ )
+ )
diff --git a/client/java/docs/Book.md b/client/java/docs/Book.md
new file mode 100644
index 0000000..be610d9
--- /dev/null
+++ b/client/java/docs/Book.md
@@ -0,0 +1,13 @@
+
+# Book
+
+## Properties
+Name | Type | Description | Notes
+------------ | ------------- | ------------- | -------------
+**author** | **String** | 作者 | [optional]
+**categoryId** | **Integer** | | [optional]
+**id** | **Integer** | | [optional]
+**name** | **String** | 书名 | [optional]
+
+
+
diff --git a/client/java/docs/BookApiApi.md b/client/java/docs/BookApiApi.md
new file mode 100644
index 0000000..60d97c7
--- /dev/null
+++ b/client/java/docs/BookApiApi.md
@@ -0,0 +1,170 @@
+# BookApiApi
+
+All URIs are relative to *http://localhost:8080*
+
+Method | HTTP request | Description
+------------- | ------------- | -------------
+[**getBookByIdUsingGET**](BookApiApi.md#getBookByIdUsingGET) | **GET** /v1/book/{id} | 根据ID获取书籍
+[**getBooksByCategoryUsingGET**](BookApiApi.md#getBooksByCategoryUsingGET) | **GET** /v1/book/getByCategoryId | 根据分类获取书籍
+[**updateUsingPOST**](BookApiApi.md#updateUsingPOST) | **POST** /v1/book/update | 更新书籍
+
+
+
+# **getBookByIdUsingGET**
+> Book getBookByIdUsingGET(id)
+
+根据ID获取书籍
+
+### Example
+```java
+// Import classes:
+//import io.swagger.client.ApiClient;
+//import io.swagger.client.ApiException;
+//import io.swagger.client.Configuration;
+//import io.swagger.client.auth.*;
+//import io.swagger.client.api.BookApiApi;
+
+ApiClient defaultClient = Configuration.getDefaultApiClient();
+
+// Configure API key authorization: api_key
+ApiKeyAuth api_key = (ApiKeyAuth) defaultClient.getAuthentication("api_key");
+api_key.setApiKey("YOUR API KEY");
+// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)
+//api_key.setApiKeyPrefix("Token");
+
+BookApiApi apiInstance = new BookApiApi();
+Integer id = 56; // Integer | id
+try {
+ Book result = apiInstance.getBookByIdUsingGET(id);
+ System.out.println(result);
+} catch (ApiException e) {
+ System.err.println("Exception when calling BookApiApi#getBookByIdUsingGET");
+ e.printStackTrace();
+}
+```
+
+### Parameters
+
+Name | Type | Description | Notes
+------------- | ------------- | ------------- | -------------
+ **id** | **Integer**| id |
+
+### Return type
+
+[**Book**](Book.md)
+
+### Authorization
+
+[api_key](../README.md#api_key)
+
+### HTTP request headers
+
+ - **Content-Type**: application/json
+ - **Accept**: */*
+
+
+# **getBooksByCategoryUsingGET**
+> List<Book> getBooksByCategoryUsingGET(id)
+
+根据分类获取书籍
+
+### Example
+```java
+// Import classes:
+//import io.swagger.client.ApiClient;
+//import io.swagger.client.ApiException;
+//import io.swagger.client.Configuration;
+//import io.swagger.client.auth.*;
+//import io.swagger.client.api.BookApiApi;
+
+ApiClient defaultClient = Configuration.getDefaultApiClient();
+
+// Configure API key authorization: api_key
+ApiKeyAuth api_key = (ApiKeyAuth) defaultClient.getAuthentication("api_key");
+api_key.setApiKey("YOUR API KEY");
+// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)
+//api_key.setApiKeyPrefix("Token");
+
+BookApiApi apiInstance = new BookApiApi();
+Integer id = 56; // Integer | id
+try {
+ List result = apiInstance.getBooksByCategoryUsingGET(id);
+ System.out.println(result);
+} catch (ApiException e) {
+ System.err.println("Exception when calling BookApiApi#getBooksByCategoryUsingGET");
+ e.printStackTrace();
+}
+```
+
+### Parameters
+
+Name | Type | Description | Notes
+------------- | ------------- | ------------- | -------------
+ **id** | **Integer**| id |
+
+### Return type
+
+[**List<Book>**](Book.md)
+
+### Authorization
+
+[api_key](../README.md#api_key)
+
+### HTTP request headers
+
+ - **Content-Type**: application/json
+ - **Accept**: */*
+
+
+# **updateUsingPOST**
+> Boolean updateUsingPOST(id)
+
+更新书籍
+
+### Example
+```java
+// Import classes:
+//import io.swagger.client.ApiClient;
+//import io.swagger.client.ApiException;
+//import io.swagger.client.Configuration;
+//import io.swagger.client.auth.*;
+//import io.swagger.client.api.BookApiApi;
+
+ApiClient defaultClient = Configuration.getDefaultApiClient();
+
+// Configure API key authorization: api_key
+ApiKeyAuth api_key = (ApiKeyAuth) defaultClient.getAuthentication("api_key");
+api_key.setApiKey("YOUR API KEY");
+// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)
+//api_key.setApiKeyPrefix("Token");
+
+BookApiApi apiInstance = new BookApiApi();
+Integer id = 56; // Integer | id
+try {
+ Boolean result = apiInstance.updateUsingPOST(id);
+ System.out.println(result);
+} catch (ApiException e) {
+ System.err.println("Exception when calling BookApiApi#updateUsingPOST");
+ e.printStackTrace();
+}
+```
+
+### Parameters
+
+Name | Type | Description | Notes
+------------- | ------------- | ------------- | -------------
+ **id** | **Integer**| id | [optional]
+
+### Return type
+
+**Boolean**
+
+### Authorization
+
+[api_key](../README.md#api_key)
+
+### HTTP request headers
+
+ - **Content-Type**: application/json
+ - **Accept**: */*
+
diff --git a/client/java/docs/Category.md b/client/java/docs/Category.md
new file mode 100644
index 0000000..be682f1
--- /dev/null
+++ b/client/java/docs/Category.md
@@ -0,0 +1,11 @@
+
+# Category
+
+## Properties
+Name | Type | Description | Notes
+------------ | ------------- | ------------- | -------------
+**id** | **Integer** | | [optional]
+**name** | **String** | | [optional]
+
+
+
diff --git a/client/java/docs/CategoryApiApi.md b/client/java/docs/CategoryApiApi.md
new file mode 100644
index 0000000..7bb7dbc
--- /dev/null
+++ b/client/java/docs/CategoryApiApi.md
@@ -0,0 +1,92 @@
+# CategoryApiApi
+
+All URIs are relative to *http://localhost:8080*
+
+Method | HTTP request | Description
+------------- | ------------- | -------------
+[**getAllUsingGET**](CategoryApiApi.md#getAllUsingGET) | **GET** /v1/category/ | 获取全部分类
+[**getUsingGET**](CategoryApiApi.md#getUsingGET) | **GET** /v1/category/{id} | 根据ID获取分类
+
+
+
+# **getAllUsingGET**
+> List<Category> getAllUsingGET()
+
+获取全部分类
+
+### Example
+```java
+// Import classes:
+//import io.swagger.client.ApiException;
+//import io.swagger.client.api.CategoryApiApi;
+
+
+CategoryApiApi apiInstance = new CategoryApiApi();
+try {
+ List result = apiInstance.getAllUsingGET();
+ System.out.println(result);
+} catch (ApiException e) {
+ System.err.println("Exception when calling CategoryApiApi#getAllUsingGET");
+ e.printStackTrace();
+}
+```
+
+### Parameters
+This endpoint does not need any parameter.
+
+### Return type
+
+[**List<Category>**](Category.md)
+
+### Authorization
+
+No authorization required
+
+### HTTP request headers
+
+ - **Content-Type**: application/json
+ - **Accept**: */*
+
+
+# **getUsingGET**
+> Category getUsingGET(id)
+
+根据ID获取分类
+
+### Example
+```java
+// Import classes:
+//import io.swagger.client.ApiException;
+//import io.swagger.client.api.CategoryApiApi;
+
+
+CategoryApiApi apiInstance = new CategoryApiApi();
+Integer id = 56; // Integer | id
+try {
+ Category result = apiInstance.getUsingGET(id);
+ System.out.println(result);
+} catch (ApiException e) {
+ System.err.println("Exception when calling CategoryApiApi#getUsingGET");
+ e.printStackTrace();
+}
+```
+
+### Parameters
+
+Name | Type | Description | Notes
+------------- | ------------- | ------------- | -------------
+ **id** | **Integer**| id |
+
+### Return type
+
+[**Category**](Category.md)
+
+### Authorization
+
+No authorization required
+
+### HTTP request headers
+
+ - **Content-Type**: application/json
+ - **Accept**: */*
+
diff --git a/client/java/git_push.sh b/client/java/git_push.sh
new file mode 100644
index 0000000..ed37461
--- /dev/null
+++ b/client/java/git_push.sh
@@ -0,0 +1,52 @@
+#!/bin/sh
+# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/
+#
+# Usage example: /bin/sh ./git_push.sh wing328 swagger-petstore-perl "minor update"
+
+git_user_id=$1
+git_repo_id=$2
+release_note=$3
+
+if [ "$git_user_id" = "" ]; then
+ git_user_id="GIT_USER_ID"
+ echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id"
+fi
+
+if [ "$git_repo_id" = "" ]; then
+ git_repo_id="GIT_REPO_ID"
+ echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id"
+fi
+
+if [ "$release_note" = "" ]; then
+ release_note="Minor update"
+ echo "[INFO] No command line input provided. Set \$release_note to $release_note"
+fi
+
+# Initialize the local directory as a Git repository
+git init
+
+# Adds the files in the local repository and stages them for commit.
+git add .
+
+# Commits the tracked changes and prepares them to be pushed to a remote repository.
+git commit -m "$release_note"
+
+# Sets the new remote
+git_remote=`git remote`
+if [ "$git_remote" = "" ]; then # git remote not defined
+
+ if [ "$GIT_TOKEN" = "" ]; then
+ echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git crediential in your environment."
+ git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git
+ else
+ git remote add origin https://${git_user_id}:${GIT_TOKEN}@github.com/${git_user_id}/${git_repo_id}.git
+ fi
+
+fi
+
+git pull origin master
+
+# Pushes (Forces) the changes in the local repository up to the remote repository
+echo "Git pushing to https://github.com/${git_user_id}/${git_repo_id}.git"
+git push origin master 2>&1 | grep -v 'To https'
+
diff --git a/client/java/gradle.properties b/client/java/gradle.properties
new file mode 100644
index 0000000..05644f0
--- /dev/null
+++ b/client/java/gradle.properties
@@ -0,0 +1,2 @@
+# Uncomment to build for Android
+#target = android
\ No newline at end of file
diff --git a/client/java/gradle/wrapper/gradle-wrapper.jar b/client/java/gradle/wrapper/gradle-wrapper.jar
new file mode 100644
index 0000000..2c6137b
Binary files /dev/null and b/client/java/gradle/wrapper/gradle-wrapper.jar differ
diff --git a/client/java/gradle/wrapper/gradle-wrapper.properties b/client/java/gradle/wrapper/gradle-wrapper.properties
new file mode 100644
index 0000000..b7a3647
--- /dev/null
+++ b/client/java/gradle/wrapper/gradle-wrapper.properties
@@ -0,0 +1,6 @@
+#Tue May 17 23:08:05 CST 2016
+distributionBase=GRADLE_USER_HOME
+distributionPath=wrapper/dists
+zipStoreBase=GRADLE_USER_HOME
+zipStorePath=wrapper/dists
+distributionUrl=https\://services.gradle.org/distributions/gradle-2.6-bin.zip
diff --git a/client/java/gradlew b/client/java/gradlew
new file mode 100644
index 0000000..9d82f78
--- /dev/null
+++ b/client/java/gradlew
@@ -0,0 +1,160 @@
+#!/usr/bin/env bash
+
+##############################################################################
+##
+## Gradle start up script for UN*X
+##
+##############################################################################
+
+# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+DEFAULT_JVM_OPTS=""
+
+APP_NAME="Gradle"
+APP_BASE_NAME=`basename "$0"`
+
+# Use the maximum available, or set MAX_FD != -1 to use that value.
+MAX_FD="maximum"
+
+warn ( ) {
+ echo "$*"
+}
+
+die ( ) {
+ echo
+ echo "$*"
+ echo
+ exit 1
+}
+
+# OS specific support (must be 'true' or 'false').
+cygwin=false
+msys=false
+darwin=false
+case "`uname`" in
+ CYGWIN* )
+ cygwin=true
+ ;;
+ Darwin* )
+ darwin=true
+ ;;
+ MINGW* )
+ msys=true
+ ;;
+esac
+
+# Attempt to set APP_HOME
+# Resolve links: $0 may be a link
+PRG="$0"
+# Need this for relative symlinks.
+while [ -h "$PRG" ] ; do
+ ls=`ls -ld "$PRG"`
+ link=`expr "$ls" : '.*-> \(.*\)$'`
+ if expr "$link" : '/.*' > /dev/null; then
+ PRG="$link"
+ else
+ PRG=`dirname "$PRG"`"/$link"
+ fi
+done
+SAVED="`pwd`"
+cd "`dirname \"$PRG\"`/" >/dev/null
+APP_HOME="`pwd -P`"
+cd "$SAVED" >/dev/null
+
+CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
+
+# Determine the Java command to use to start the JVM.
+if [ -n "$JAVA_HOME" ] ; then
+ if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
+ # IBM's JDK on AIX uses strange locations for the executables
+ JAVACMD="$JAVA_HOME/jre/sh/java"
+ else
+ JAVACMD="$JAVA_HOME/bin/java"
+ fi
+ if [ ! -x "$JAVACMD" ] ; then
+ die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+ fi
+else
+ JAVACMD="java"
+ which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+fi
+
+# Increase the maximum file descriptors if we can.
+if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
+ MAX_FD_LIMIT=`ulimit -H -n`
+ if [ $? -eq 0 ] ; then
+ if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
+ MAX_FD="$MAX_FD_LIMIT"
+ fi
+ ulimit -n $MAX_FD
+ if [ $? -ne 0 ] ; then
+ warn "Could not set maximum file descriptor limit: $MAX_FD"
+ fi
+ else
+ warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
+ fi
+fi
+
+# For Darwin, add options to specify how the application appears in the dock
+if $darwin; then
+ GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
+fi
+
+# For Cygwin, switch paths to Windows format before running java
+if $cygwin ; then
+ APP_HOME=`cygpath --path --mixed "$APP_HOME"`
+ CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
+ JAVACMD=`cygpath --unix "$JAVACMD"`
+
+ # We build the pattern for arguments to be converted via cygpath
+ ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
+ SEP=""
+ for dir in $ROOTDIRSRAW ; do
+ ROOTDIRS="$ROOTDIRS$SEP$dir"
+ SEP="|"
+ done
+ OURCYGPATTERN="(^($ROOTDIRS))"
+ # Add a user-defined pattern to the cygpath arguments
+ if [ "$GRADLE_CYGPATTERN" != "" ] ; then
+ OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
+ fi
+ # Now convert the arguments - kludge to limit ourselves to /bin/sh
+ i=0
+ for arg in "$@" ; do
+ CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
+ CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
+
+ if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
+ eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
+ else
+ eval `echo args$i`="\"$arg\""
+ fi
+ i=$((i+1))
+ done
+ case $i in
+ (0) set -- ;;
+ (1) set -- "$args0" ;;
+ (2) set -- "$args0" "$args1" ;;
+ (3) set -- "$args0" "$args1" "$args2" ;;
+ (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
+ (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
+ (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
+ (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
+ (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
+ (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
+ esac
+fi
+
+# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
+function splitJvmOpts() {
+ JVM_OPTS=("$@")
+}
+eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
+JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
+
+exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
diff --git a/client/java/gradlew.bat b/client/java/gradlew.bat
new file mode 100644
index 0000000..5f19212
--- /dev/null
+++ b/client/java/gradlew.bat
@@ -0,0 +1,90 @@
+@if "%DEBUG%" == "" @echo off
+@rem ##########################################################################
+@rem
+@rem Gradle startup script for Windows
+@rem
+@rem ##########################################################################
+
+@rem Set local scope for the variables with windows NT shell
+if "%OS%"=="Windows_NT" setlocal
+
+@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+set DEFAULT_JVM_OPTS=
+
+set DIRNAME=%~dp0
+if "%DIRNAME%" == "" set DIRNAME=.
+set APP_BASE_NAME=%~n0
+set APP_HOME=%DIRNAME%
+
+@rem Find java.exe
+if defined JAVA_HOME goto findJavaFromJavaHome
+
+set JAVA_EXE=java.exe
+%JAVA_EXE% -version >NUL 2>&1
+if "%ERRORLEVEL%" == "0" goto init
+
+echo.
+echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
+echo.
+echo Please set the JAVA_HOME variable in your environment to match the
+echo location of your Java installation.
+
+goto fail
+
+:findJavaFromJavaHome
+set JAVA_HOME=%JAVA_HOME:"=%
+set JAVA_EXE=%JAVA_HOME%/bin/java.exe
+
+if exist "%JAVA_EXE%" goto init
+
+echo.
+echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
+echo.
+echo Please set the JAVA_HOME variable in your environment to match the
+echo location of your Java installation.
+
+goto fail
+
+:init
+@rem Get command-line arguments, handling Windows variants
+
+if not "%OS%" == "Windows_NT" goto win9xME_args
+if "%@eval[2+2]" == "4" goto 4NT_args
+
+:win9xME_args
+@rem Slurp the command line arguments.
+set CMD_LINE_ARGS=
+set _SKIP=2
+
+:win9xME_args_slurp
+if "x%~1" == "x" goto execute
+
+set CMD_LINE_ARGS=%*
+goto execute
+
+:4NT_args
+@rem Get arguments from the 4NT Shell from JP Software
+set CMD_LINE_ARGS=%$
+
+:execute
+@rem Setup the command line
+
+set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
+
+@rem Execute Gradle
+"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
+
+:end
+@rem End local scope for the variables with windows NT shell
+if "%ERRORLEVEL%"=="0" goto mainEnd
+
+:fail
+rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
+rem the _cmd.exe /c_ return code!
+if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
+exit /b 1
+
+:mainEnd
+if "%OS%"=="Windows_NT" endlocal
+
+:omega
diff --git a/client/java/pom.xml b/client/java/pom.xml
new file mode 100644
index 0000000..29b3cfa
--- /dev/null
+++ b/client/java/pom.xml
@@ -0,0 +1,212 @@
+
+ 4.0.0
+ com.example
+ swagger-client-java
+ jar
+ swagger-client-java
+ 1.0.0
+ https://github.com/swagger-api/swagger-codegen
+ Swagger Java
+
+ scm:git:git@github.com:swagger-api/swagger-codegen.git
+ scm:git:git@github.com:swagger-api/swagger-codegen.git
+ https://github.com/swagger-api/swagger-codegen
+
+
+ 2.2.0
+
+
+
+
+ Unlicense
+ http://www.apache.org/licenses/LICENSE-2.0.html
+ repo
+
+
+
+
+
+ Swagger
+ apiteam@swagger.io
+ Swagger
+ http://swagger.io
+
+
+
+
+
+
+ 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
+
+
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-jar-plugin
+ 2.2
+
+
+
+ jar
+ test-jar
+
+
+
+
+
+
+
+
+ org.codehaus.mojo
+ build-helper-maven-plugin
+ 1.10
+
+
+ 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-javadoc-plugin
+ 2.10.4
+
+
+ attach-javadocs
+
+ jar
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-source-plugin
+ 2.2.1
+
+
+ attach-sources
+
+ jar-no-fork
+
+
+
+
+
+
+
+
+
+ sign-artifacts
+
+
+
+ org.apache.maven.plugins
+ maven-gpg-plugin
+ 1.5
+
+
+ sign-artifacts
+ verify
+
+ sign
+
+
+
+
+
+
+
+
+
+
+
+ io.swagger
+ swagger-annotations
+ ${swagger-core-version}
+
+
+ com.squareup.okhttp
+ okhttp
+ ${okhttp-version}
+
+
+ com.squareup.okhttp
+ logging-interceptor
+ ${okhttp-version}
+
+
+ com.google.code.gson
+ gson
+ ${gson-version}
+
+
+
+ junit
+ junit
+ ${junit-version}
+ test
+
+
+
+ 1.8
+ ${java.version}
+ ${java.version}
+ 1.5.15
+ 2.7.5
+ 2.8.1
+ 2.9.9
+ 1.0.0
+ 4.12
+ UTF-8
+
+
diff --git a/client/java/settings.gradle b/client/java/settings.gradle
new file mode 100644
index 0000000..8f30e98
--- /dev/null
+++ b/client/java/settings.gradle
@@ -0,0 +1 @@
+rootProject.name = "swagger-client-java"
\ No newline at end of file
diff --git a/client/java/src/main/AndroidManifest.xml b/client/java/src/main/AndroidManifest.xml
new file mode 100644
index 0000000..465dcb5
--- /dev/null
+++ b/client/java/src/main/AndroidManifest.xml
@@ -0,0 +1,3 @@
+
+
+
diff --git a/client/java/src/main/java/io/swagger/client/ApiCallback.java b/client/java/src/main/java/io/swagger/client/ApiCallback.java
new file mode 100644
index 0000000..5f685e9
--- /dev/null
+++ b/client/java/src/main/java/io/swagger/client/ApiCallback.java
@@ -0,0 +1,62 @@
+/*
+ * Swagger Demo
+ * Swagger的简单示例, 包括swagger-codegen, swagger2markup 和 asciidoctor.
+ *
+ * OpenAPI spec version: v1
+ * Contact: damon.q@iv66.net
+ *
+ * NOTE: This class is auto generated by the swagger code generator program.
+ * https://github.com/swagger-api/swagger-codegen.git
+ * Do not edit the class manually.
+ */
+
+
+package io.swagger.client;
+
+import java.io.IOException;
+
+import java.util.Map;
+import java.util.List;
+
+/**
+ * Callback for asynchronous API call.
+ *
+ * @param The return type
+ */
+public interface ApiCallback {
+ /**
+ * This is called when the API call fails.
+ *
+ * @param e The exception causing the failure
+ * @param statusCode Status code of the response if available, otherwise it would be 0
+ * @param responseHeaders Headers of the response if available, otherwise it would be null
+ */
+ void onFailure(ApiException e, int statusCode, Map> responseHeaders);
+
+ /**
+ * This is called when the API call succeeded.
+ *
+ * @param result The result deserialized from response
+ * @param statusCode Status code of the response
+ * @param responseHeaders Headers of the response
+ */
+ void onSuccess(T result, int statusCode, Map> responseHeaders);
+
+ /**
+ * This is called when the API upload processing.
+ *
+ * @param bytesWritten bytes Written
+ * @param contentLength content length of request body
+ * @param done write end
+ */
+ void onUploadProgress(long bytesWritten, long contentLength, boolean done);
+
+ /**
+ * This is called when the API downlond processing.
+ *
+ * @param bytesRead bytes Read
+ * @param contentLength content lenngth of the response
+ * @param done Read end
+ */
+ void onDownloadProgress(long bytesRead, long contentLength, boolean done);
+}
diff --git a/client/java/src/main/java/io/swagger/client/ApiClient.java b/client/java/src/main/java/io/swagger/client/ApiClient.java
new file mode 100644
index 0000000..39ebae1
--- /dev/null
+++ b/client/java/src/main/java/io/swagger/client/ApiClient.java
@@ -0,0 +1,1359 @@
+/*
+ * Swagger Demo
+ * Swagger的简单示例, 包括swagger-codegen, swagger2markup 和 asciidoctor.
+ *
+ * OpenAPI spec version: v1
+ * Contact: damon.q@iv66.net
+ *
+ * NOTE: This class is auto generated by the swagger code generator program.
+ * https://github.com/swagger-api/swagger-codegen.git
+ * Do not edit the class manually.
+ */
+
+
+package io.swagger.client;
+
+import com.squareup.okhttp.Call;
+import com.squareup.okhttp.Callback;
+import com.squareup.okhttp.OkHttpClient;
+import com.squareup.okhttp.Request;
+import com.squareup.okhttp.Response;
+import com.squareup.okhttp.RequestBody;
+import com.squareup.okhttp.FormEncodingBuilder;
+import com.squareup.okhttp.MultipartBuilder;
+import com.squareup.okhttp.MediaType;
+import com.squareup.okhttp.Headers;
+import com.squareup.okhttp.internal.http.HttpMethod;
+import com.squareup.okhttp.logging.HttpLoggingInterceptor;
+import com.squareup.okhttp.logging.HttpLoggingInterceptor.Level;
+
+import java.lang.reflect.Type;
+
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.HashMap;
+import java.util.List;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.TimeZone;
+import java.util.concurrent.TimeUnit;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import java.net.URLEncoder;
+import java.net.URLConnection;
+
+import java.io.File;
+import java.io.InputStream;
+import java.io.IOException;
+import java.io.UnsupportedEncodingException;
+
+import java.security.GeneralSecurityException;
+import java.security.KeyStore;
+import java.security.SecureRandom;
+import java.security.cert.Certificate;
+import java.security.cert.CertificateException;
+import java.security.cert.CertificateFactory;
+import java.security.cert.X509Certificate;
+
+import java.text.DateFormat;
+import java.text.SimpleDateFormat;
+import java.text.ParseException;
+
+import javax.net.ssl.HostnameVerifier;
+import javax.net.ssl.KeyManager;
+import javax.net.ssl.KeyManagerFactory;
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.SSLSession;
+import javax.net.ssl.TrustManager;
+import javax.net.ssl.TrustManagerFactory;
+import javax.net.ssl.X509TrustManager;
+
+import okio.BufferedSink;
+import okio.Okio;
+
+import io.swagger.client.auth.Authentication;
+import io.swagger.client.auth.HttpBasicAuth;
+import io.swagger.client.auth.ApiKeyAuth;
+import io.swagger.client.auth.OAuth;
+
+public class ApiClient {
+ public static final double JAVA_VERSION;
+ public static final boolean IS_ANDROID;
+ public static final int ANDROID_SDK_VERSION;
+
+ static {
+ JAVA_VERSION = Double.parseDouble(System.getProperty("java.specification.version"));
+ boolean isAndroid;
+ try {
+ Class.forName("android.app.Activity");
+ isAndroid = true;
+ } catch (ClassNotFoundException e) {
+ isAndroid = false;
+ }
+ IS_ANDROID = isAndroid;
+ int sdkVersion = 0;
+ if (IS_ANDROID) {
+ try {
+ sdkVersion = Class.forName("android.os.Build$VERSION").getField("SDK_INT").getInt(null);
+ } catch (Exception e) {
+ try {
+ sdkVersion = Integer.parseInt((String) Class.forName("android.os.Build$VERSION").getField("SDK").get(null));
+ } catch (Exception e2) { }
+ }
+ }
+ ANDROID_SDK_VERSION = sdkVersion;
+ }
+
+ /**
+ * The datetime format to be used when lenientDatetimeFormat
is enabled.
+ */
+ public static final String LENIENT_DATETIME_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSZ";
+
+ private String basePath = "http://localhost:8080";
+ private boolean lenientOnJson = false;
+ private boolean debugging = false;
+ private Map defaultHeaderMap = new HashMap();
+ private String tempFolderPath = null;
+
+ private Map authentications;
+
+ private DateFormat dateFormat;
+ private DateFormat datetimeFormat;
+ private boolean lenientDatetimeFormat;
+ private int dateLength;
+
+ private InputStream sslCaCert;
+ private boolean verifyingSsl;
+ private KeyManager[] keyManagers;
+
+ private OkHttpClient httpClient;
+ private JSON json;
+
+ private HttpLoggingInterceptor loggingInterceptor;
+
+ /*
+ * Constructor for ApiClient
+ */
+ public ApiClient() {
+ httpClient = new OkHttpClient();
+
+
+ verifyingSsl = true;
+
+ json = new JSON(this);
+
+ /*
+ * Use RFC3339 format for date and datetime.
+ * See http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14
+ */
+ this.dateFormat = new SimpleDateFormat("yyyy-MM-dd");
+ // Always use UTC as the default time zone when dealing with date (without time).
+ this.dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
+ initDatetimeFormat();
+
+ // Be lenient on datetime formats when parsing datetime from string.
+ // See parseDatetime
.
+ this.lenientDatetimeFormat = true;
+
+ // Set default User-Agent.
+ setUserAgent("Swagger-Codegen/1.0.0/java");
+
+ // Setup authentications (key: authentication name, value: authentication).
+ authentications = new HashMap();
+ authentications.put("api_key", new ApiKeyAuth("header", "api_key"));
+ // Prevent the authentications from being modified.
+ authentications = Collections.unmodifiableMap(authentications);
+ }
+
+ /**
+ * Get base path
+ *
+ * @return Baes path
+ */
+ public String getBasePath() {
+ return basePath;
+ }
+
+ /**
+ * Set base path
+ *
+ * @param basePath Base path of the URL (e.g http://localhost:8080
+ * @return An instance of OkHttpClient
+ */
+ public ApiClient setBasePath(String basePath) {
+ this.basePath = basePath;
+ return this;
+ }
+
+ /**
+ * Get HTTP client
+ *
+ * @return An instance of OkHttpClient
+ */
+ public OkHttpClient getHttpClient() {
+ return httpClient;
+ }
+
+ /**
+ * Set HTTP client
+ *
+ * @param httpClient An instance of OkHttpClient
+ * @return Api Client
+ */
+ public ApiClient setHttpClient(OkHttpClient httpClient) {
+ this.httpClient = httpClient;
+ return this;
+ }
+
+ /**
+ * Get JSON
+ *
+ * @return JSON object
+ */
+ public JSON getJSON() {
+ return json;
+ }
+
+ /**
+ * Set JSON
+ *
+ * @param json JSON object
+ * @return Api client
+ */
+ public ApiClient setJSON(JSON json) {
+ this.json = json;
+ return this;
+ }
+
+ /**
+ * True if isVerifyingSsl flag is on
+ *
+ * @return True if isVerifySsl flag is on
+ */
+ public boolean isVerifyingSsl() {
+ return verifyingSsl;
+ }
+
+ /**
+ * Configure whether to verify certificate and hostname when making https requests.
+ * Default to true.
+ * NOTE: Do NOT set to false in production code, otherwise you would face multiple types of cryptographic attacks.
+ *
+ * @param verifyingSsl True to verify TLS/SSL connection
+ * @return ApiClient
+ */
+ public ApiClient setVerifyingSsl(boolean verifyingSsl) {
+ this.verifyingSsl = verifyingSsl;
+ applySslSettings();
+ return this;
+ }
+
+ /**
+ * Get SSL CA cert.
+ *
+ * @return Input stream to the SSL CA cert
+ */
+ public InputStream getSslCaCert() {
+ return sslCaCert;
+ }
+
+ /**
+ * Configure the CA certificate to be trusted when making https requests.
+ * Use null to reset to default.
+ *
+ * @param sslCaCert input stream for SSL CA cert
+ * @return ApiClient
+ */
+ public ApiClient setSslCaCert(InputStream sslCaCert) {
+ this.sslCaCert = sslCaCert;
+ applySslSettings();
+ return this;
+ }
+
+ public KeyManager[] getKeyManagers() {
+ return keyManagers;
+ }
+
+ /**
+ * Configure client keys to use for authorization in an SSL session.
+ * Use null to reset to default.
+ *
+ * @param managers The KeyManagers to use
+ * @return ApiClient
+ */
+ public ApiClient setKeyManagers(KeyManager[] managers) {
+ this.keyManagers = managers;
+ applySslSettings();
+ return this;
+ }
+
+ public DateFormat getDateFormat() {
+ return dateFormat;
+ }
+
+ public ApiClient setDateFormat(DateFormat dateFormat) {
+ this.dateFormat = dateFormat;
+ this.dateLength = this.dateFormat.format(new Date()).length();
+ return this;
+ }
+
+ public DateFormat getDatetimeFormat() {
+ return datetimeFormat;
+ }
+
+ public ApiClient setDatetimeFormat(DateFormat datetimeFormat) {
+ this.datetimeFormat = datetimeFormat;
+ return this;
+ }
+
+ /**
+ * Whether to allow various ISO 8601 datetime formats when parsing a datetime string.
+ * @see #parseDatetime(String)
+ * @return True if lenientDatetimeFormat flag is set to true
+ */
+ public boolean isLenientDatetimeFormat() {
+ return lenientDatetimeFormat;
+ }
+
+ public ApiClient setLenientDatetimeFormat(boolean lenientDatetimeFormat) {
+ this.lenientDatetimeFormat = lenientDatetimeFormat;
+ return this;
+ }
+
+ /**
+ * Parse the given date string into Date object.
+ * The default dateFormat
supports these ISO 8601 date formats:
+ * 2015-08-16
+ * 2015-8-16
+ * @param str String to be parsed
+ * @return Date
+ */
+ public Date parseDate(String str) {
+ if (str == null)
+ return null;
+ try {
+ return dateFormat.parse(str);
+ } catch (ParseException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ /**
+ * Parse the given datetime string into Date object.
+ * When lenientDatetimeFormat is enabled, the following ISO 8601 datetime formats are supported:
+ * 2015-08-16T08:20:05Z
+ * 2015-8-16T8:20:05Z
+ * 2015-08-16T08:20:05+00:00
+ * 2015-08-16T08:20:05+0000
+ * 2015-08-16T08:20:05.376Z
+ * 2015-08-16T08:20:05.376+00:00
+ * 2015-08-16T08:20:05.376+00
+ * Note: The 3-digit milli-seconds is optional. Time zone is required and can be in one of
+ * these formats:
+ * Z (same with +0000)
+ * +08:00 (same with +0800)
+ * -02 (same with -0200)
+ * -0200
+ * @see ISO 8601
+ * @param str Date time string to be parsed
+ * @return Date representation of the string
+ */
+ public Date parseDatetime(String str) {
+ if (str == null)
+ return null;
+
+ DateFormat format;
+ if (lenientDatetimeFormat) {
+ /*
+ * When lenientDatetimeFormat is enabled, normalize the date string
+ * into LENIENT_DATETIME_FORMAT
to support various formats
+ * defined by ISO 8601.
+ */
+ // normalize time zone
+ // trailing "Z": 2015-08-16T08:20:05Z => 2015-08-16T08:20:05+0000
+ str = str.replaceAll("[zZ]\\z", "+0000");
+ // remove colon in time zone: 2015-08-16T08:20:05+00:00 => 2015-08-16T08:20:05+0000
+ str = str.replaceAll("([+-]\\d{2}):(\\d{2})\\z", "$1$2");
+ // expand time zone: 2015-08-16T08:20:05+00 => 2015-08-16T08:20:05+0000
+ str = str.replaceAll("([+-]\\d{2})\\z", "$100");
+ // add milliseconds when missing
+ // 2015-08-16T08:20:05+0000 => 2015-08-16T08:20:05.000+0000
+ str = str.replaceAll("(:\\d{1,2})([+-]\\d{4})\\z", "$1.000$2");
+ format = new SimpleDateFormat(LENIENT_DATETIME_FORMAT);
+ } else {
+ format = this.datetimeFormat;
+ }
+
+ try {
+ return format.parse(str);
+ } catch (ParseException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ /*
+ * Parse date or date time in string format into Date object.
+ *
+ * @param str Date time string to be parsed
+ * @return Date representation of the string
+ */
+ public Date parseDateOrDatetime(String str) {
+ if (str == null)
+ return null;
+ else if (str.length() <= dateLength)
+ return parseDate(str);
+ else
+ return parseDatetime(str);
+ }
+
+ /**
+ * Format the given Date object into string (Date format).
+ *
+ * @param date Date object
+ * @return Formatted date in string representation
+ */
+ public String formatDate(Date date) {
+ return dateFormat.format(date);
+ }
+
+ /**
+ * Format the given Date object into string (Datetime format).
+ *
+ * @param date Date object
+ * @return Formatted datetime in string representation
+ */
+ public String formatDatetime(Date date) {
+ return datetimeFormat.format(date);
+ }
+
+ /**
+ * Get authentications (key: authentication name, value: authentication).
+ *
+ * @return Map of authentication objects
+ */
+ public Map getAuthentications() {
+ return authentications;
+ }
+
+ /**
+ * Get authentication for the given name.
+ *
+ * @param authName The authentication name
+ * @return The authentication, null if not found
+ */
+ public Authentication getAuthentication(String authName) {
+ return authentications.get(authName);
+ }
+
+ /**
+ * Helper method to set username for the first HTTP basic authentication.
+ *
+ * @param username Username
+ */
+ public void setUsername(String username) {
+ for (Authentication auth : authentications.values()) {
+ if (auth instanceof HttpBasicAuth) {
+ ((HttpBasicAuth) auth).setUsername(username);
+ return;
+ }
+ }
+ throw new RuntimeException("No HTTP basic authentication configured!");
+ }
+
+ /**
+ * Helper method to set password for the first HTTP basic authentication.
+ *
+ * @param password Password
+ */
+ public void setPassword(String password) {
+ for (Authentication auth : authentications.values()) {
+ if (auth instanceof HttpBasicAuth) {
+ ((HttpBasicAuth) auth).setPassword(password);
+ return;
+ }
+ }
+ throw new RuntimeException("No HTTP basic authentication configured!");
+ }
+
+ /**
+ * Helper method to set API key value for the first API key authentication.
+ *
+ * @param apiKey API key
+ */
+ public void setApiKey(String apiKey) {
+ for (Authentication auth : authentications.values()) {
+ if (auth instanceof ApiKeyAuth) {
+ ((ApiKeyAuth) auth).setApiKey(apiKey);
+ return;
+ }
+ }
+ throw new RuntimeException("No API key authentication configured!");
+ }
+
+ /**
+ * Helper method to set API key prefix for the first API key authentication.
+ *
+ * @param apiKeyPrefix API key prefix
+ */
+ public void setApiKeyPrefix(String apiKeyPrefix) {
+ for (Authentication auth : authentications.values()) {
+ if (auth instanceof ApiKeyAuth) {
+ ((ApiKeyAuth) auth).setApiKeyPrefix(apiKeyPrefix);
+ return;
+ }
+ }
+ throw new RuntimeException("No API key authentication configured!");
+ }
+
+ /**
+ * Helper method to set access token for the first OAuth2 authentication.
+ *
+ * @param accessToken Access token
+ */
+ public void setAccessToken(String accessToken) {
+ for (Authentication auth : authentications.values()) {
+ if (auth instanceof OAuth) {
+ ((OAuth) auth).setAccessToken(accessToken);
+ return;
+ }
+ }
+ throw new RuntimeException("No OAuth2 authentication configured!");
+ }
+
+ /**
+ * Set the User-Agent header's value (by adding to the default header map).
+ *
+ * @param userAgent HTTP request's user agent
+ * @return ApiClient
+ */
+ public ApiClient setUserAgent(String userAgent) {
+ addDefaultHeader("User-Agent", userAgent);
+ return this;
+ }
+
+ /**
+ * Add a default header.
+ *
+ * @param key The header's key
+ * @param value The header's value
+ * @return ApiClient
+ */
+ public ApiClient addDefaultHeader(String key, String value) {
+ defaultHeaderMap.put(key, value);
+ return this;
+ }
+
+ /**
+ * @see setLenient
+ *
+ * @return True if lenientOnJson is enabled, false otherwise.
+ */
+ public boolean isLenientOnJson() {
+ return lenientOnJson;
+ }
+
+ /**
+ * Set LenientOnJson
+ *
+ * @param lenient True to enable lenientOnJson
+ * @return ApiClient
+ */
+ public ApiClient setLenientOnJson(boolean lenient) {
+ this.lenientOnJson = lenient;
+ return this;
+ }
+
+ /**
+ * Check that whether debugging is enabled for this API client.
+ *
+ * @return True if debugging is enabled, false otherwise.
+ */
+ public boolean isDebugging() {
+ return debugging;
+ }
+
+ /**
+ * Enable/disable debugging for this API client.
+ *
+ * @param debugging To enable (true) or disable (false) debugging
+ * @return ApiClient
+ */
+ public ApiClient setDebugging(boolean debugging) {
+ if (debugging != this.debugging) {
+ if (debugging) {
+ loggingInterceptor = new HttpLoggingInterceptor();
+ loggingInterceptor.setLevel(Level.BODY);
+ httpClient.interceptors().add(loggingInterceptor);
+ } else {
+ httpClient.interceptors().remove(loggingInterceptor);
+ loggingInterceptor = null;
+ }
+ }
+ this.debugging = debugging;
+ return this;
+ }
+
+ /**
+ * The path of temporary folder used to store downloaded files from endpoints
+ * with file response. The default value is null
, i.e. using
+ * the system's default tempopary folder.
+ *
+ * @see createTempFile
+ * @return Temporary folder path
+ */
+ public String getTempFolderPath() {
+ return tempFolderPath;
+ }
+
+ /**
+ * Set the tempoaray folder path (for downloading files)
+ *
+ * @param tempFolderPath Temporary folder path
+ * @return ApiClient
+ */
+ public ApiClient setTempFolderPath(String tempFolderPath) {
+ this.tempFolderPath = tempFolderPath;
+ return this;
+ }
+
+ /**
+ * Get connection timeout (in milliseconds).
+ *
+ * @return Timeout in milliseconds
+ */
+ public int getConnectTimeout() {
+ return httpClient.getConnectTimeout();
+ }
+
+ /**
+ * Sets the connect timeout (in milliseconds).
+ * A value of 0 means no timeout, otherwise values must be between 1 and
+ *
+ * @param connectionTimeout connection timeout in milliseconds
+ * @return Api client
+ */
+ public ApiClient setConnectTimeout(int connectionTimeout) {
+ httpClient.setConnectTimeout(connectionTimeout, TimeUnit.MILLISECONDS);
+ return this;
+ }
+
+ /**
+ * Format the given parameter object into string.
+ *
+ * @param param Parameter
+ * @return String representation of the parameter
+ */
+ public String parameterToString(Object param) {
+ if (param == null) {
+ return "";
+ } else if (param instanceof Date) {
+ return formatDatetime((Date) param);
+ } else if (param instanceof Collection) {
+ StringBuilder b = new StringBuilder();
+ for (Object o : (Collection)param) {
+ if (b.length() > 0) {
+ b.append(",");
+ }
+ b.append(String.valueOf(o));
+ }
+ return b.toString();
+ } else {
+ return String.valueOf(param);
+ }
+ }
+
+ /**
+ * Format to {@code Pair} objects.
+ *
+ * @param collectionFormat collection format (e.g. csv, tsv)
+ * @param name Name
+ * @param value Value
+ * @return A list of Pair objects
+ */
+ public List parameterToPairs(String collectionFormat, String name, Object value){
+ List params = new ArrayList();
+
+ // preconditions
+ if (name == null || name.isEmpty() || value == null) return params;
+
+ Collection valueCollection = null;
+ if (value instanceof Collection) {
+ valueCollection = (Collection) value;
+ } else {
+ params.add(new Pair(name, parameterToString(value)));
+ return params;
+ }
+
+ if (valueCollection.isEmpty()){
+ return params;
+ }
+
+ // get the collection format
+ collectionFormat = (collectionFormat == null || collectionFormat.isEmpty() ? "csv" : collectionFormat); // default: csv
+
+ // create the params based on the collection format
+ if (collectionFormat.equals("multi")) {
+ for (Object item : valueCollection) {
+ params.add(new Pair(name, parameterToString(item)));
+ }
+
+ return params;
+ }
+
+ String delimiter = ",";
+
+ if (collectionFormat.equals("csv")) {
+ delimiter = ",";
+ } else if (collectionFormat.equals("ssv")) {
+ delimiter = " ";
+ } else if (collectionFormat.equals("tsv")) {
+ delimiter = "\t";
+ } else if (collectionFormat.equals("pipes")) {
+ delimiter = "|";
+ }
+
+ StringBuilder sb = new StringBuilder() ;
+ for (Object item : valueCollection) {
+ sb.append(delimiter);
+ sb.append(parameterToString(item));
+ }
+
+ params.add(new Pair(name, sb.substring(1)));
+
+ return params;
+ }
+
+ /**
+ * Sanitize filename by removing path.
+ * e.g. ../../sun.gif becomes sun.gif
+ *
+ * @param filename The filename to be sanitized
+ * @return The sanitized filename
+ */
+ public String sanitizeFilename(String filename) {
+ return filename.replaceAll(".*[/\\\\]", "");
+ }
+
+ /**
+ * Check if the given MIME is a JSON MIME.
+ * JSON MIME examples:
+ * application/json
+ * application/json; charset=UTF8
+ * APPLICATION/JSON
+ * application/vnd.company+json
+ * @param mime MIME (Multipurpose Internet Mail Extensions)
+ * @return True if the given MIME is JSON, false otherwise.
+ */
+ public boolean isJsonMime(String mime) {
+ String jsonMime = "(?i)^(application/json|[^;/ \t]+/[^;/ \t]+[+]json)[ \t]*(;.*)?$";
+ return mime != null && (mime.matches(jsonMime) || mime.equalsIgnoreCase("application/json-patch+json"));
+ }
+
+ /**
+ * Select the Accept header's value from the given accepts array:
+ * if JSON exists in the given array, use it;
+ * otherwise use all of them (joining into a string)
+ *
+ * @param accepts The accepts array to select from
+ * @return The Accept header to use. If the given array is empty,
+ * null will be returned (not to set the Accept header explicitly).
+ */
+ public String selectHeaderAccept(String[] accepts) {
+ if (accepts.length == 0) {
+ return null;
+ }
+ for (String accept : accepts) {
+ if (isJsonMime(accept)) {
+ return accept;
+ }
+ }
+ return StringUtil.join(accepts, ",");
+ }
+
+ /**
+ * Select the Content-Type header's value from the given array:
+ * if JSON exists in the given array, use it;
+ * otherwise use the first one of the array.
+ *
+ * @param contentTypes The Content-Type array to select from
+ * @return The Content-Type header to use. If the given array is empty,
+ * JSON will be used.
+ */
+ public String selectHeaderContentType(String[] contentTypes) {
+ if (contentTypes.length == 0) {
+ return "application/json";
+ }
+ for (String contentType : contentTypes) {
+ if (isJsonMime(contentType)) {
+ return contentType;
+ }
+ }
+ return contentTypes[0];
+ }
+
+ /**
+ * Escape the given string to be used as URL query value.
+ *
+ * @param str String to be escaped
+ * @return Escaped string
+ */
+ public String escapeString(String str) {
+ try {
+ return URLEncoder.encode(str, "utf8").replaceAll("\\+", "%20");
+ } catch (UnsupportedEncodingException e) {
+ return str;
+ }
+ }
+
+ /**
+ * Deserialize response body to Java object, according to the return type and
+ * the Content-Type response header.
+ *
+ * @param Type
+ * @param response HTTP response
+ * @param returnType The type of the Java object
+ * @return The deserialized Java object
+ * @throws ApiException If fail to deserialize response body, i.e. cannot read response body
+ * or the Content-Type of the response is not supported.
+ */
+ @SuppressWarnings("unchecked")
+ public T deserialize(Response response, Type returnType) throws ApiException {
+ if (response == null || returnType == null) {
+ return null;
+ }
+
+ if ("byte[]".equals(returnType.toString())) {
+ // Handle binary response (byte array).
+ try {
+ return (T) response.body().bytes();
+ } catch (IOException e) {
+ throw new ApiException(e);
+ }
+ } else if (returnType.equals(File.class)) {
+ // Handle file downloading.
+ return (T) downloadFileFromResponse(response);
+ }
+
+ String respBody;
+ try {
+ if (response.body() != null)
+ respBody = response.body().string();
+ else
+ respBody = null;
+ } catch (IOException e) {
+ throw new ApiException(e);
+ }
+
+ if (respBody == null || "".equals(respBody)) {
+ return null;
+ }
+
+ String contentType = response.headers().get("Content-Type");
+ if (contentType == null) {
+ // ensuring a default content type
+ contentType = "application/json";
+ }
+ if (isJsonMime(contentType)) {
+ return json.deserialize(respBody, returnType);
+ } else if (returnType.equals(String.class)) {
+ // Expecting string, return the raw response body.
+ return (T) respBody;
+ } else {
+ throw new ApiException(
+ "Content type \"" + contentType + "\" is not supported for type: " + returnType,
+ response.code(),
+ response.headers().toMultimap(),
+ respBody);
+ }
+ }
+
+ /**
+ * Serialize the given Java object into request body according to the object's
+ * class and the request Content-Type.
+ *
+ * @param obj The Java object
+ * @param contentType The request Content-Type
+ * @return The serialized request body
+ * @throws ApiException If fail to serialize the given object
+ */
+ public RequestBody serialize(Object obj, String contentType) throws ApiException {
+ if (obj instanceof byte[]) {
+ // Binary (byte array) body parameter support.
+ return RequestBody.create(MediaType.parse(contentType), (byte[]) obj);
+ } else if (obj instanceof File) {
+ // File body parameter support.
+ return RequestBody.create(MediaType.parse(contentType), (File) obj);
+ } else if (isJsonMime(contentType)) {
+ String content;
+ if (obj != null) {
+ content = json.serialize(obj);
+ } else {
+ content = null;
+ }
+ return RequestBody.create(MediaType.parse(contentType), content);
+ } else {
+ throw new ApiException("Content type \"" + contentType + "\" is not supported");
+ }
+ }
+
+ /**
+ * Download file from the given response.
+ *
+ * @param response An instance of the Response object
+ * @throws ApiException If fail to read file content from response and write to disk
+ * @return Downloaded file
+ */
+ public File downloadFileFromResponse(Response response) throws ApiException {
+ try {
+ File file = prepareDownloadFile(response);
+ BufferedSink sink = Okio.buffer(Okio.sink(file));
+ sink.writeAll(response.body().source());
+ sink.close();
+ return file;
+ } catch (IOException e) {
+ throw new ApiException(e);
+ }
+ }
+
+ /**
+ * Prepare file for download
+ *
+ * @param response An instance of the Response object
+ * @throws IOException If fail to prepare file for download
+ * @return Prepared file for the download
+ */
+ public File prepareDownloadFile(Response response) throws IOException {
+ String filename = null;
+ String contentDisposition = response.header("Content-Disposition");
+ if (contentDisposition != null && !"".equals(contentDisposition)) {
+ // Get filename from the Content-Disposition header.
+ Pattern pattern = Pattern.compile("filename=['\"]?([^'\"\\s]+)['\"]?");
+ Matcher matcher = pattern.matcher(contentDisposition);
+ if (matcher.find()) {
+ filename = sanitizeFilename(matcher.group(1));
+ }
+ }
+
+ String prefix = null;
+ String suffix = null;
+ if (filename == null) {
+ prefix = "download-";
+ suffix = "";
+ } else {
+ int pos = filename.lastIndexOf(".");
+ if (pos == -1) {
+ prefix = filename + "-";
+ } else {
+ prefix = filename.substring(0, pos) + "-";
+ suffix = filename.substring(pos);
+ }
+ // File.createTempFile requires the prefix to be at least three characters long
+ if (prefix.length() < 3)
+ prefix = "download-";
+ }
+
+ if (tempFolderPath == null)
+ return File.createTempFile(prefix, suffix);
+ else
+ return File.createTempFile(prefix, suffix, new File(tempFolderPath));
+ }
+
+ /**
+ * {@link #execute(Call, Type)}
+ *
+ * @param Type
+ * @param call An instance of the Call object
+ * @throws ApiException If fail to execute the call
+ * @return ApiResponse<T>
+ */
+ public ApiResponse execute(Call call) throws ApiException {
+ return execute(call, null);
+ }
+
+ /**
+ * Execute HTTP call and deserialize the HTTP response body into the given return type.
+ *
+ * @param returnType The return type used to deserialize HTTP response body
+ * @param The return type corresponding to (same with) returnType
+ * @param call Call
+ * @return ApiResponse object containing response status, headers and
+ * data, which is a Java object deserialized from response body and would be null
+ * when returnType is null.
+ * @throws ApiException If fail to execute the call
+ */
+ public ApiResponse execute(Call call, Type returnType) throws ApiException {
+ try {
+ Response response = call.execute();
+ T data = handleResponse(response, returnType);
+ return new ApiResponse(response.code(), response.headers().toMultimap(), data);
+ } catch (IOException e) {
+ throw new ApiException(e);
+ }
+ }
+
+ /**
+ * {@link #executeAsync(Call, Type, ApiCallback)}
+ *
+ * @param Type
+ * @param call An instance of the Call object
+ * @param callback ApiCallback<T>
+ */
+ public void executeAsync(Call call, ApiCallback callback) {
+ executeAsync(call, null, callback);
+ }
+
+ /**
+ * Execute HTTP call asynchronously.
+ *
+ * @see #execute(Call, Type)
+ * @param Type
+ * @param call The callback to be executed when the API call finishes
+ * @param returnType Return type
+ * @param callback ApiCallback
+ */
+ @SuppressWarnings("unchecked")
+ public void executeAsync(Call call, final Type returnType, final ApiCallback callback) {
+ call.enqueue(new Callback() {
+ @Override
+ public void onFailure(Request request, IOException e) {
+ callback.onFailure(new ApiException(e), 0, null);
+ }
+
+ @Override
+ public void onResponse(Response response) throws IOException {
+ T result;
+ try {
+ result = (T) handleResponse(response, returnType);
+ } catch (ApiException e) {
+ callback.onFailure(e, response.code(), response.headers().toMultimap());
+ return;
+ }
+ callback.onSuccess(result, response.code(), response.headers().toMultimap());
+ }
+ });
+ }
+
+ /**
+ * Handle the given response, return the deserialized object when the response is successful.
+ *
+ * @param Type
+ * @param response Response
+ * @param returnType Return type
+ * @throws ApiException If the response has a unsuccessful status code or
+ * fail to deserialize the response body
+ * @return Type
+ */
+ public T handleResponse(Response response, Type returnType) throws ApiException {
+ if (response.isSuccessful()) {
+ if (returnType == null || response.code() == 204) {
+ // returning null if the returnType is not defined,
+ // or the status code is 204 (No Content)
+ if (response.body() != null) {
+ try {
+ response.body().close();
+ } catch (IOException e) {
+ throw new ApiException(response.message(), e, response.code(), response.headers().toMultimap());
+ }
+ }
+ return null;
+ } else {
+ return deserialize(response, returnType);
+ }
+ } else {
+ String respBody = null;
+ if (response.body() != null) {
+ try {
+ respBody = response.body().string();
+ } catch (IOException e) {
+ throw new ApiException(response.message(), e, response.code(), response.headers().toMultimap());
+ }
+ }
+ throw new ApiException(response.message(), response.code(), response.headers().toMultimap(), respBody);
+ }
+ }
+
+ /**
+ * Build HTTP call with the given options.
+ *
+ * @param path The sub-path of the HTTP URL
+ * @param method The request method, one of "GET", "HEAD", "OPTIONS", "POST", "PUT", "PATCH" and "DELETE"
+ * @param queryParams The query parameters
+ * @param body The request body object
+ * @param headerParams The header parameters
+ * @param formParams The form parameters
+ * @param authNames The authentications to apply
+ * @param progressRequestListener Progress request listener
+ * @return The HTTP call
+ * @throws ApiException If fail to serialize the request body object
+ */
+ public Call buildCall(String path, String method, List queryParams, Object body, Map headerParams, Map formParams, String[] authNames, ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
+ Request request = buildRequest(path, method, queryParams, body, headerParams, formParams, authNames, progressRequestListener);
+
+ return httpClient.newCall(request);
+ }
+
+ /**
+ * Build an HTTP request with the given options.
+ *
+ * @param path The sub-path of the HTTP URL
+ * @param method The request method, one of "GET", "HEAD", "OPTIONS", "POST", "PUT", "PATCH" and "DELETE"
+ * @param queryParams The query parameters
+ * @param body The request body object
+ * @param headerParams The header parameters
+ * @param formParams The form parameters
+ * @param authNames The authentications to apply
+ * @param progressRequestListener Progress request listener
+ * @return The HTTP request
+ * @throws ApiException If fail to serialize the request body object
+ */
+ public Request buildRequest(String path, String method, List queryParams, Object body, Map headerParams, Map formParams, String[] authNames, ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
+ updateParamsForAuth(authNames, queryParams, headerParams);
+
+ final String url = buildUrl(path, queryParams);
+ final Request.Builder reqBuilder = new Request.Builder().url(url);
+ processHeaderParams(headerParams, reqBuilder);
+
+ String contentType = (String) headerParams.get("Content-Type");
+ // ensuring a default content type
+ if (contentType == null) {
+ contentType = "application/json";
+ }
+
+ RequestBody reqBody;
+ if (!HttpMethod.permitsRequestBody(method)) {
+ reqBody = null;
+ } else if ("application/x-www-form-urlencoded".equals(contentType)) {
+ reqBody = buildRequestBodyFormEncoding(formParams);
+ } else if ("multipart/form-data".equals(contentType)) {
+ reqBody = buildRequestBodyMultipart(formParams);
+ } else if (body == null) {
+ if ("DELETE".equals(method)) {
+ // allow calling DELETE without sending a request body
+ reqBody = null;
+ } else {
+ // use an empty request body (for POST, PUT and PATCH)
+ reqBody = RequestBody.create(MediaType.parse(contentType), "");
+ }
+ } else {
+ reqBody = serialize(body, contentType);
+ }
+
+ Request request = null;
+
+ if(progressRequestListener != null && reqBody != null) {
+ ProgressRequestBody progressRequestBody = new ProgressRequestBody(reqBody, progressRequestListener);
+ request = reqBuilder.method(method, progressRequestBody).build();
+ } else {
+ request = reqBuilder.method(method, reqBody).build();
+ }
+
+ return request;
+ }
+
+ /**
+ * Build full URL by concatenating base path, the given sub path and query parameters.
+ *
+ * @param path The sub path
+ * @param queryParams The query parameters
+ * @return The full URL
+ */
+ public String buildUrl(String path, List queryParams) {
+ final StringBuilder url = new StringBuilder();
+ url.append(basePath).append(path);
+
+ if (queryParams != null && !queryParams.isEmpty()) {
+ // support (constant) query string in `path`, e.g. "/posts?draft=1"
+ String prefix = path.contains("?") ? "&" : "?";
+ for (Pair param : queryParams) {
+ if (param.getValue() != null) {
+ if (prefix != null) {
+ url.append(prefix);
+ prefix = null;
+ } else {
+ url.append("&");
+ }
+ String value = parameterToString(param.getValue());
+ url.append(escapeString(param.getName())).append("=").append(escapeString(value));
+ }
+ }
+ }
+
+ return url.toString();
+ }
+
+ /**
+ * Set header parameters to the request builder, including default headers.
+ *
+ * @param headerParams Header parameters in the ofrm of Map
+ * @param reqBuilder Reqeust.Builder
+ */
+ public void processHeaderParams(Map headerParams, Request.Builder reqBuilder) {
+ for (Entry param : headerParams.entrySet()) {
+ reqBuilder.header(param.getKey(), parameterToString(param.getValue()));
+ }
+ for (Entry header : defaultHeaderMap.entrySet()) {
+ if (!headerParams.containsKey(header.getKey())) {
+ reqBuilder.header(header.getKey(), parameterToString(header.getValue()));
+ }
+ }
+ }
+
+ /**
+ * Update query and header parameters based on authentication settings.
+ *
+ * @param authNames The authentications to apply
+ * @param queryParams List of query parameters
+ * @param headerParams Map of header parameters
+ */
+ public void updateParamsForAuth(String[] authNames, List queryParams, Map headerParams) {
+ for (String authName : authNames) {
+ Authentication auth = authentications.get(authName);
+ if (auth == null) throw new RuntimeException("Authentication undefined: " + authName);
+ auth.applyToParams(queryParams, headerParams);
+ }
+ }
+
+ /**
+ * Build a form-encoding request body with the given form parameters.
+ *
+ * @param formParams Form parameters in the form of Map
+ * @return RequestBody
+ */
+ public RequestBody buildRequestBodyFormEncoding(Map formParams) {
+ FormEncodingBuilder formBuilder = new FormEncodingBuilder();
+ for (Entry param : formParams.entrySet()) {
+ formBuilder.add(param.getKey(), parameterToString(param.getValue()));
+ }
+ return formBuilder.build();
+ }
+
+ /**
+ * Build a multipart (file uploading) request body with the given form parameters,
+ * which could contain text fields and file fields.
+ *
+ * @param formParams Form parameters in the form of Map
+ * @return RequestBody
+ */
+ public RequestBody buildRequestBodyMultipart(Map formParams) {
+ MultipartBuilder mpBuilder = new MultipartBuilder().type(MultipartBuilder.FORM);
+ for (Entry param : formParams.entrySet()) {
+ if (param.getValue() instanceof File) {
+ File file = (File) param.getValue();
+ Headers partHeaders = Headers.of("Content-Disposition", "form-data; name=\"" + param.getKey() + "\"; filename=\"" + file.getName() + "\"");
+ MediaType mediaType = MediaType.parse(guessContentTypeFromFile(file));
+ mpBuilder.addPart(partHeaders, RequestBody.create(mediaType, file));
+ } else {
+ Headers partHeaders = Headers.of("Content-Disposition", "form-data; name=\"" + param.getKey() + "\"");
+ mpBuilder.addPart(partHeaders, RequestBody.create(null, parameterToString(param.getValue())));
+ }
+ }
+ return mpBuilder.build();
+ }
+
+ /**
+ * Guess Content-Type header from the given file (defaults to "application/octet-stream").
+ *
+ * @param file The given file
+ * @return The guessed Content-Type
+ */
+ public String guessContentTypeFromFile(File file) {
+ String contentType = URLConnection.guessContentTypeFromName(file.getName());
+ if (contentType == null) {
+ return "application/octet-stream";
+ } else {
+ return contentType;
+ }
+ }
+
+ /**
+ * Initialize datetime format according to the current environment, e.g. Java 1.7 and Android.
+ */
+ private void initDatetimeFormat() {
+ String formatWithTimeZone = null;
+ if (IS_ANDROID) {
+ if (ANDROID_SDK_VERSION >= 18) {
+ // The time zone format "ZZZZZ" is available since Android 4.3 (SDK version 18)
+ formatWithTimeZone = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ";
+ }
+ } else if (JAVA_VERSION >= 1.7) {
+ // The time zone format "XXX" is available since Java 1.7
+ formatWithTimeZone = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX";
+ }
+ if (formatWithTimeZone != null) {
+ this.datetimeFormat = new SimpleDateFormat(formatWithTimeZone);
+ // NOTE: Use the system's default time zone (mainly for datetime formatting).
+ } else {
+ // Use a common format that works across all systems.
+ this.datetimeFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
+ // Always use the UTC time zone as we are using a constant trailing "Z" here.
+ this.datetimeFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
+ }
+ }
+
+ /**
+ * Apply SSL related settings to httpClient according to the current values of
+ * verifyingSsl and sslCaCert.
+ */
+ private void applySslSettings() {
+ try {
+ TrustManager[] trustManagers = null;
+ HostnameVerifier hostnameVerifier = null;
+ if (!verifyingSsl) {
+ TrustManager trustAll = new X509TrustManager() {
+ @Override
+ public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
+ @Override
+ public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
+ @Override
+ public X509Certificate[] getAcceptedIssuers() { return null; }
+ };
+ SSLContext sslContext = SSLContext.getInstance("TLS");
+ trustManagers = new TrustManager[]{ trustAll };
+ hostnameVerifier = new HostnameVerifier() {
+ @Override
+ public boolean verify(String hostname, SSLSession session) { return true; }
+ };
+ } else if (sslCaCert != null) {
+ char[] password = null; // Any password will work.
+ CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
+ Collection extends Certificate> certificates = certificateFactory.generateCertificates(sslCaCert);
+ if (certificates.isEmpty()) {
+ throw new IllegalArgumentException("expected non-empty set of trusted certificates");
+ }
+ KeyStore caKeyStore = newEmptyKeyStore(password);
+ int index = 0;
+ for (Certificate certificate : certificates) {
+ String certificateAlias = "ca" + Integer.toString(index++);
+ caKeyStore.setCertificateEntry(certificateAlias, certificate);
+ }
+ TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
+ trustManagerFactory.init(caKeyStore);
+ trustManagers = trustManagerFactory.getTrustManagers();
+ }
+
+ if (keyManagers != null || trustManagers != null) {
+ SSLContext sslContext = SSLContext.getInstance("TLS");
+ sslContext.init(keyManagers, trustManagers, new SecureRandom());
+ httpClient.setSslSocketFactory(sslContext.getSocketFactory());
+ } else {
+ httpClient.setSslSocketFactory(null);
+ }
+ httpClient.setHostnameVerifier(hostnameVerifier);
+ } catch (GeneralSecurityException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ private KeyStore newEmptyKeyStore(char[] password) throws GeneralSecurityException {
+ try {
+ KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
+ keyStore.load(null, password);
+ return keyStore;
+ } catch (IOException e) {
+ throw new AssertionError(e);
+ }
+ }
+}
diff --git a/client/java/src/main/java/io/swagger/client/ApiException.java b/client/java/src/main/java/io/swagger/client/ApiException.java
new file mode 100644
index 0000000..c0b943f
--- /dev/null
+++ b/client/java/src/main/java/io/swagger/client/ApiException.java
@@ -0,0 +1,91 @@
+/*
+ * Swagger Demo
+ * Swagger的简单示例, 包括swagger-codegen, swagger2markup 和 asciidoctor.
+ *
+ * OpenAPI spec version: v1
+ * Contact: damon.q@iv66.net
+ *
+ * NOTE: This class is auto generated by the swagger code generator program.
+ * https://github.com/swagger-api/swagger-codegen.git
+ * Do not edit the class manually.
+ */
+
+
+package io.swagger.client;
+
+import java.util.Map;
+import java.util.List;
+
+@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2017-11-09T10:58:38.431+08:00")
+public class ApiException extends Exception {
+ private int code = 0;
+ private Map> responseHeaders = null;
+ private String responseBody = null;
+
+ public ApiException() {}
+
+ public ApiException(Throwable throwable) {
+ super(throwable);
+ }
+
+ public ApiException(String message) {
+ super(message);
+ }
+
+ public ApiException(String message, Throwable throwable, int code, Map> responseHeaders, String responseBody) {
+ super(message, throwable);
+ this.code = code;
+ this.responseHeaders = responseHeaders;
+ this.responseBody = responseBody;
+ }
+
+ public ApiException(String message, int code, Map> responseHeaders, String responseBody) {
+ this(message, (Throwable) null, code, responseHeaders, responseBody);
+ }
+
+ public ApiException(String message, Throwable throwable, int code, Map> responseHeaders) {
+ this(message, throwable, code, responseHeaders, null);
+ }
+
+ public ApiException(int code, Map> responseHeaders, String responseBody) {
+ this((String) null, (Throwable) null, code, responseHeaders, responseBody);
+ }
+
+ public ApiException(int code, String message) {
+ super(message);
+ this.code = code;
+ }
+
+ public ApiException(int code, String message, Map> responseHeaders, String responseBody) {
+ this(code, message);
+ this.responseHeaders = responseHeaders;
+ this.responseBody = responseBody;
+ }
+
+ /**
+ * Get the HTTP status code.
+ *
+ * @return HTTP status code
+ */
+ public int getCode() {
+ return code;
+ }
+
+ /**
+ * Get the HTTP response headers.
+ *
+ * @return A map of list of string
+ */
+ public Map> getResponseHeaders() {
+ return responseHeaders;
+ }
+
+ /**
+ * Get the HTTP response body.
+ *
+ * @return Response body in the form of string
+ */
+ public String getResponseBody() {
+ return responseBody;
+ }
+}
diff --git a/client/java/src/main/java/io/swagger/client/ApiResponse.java b/client/java/src/main/java/io/swagger/client/ApiResponse.java
new file mode 100644
index 0000000..be3888b
--- /dev/null
+++ b/client/java/src/main/java/io/swagger/client/ApiResponse.java
@@ -0,0 +1,59 @@
+/*
+ * Swagger Demo
+ * Swagger的简单示例, 包括swagger-codegen, swagger2markup 和 asciidoctor.
+ *
+ * OpenAPI spec version: v1
+ * Contact: damon.q@iv66.net
+ *
+ * NOTE: This class is auto generated by the swagger code generator program.
+ * https://github.com/swagger-api/swagger-codegen.git
+ * Do not edit the class manually.
+ */
+
+
+package io.swagger.client;
+
+import java.util.List;
+import java.util.Map;
+
+/**
+ * API response returned by API call.
+ *
+ * @param The type of data that is deserialized from response body
+ */
+public class ApiResponse {
+ final private int statusCode;
+ final private Map> headers;
+ final private T data;
+
+ /**
+ * @param statusCode The status code of HTTP response
+ * @param headers The headers of HTTP response
+ */
+ public ApiResponse(int statusCode, Map> headers) {
+ this(statusCode, headers, null);
+ }
+
+ /**
+ * @param statusCode The status code of HTTP response
+ * @param headers The headers of HTTP response
+ * @param data The object deserialized from response bod
+ */
+ public ApiResponse(int statusCode, Map> headers, T data) {
+ this.statusCode = statusCode;
+ this.headers = headers;
+ this.data = data;
+ }
+
+ public int getStatusCode() {
+ return statusCode;
+ }
+
+ public Map> getHeaders() {
+ return headers;
+ }
+
+ public T getData() {
+ return data;
+ }
+}
diff --git a/client/java/src/main/java/io/swagger/client/Configuration.java b/client/java/src/main/java/io/swagger/client/Configuration.java
new file mode 100644
index 0000000..39389d8
--- /dev/null
+++ b/client/java/src/main/java/io/swagger/client/Configuration.java
@@ -0,0 +1,39 @@
+/*
+ * Swagger Demo
+ * Swagger的简单示例, 包括swagger-codegen, swagger2markup 和 asciidoctor.
+ *
+ * OpenAPI spec version: v1
+ * Contact: damon.q@iv66.net
+ *
+ * NOTE: This class is auto generated by the swagger code generator program.
+ * https://github.com/swagger-api/swagger-codegen.git
+ * Do not edit the class manually.
+ */
+
+
+package io.swagger.client;
+
+@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2017-11-09T10:58:38.431+08:00")
+public class Configuration {
+ private static ApiClient defaultApiClient = new ApiClient();
+
+ /**
+ * Get the default API client, which would be used when creating API
+ * instances without providing an API client.
+ *
+ * @return Default API client
+ */
+ public static ApiClient getDefaultApiClient() {
+ return defaultApiClient;
+ }
+
+ /**
+ * Set the default API client, which would be used when creating API
+ * instances without providing an API client.
+ *
+ * @param apiClient API client
+ */
+ public static void setDefaultApiClient(ApiClient apiClient) {
+ defaultApiClient = apiClient;
+ }
+}
diff --git a/client/java/src/main/java/io/swagger/client/GzipRequestInterceptor.java b/client/java/src/main/java/io/swagger/client/GzipRequestInterceptor.java
new file mode 100644
index 0000000..de1916f
--- /dev/null
+++ b/client/java/src/main/java/io/swagger/client/GzipRequestInterceptor.java
@@ -0,0 +1,81 @@
+/*
+ * Swagger Demo
+ * Swagger的简单示例, 包括swagger-codegen, swagger2markup 和 asciidoctor.
+ *
+ * OpenAPI spec version: v1
+ * Contact: damon.q@iv66.net
+ *
+ * NOTE: This class is auto generated by the swagger code generator program.
+ * https://github.com/swagger-api/swagger-codegen.git
+ * Do not edit the class manually.
+ */
+
+
+package io.swagger.client;
+
+import com.squareup.okhttp.*;
+import okio.Buffer;
+import okio.BufferedSink;
+import okio.GzipSink;
+import okio.Okio;
+
+import java.io.IOException;
+
+/**
+ * Encodes request bodies using gzip.
+ *
+ * Taken from https://github.com/square/okhttp/issues/350
+ */
+class GzipRequestInterceptor implements Interceptor {
+ @Override public Response intercept(Chain chain) throws IOException {
+ Request originalRequest = chain.request();
+ if (originalRequest.body() == null || originalRequest.header("Content-Encoding") != null) {
+ return chain.proceed(originalRequest);
+ }
+
+ Request compressedRequest = originalRequest.newBuilder()
+ .header("Content-Encoding", "gzip")
+ .method(originalRequest.method(), forceContentLength(gzip(originalRequest.body())))
+ .build();
+ return chain.proceed(compressedRequest);
+ }
+
+ private RequestBody forceContentLength(final RequestBody requestBody) throws IOException {
+ final Buffer buffer = new Buffer();
+ requestBody.writeTo(buffer);
+ return new RequestBody() {
+ @Override
+ public MediaType contentType() {
+ return requestBody.contentType();
+ }
+
+ @Override
+ public long contentLength() {
+ return buffer.size();
+ }
+
+ @Override
+ public void writeTo(BufferedSink sink) throws IOException {
+ sink.write(buffer.snapshot());
+ }
+ };
+ }
+
+ private RequestBody gzip(final RequestBody body) {
+ return new RequestBody() {
+ @Override public MediaType contentType() {
+ return body.contentType();
+ }
+
+ @Override public long contentLength() {
+ return -1; // We don't know the compressed length in advance!
+ }
+
+ @Override public void writeTo(BufferedSink sink) throws IOException {
+ BufferedSink gzipSink = Okio.buffer(new GzipSink(sink));
+ body.writeTo(gzipSink);
+ gzipSink.close();
+ }
+ };
+ }
+}
\ No newline at end of file
diff --git a/client/java/src/main/java/io/swagger/client/JSON.java b/client/java/src/main/java/io/swagger/client/JSON.java
new file mode 100644
index 0000000..89ea654
--- /dev/null
+++ b/client/java/src/main/java/io/swagger/client/JSON.java
@@ -0,0 +1,227 @@
+/*
+ * Swagger Demo
+ * Swagger的简单示例, 包括swagger-codegen, swagger2markup 和 asciidoctor.
+ *
+ * OpenAPI spec version: v1
+ * Contact: damon.q@iv66.net
+ *
+ * NOTE: This class is auto generated by the swagger code generator program.
+ * https://github.com/swagger-api/swagger-codegen.git
+ * Do not edit the class manually.
+ */
+
+
+package io.swagger.client;
+
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import com.google.gson.JsonDeserializationContext;
+import com.google.gson.JsonDeserializer;
+import com.google.gson.JsonElement;
+import com.google.gson.JsonNull;
+import com.google.gson.JsonParseException;
+import com.google.gson.JsonPrimitive;
+import com.google.gson.JsonSerializationContext;
+import com.google.gson.JsonSerializer;
+import com.google.gson.TypeAdapter;
+import com.google.gson.stream.JsonReader;
+import com.google.gson.stream.JsonWriter;
+
+import java.io.IOException;
+import java.io.StringReader;
+import java.lang.reflect.Type;
+import java.util.Date;
+
+import java.time.LocalDate;
+import java.time.OffsetDateTime;
+import java.time.format.DateTimeFormatter;
+
+public class JSON {
+ private ApiClient apiClient;
+ private Gson gson;
+
+ /**
+ * JSON constructor.
+ *
+ * @param apiClient An instance of ApiClient
+ */
+ public JSON(ApiClient apiClient) {
+ this.apiClient = apiClient;
+ gson = new GsonBuilder()
+ .registerTypeAdapter(Date.class, new DateAdapter(apiClient))
+ .registerTypeAdapter(OffsetDateTime.class, new OffsetDateTimeTypeAdapter())
+ .registerTypeAdapter(LocalDate.class, new LocalDateTypeAdapter())
+ .create();
+ }
+
+ /**
+ * Get Gson.
+ *
+ * @return Gson
+ */
+ public Gson getGson() {
+ return gson;
+ }
+
+ /**
+ * Set Gson.
+ *
+ * @param gson Gson
+ */
+ public void setGson(Gson gson) {
+ this.gson = gson;
+ }
+
+ /**
+ * Serialize the given Java object into JSON string.
+ *
+ * @param obj Object
+ * @return String representation of the JSON
+ */
+ public String serialize(Object obj) {
+ return gson.toJson(obj);
+ }
+
+ /**
+ * Deserialize the given JSON string to Java object.
+ *
+ * @param Type
+ * @param body The JSON string
+ * @param returnType The type to deserialize into
+ * @return The deserialized Java object
+ */
+ @SuppressWarnings("unchecked")
+ public T deserialize(String body, Type returnType) {
+ try {
+ if (apiClient.isLenientOnJson()) {
+ JsonReader jsonReader = new JsonReader(new StringReader(body));
+ // see https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/stream/JsonReader.html#setLenient(boolean)
+ jsonReader.setLenient(true);
+ return gson.fromJson(jsonReader, returnType);
+ } else {
+ return gson.fromJson(body, returnType);
+ }
+ } catch (JsonParseException e) {
+ // Fallback processing when failed to parse JSON form response body:
+ // return the response body string directly for the String return type;
+ // parse response body into date or datetime for the Date return type.
+ if (returnType.equals(String.class))
+ return (T) body;
+ else if (returnType.equals(Date.class))
+ return (T) apiClient.parseDateOrDatetime(body);
+ else throw(e);
+ }
+ }
+}
+
+class DateAdapter implements JsonSerializer, JsonDeserializer {
+ private final ApiClient apiClient;
+
+ /**
+ * Constructor for DateAdapter
+ *
+ * @param apiClient Api client
+ */
+ public DateAdapter(ApiClient apiClient) {
+ super();
+ this.apiClient = apiClient;
+ }
+
+ /**
+ * Serialize
+ *
+ * @param src Date
+ * @param typeOfSrc Type
+ * @param context Json Serialization Context
+ * @return Json Element
+ */
+ @Override
+ public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) {
+ if (src == null) {
+ return JsonNull.INSTANCE;
+ } else {
+ return new JsonPrimitive(apiClient.formatDatetime(src));
+ }
+ }
+
+ /**
+ * Deserialize
+ *
+ * @param json Json element
+ * @param date Type
+ * @param context Json Serialization Context
+ * @return Date
+ * @throws JsonParseException if fail to parse
+ */
+ @Override
+ public Date deserialize(JsonElement json, Type date, JsonDeserializationContext context) throws JsonParseException {
+ String str = json.getAsJsonPrimitive().getAsString();
+ try {
+ return apiClient.parseDateOrDatetime(str);
+ } catch (RuntimeException e) {
+ throw new JsonParseException(e);
+ }
+ }
+}
+
+/**
+ * Gson TypeAdapter for jsr310 OffsetDateTime type
+ */
+class OffsetDateTimeTypeAdapter extends TypeAdapter {
+
+ private final DateTimeFormatter formatter = DateTimeFormatter.ISO_OFFSET_DATE_TIME;
+
+ @Override
+ public void write(JsonWriter out, OffsetDateTime date) throws IOException {
+ if (date == null) {
+ out.nullValue();
+ } else {
+ out.value(formatter.format(date));
+ }
+ }
+
+ @Override
+ public OffsetDateTime read(JsonReader in) throws IOException {
+ switch (in.peek()) {
+ case NULL:
+ in.nextNull();
+ return null;
+ default:
+ String date = in.nextString();
+ if (date.endsWith("+0000")) {
+ date = date.substring(0, date.length()-5) + "Z";
+ }
+
+ return OffsetDateTime.parse(date, formatter);
+ }
+ }
+}
+
+/**
+ * Gson TypeAdapter for jsr310 LocalDate type
+ */
+class LocalDateTypeAdapter extends TypeAdapter {
+
+ private final DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE;
+
+ @Override
+ public void write(JsonWriter out, LocalDate date) throws IOException {
+ if (date == null) {
+ out.nullValue();
+ } else {
+ out.value(formatter.format(date));
+ }
+ }
+
+ @Override
+ public LocalDate read(JsonReader in) throws IOException {
+ switch (in.peek()) {
+ case NULL:
+ in.nextNull();
+ return null;
+ default:
+ String date = in.nextString();
+ return LocalDate.parse(date, formatter);
+ }
+ }
+}
diff --git a/client/java/src/main/java/io/swagger/client/Pair.java b/client/java/src/main/java/io/swagger/client/Pair.java
new file mode 100644
index 0000000..8e02cc1
--- /dev/null
+++ b/client/java/src/main/java/io/swagger/client/Pair.java
@@ -0,0 +1,52 @@
+/*
+ * Swagger Demo
+ * Swagger的简单示例, 包括swagger-codegen, swagger2markup 和 asciidoctor.
+ *
+ * OpenAPI spec version: v1
+ * Contact: damon.q@iv66.net
+ *
+ * NOTE: This class is auto generated by the swagger code generator program.
+ * https://github.com/swagger-api/swagger-codegen.git
+ * Do not edit the class manually.
+ */
+
+
+package io.swagger.client;
+
+@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2017-11-09T10:58:38.431+08:00")
+public class Pair {
+ private String name = "";
+ private String value = "";
+
+ public Pair (String name, String value) {
+ setName(name);
+ setValue(value);
+ }
+
+ private void setName(String name) {
+ if (!isValidString(name)) return;
+
+ this.name = name;
+ }
+
+ private void setValue(String value) {
+ if (!isValidString(value)) return;
+
+ this.value = value;
+ }
+
+ public String getName() {
+ return this.name;
+ }
+
+ public String getValue() {
+ return this.value;
+ }
+
+ private boolean isValidString(String arg) {
+ if (arg == null) return false;
+ if (arg.trim().isEmpty()) return false;
+
+ return true;
+ }
+}
diff --git a/client/java/src/main/java/io/swagger/client/ProgressRequestBody.java b/client/java/src/main/java/io/swagger/client/ProgressRequestBody.java
new file mode 100644
index 0000000..cc93a90
--- /dev/null
+++ b/client/java/src/main/java/io/swagger/client/ProgressRequestBody.java
@@ -0,0 +1,77 @@
+/*
+ * Swagger Demo
+ * Swagger的简单示例, 包括swagger-codegen, swagger2markup 和 asciidoctor.
+ *
+ * OpenAPI spec version: v1
+ * Contact: damon.q@iv66.net
+ *
+ * NOTE: This class is auto generated by the swagger code generator program.
+ * https://github.com/swagger-api/swagger-codegen.git
+ * Do not edit the class manually.
+ */
+
+
+package io.swagger.client;
+
+import com.squareup.okhttp.MediaType;
+import com.squareup.okhttp.RequestBody;
+
+import java.io.IOException;
+
+import okio.Buffer;
+import okio.BufferedSink;
+import okio.ForwardingSink;
+import okio.Okio;
+import okio.Sink;
+
+public class ProgressRequestBody extends RequestBody {
+
+ public interface ProgressRequestListener {
+ void onRequestProgress(long bytesWritten, long contentLength, boolean done);
+ }
+
+ private final RequestBody requestBody;
+
+ private final ProgressRequestListener progressListener;
+
+ public ProgressRequestBody(RequestBody requestBody, ProgressRequestListener progressListener) {
+ this.requestBody = requestBody;
+ this.progressListener = progressListener;
+ }
+
+ @Override
+ public MediaType contentType() {
+ return requestBody.contentType();
+ }
+
+ @Override
+ public long contentLength() throws IOException {
+ return requestBody.contentLength();
+ }
+
+ @Override
+ public void writeTo(BufferedSink sink) throws IOException {
+ BufferedSink bufferedSink = Okio.buffer(sink(sink));
+ requestBody.writeTo(bufferedSink);
+ bufferedSink.flush();
+ }
+
+ private Sink sink(Sink sink) {
+ return new ForwardingSink(sink) {
+
+ long bytesWritten = 0L;
+ long contentLength = 0L;
+
+ @Override
+ public void write(Buffer source, long byteCount) throws IOException {
+ super.write(source, byteCount);
+ if (contentLength == 0) {
+ contentLength = contentLength();
+ }
+
+ bytesWritten += byteCount;
+ progressListener.onRequestProgress(bytesWritten, contentLength, bytesWritten == contentLength);
+ }
+ };
+ }
+}
diff --git a/client/java/src/main/java/io/swagger/client/ProgressResponseBody.java b/client/java/src/main/java/io/swagger/client/ProgressResponseBody.java
new file mode 100644
index 0000000..e747c31
--- /dev/null
+++ b/client/java/src/main/java/io/swagger/client/ProgressResponseBody.java
@@ -0,0 +1,76 @@
+/*
+ * Swagger Demo
+ * Swagger的简单示例, 包括swagger-codegen, swagger2markup 和 asciidoctor.
+ *
+ * OpenAPI spec version: v1
+ * Contact: damon.q@iv66.net
+ *
+ * NOTE: This class is auto generated by the swagger code generator program.
+ * https://github.com/swagger-api/swagger-codegen.git
+ * Do not edit the class manually.
+ */
+
+
+package io.swagger.client;
+
+import com.squareup.okhttp.MediaType;
+import com.squareup.okhttp.ResponseBody;
+
+import java.io.IOException;
+
+import okio.Buffer;
+import okio.BufferedSource;
+import okio.ForwardingSource;
+import okio.Okio;
+import okio.Source;
+
+public class ProgressResponseBody extends ResponseBody {
+
+ public interface ProgressListener {
+ void update(long bytesRead, long contentLength, boolean done);
+ }
+
+ private final ResponseBody responseBody;
+ private final ProgressListener progressListener;
+ private BufferedSource bufferedSource;
+
+ public ProgressResponseBody(ResponseBody responseBody, ProgressListener progressListener) {
+ this.responseBody = responseBody;
+ this.progressListener = progressListener;
+ }
+
+ @Override
+ public MediaType contentType() {
+ return responseBody.contentType();
+ }
+
+ @Override
+ public long contentLength() throws IOException {
+ return responseBody.contentLength();
+ }
+
+ @Override
+ public BufferedSource source() throws IOException {
+ if (bufferedSource == null) {
+ bufferedSource = Okio.buffer(source(responseBody.source()));
+ }
+ return bufferedSource;
+ }
+
+ private Source source(Source source) {
+ return new ForwardingSource(source) {
+ long totalBytesRead = 0L;
+
+ @Override
+ public long read(Buffer sink, long byteCount) throws IOException {
+ long bytesRead = super.read(sink, byteCount);
+ // read() returns the number of bytes read, or -1 if this source is exhausted.
+ totalBytesRead += bytesRead != -1 ? bytesRead : 0;
+ progressListener.update(totalBytesRead, responseBody.contentLength(), bytesRead == -1);
+ return bytesRead;
+ }
+ };
+ }
+}
+
+
diff --git a/client/java/src/main/java/io/swagger/client/StringUtil.java b/client/java/src/main/java/io/swagger/client/StringUtil.java
new file mode 100644
index 0000000..b231e00
--- /dev/null
+++ b/client/java/src/main/java/io/swagger/client/StringUtil.java
@@ -0,0 +1,55 @@
+/*
+ * Swagger Demo
+ * Swagger的简单示例, 包括swagger-codegen, swagger2markup 和 asciidoctor.
+ *
+ * OpenAPI spec version: v1
+ * Contact: damon.q@iv66.net
+ *
+ * NOTE: This class is auto generated by the swagger code generator program.
+ * https://github.com/swagger-api/swagger-codegen.git
+ * Do not edit the class manually.
+ */
+
+
+package io.swagger.client;
+
+@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2017-11-09T10:58:38.431+08:00")
+public class StringUtil {
+ /**
+ * Check if the given array contains the given value (with case-insensitive comparison).
+ *
+ * @param array The array
+ * @param value The value to search
+ * @return true if the array contains the value
+ */
+ public static boolean containsIgnoreCase(String[] array, String value) {
+ for (String str : array) {
+ if (value == null && str == null) return true;
+ if (value != null && value.equalsIgnoreCase(str)) return true;
+ }
+ return false;
+ }
+
+ /**
+ * Join an array of strings with the given separator.
+ *
+ * Note: This might be replaced by utility method from commons-lang or guava someday
+ * if one of those libraries is added as dependency.
+ *
+ *
+ * @param array The array of strings
+ * @param separator The separator
+ * @return the resulting string
+ */
+ public static String join(String[] array, String separator) {
+ int len = array.length;
+ if (len == 0) return "";
+
+ StringBuilder out = new StringBuilder();
+ out.append(array[0]);
+ for (int i = 1; i < len; i++) {
+ out.append(separator).append(array[i]);
+ }
+ return out.toString();
+ }
+}
diff --git a/client/java/src/main/java/io/swagger/client/api/BookApiApi.java b/client/java/src/main/java/io/swagger/client/api/BookApiApi.java
new file mode 100644
index 0000000..448e0fc
--- /dev/null
+++ b/client/java/src/main/java/io/swagger/client/api/BookApiApi.java
@@ -0,0 +1,430 @@
+/*
+ * Swagger Demo
+ * Swagger的简单示例, 包括swagger-codegen, swagger2markup 和 asciidoctor.
+ *
+ * OpenAPI spec version: v1
+ * Contact: damon.q@iv66.net
+ *
+ * NOTE: This class is auto generated by the swagger code generator program.
+ * https://github.com/swagger-api/swagger-codegen.git
+ * Do not edit the class manually.
+ */
+
+
+package io.swagger.client.api;
+
+import io.swagger.client.ApiCallback;
+import io.swagger.client.ApiClient;
+import io.swagger.client.ApiException;
+import io.swagger.client.ApiResponse;
+import io.swagger.client.Configuration;
+import io.swagger.client.Pair;
+import io.swagger.client.ProgressRequestBody;
+import io.swagger.client.ProgressResponseBody;
+
+import com.google.gson.reflect.TypeToken;
+
+import java.io.IOException;
+
+
+import io.swagger.client.model.Book;
+
+import java.lang.reflect.Type;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+public class BookApiApi {
+ private ApiClient apiClient;
+
+ public BookApiApi() {
+ this(Configuration.getDefaultApiClient());
+ }
+
+ public BookApiApi(ApiClient apiClient) {
+ this.apiClient = apiClient;
+ }
+
+ public ApiClient getApiClient() {
+ return apiClient;
+ }
+
+ public void setApiClient(ApiClient apiClient) {
+ this.apiClient = apiClient;
+ }
+
+ /**
+ * Build call for getBookByIdUsingGET
+ * @param id id (required)
+ * @param progressListener Progress listener
+ * @param progressRequestListener Progress request listener
+ * @return Call to execute
+ * @throws ApiException If fail to serialize the request body object
+ */
+ public com.squareup.okhttp.Call getBookByIdUsingGETCall(Integer id, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
+ Object localVarPostBody = null;
+
+ // create path and map variables
+ String localVarPath = "/v1/book/{id}"
+ .replaceAll("\\{" + "id" + "\\}", apiClient.escapeString(id.toString()));
+
+ List localVarQueryParams = new ArrayList();
+
+ Map localVarHeaderParams = new HashMap();
+
+ Map localVarFormParams = new HashMap();
+
+ final String[] localVarAccepts = {
+ "*/*"
+ };
+ final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
+ if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept);
+
+ final String[] localVarContentTypes = {
+ "application/json"
+ };
+ final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
+ localVarHeaderParams.put("Content-Type", localVarContentType);
+
+ if(progressListener != null) {
+ apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() {
+ @Override
+ public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException {
+ com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request());
+ return originalResponse.newBuilder()
+ .body(new ProgressResponseBody(originalResponse.body(), progressListener))
+ .build();
+ }
+ });
+ }
+
+ String[] localVarAuthNames = new String[] { "api_key" };
+ return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener);
+ }
+
+ @SuppressWarnings("rawtypes")
+ private com.squareup.okhttp.Call getBookByIdUsingGETValidateBeforeCall(Integer id, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
+
+ // verify the required parameter 'id' is set
+ if (id == null) {
+ throw new ApiException("Missing the required parameter 'id' when calling getBookByIdUsingGET(Async)");
+ }
+
+
+ com.squareup.okhttp.Call call = getBookByIdUsingGETCall(id, progressListener, progressRequestListener);
+ return call;
+
+
+
+
+
+ }
+
+ /**
+ * 根据ID获取书籍
+ *
+ * @param id id (required)
+ * @return Book
+ * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
+ */
+ public Book getBookByIdUsingGET(Integer id) throws ApiException {
+ ApiResponse resp = getBookByIdUsingGETWithHttpInfo(id);
+ return resp.getData();
+ }
+
+ /**
+ * 根据ID获取书籍
+ *
+ * @param id id (required)
+ * @return ApiResponse<Book>
+ * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
+ */
+ public ApiResponse getBookByIdUsingGETWithHttpInfo(Integer id) throws ApiException {
+ com.squareup.okhttp.Call call = getBookByIdUsingGETValidateBeforeCall(id, null, null);
+ Type localVarReturnType = new TypeToken(){}.getType();
+ return apiClient.execute(call, localVarReturnType);
+ }
+
+ /**
+ * 根据ID获取书籍 (asynchronously)
+ *
+ * @param id id (required)
+ * @param callback The callback to be executed when the API call finishes
+ * @return The request call
+ * @throws ApiException If fail to process the API call, e.g. serializing the request body object
+ */
+ public com.squareup.okhttp.Call getBookByIdUsingGETAsync(Integer id, final ApiCallback callback) throws ApiException {
+
+ ProgressResponseBody.ProgressListener progressListener = null;
+ ProgressRequestBody.ProgressRequestListener progressRequestListener = null;
+
+ if (callback != null) {
+ progressListener = new ProgressResponseBody.ProgressListener() {
+ @Override
+ public void update(long bytesRead, long contentLength, boolean done) {
+ callback.onDownloadProgress(bytesRead, contentLength, done);
+ }
+ };
+
+ progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
+ @Override
+ public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
+ callback.onUploadProgress(bytesWritten, contentLength, done);
+ }
+ };
+ }
+
+ com.squareup.okhttp.Call call = getBookByIdUsingGETValidateBeforeCall(id, progressListener, progressRequestListener);
+ Type localVarReturnType = new TypeToken(){}.getType();
+ apiClient.executeAsync(call, localVarReturnType, callback);
+ return call;
+ }
+ /**
+ * Build call for getBooksByCategoryUsingGET
+ * @param id id (required)
+ * @param progressListener Progress listener
+ * @param progressRequestListener Progress request listener
+ * @return Call to execute
+ * @throws ApiException If fail to serialize the request body object
+ */
+ public com.squareup.okhttp.Call getBooksByCategoryUsingGETCall(Integer id, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
+ Object localVarPostBody = null;
+
+ // create path and map variables
+ String localVarPath = "/v1/book/getByCategoryId";
+
+ List localVarQueryParams = new ArrayList();
+ if (id != null)
+ localVarQueryParams.addAll(apiClient.parameterToPairs("", "id", id));
+
+ Map localVarHeaderParams = new HashMap();
+
+ Map localVarFormParams = new HashMap();
+
+ final String[] localVarAccepts = {
+ "*/*"
+ };
+ final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
+ if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept);
+
+ final String[] localVarContentTypes = {
+ "application/json"
+ };
+ final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
+ localVarHeaderParams.put("Content-Type", localVarContentType);
+
+ if(progressListener != null) {
+ apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() {
+ @Override
+ public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException {
+ com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request());
+ return originalResponse.newBuilder()
+ .body(new ProgressResponseBody(originalResponse.body(), progressListener))
+ .build();
+ }
+ });
+ }
+
+ String[] localVarAuthNames = new String[] { "api_key" };
+ return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener);
+ }
+
+ @SuppressWarnings("rawtypes")
+ private com.squareup.okhttp.Call getBooksByCategoryUsingGETValidateBeforeCall(Integer id, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
+
+ // verify the required parameter 'id' is set
+ if (id == null) {
+ throw new ApiException("Missing the required parameter 'id' when calling getBooksByCategoryUsingGET(Async)");
+ }
+
+
+ com.squareup.okhttp.Call call = getBooksByCategoryUsingGETCall(id, progressListener, progressRequestListener);
+ return call;
+
+
+
+
+
+ }
+
+ /**
+ * 根据分类获取书籍
+ *
+ * @param id id (required)
+ * @return List<Book>
+ * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
+ */
+ public List getBooksByCategoryUsingGET(Integer id) throws ApiException {
+ ApiResponse> resp = getBooksByCategoryUsingGETWithHttpInfo(id);
+ return resp.getData();
+ }
+
+ /**
+ * 根据分类获取书籍
+ *
+ * @param id id (required)
+ * @return ApiResponse<List<Book>>
+ * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
+ */
+ public ApiResponse> getBooksByCategoryUsingGETWithHttpInfo(Integer id) throws ApiException {
+ com.squareup.okhttp.Call call = getBooksByCategoryUsingGETValidateBeforeCall(id, null, null);
+ Type localVarReturnType = new TypeToken>(){}.getType();
+ return apiClient.execute(call, localVarReturnType);
+ }
+
+ /**
+ * 根据分类获取书籍 (asynchronously)
+ *
+ * @param id id (required)
+ * @param callback The callback to be executed when the API call finishes
+ * @return The request call
+ * @throws ApiException If fail to process the API call, e.g. serializing the request body object
+ */
+ public com.squareup.okhttp.Call getBooksByCategoryUsingGETAsync(Integer id, final ApiCallback> callback) throws ApiException {
+
+ ProgressResponseBody.ProgressListener progressListener = null;
+ ProgressRequestBody.ProgressRequestListener progressRequestListener = null;
+
+ if (callback != null) {
+ progressListener = new ProgressResponseBody.ProgressListener() {
+ @Override
+ public void update(long bytesRead, long contentLength, boolean done) {
+ callback.onDownloadProgress(bytesRead, contentLength, done);
+ }
+ };
+
+ progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
+ @Override
+ public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
+ callback.onUploadProgress(bytesWritten, contentLength, done);
+ }
+ };
+ }
+
+ com.squareup.okhttp.Call call = getBooksByCategoryUsingGETValidateBeforeCall(id, progressListener, progressRequestListener);
+ Type localVarReturnType = new TypeToken>(){}.getType();
+ apiClient.executeAsync(call, localVarReturnType, callback);
+ return call;
+ }
+ /**
+ * Build call for updateUsingPOST
+ * @param id id (optional)
+ * @param progressListener Progress listener
+ * @param progressRequestListener Progress request listener
+ * @return Call to execute
+ * @throws ApiException If fail to serialize the request body object
+ */
+ public com.squareup.okhttp.Call updateUsingPOSTCall(Integer id, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
+ Object localVarPostBody = id;
+
+ // create path and map variables
+ String localVarPath = "/v1/book/update";
+
+ List localVarQueryParams = new ArrayList();
+
+ Map localVarHeaderParams = new HashMap();
+
+ Map localVarFormParams = new HashMap();
+
+ final String[] localVarAccepts = {
+ "*/*"
+ };
+ final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
+ if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept);
+
+ final String[] localVarContentTypes = {
+ "application/json"
+ };
+ final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
+ localVarHeaderParams.put("Content-Type", localVarContentType);
+
+ if(progressListener != null) {
+ apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() {
+ @Override
+ public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException {
+ com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request());
+ return originalResponse.newBuilder()
+ .body(new ProgressResponseBody(originalResponse.body(), progressListener))
+ .build();
+ }
+ });
+ }
+
+ String[] localVarAuthNames = new String[] { "api_key" };
+ return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener);
+ }
+
+ @SuppressWarnings("rawtypes")
+ private com.squareup.okhttp.Call updateUsingPOSTValidateBeforeCall(Integer id, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
+
+
+ com.squareup.okhttp.Call call = updateUsingPOSTCall(id, progressListener, progressRequestListener);
+ return call;
+
+
+
+
+
+ }
+
+ /**
+ * 更新书籍
+ *
+ * @param id id (optional)
+ * @return Boolean
+ * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
+ */
+ public Boolean updateUsingPOST(Integer id) throws ApiException {
+ ApiResponse resp = updateUsingPOSTWithHttpInfo(id);
+ return resp.getData();
+ }
+
+ /**
+ * 更新书籍
+ *
+ * @param id id (optional)
+ * @return ApiResponse<Boolean>
+ * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
+ */
+ public ApiResponse updateUsingPOSTWithHttpInfo(Integer id) throws ApiException {
+ com.squareup.okhttp.Call call = updateUsingPOSTValidateBeforeCall(id, null, null);
+ Type localVarReturnType = new TypeToken(){}.getType();
+ return apiClient.execute(call, localVarReturnType);
+ }
+
+ /**
+ * 更新书籍 (asynchronously)
+ *
+ * @param id id (optional)
+ * @param callback The callback to be executed when the API call finishes
+ * @return The request call
+ * @throws ApiException If fail to process the API call, e.g. serializing the request body object
+ */
+ public com.squareup.okhttp.Call updateUsingPOSTAsync(Integer id, final ApiCallback callback) throws ApiException {
+
+ ProgressResponseBody.ProgressListener progressListener = null;
+ ProgressRequestBody.ProgressRequestListener progressRequestListener = null;
+
+ if (callback != null) {
+ progressListener = new ProgressResponseBody.ProgressListener() {
+ @Override
+ public void update(long bytesRead, long contentLength, boolean done) {
+ callback.onDownloadProgress(bytesRead, contentLength, done);
+ }
+ };
+
+ progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
+ @Override
+ public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
+ callback.onUploadProgress(bytesWritten, contentLength, done);
+ }
+ };
+ }
+
+ com.squareup.okhttp.Call call = updateUsingPOSTValidateBeforeCall(id, progressListener, progressRequestListener);
+ Type localVarReturnType = new TypeToken(){}.getType();
+ apiClient.executeAsync(call, localVarReturnType, callback);
+ return call;
+ }
+}
diff --git a/client/java/src/main/java/io/swagger/client/api/CategoryApiApi.java b/client/java/src/main/java/io/swagger/client/api/CategoryApiApi.java
new file mode 100644
index 0000000..61ca50b
--- /dev/null
+++ b/client/java/src/main/java/io/swagger/client/api/CategoryApiApi.java
@@ -0,0 +1,299 @@
+/*
+ * Swagger Demo
+ * Swagger的简单示例, 包括swagger-codegen, swagger2markup 和 asciidoctor.
+ *
+ * OpenAPI spec version: v1
+ * Contact: damon.q@iv66.net
+ *
+ * NOTE: This class is auto generated by the swagger code generator program.
+ * https://github.com/swagger-api/swagger-codegen.git
+ * Do not edit the class manually.
+ */
+
+
+package io.swagger.client.api;
+
+import io.swagger.client.ApiCallback;
+import io.swagger.client.ApiClient;
+import io.swagger.client.ApiException;
+import io.swagger.client.ApiResponse;
+import io.swagger.client.Configuration;
+import io.swagger.client.Pair;
+import io.swagger.client.ProgressRequestBody;
+import io.swagger.client.ProgressResponseBody;
+
+import com.google.gson.reflect.TypeToken;
+
+import java.io.IOException;
+
+
+import io.swagger.client.model.Category;
+
+import java.lang.reflect.Type;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+public class CategoryApiApi {
+ private ApiClient apiClient;
+
+ public CategoryApiApi() {
+ this(Configuration.getDefaultApiClient());
+ }
+
+ public CategoryApiApi(ApiClient apiClient) {
+ this.apiClient = apiClient;
+ }
+
+ public ApiClient getApiClient() {
+ return apiClient;
+ }
+
+ public void setApiClient(ApiClient apiClient) {
+ this.apiClient = apiClient;
+ }
+
+ /**
+ * Build call for getAllUsingGET
+ * @param progressListener Progress listener
+ * @param progressRequestListener Progress request listener
+ * @return Call to execute
+ * @throws ApiException If fail to serialize the request body object
+ */
+ public com.squareup.okhttp.Call getAllUsingGETCall(final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
+ Object localVarPostBody = null;
+
+ // create path and map variables
+ String localVarPath = "/v1/category/";
+
+ List localVarQueryParams = new ArrayList();
+
+ Map localVarHeaderParams = new HashMap();
+
+ Map localVarFormParams = new HashMap();
+
+ final String[] localVarAccepts = {
+ "*/*"
+ };
+ final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
+ if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept);
+
+ final String[] localVarContentTypes = {
+ "application/json"
+ };
+ final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
+ localVarHeaderParams.put("Content-Type", localVarContentType);
+
+ if(progressListener != null) {
+ apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() {
+ @Override
+ public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException {
+ com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request());
+ return originalResponse.newBuilder()
+ .body(new ProgressResponseBody(originalResponse.body(), progressListener))
+ .build();
+ }
+ });
+ }
+
+ String[] localVarAuthNames = new String[] { };
+ return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener);
+ }
+
+ @SuppressWarnings("rawtypes")
+ private com.squareup.okhttp.Call getAllUsingGETValidateBeforeCall(final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
+
+
+ com.squareup.okhttp.Call call = getAllUsingGETCall(progressListener, progressRequestListener);
+ return call;
+
+
+
+
+
+ }
+
+ /**
+ * 获取全部分类
+ *
+ * @return List<Category>
+ * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
+ */
+ public List getAllUsingGET() throws ApiException {
+ ApiResponse> resp = getAllUsingGETWithHttpInfo();
+ return resp.getData();
+ }
+
+ /**
+ * 获取全部分类
+ *
+ * @return ApiResponse<List<Category>>
+ * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
+ */
+ public ApiResponse> getAllUsingGETWithHttpInfo() throws ApiException {
+ com.squareup.okhttp.Call call = getAllUsingGETValidateBeforeCall(null, null);
+ Type localVarReturnType = new TypeToken>(){}.getType();
+ return apiClient.execute(call, localVarReturnType);
+ }
+
+ /**
+ * 获取全部分类 (asynchronously)
+ *
+ * @param callback The callback to be executed when the API call finishes
+ * @return The request call
+ * @throws ApiException If fail to process the API call, e.g. serializing the request body object
+ */
+ public com.squareup.okhttp.Call getAllUsingGETAsync(final ApiCallback> callback) throws ApiException {
+
+ ProgressResponseBody.ProgressListener progressListener = null;
+ ProgressRequestBody.ProgressRequestListener progressRequestListener = null;
+
+ if (callback != null) {
+ progressListener = new ProgressResponseBody.ProgressListener() {
+ @Override
+ public void update(long bytesRead, long contentLength, boolean done) {
+ callback.onDownloadProgress(bytesRead, contentLength, done);
+ }
+ };
+
+ progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
+ @Override
+ public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
+ callback.onUploadProgress(bytesWritten, contentLength, done);
+ }
+ };
+ }
+
+ com.squareup.okhttp.Call call = getAllUsingGETValidateBeforeCall(progressListener, progressRequestListener);
+ Type localVarReturnType = new TypeToken>(){}.getType();
+ apiClient.executeAsync(call, localVarReturnType, callback);
+ return call;
+ }
+ /**
+ * Build call for getUsingGET
+ * @param id id (required)
+ * @param progressListener Progress listener
+ * @param progressRequestListener Progress request listener
+ * @return Call to execute
+ * @throws ApiException If fail to serialize the request body object
+ */
+ public com.squareup.okhttp.Call getUsingGETCall(Integer id, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
+ Object localVarPostBody = null;
+
+ // create path and map variables
+ String localVarPath = "/v1/category/{id}"
+ .replaceAll("\\{" + "id" + "\\}", apiClient.escapeString(id.toString()));
+
+ List localVarQueryParams = new ArrayList();
+
+ Map localVarHeaderParams = new HashMap();
+
+ Map localVarFormParams = new HashMap();
+
+ final String[] localVarAccepts = {
+ "*/*"
+ };
+ final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
+ if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept);
+
+ final String[] localVarContentTypes = {
+ "application/json"
+ };
+ final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
+ localVarHeaderParams.put("Content-Type", localVarContentType);
+
+ if(progressListener != null) {
+ apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() {
+ @Override
+ public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException {
+ com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request());
+ return originalResponse.newBuilder()
+ .body(new ProgressResponseBody(originalResponse.body(), progressListener))
+ .build();
+ }
+ });
+ }
+
+ String[] localVarAuthNames = new String[] { };
+ return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener);
+ }
+
+ @SuppressWarnings("rawtypes")
+ private com.squareup.okhttp.Call getUsingGETValidateBeforeCall(Integer id, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
+
+ // verify the required parameter 'id' is set
+ if (id == null) {
+ throw new ApiException("Missing the required parameter 'id' when calling getUsingGET(Async)");
+ }
+
+
+ com.squareup.okhttp.Call call = getUsingGETCall(id, progressListener, progressRequestListener);
+ return call;
+
+
+
+
+
+ }
+
+ /**
+ * 根据ID获取分类
+ *
+ * @param id id (required)
+ * @return Category
+ * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
+ */
+ public Category getUsingGET(Integer id) throws ApiException {
+ ApiResponse resp = getUsingGETWithHttpInfo(id);
+ return resp.getData();
+ }
+
+ /**
+ * 根据ID获取分类
+ *
+ * @param id id (required)
+ * @return ApiResponse<Category>
+ * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
+ */
+ public ApiResponse getUsingGETWithHttpInfo(Integer id) throws ApiException {
+ com.squareup.okhttp.Call call = getUsingGETValidateBeforeCall(id, null, null);
+ Type localVarReturnType = new TypeToken(){}.getType();
+ return apiClient.execute(call, localVarReturnType);
+ }
+
+ /**
+ * 根据ID获取分类 (asynchronously)
+ *
+ * @param id id (required)
+ * @param callback The callback to be executed when the API call finishes
+ * @return The request call
+ * @throws ApiException If fail to process the API call, e.g. serializing the request body object
+ */
+ public com.squareup.okhttp.Call getUsingGETAsync(Integer id, final ApiCallback callback) throws ApiException {
+
+ ProgressResponseBody.ProgressListener progressListener = null;
+ ProgressRequestBody.ProgressRequestListener progressRequestListener = null;
+
+ if (callback != null) {
+ progressListener = new ProgressResponseBody.ProgressListener() {
+ @Override
+ public void update(long bytesRead, long contentLength, boolean done) {
+ callback.onDownloadProgress(bytesRead, contentLength, done);
+ }
+ };
+
+ progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
+ @Override
+ public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
+ callback.onUploadProgress(bytesWritten, contentLength, done);
+ }
+ };
+ }
+
+ com.squareup.okhttp.Call call = getUsingGETValidateBeforeCall(id, progressListener, progressRequestListener);
+ Type localVarReturnType = new TypeToken(){}.getType();
+ apiClient.executeAsync(call, localVarReturnType, callback);
+ return call;
+ }
+}
diff --git a/client/java/src/main/java/io/swagger/client/auth/ApiKeyAuth.java b/client/java/src/main/java/io/swagger/client/auth/ApiKeyAuth.java
new file mode 100644
index 0000000..6b098e7
--- /dev/null
+++ b/client/java/src/main/java/io/swagger/client/auth/ApiKeyAuth.java
@@ -0,0 +1,75 @@
+/*
+ * Swagger Demo
+ * Swagger的简单示例, 包括swagger-codegen, swagger2markup 和 asciidoctor.
+ *
+ * OpenAPI spec version: v1
+ * Contact: damon.q@iv66.net
+ *
+ * NOTE: This class is auto generated by the swagger code generator program.
+ * https://github.com/swagger-api/swagger-codegen.git
+ * Do not edit the class manually.
+ */
+
+
+package io.swagger.client.auth;
+
+import io.swagger.client.Pair;
+
+import java.util.Map;
+import java.util.List;
+
+@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2017-11-09T10:58:38.431+08:00")
+public class ApiKeyAuth implements Authentication {
+ private final String location;
+ private final String paramName;
+
+ private String apiKey;
+ private String apiKeyPrefix;
+
+ public ApiKeyAuth(String location, String paramName) {
+ this.location = location;
+ this.paramName = paramName;
+ }
+
+ public String getLocation() {
+ return location;
+ }
+
+ public String getParamName() {
+ return paramName;
+ }
+
+ public String getApiKey() {
+ return apiKey;
+ }
+
+ public void setApiKey(String apiKey) {
+ this.apiKey = apiKey;
+ }
+
+ public String getApiKeyPrefix() {
+ return apiKeyPrefix;
+ }
+
+ public void setApiKeyPrefix(String apiKeyPrefix) {
+ this.apiKeyPrefix = apiKeyPrefix;
+ }
+
+ @Override
+ public void applyToParams(List queryParams, Map headerParams) {
+ if (apiKey == null) {
+ return;
+ }
+ String value;
+ if (apiKeyPrefix != null) {
+ value = apiKeyPrefix + " " + apiKey;
+ } else {
+ value = apiKey;
+ }
+ if ("query".equals(location)) {
+ queryParams.add(new Pair(paramName, value));
+ } else if ("header".equals(location)) {
+ headerParams.put(paramName, value);
+ }
+ }
+}
diff --git a/client/java/src/main/java/io/swagger/client/auth/Authentication.java b/client/java/src/main/java/io/swagger/client/auth/Authentication.java
new file mode 100644
index 0000000..bc92073
--- /dev/null
+++ b/client/java/src/main/java/io/swagger/client/auth/Authentication.java
@@ -0,0 +1,29 @@
+/*
+ * Swagger Demo
+ * Swagger的简单示例, 包括swagger-codegen, swagger2markup 和 asciidoctor.
+ *
+ * OpenAPI spec version: v1
+ * Contact: damon.q@iv66.net
+ *
+ * NOTE: This class is auto generated by the swagger code generator program.
+ * https://github.com/swagger-api/swagger-codegen.git
+ * Do not edit the class manually.
+ */
+
+
+package io.swagger.client.auth;
+
+import io.swagger.client.Pair;
+
+import java.util.Map;
+import java.util.List;
+
+public interface Authentication {
+ /**
+ * Apply authentication settings to header and query params.
+ *
+ * @param queryParams List of query parameters
+ * @param headerParams Map of header parameters
+ */
+ void applyToParams(List queryParams, Map headerParams);
+}
diff --git a/client/java/src/main/java/io/swagger/client/auth/HttpBasicAuth.java b/client/java/src/main/java/io/swagger/client/auth/HttpBasicAuth.java
new file mode 100644
index 0000000..06b9de2
--- /dev/null
+++ b/client/java/src/main/java/io/swagger/client/auth/HttpBasicAuth.java
@@ -0,0 +1,54 @@
+/*
+ * Swagger Demo
+ * Swagger的简单示例, 包括swagger-codegen, swagger2markup 和 asciidoctor.
+ *
+ * OpenAPI spec version: v1
+ * Contact: damon.q@iv66.net
+ *
+ * NOTE: This class is auto generated by the swagger code generator program.
+ * https://github.com/swagger-api/swagger-codegen.git
+ * Do not edit the class manually.
+ */
+
+
+package io.swagger.client.auth;
+
+import io.swagger.client.Pair;
+
+import com.squareup.okhttp.Credentials;
+
+import java.util.Map;
+import java.util.List;
+
+import java.io.UnsupportedEncodingException;
+
+public class HttpBasicAuth implements Authentication {
+ private String username;
+ private String password;
+
+ public String getUsername() {
+ return username;
+ }
+
+ public void setUsername(String username) {
+ this.username = username;
+ }
+
+ public String getPassword() {
+ return password;
+ }
+
+ public void setPassword(String password) {
+ this.password = password;
+ }
+
+ @Override
+ public void applyToParams(List queryParams, Map headerParams) {
+ if (username == null && password == null) {
+ return;
+ }
+ headerParams.put("Authorization", Credentials.basic(
+ username == null ? "" : username,
+ password == null ? "" : password));
+ }
+}
diff --git a/client/java/src/main/java/io/swagger/client/auth/OAuth.java b/client/java/src/main/java/io/swagger/client/auth/OAuth.java
new file mode 100644
index 0000000..76a61c4
--- /dev/null
+++ b/client/java/src/main/java/io/swagger/client/auth/OAuth.java
@@ -0,0 +1,39 @@
+/*
+ * Swagger Demo
+ * Swagger的简单示例, 包括swagger-codegen, swagger2markup 和 asciidoctor.
+ *
+ * OpenAPI spec version: v1
+ * Contact: damon.q@iv66.net
+ *
+ * NOTE: This class is auto generated by the swagger code generator program.
+ * https://github.com/swagger-api/swagger-codegen.git
+ * Do not edit the class manually.
+ */
+
+
+package io.swagger.client.auth;
+
+import io.swagger.client.Pair;
+
+import java.util.Map;
+import java.util.List;
+
+@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2017-11-09T10:58:38.431+08:00")
+public class OAuth implements Authentication {
+ private String accessToken;
+
+ public String getAccessToken() {
+ return accessToken;
+ }
+
+ public void setAccessToken(String accessToken) {
+ this.accessToken = accessToken;
+ }
+
+ @Override
+ public void applyToParams(List queryParams, Map headerParams) {
+ if (accessToken != null) {
+ headerParams.put("Authorization", "Bearer " + accessToken);
+ }
+ }
+}
diff --git a/client/java/src/main/java/io/swagger/client/auth/OAuthFlow.java b/client/java/src/main/java/io/swagger/client/auth/OAuthFlow.java
new file mode 100644
index 0000000..a939aaa
--- /dev/null
+++ b/client/java/src/main/java/io/swagger/client/auth/OAuthFlow.java
@@ -0,0 +1,18 @@
+/*
+ * Swagger Demo
+ * Swagger的简单示例, 包括swagger-codegen, swagger2markup 和 asciidoctor.
+ *
+ * OpenAPI spec version: v1
+ * Contact: damon.q@iv66.net
+ *
+ * NOTE: This class is auto generated by the swagger code generator program.
+ * https://github.com/swagger-api/swagger-codegen.git
+ * Do not edit the class manually.
+ */
+
+
+package io.swagger.client.auth;
+
+public enum OAuthFlow {
+ accessCode, implicit, password, application
+}
diff --git a/client/java/src/main/java/io/swagger/client/model/Book.java b/client/java/src/main/java/io/swagger/client/model/Book.java
new file mode 100644
index 0000000..b33325e
--- /dev/null
+++ b/client/java/src/main/java/io/swagger/client/model/Book.java
@@ -0,0 +1,162 @@
+/*
+ * Swagger Demo
+ * Swagger的简单示例, 包括swagger-codegen, swagger2markup 和 asciidoctor.
+ *
+ * OpenAPI spec version: v1
+ * Contact: damon.q@iv66.net
+ *
+ * NOTE: This class is auto generated by the swagger code generator program.
+ * https://github.com/swagger-api/swagger-codegen.git
+ * Do not edit the class manually.
+ */
+
+
+package io.swagger.client.model;
+
+import java.util.Objects;
+import com.google.gson.TypeAdapter;
+import com.google.gson.annotations.JsonAdapter;
+import com.google.gson.annotations.SerializedName;
+import com.google.gson.stream.JsonReader;
+import com.google.gson.stream.JsonWriter;
+import io.swagger.annotations.ApiModel;
+import io.swagger.annotations.ApiModelProperty;
+import java.io.IOException;
+
+/**
+ * Book
+ */
+@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2017-11-09T10:58:38.431+08:00")
+public class Book {
+ @SerializedName("author")
+ private String author = null;
+
+ @SerializedName("categoryId")
+ private Integer categoryId = null;
+
+ @SerializedName("id")
+ private Integer id = null;
+
+ @SerializedName("name")
+ private String name = null;
+
+ public Book author(String author) {
+ this.author = author;
+ return this;
+ }
+
+ /**
+ * 作者
+ * @return author
+ **/
+ @ApiModelProperty(value = "作者")
+ public String getAuthor() {
+ return author;
+ }
+
+ public void setAuthor(String author) {
+ this.author = author;
+ }
+
+ public Book categoryId(Integer categoryId) {
+ this.categoryId = categoryId;
+ return this;
+ }
+
+ /**
+ * Get categoryId
+ * @return categoryId
+ **/
+ @ApiModelProperty(value = "")
+ public Integer getCategoryId() {
+ return categoryId;
+ }
+
+ public void setCategoryId(Integer categoryId) {
+ this.categoryId = categoryId;
+ }
+
+ public Book id(Integer id) {
+ this.id = id;
+ return this;
+ }
+
+ /**
+ * Get id
+ * @return id
+ **/
+ @ApiModelProperty(value = "")
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public Book name(String name) {
+ this.name = name;
+ return this;
+ }
+
+ /**
+ * 书名
+ * @return name
+ **/
+ @ApiModelProperty(value = "书名")
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+
+ @Override
+ public boolean equals(java.lang.Object o) {
+ if (this == o) {
+ return true;
+ }
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
+ Book book = (Book) o;
+ return Objects.equals(this.author, book.author) &&
+ Objects.equals(this.categoryId, book.categoryId) &&
+ Objects.equals(this.id, book.id) &&
+ Objects.equals(this.name, book.name);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(author, categoryId, id, name);
+ }
+
+
+ @Override
+ public String toString() {
+ StringBuilder sb = new StringBuilder();
+ sb.append("class Book {\n");
+
+ sb.append(" author: ").append(toIndentedString(author)).append("\n");
+ sb.append(" categoryId: ").append(toIndentedString(categoryId)).append("\n");
+ sb.append(" id: ").append(toIndentedString(id)).append("\n");
+ sb.append(" name: ").append(toIndentedString(name)).append("\n");
+ sb.append("}");
+ return sb.toString();
+ }
+
+ /**
+ * Convert the given object to string with each line indented by 4 spaces
+ * (except the first line).
+ */
+ private String toIndentedString(java.lang.Object o) {
+ if (o == null) {
+ return "null";
+ }
+ return o.toString().replace("\n", "\n ");
+ }
+
+}
+
diff --git a/client/java/src/main/java/io/swagger/client/model/Category.java b/client/java/src/main/java/io/swagger/client/model/Category.java
new file mode 100644
index 0000000..14e352f
--- /dev/null
+++ b/client/java/src/main/java/io/swagger/client/model/Category.java
@@ -0,0 +1,116 @@
+/*
+ * Swagger Demo
+ * Swagger的简单示例, 包括swagger-codegen, swagger2markup 和 asciidoctor.
+ *
+ * OpenAPI spec version: v1
+ * Contact: damon.q@iv66.net
+ *
+ * NOTE: This class is auto generated by the swagger code generator program.
+ * https://github.com/swagger-api/swagger-codegen.git
+ * Do not edit the class manually.
+ */
+
+
+package io.swagger.client.model;
+
+import java.util.Objects;
+import com.google.gson.TypeAdapter;
+import com.google.gson.annotations.JsonAdapter;
+import com.google.gson.annotations.SerializedName;
+import com.google.gson.stream.JsonReader;
+import com.google.gson.stream.JsonWriter;
+import io.swagger.annotations.ApiModel;
+import io.swagger.annotations.ApiModelProperty;
+import java.io.IOException;
+
+/**
+ * Category
+ */
+@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2017-11-09T10:58:38.431+08:00")
+public class Category {
+ @SerializedName("id")
+ private Integer id = null;
+
+ @SerializedName("name")
+ private String name = null;
+
+ public Category id(Integer id) {
+ this.id = id;
+ return this;
+ }
+
+ /**
+ * Get id
+ * @return id
+ **/
+ @ApiModelProperty(value = "")
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public Category name(String name) {
+ this.name = name;
+ return this;
+ }
+
+ /**
+ * Get name
+ * @return name
+ **/
+ @ApiModelProperty(value = "")
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+
+ @Override
+ public boolean equals(java.lang.Object o) {
+ if (this == o) {
+ return true;
+ }
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
+ Category category = (Category) o;
+ return Objects.equals(this.id, category.id) &&
+ Objects.equals(this.name, category.name);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(id, name);
+ }
+
+
+ @Override
+ public String toString() {
+ StringBuilder sb = new StringBuilder();
+ sb.append("class Category {\n");
+
+ sb.append(" id: ").append(toIndentedString(id)).append("\n");
+ sb.append(" name: ").append(toIndentedString(name)).append("\n");
+ sb.append("}");
+ return sb.toString();
+ }
+
+ /**
+ * Convert the given object to string with each line indented by 4 spaces
+ * (except the first line).
+ */
+ private String toIndentedString(java.lang.Object o) {
+ if (o == null) {
+ return "null";
+ }
+ return o.toString().replace("\n", "\n ");
+ }
+
+}
+
diff --git a/client/java/src/test/java/io/swagger/client/api/BookApiApiTest.java b/client/java/src/test/java/io/swagger/client/api/BookApiApiTest.java
new file mode 100644
index 0000000..d044c90
--- /dev/null
+++ b/client/java/src/test/java/io/swagger/client/api/BookApiApiTest.java
@@ -0,0 +1,83 @@
+/*
+ * Swagger Demo
+ * Swagger的简单示例, 包括swagger-codegen, swagger2markup 和 asciidoctor.
+ *
+ * OpenAPI spec version: v1
+ * Contact: damon.q@iv66.net
+ *
+ * NOTE: This class is auto generated by the swagger code generator program.
+ * https://github.com/swagger-api/swagger-codegen.git
+ * Do not edit the class manually.
+ */
+
+
+package io.swagger.client.api;
+
+import io.swagger.client.ApiException;
+import io.swagger.client.model.Book;
+import org.junit.Test;
+import org.junit.Ignore;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * API tests for BookApiApi
+ */
+@Ignore
+public class BookApiApiTest {
+
+ private final BookApiApi api = new BookApiApi();
+
+
+ /**
+ * 根据ID获取书籍
+ *
+ *
+ *
+ * @throws ApiException
+ * if the Api call fails
+ */
+ @Test
+ public void getBookByIdUsingGETTest() throws ApiException {
+ Integer id = null;
+ Book response = api.getBookByIdUsingGET(id);
+
+ // TODO: test validations
+ }
+
+ /**
+ * 根据分类获取书籍
+ *
+ *
+ *
+ * @throws ApiException
+ * if the Api call fails
+ */
+ @Test
+ public void getBooksByCategoryUsingGETTest() throws ApiException {
+ Integer id = null;
+ List response = api.getBooksByCategoryUsingGET(id);
+
+ // TODO: test validations
+ }
+
+ /**
+ * 更新书籍
+ *
+ *
+ *
+ * @throws ApiException
+ * if the Api call fails
+ */
+ @Test
+ public void updateUsingPOSTTest() throws ApiException {
+ Integer id = null;
+ Boolean response = api.updateUsingPOST(id);
+
+ // TODO: test validations
+ }
+
+}
diff --git a/client/java/src/test/java/io/swagger/client/api/CategoryApiApiTest.java b/client/java/src/test/java/io/swagger/client/api/CategoryApiApiTest.java
new file mode 100644
index 0000000..816618e
--- /dev/null
+++ b/client/java/src/test/java/io/swagger/client/api/CategoryApiApiTest.java
@@ -0,0 +1,66 @@
+/*
+ * Swagger Demo
+ * Swagger的简单示例, 包括swagger-codegen, swagger2markup 和 asciidoctor.
+ *
+ * OpenAPI spec version: v1
+ * Contact: damon.q@iv66.net
+ *
+ * NOTE: This class is auto generated by the swagger code generator program.
+ * https://github.com/swagger-api/swagger-codegen.git
+ * Do not edit the class manually.
+ */
+
+
+package io.swagger.client.api;
+
+import io.swagger.client.ApiException;
+import io.swagger.client.model.Category;
+import org.junit.Test;
+import org.junit.Ignore;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * API tests for CategoryApiApi
+ */
+@Ignore
+public class CategoryApiApiTest {
+
+ private final CategoryApiApi api = new CategoryApiApi();
+
+
+ /**
+ * 获取全部分类
+ *
+ *
+ *
+ * @throws ApiException
+ * if the Api call fails
+ */
+ @Test
+ public void getAllUsingGETTest() throws ApiException {
+ List response = api.getAllUsingGET();
+
+ // TODO: test validations
+ }
+
+ /**
+ * 根据ID获取分类
+ *
+ *
+ *
+ * @throws ApiException
+ * if the Api call fails
+ */
+ @Test
+ public void getUsingGETTest() throws ApiException {
+ Integer id = null;
+ Category response = api.getUsingGET(id);
+
+ // TODO: test validations
+ }
+
+}
diff --git a/docs/swagger-example.html b/docs/swagger-example.html
new file mode 100644
index 0000000..bab6f76
--- /dev/null
+++ b/docs/swagger-example.html
@@ -0,0 +1,1321 @@
+
+
+
+
+
+
+
+Swagger Demo
+
+
+
+
+
+
+
+
+
+
1. Overview
+
+
+
Swagger的简单示例, 包括swagger-codegen, swagger2markup 和 asciidoctor.
+
+
+
+
+
+
1.4. URI scheme
+
+
Host : localhost:8080
+BasePath : /
+Schemes : HTTP, HTTPS
+
+
+
+
+
+
+
2. Paths
+
+
+
2.1. 根据分类获取书籍
+
+
+
GET /v1/book/getByCategoryId
+
+
+
+
2.1.1. Parameters
+
+
+
+
+
+
+
+
+
+Type
+Name
+Description
+Schema
+
+
+
+
+Query
+id
+required
+id
+integer (int32)
+
+
+
+
+
+
2.1.2. Responses
+
+
+
+
+
+
+
+
+HTTP Code
+Description
+Schema
+
+
+
+
+200
+OK
+< Book > array
+
+
+401
+Unauthorized
+No Content
+
+
+403
+Forbidden
+No Content
+
+
+404
+Not Found
+No Content
+
+
+
+
+
+
+
+
+
2.1.6. Security
+
+
+
+
+
+
+
+Type
+Name
+
+
+
+
+apiKey
+api_key
+
+
+
+
+
+
+
2.2. 更新书籍
+
+
+
2.2.1. Parameters
+
+
+
+
+
+
+
+
+
+Type
+Name
+Description
+Schema
+
+
+
+
+Body
+id
+optional
+id
+integer (int32)
+
+
+
+
+
+
2.2.2. Responses
+
+
+
+
+
+
+
+
+HTTP Code
+Description
+Schema
+
+
+
+
+200
+OK
+boolean
+
+
+201
+Created
+No Content
+
+
+401
+Unauthorized
+No Content
+
+
+403
+Forbidden
+No Content
+
+
+404
+Not Found
+No Content
+
+
+
+
+
+
+
+
+
2.2.6. Security
+
+
+
+
+
+
+
+Type
+Name
+
+
+
+
+apiKey
+api_key
+
+
+
+
+
+
+
2.3. 根据ID获取书籍
+
+
+
2.3.1. Parameters
+
+
+
+
+
+
+
+
+
+Type
+Name
+Description
+Schema
+
+
+
+
+Path
+id
+required
+id
+integer (int32)
+
+
+
+
+
+
2.3.2. Responses
+
+
+
+
+
+
+
+
+HTTP Code
+Description
+Schema
+
+
+
+
+200
+OK
+Book
+
+
+401
+Unauthorized
+No Content
+
+
+403
+Forbidden
+No Content
+
+
+404
+Not Found
+No Content
+
+
+
+
+
+
+
+
+
2.3.6. Security
+
+
+
+
+
+
+
+Type
+Name
+
+
+
+
+apiKey
+api_key
+
+
+
+
+
+
+
2.4. 获取全部分类
+
+
+
2.4.1. Responses
+
+
+
+
+
+
+
+
+HTTP Code
+Description
+Schema
+
+
+
+
+200
+OK
+< Category > array
+
+
+401
+Unauthorized
+No Content
+
+
+403
+Forbidden
+No Content
+
+
+404
+Not Found
+No Content
+
+
+
+
+
+
+
+
+
+
2.5. 根据ID获取分类
+
+
+
2.5.1. Parameters
+
+
+
+
+
+
+
+
+
+Type
+Name
+Description
+Schema
+
+
+
+
+Path
+id
+required
+id
+integer (int32)
+
+
+
+
+
+
2.5.2. Responses
+
+
+
+
+
+
+
+
+HTTP Code
+Description
+Schema
+
+
+
+
+200
+OK
+Category
+
+
+401
+Unauthorized
+No Content
+
+
+403
+Forbidden
+No Content
+
+
+404
+Not Found
+No Content
+
+
+
+
+
+
+
+
+
+
+
+
3. Definitions
+
+
+
3.1. Book
+
+
+
+
+
+
+
+
+Name
+Description
+Schema
+
+
+
+
+author
+optional
+作者
+string
+
+
+categoryId
+optional
+
+integer (int32)
+
+
+id
+optional
+
+integer (int32)
+
+
+name
+optional
+书名
+string
+
+
+
+
+
+
3.2. Category
+
+
+
+
+
+
+
+Name
+Schema
+
+
+
+
+id
+optional
+integer (int32)
+
+
+name
+optional
+string
+
+
+
+
+
+
+
+
4. Security
+
+
+
4.1. api_key
+
+
Type : apiKey
+Name : api_key
+In : HEADER
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/mvnw b/mvnw
new file mode 100644
index 0000000..5bf251c
--- /dev/null
+++ b/mvnw
@@ -0,0 +1,225 @@
+#!/bin/sh
+# ----------------------------------------------------------------------------
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you 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.
+# ----------------------------------------------------------------------------
+
+# ----------------------------------------------------------------------------
+# Maven2 Start Up Batch script
+#
+# Required ENV vars:
+# ------------------
+# JAVA_HOME - location of a JDK home dir
+#
+# Optional ENV vars
+# -----------------
+# M2_HOME - location of maven2's installed home dir
+# MAVEN_OPTS - parameters passed to the Java VM when running Maven
+# e.g. to debug Maven itself, use
+# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
+# MAVEN_SKIP_RC - flag to disable loading of mavenrc files
+# ----------------------------------------------------------------------------
+
+if [ -z "$MAVEN_SKIP_RC" ] ; then
+
+ if [ -f /etc/mavenrc ] ; then
+ . /etc/mavenrc
+ fi
+
+ if [ -f "$HOME/.mavenrc" ] ; then
+ . "$HOME/.mavenrc"
+ fi
+
+fi
+
+# OS specific support. $var _must_ be set to either true or false.
+cygwin=false;
+darwin=false;
+mingw=false
+case "`uname`" in
+ CYGWIN*) cygwin=true ;;
+ MINGW*) mingw=true;;
+ Darwin*) darwin=true
+ # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home
+ # See https://developer.apple.com/library/mac/qa/qa1170/_index.html
+ if [ -z "$JAVA_HOME" ]; then
+ if [ -x "/usr/libexec/java_home" ]; then
+ export JAVA_HOME="`/usr/libexec/java_home`"
+ else
+ export JAVA_HOME="/Library/Java/Home"
+ fi
+ fi
+ ;;
+esac
+
+if [ -z "$JAVA_HOME" ] ; then
+ if [ -r /etc/gentoo-release ] ; then
+ JAVA_HOME=`java-config --jre-home`
+ fi
+fi
+
+if [ -z "$M2_HOME" ] ; then
+ ## resolve links - $0 may be a link to maven's home
+ PRG="$0"
+
+ # need this for relative symlinks
+ while [ -h "$PRG" ] ; do
+ ls=`ls -ld "$PRG"`
+ link=`expr "$ls" : '.*-> \(.*\)$'`
+ if expr "$link" : '/.*' > /dev/null; then
+ PRG="$link"
+ else
+ PRG="`dirname "$PRG"`/$link"
+ fi
+ done
+
+ saveddir=`pwd`
+
+ M2_HOME=`dirname "$PRG"`/..
+
+ # make it fully qualified
+ M2_HOME=`cd "$M2_HOME" && pwd`
+
+ cd "$saveddir"
+ # echo Using m2 at $M2_HOME
+fi
+
+# For Cygwin, ensure paths are in UNIX format before anything is touched
+if $cygwin ; then
+ [ -n "$M2_HOME" ] &&
+ M2_HOME=`cygpath --unix "$M2_HOME"`
+ [ -n "$JAVA_HOME" ] &&
+ JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
+ [ -n "$CLASSPATH" ] &&
+ CLASSPATH=`cygpath --path --unix "$CLASSPATH"`
+fi
+
+# For Migwn, ensure paths are in UNIX format before anything is touched
+if $mingw ; then
+ [ -n "$M2_HOME" ] &&
+ M2_HOME="`(cd "$M2_HOME"; pwd)`"
+ [ -n "$JAVA_HOME" ] &&
+ JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`"
+ # TODO classpath?
+fi
+
+if [ -z "$JAVA_HOME" ]; then
+ javaExecutable="`which javac`"
+ if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then
+ # readlink(1) is not available as standard on Solaris 10.
+ readLink=`which readlink`
+ if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then
+ if $darwin ; then
+ javaHome="`dirname \"$javaExecutable\"`"
+ javaExecutable="`cd \"$javaHome\" && pwd -P`/javac"
+ else
+ javaExecutable="`readlink -f \"$javaExecutable\"`"
+ fi
+ javaHome="`dirname \"$javaExecutable\"`"
+ javaHome=`expr "$javaHome" : '\(.*\)/bin'`
+ JAVA_HOME="$javaHome"
+ export JAVA_HOME
+ fi
+ fi
+fi
+
+if [ -z "$JAVACMD" ] ; then
+ if [ -n "$JAVA_HOME" ] ; then
+ if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
+ # IBM's JDK on AIX uses strange locations for the executables
+ JAVACMD="$JAVA_HOME/jre/sh/java"
+ else
+ JAVACMD="$JAVA_HOME/bin/java"
+ fi
+ else
+ JAVACMD="`which java`"
+ fi
+fi
+
+if [ ! -x "$JAVACMD" ] ; then
+ echo "Error: JAVA_HOME is not defined correctly." >&2
+ echo " We cannot execute $JAVACMD" >&2
+ exit 1
+fi
+
+if [ -z "$JAVA_HOME" ] ; then
+ echo "Warning: JAVA_HOME environment variable is not set."
+fi
+
+CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher
+
+# traverses directory structure from process work directory to filesystem root
+# first directory with .mvn subdirectory is considered project base directory
+find_maven_basedir() {
+
+ if [ -z "$1" ]
+ then
+ echo "Path not specified to find_maven_basedir"
+ return 1
+ fi
+
+ basedir="$1"
+ wdir="$1"
+ while [ "$wdir" != '/' ] ; do
+ if [ -d "$wdir"/.mvn ] ; then
+ basedir=$wdir
+ break
+ fi
+ # workaround for JBEAP-8937 (on Solaris 10/Sparc)
+ if [ -d "${wdir}" ]; then
+ wdir=`cd "$wdir/.."; pwd`
+ fi
+ # end of workaround
+ done
+ echo "${basedir}"
+}
+
+# concatenates all lines of a file
+concat_lines() {
+ if [ -f "$1" ]; then
+ echo "$(tr -s '\n' ' ' < "$1")"
+ fi
+}
+
+BASE_DIR=`find_maven_basedir "$(pwd)"`
+if [ -z "$BASE_DIR" ]; then
+ exit 1;
+fi
+
+export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}
+echo $MAVEN_PROJECTBASEDIR
+MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
+
+# For Cygwin, switch paths to Windows format before running java
+if $cygwin; then
+ [ -n "$M2_HOME" ] &&
+ M2_HOME=`cygpath --path --windows "$M2_HOME"`
+ [ -n "$JAVA_HOME" ] &&
+ JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"`
+ [ -n "$CLASSPATH" ] &&
+ CLASSPATH=`cygpath --path --windows "$CLASSPATH"`
+ [ -n "$MAVEN_PROJECTBASEDIR" ] &&
+ MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"`
+fi
+
+WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
+
+exec "$JAVACMD" \
+ $MAVEN_OPTS \
+ -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
+ "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
+ ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@"
diff --git a/mvnw.cmd b/mvnw.cmd
new file mode 100644
index 0000000..019bd74
--- /dev/null
+++ b/mvnw.cmd
@@ -0,0 +1,143 @@
+@REM ----------------------------------------------------------------------------
+@REM Licensed to the Apache Software Foundation (ASF) under one
+@REM or more contributor license agreements. See the NOTICE file
+@REM distributed with this work for additional information
+@REM regarding copyright ownership. The ASF licenses this file
+@REM to you under the Apache License, Version 2.0 (the
+@REM "License"); you may not use this file except in compliance
+@REM with the License. You may obtain a copy of the License at
+@REM
+@REM http://www.apache.org/licenses/LICENSE-2.0
+@REM
+@REM Unless required by applicable law or agreed to in writing,
+@REM software distributed under the License is distributed on an
+@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+@REM KIND, either express or implied. See the License for the
+@REM specific language governing permissions and limitations
+@REM under the License.
+@REM ----------------------------------------------------------------------------
+
+@REM ----------------------------------------------------------------------------
+@REM Maven2 Start Up Batch script
+@REM
+@REM Required ENV vars:
+@REM JAVA_HOME - location of a JDK home dir
+@REM
+@REM Optional ENV vars
+@REM M2_HOME - location of maven2's installed home dir
+@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
+@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending
+@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
+@REM e.g. to debug Maven itself, use
+@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
+@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
+@REM ----------------------------------------------------------------------------
+
+@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
+@echo off
+@REM enable echoing my setting MAVEN_BATCH_ECHO to 'on'
+@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
+
+@REM set %HOME% to equivalent of $HOME
+if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
+
+@REM Execute a user defined script before this one
+if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
+@REM check for pre script, once with legacy .bat ending and once with .cmd ending
+if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat"
+if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd"
+:skipRcPre
+
+@setlocal
+
+set ERROR_CODE=0
+
+@REM To isolate internal variables from possible post scripts, we use another setlocal
+@setlocal
+
+@REM ==== START VALIDATION ====
+if not "%JAVA_HOME%" == "" goto OkJHome
+
+echo.
+echo Error: JAVA_HOME not found in your environment. >&2
+echo Please set the JAVA_HOME variable in your environment to match the >&2
+echo location of your Java installation. >&2
+echo.
+goto error
+
+:OkJHome
+if exist "%JAVA_HOME%\bin\java.exe" goto init
+
+echo.
+echo Error: JAVA_HOME is set to an invalid directory. >&2
+echo JAVA_HOME = "%JAVA_HOME%" >&2
+echo Please set the JAVA_HOME variable in your environment to match the >&2
+echo location of your Java installation. >&2
+echo.
+goto error
+
+@REM ==== END VALIDATION ====
+
+:init
+
+@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
+@REM Fallback to current working directory if not found.
+
+set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
+IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
+
+set EXEC_DIR=%CD%
+set WDIR=%EXEC_DIR%
+:findBaseDir
+IF EXIST "%WDIR%"\.mvn goto baseDirFound
+cd ..
+IF "%WDIR%"=="%CD%" goto baseDirNotFound
+set WDIR=%CD%
+goto findBaseDir
+
+:baseDirFound
+set MAVEN_PROJECTBASEDIR=%WDIR%
+cd "%EXEC_DIR%"
+goto endDetectBaseDir
+
+:baseDirNotFound
+set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
+cd "%EXEC_DIR%"
+
+:endDetectBaseDir
+
+IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
+
+@setlocal EnableExtensions EnableDelayedExpansion
+for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
+@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
+
+:endReadAdditionalConfig
+
+SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
+
+set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
+set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
+
+%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
+if ERRORLEVEL 1 goto error
+goto end
+
+:error
+set ERROR_CODE=1
+
+:end
+@endlocal & set ERROR_CODE=%ERROR_CODE%
+
+if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost
+@REM check for post script, once with legacy .bat ending and once with .cmd ending
+if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat"
+if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd"
+:skipRcPost
+
+@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
+if "%MAVEN_BATCH_PAUSE%" == "on" pause
+
+if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE%
+
+exit /B %ERROR_CODE%
diff --git a/pom.xml b/pom.xml
new file mode 100644
index 0000000..f0860a4
--- /dev/null
+++ b/pom.xml
@@ -0,0 +1,39 @@
+
+
+ 4.0.0
+
+ com.example
+ swagger-example
+ 1.0.0
+ pom
+
+ swagger-example
+ Demo project for Spring Boot
+
+
+ org.springframework.boot
+ spring-boot-starter-parent
+ 1.5.8.RELEASE
+
+
+
+
+ swagger-server
+
+
+
+ UTF-8
+ UTF-8
+ 1.8
+
+
+
+
+
+ org.springframework.boot
+ spring-boot-maven-plugin
+
+
+
+
diff --git a/server/jaxrs-resteasy/.swagger-codegen-ignore b/server/jaxrs-resteasy/.swagger-codegen-ignore
new file mode 100644
index 0000000..c5fa491
--- /dev/null
+++ b/server/jaxrs-resteasy/.swagger-codegen-ignore
@@ -0,0 +1,23 @@
+# Swagger Codegen Ignore
+# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen
+
+# Use this file to prevent files from being overwritten by the generator.
+# The patterns follow closely to .gitignore or .dockerignore.
+
+# As an example, the C# client generator defines ApiClient.cs.
+# You can make changes and tell Swagger Codgen to ignore just this file by uncommenting the following line:
+#ApiClient.cs
+
+# You can match any string of characters against a directory, file or extension with a single asterisk (*):
+#foo/*/qux
+# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux
+
+# You can recursively match patterns against a directory, file or extension with a double asterisk (**):
+#foo/**/qux
+# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux
+
+# You can also negate patterns with an exclamation (!).
+# For example, you can ignore all files in a docs folder with the file extension .md:
+#docs/*.md
+# Then explicitly reverse the ignore rule for a single file:
+#!docs/README.md
diff --git a/server/jaxrs-resteasy/.swagger-codegen/VERSION b/server/jaxrs-resteasy/.swagger-codegen/VERSION
new file mode 100644
index 0000000..717311e
--- /dev/null
+++ b/server/jaxrs-resteasy/.swagger-codegen/VERSION
@@ -0,0 +1 @@
+unset
\ No newline at end of file
diff --git a/server/jaxrs-resteasy/README.md b/server/jaxrs-resteasy/README.md
new file mode 100644
index 0000000..78fa5ef
--- /dev/null
+++ b/server/jaxrs-resteasy/README.md
@@ -0,0 +1,23 @@
+# Swagger generated server
+
+## Overview
+This server was generated by the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project. By using the
+[OpenAPI-Spec](https://github.com/swagger-api/swagger-core/wiki) from a remote server, you can easily generate a server stub. This
+is an example of building a swagger-enabled JAX-RS server.
+
+This example uses the [JAX-RS](https://jax-rs-spec.java.net/) framework.
+
+To run the server, please execute the following:
+
+```
+mvn clean package jetty:run
+```
+
+You can then view the swagger listing here:
+
+```
+http://localhost:8080/swagger.json
+```
+
+Note that if you have configured the `host` to be something other than localhost, the calls through
+swagger-ui will be directed to that host and not localhost!
\ No newline at end of file
diff --git a/server/jaxrs-resteasy/build.gradle b/server/jaxrs-resteasy/build.gradle
new file mode 100644
index 0000000..0f0104c
--- /dev/null
+++ b/server/jaxrs-resteasy/build.gradle
@@ -0,0 +1,28 @@
+apply plugin: 'war'
+
+project.version = "1.0.0"
+project.group = "com.example"
+
+repositories {
+ mavenCentral()
+}
+
+dependencies {
+ providedCompile 'org.jboss.resteasy:resteasy-jaxrs:3.0.11.Final'
+ providedCompile 'org.jboss.resteasy:jaxrs-api:3.0.11.Final'
+ providedCompile 'org.jboss.resteasy:resteasy-validator-provider-11:3.0.11.Final'
+ providedCompile 'org.jboss.resteasy:resteasy-multipart-provider:3.0.11.Final'
+ providedCompile 'javax.annotation:javax.annotation-api:1.2'
+ providedCompile 'org.jboss.spec.javax.servlet:jboss-servlet-api_3.0_spec:1.0.0.Final'
+ compile 'org.jboss.resteasy:resteasy-jackson2-provider:3.0.11.Final'
+ testCompile 'junit:junit:4.12',
+ 'org.hamcrest:hamcrest-core:1.3'
+}
+
+sourceSets {
+ main {
+ java {
+ srcDir 'src/gen/java'
+ }
+ }
+}
diff --git a/server/jaxrs-resteasy/pom.xml b/server/jaxrs-resteasy/pom.xml
new file mode 100644
index 0000000..1f9d357
--- /dev/null
+++ b/server/jaxrs-resteasy/pom.xml
@@ -0,0 +1,167 @@
+
+ 4.0.0
+ com.example
+ swagger-client-java
+ war
+ swagger-client-java
+ 1.0.0
+
+ src/main/java
+
+
+ org.apache.maven.plugins
+ maven-war-plugin
+ 3.1.0
+
+
+ maven-failsafe-plugin
+ 2.6
+
+
+
+ integration-test
+ verify
+
+
+
+
+
+ org.codehaus.mojo
+ build-helper-maven-plugin
+ 1.9.1
+
+
+ add-source
+ generate-sources
+
+ add-source
+
+
+
+
+ src/gen/java
+
+
+
+
+
+
+
+
+
+ org.slf4j
+ slf4j-log4j12
+ ${slf4j-version}
+
+
+ javax.servlet
+ servlet-api
+ ${servlet-api-version}
+ provided
+
+
+
+ org.jboss.resteasy
+ resteasy-jaxrs
+ ${resteasy-version}
+ provided
+
+
+ org.jboss.resteasy
+ jaxrs-api
+ ${resteasy-version}
+ provided
+
+
+ org.jboss.resteasy
+ resteasy-validator-provider-11
+ ${resteasy-version}
+ provided
+
+
+ org.jboss.resteasy
+ resteasy-multipart-provider
+ ${resteasy-version}
+ provided
+
+
+ org.jboss.resteasy
+ resteasy-jackson2-provider
+ ${resteasy-version}
+
+
+ javax.annotation
+ javax.annotation-api
+ 1.2
+ provided
+
+
+
+ com.fasterxml.jackson.datatype
+ jackson-datatype-joda
+ 2.4.1
+
+
+ joda-time
+ joda-time
+ 2.7
+
+
+ io.swagger
+ swagger-jaxrs
+ ${swagger-core-version}
+
+
+ junit
+ junit
+ ${junit-version}
+ test
+
+
+ org.testng
+ testng
+ 6.8.8
+ test
+
+
+ junit
+ junit
+
+
+ snakeyaml
+ org.yaml
+
+
+ bsh
+ org.beanshell
+
+
+
+
+
+ javax.validation
+ validation-api
+ 1.1.0.Final
+ provided
+
+
+
+
+
+ sonatype-snapshots
+ https://oss.sonatype.org/content/repositories/snapshots
+
+ true
+
+
+
+
+ 1.5.15
+ 9.2.9.v20150224
+ 3.0.11.Final
+ 1.6.3
+ 4.8.1
+ 2.5
+
+
diff --git a/server/jaxrs-resteasy/settings.gradle b/server/jaxrs-resteasy/settings.gradle
new file mode 100644
index 0000000..8f30e98
--- /dev/null
+++ b/server/jaxrs-resteasy/settings.gradle
@@ -0,0 +1 @@
+rootProject.name = "swagger-client-java"
\ No newline at end of file
diff --git a/server/jaxrs-resteasy/src/gen/java/io/swagger/api/ApiException.java b/server/jaxrs-resteasy/src/gen/java/io/swagger/api/ApiException.java
new file mode 100644
index 0000000..d007232
--- /dev/null
+++ b/server/jaxrs-resteasy/src/gen/java/io/swagger/api/ApiException.java
@@ -0,0 +1,10 @@
+package io.swagger.api;
+
+@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaResteasyServerCodegen", date = "2017-11-09T10:58:42.375+08:00")
+public class ApiException extends Exception{
+ private int code;
+ public ApiException (int code, String msg) {
+ super(msg);
+ this.code = code;
+ }
+}
diff --git a/server/jaxrs-resteasy/src/gen/java/io/swagger/api/ApiOriginFilter.java b/server/jaxrs-resteasy/src/gen/java/io/swagger/api/ApiOriginFilter.java
new file mode 100644
index 0000000..fc168ff
--- /dev/null
+++ b/server/jaxrs-resteasy/src/gen/java/io/swagger/api/ApiOriginFilter.java
@@ -0,0 +1,22 @@
+package io.swagger.api;
+
+import java.io.IOException;
+
+import javax.servlet.*;
+import javax.servlet.http.HttpServletResponse;
+
+@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaResteasyServerCodegen", date = "2017-11-09T10:58:42.375+08:00")
+public class ApiOriginFilter implements javax.servlet.Filter {
+ public void doFilter(ServletRequest request, ServletResponse response,
+ FilterChain chain) throws IOException, ServletException {
+ HttpServletResponse res = (HttpServletResponse) response;
+ res.addHeader("Access-Control-Allow-Origin", "*");
+ res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
+ res.addHeader("Access-Control-Allow-Headers", "Content-Type");
+ chain.doFilter(request, response);
+ }
+
+ public void destroy() {}
+
+ public void init(FilterConfig filterConfig) throws ServletException {}
+}
diff --git a/server/jaxrs-resteasy/src/gen/java/io/swagger/api/ApiResponseMessage.java b/server/jaxrs-resteasy/src/gen/java/io/swagger/api/ApiResponseMessage.java
new file mode 100644
index 0000000..ed6677a
--- /dev/null
+++ b/server/jaxrs-resteasy/src/gen/java/io/swagger/api/ApiResponseMessage.java
@@ -0,0 +1,69 @@
+package io.swagger.api;
+
+import javax.xml.bind.annotation.XmlTransient;
+
+@javax.xml.bind.annotation.XmlRootElement
+@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaResteasyServerCodegen", date = "2017-11-09T10:58:42.375+08:00")
+public class ApiResponseMessage {
+ public static final int ERROR = 1;
+ public static final int WARNING = 2;
+ public static final int INFO = 3;
+ public static final int OK = 4;
+ public static final int TOO_BUSY = 5;
+
+ int code;
+ String type;
+ String message;
+
+ public ApiResponseMessage(){}
+
+ public ApiResponseMessage(int code, String message){
+ this.code = code;
+ switch(code){
+ case ERROR:
+ setType("error");
+ break;
+ case WARNING:
+ setType("warning");
+ break;
+ case INFO:
+ setType("info");
+ break;
+ case OK:
+ setType("ok");
+ break;
+ case TOO_BUSY:
+ setType("too busy");
+ break;
+ default:
+ setType("unknown");
+ break;
+ }
+ this.message = message;
+ }
+
+ @XmlTransient
+ public int getCode() {
+ return code;
+ }
+
+ public void setCode(int code) {
+ this.code = code;
+ }
+
+ public String getType() {
+ return type;
+ }
+
+ public void setType(String type) {
+ this.type = type;
+ }
+
+ public String getMessage() {
+ return message;
+ }
+
+ public void setMessage(String message) {
+ this.message = message;
+ }
+}
diff --git a/server/jaxrs-resteasy/src/gen/java/io/swagger/api/JacksonConfig.java b/server/jaxrs-resteasy/src/gen/java/io/swagger/api/JacksonConfig.java
new file mode 100644
index 0000000..d19c912
--- /dev/null
+++ b/server/jaxrs-resteasy/src/gen/java/io/swagger/api/JacksonConfig.java
@@ -0,0 +1,47 @@
+package io.swagger.api;
+
+import com.fasterxml.jackson.core.JsonGenerationException;
+import com.fasterxml.jackson.core.JsonGenerator;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.SerializerProvider;
+import com.fasterxml.jackson.databind.ser.std.StdSerializer;
+import com.fasterxml.jackson.datatype.joda.JodaModule;
+import org.joda.time.DateTime;
+import org.joda.time.LocalDate;
+import org.joda.time.format.ISODateTimeFormat;
+
+import javax.ws.rs.ext.ContextResolver;
+import javax.ws.rs.ext.Provider;
+import java.io.IOException;
+
+@Provider
+public class JacksonConfig implements ContextResolver {
+ private final ObjectMapper objectMapper;
+
+ public JacksonConfig() throws Exception {
+
+ objectMapper = new ObjectMapper()
+ .setDateFormat(new RFC3339DateFormat())
+ .registerModule(new JodaModule() {
+ {
+ addSerializer(DateTime.class, new StdSerializer(DateTime.class) {
+ @Override
+ public void serialize(DateTime value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonGenerationException {
+ jgen.writeString(ISODateTimeFormat.dateTimeNoMillis().print(value));
+ }
+ });
+ addSerializer(LocalDate.class, new StdSerializer(LocalDate.class) {
+ @Override
+ public void serialize(LocalDate value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonGenerationException {
+ jgen.writeString(ISODateTimeFormat.date().print(value));
+ }
+ });
+
+ }
+ });
+ }
+
+ public ObjectMapper getContext(Class> arg0) {
+ return objectMapper;
+ }
+}
\ No newline at end of file
diff --git a/server/jaxrs-resteasy/src/gen/java/io/swagger/api/LocalDateProvider.java b/server/jaxrs-resteasy/src/gen/java/io/swagger/api/LocalDateProvider.java
new file mode 100644
index 0000000..ed287ac
--- /dev/null
+++ b/server/jaxrs-resteasy/src/gen/java/io/swagger/api/LocalDateProvider.java
@@ -0,0 +1,31 @@
+package io.swagger.api;
+
+import java.time.LocalDate;
+import javax.ws.rs.ext.ParamConverter;
+import javax.ws.rs.ext.ParamConverterProvider;
+import javax.ws.rs.ext.Provider;
+import java.lang.annotation.Annotation;
+import java.lang.reflect.Type;
+
+@Provider
+public class LocalDateProvider implements ParamConverterProvider {
+
+ public static class LocalDateConverter implements ParamConverter {
+
+ public LocalDate fromString(String string) {
+ LocalDate localDate = LocalDate.parse(string);
+ return localDate;
+ }
+
+ public String toString(LocalDate t) {
+ return t.toString();
+ }
+ }
+
+ public ParamConverter getConverter(Class type, Type type1, Annotation[] antns) {
+ if (LocalDate.class.equals(type)) {
+ return (ParamConverter) new LocalDateConverter();
+ }
+ return null;
+ }
+}
\ No newline at end of file
diff --git a/server/jaxrs-resteasy/src/gen/java/io/swagger/api/NotFoundException.java b/server/jaxrs-resteasy/src/gen/java/io/swagger/api/NotFoundException.java
new file mode 100644
index 0000000..659ca80
--- /dev/null
+++ b/server/jaxrs-resteasy/src/gen/java/io/swagger/api/NotFoundException.java
@@ -0,0 +1,10 @@
+package io.swagger.api;
+
+@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaResteasyServerCodegen", date = "2017-11-09T10:58:42.375+08:00")
+public class NotFoundException extends ApiException {
+ private int code;
+ public NotFoundException (int code, String msg) {
+ super(code, msg);
+ this.code = code;
+ }
+}
diff --git a/server/jaxrs-resteasy/src/gen/java/io/swagger/api/OffsetDateTimeProvider.java b/server/jaxrs-resteasy/src/gen/java/io/swagger/api/OffsetDateTimeProvider.java
new file mode 100644
index 0000000..cb9f2c6
--- /dev/null
+++ b/server/jaxrs-resteasy/src/gen/java/io/swagger/api/OffsetDateTimeProvider.java
@@ -0,0 +1,31 @@
+package io.swagger.api;
+
+import java.time.OffsetDateTime;
+import javax.ws.rs.ext.ParamConverter;
+import javax.ws.rs.ext.ParamConverterProvider;
+import javax.ws.rs.ext.Provider;
+import java.lang.annotation.Annotation;
+import java.lang.reflect.Type;
+
+@Provider
+public class OffsetDateTimeProvider implements ParamConverterProvider {
+
+ public static class OffsetDateTimeConverter implements ParamConverter {
+
+ public OffsetDateTime fromString(String string) {
+ OffsetDateTime offsetDateTime = OffsetDateTime.parse(string);
+ return offsetDateTime;
+ }
+
+ public String toString(OffsetDateTime t) {
+ return t.toString();
+ }
+ }
+
+ public ParamConverter getConverter(Class type, Type type1, Annotation[] antns) {
+ if (OffsetDateTime.class.equals(type)) {
+ return (ParamConverter) new OffsetDateTimeConverter();
+ }
+ return null;
+ }
+}
\ No newline at end of file
diff --git a/server/jaxrs-resteasy/src/gen/java/io/swagger/api/RFC3339DateFormat.java b/server/jaxrs-resteasy/src/gen/java/io/swagger/api/RFC3339DateFormat.java
new file mode 100644
index 0000000..7c9e260
--- /dev/null
+++ b/server/jaxrs-resteasy/src/gen/java/io/swagger/api/RFC3339DateFormat.java
@@ -0,0 +1,19 @@
+package io.swagger.api;
+
+import com.fasterxml.jackson.databind.util.ISO8601DateFormat;
+import com.fasterxml.jackson.databind.util.ISO8601Utils;
+
+import java.text.FieldPosition;
+import java.util.Date;
+
+public class RFC3339DateFormat extends ISO8601DateFormat {
+
+ // Same as ISO8601DateFormat but serializing milliseconds.
+ @Override
+ public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) {
+ String value = ISO8601Utils.format(date, true);
+ toAppendTo.append(value);
+ return toAppendTo;
+ }
+
+}
\ No newline at end of file
diff --git a/server/jaxrs-resteasy/src/gen/java/io/swagger/api/RestApplication.java b/server/jaxrs-resteasy/src/gen/java/io/swagger/api/RestApplication.java
new file mode 100644
index 0000000..24aa63c
--- /dev/null
+++ b/server/jaxrs-resteasy/src/gen/java/io/swagger/api/RestApplication.java
@@ -0,0 +1,9 @@
+package io.swagger.api;
+
+import javax.ws.rs.ApplicationPath;
+import javax.ws.rs.core.Application;
+
+@ApplicationPath("/")
+public class RestApplication extends Application {
+
+}
\ No newline at end of file
diff --git a/server/jaxrs-resteasy/src/gen/java/io/swagger/api/StringUtil.java b/server/jaxrs-resteasy/src/gen/java/io/swagger/api/StringUtil.java
new file mode 100644
index 0000000..69e166e
--- /dev/null
+++ b/server/jaxrs-resteasy/src/gen/java/io/swagger/api/StringUtil.java
@@ -0,0 +1,42 @@
+package io.swagger.api;
+
+@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaResteasyServerCodegen", date = "2017-11-09T10:58:42.375+08:00")
+public class StringUtil {
+ /**
+ * Check if the given array contains the given value (with case-insensitive comparison).
+ *
+ * @param array The array
+ * @param value The value to search
+ * @return true if the array contains the value
+ */
+ public static boolean containsIgnoreCase(String[] array, String value) {
+ for (String str : array) {
+ if (value == null && str == null) return true;
+ if (value != null && value.equalsIgnoreCase(str)) return true;
+ }
+ return false;
+ }
+
+ /**
+ * Join an array of strings with the given separator.
+ *
+ * Note: This might be replaced by utility method from commons-lang or guava someday
+ * if one of those libraries is added as dependency.
+ *
+ *
+ * @param array The array of strings
+ * @param separator The separator
+ * @return the resulting string
+ */
+ public static String join(String[] array, String separator) {
+ int len = array.length;
+ if (len == 0) return "";
+
+ StringBuilder out = new StringBuilder();
+ out.append(array[0]);
+ for (int i = 1; i < len; i++) {
+ out.append(separator).append(array[i]);
+ }
+ return out.toString();
+ }
+}
diff --git a/server/jaxrs-resteasy/src/gen/java/io/swagger/api/V1Api.java b/server/jaxrs-resteasy/src/gen/java/io/swagger/api/V1Api.java
new file mode 100644
index 0000000..1784978
--- /dev/null
+++ b/server/jaxrs-resteasy/src/gen/java/io/swagger/api/V1Api.java
@@ -0,0 +1,125 @@
+package io.swagger.api;
+
+import io.swagger.model.*;
+import io.swagger.api.V1ApiService;
+import io.swagger.api.factories.V1ApiServiceFactory;
+
+import io.swagger.annotations.ApiParam;
+import io.swagger.jaxrs.*;
+
+import io.swagger.model.Book;
+import io.swagger.model.Category;
+
+import java.util.List;
+import io.swagger.api.NotFoundException;
+
+import java.io.InputStream;
+
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.SecurityContext;
+import javax.ws.rs.*;
+import javax.validation.constraints.*;
+
+@Path("/v1")
+
+
+@io.swagger.annotations.Api(description = "the v1 API")
+@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaResteasyServerCodegen", date = "2017-11-09T10:58:42.375+08:00")
+public class V1Api {
+ private final V1ApiService delegate = V1ApiServiceFactory.getV1Api();
+
+ @GET
+ @Path("/category/")
+ @Consumes({ "application/json" })
+ @Produces({ "*/*" })
+ @io.swagger.annotations.ApiOperation(value = "获取全部分类", notes = "", response = Category.class, responseContainer = "List", tags={ "category-api", })
+ @io.swagger.annotations.ApiResponses(value = {
+ @io.swagger.annotations.ApiResponse(code = 200, message = "OK", response = Category.class, responseContainer = "List"),
+
+ @io.swagger.annotations.ApiResponse(code = 401, message = "Unauthorized", response = Category.class, responseContainer = "List"),
+
+ @io.swagger.annotations.ApiResponse(code = 403, message = "Forbidden", response = Category.class, responseContainer = "List"),
+
+ @io.swagger.annotations.ApiResponse(code = 404, message = "Not Found", response = Category.class, responseContainer = "List") })
+ public Response getAllUsingGET(@Context SecurityContext securityContext)
+ throws NotFoundException {
+ return delegate.getAllUsingGET(securityContext);
+ }
+ @GET
+ @Path("/book/{id}")
+ @Consumes({ "application/json" })
+ @Produces({ "*/*" })
+ @io.swagger.annotations.ApiOperation(value = "根据ID获取书籍", notes = "", response = Book.class, authorizations = {
+ @io.swagger.annotations.Authorization(value = "api_key")
+ }, tags={ "book-api", })
+ @io.swagger.annotations.ApiResponses(value = {
+ @io.swagger.annotations.ApiResponse(code = 200, message = "OK", response = Book.class),
+
+ @io.swagger.annotations.ApiResponse(code = 401, message = "Unauthorized", response = Book.class),
+
+ @io.swagger.annotations.ApiResponse(code = 403, message = "Forbidden", response = Book.class),
+
+ @io.swagger.annotations.ApiResponse(code = 404, message = "Not Found", response = Book.class) })
+ public Response getBookByIdUsingGET( @PathParam("id") Integer id,@Context SecurityContext securityContext)
+ throws NotFoundException {
+ return delegate.getBookByIdUsingGET(id,securityContext);
+ }
+ @GET
+ @Path("/book/getByCategoryId")
+ @Consumes({ "application/json" })
+ @Produces({ "*/*" })
+ @io.swagger.annotations.ApiOperation(value = "根据分类获取书籍", notes = "", response = Book.class, responseContainer = "List", authorizations = {
+ @io.swagger.annotations.Authorization(value = "api_key")
+ }, tags={ "book-api", })
+ @io.swagger.annotations.ApiResponses(value = {
+ @io.swagger.annotations.ApiResponse(code = 200, message = "OK", response = Book.class, responseContainer = "List"),
+
+ @io.swagger.annotations.ApiResponse(code = 401, message = "Unauthorized", response = Book.class, responseContainer = "List"),
+
+ @io.swagger.annotations.ApiResponse(code = 403, message = "Forbidden", response = Book.class, responseContainer = "List"),
+
+ @io.swagger.annotations.ApiResponse(code = 404, message = "Not Found", response = Book.class, responseContainer = "List") })
+ public Response getBooksByCategoryUsingGET( @NotNull @QueryParam("id") Integer id,@Context SecurityContext securityContext)
+ throws NotFoundException {
+ return delegate.getBooksByCategoryUsingGET(id,securityContext);
+ }
+ @GET
+ @Path("/category/{id}")
+ @Consumes({ "application/json" })
+ @Produces({ "*/*" })
+ @io.swagger.annotations.ApiOperation(value = "根据ID获取分类", notes = "", response = Category.class, tags={ "category-api", })
+ @io.swagger.annotations.ApiResponses(value = {
+ @io.swagger.annotations.ApiResponse(code = 200, message = "OK", response = Category.class),
+
+ @io.swagger.annotations.ApiResponse(code = 401, message = "Unauthorized", response = Category.class),
+
+ @io.swagger.annotations.ApiResponse(code = 403, message = "Forbidden", response = Category.class),
+
+ @io.swagger.annotations.ApiResponse(code = 404, message = "Not Found", response = Category.class) })
+ public Response getUsingGET( @PathParam("id") Integer id,@Context SecurityContext securityContext)
+ throws NotFoundException {
+ return delegate.getUsingGET(id,securityContext);
+ }
+ @POST
+ @Path("/book/update")
+ @Consumes({ "application/json" })
+ @Produces({ "*/*" })
+ @io.swagger.annotations.ApiOperation(value = "更新书籍", notes = "", response = Boolean.class, authorizations = {
+ @io.swagger.annotations.Authorization(value = "api_key")
+ }, tags={ "book-api", })
+ @io.swagger.annotations.ApiResponses(value = {
+ @io.swagger.annotations.ApiResponse(code = 200, message = "OK", response = Boolean.class),
+
+ @io.swagger.annotations.ApiResponse(code = 201, message = "Created", response = Boolean.class),
+
+ @io.swagger.annotations.ApiResponse(code = 401, message = "Unauthorized", response = Boolean.class),
+
+ @io.swagger.annotations.ApiResponse(code = 403, message = "Forbidden", response = Boolean.class),
+
+ @io.swagger.annotations.ApiResponse(code = 404, message = "Not Found", response = Boolean.class) })
+ public Response updateUsingPOST(@ApiParam(value = "id" ) Integer id,@Context SecurityContext securityContext)
+ throws NotFoundException {
+ return delegate.updateUsingPOST(id,securityContext);
+ }
+}
diff --git a/server/jaxrs-resteasy/src/gen/java/io/swagger/api/V1ApiService.java b/server/jaxrs-resteasy/src/gen/java/io/swagger/api/V1ApiService.java
new file mode 100644
index 0000000..4f01be0
--- /dev/null
+++ b/server/jaxrs-resteasy/src/gen/java/io/swagger/api/V1ApiService.java
@@ -0,0 +1,30 @@
+package io.swagger.api;
+
+import io.swagger.api.*;
+import io.swagger.model.*;
+
+
+import io.swagger.model.Book;
+import io.swagger.model.Category;
+
+import java.util.List;
+import io.swagger.api.NotFoundException;
+
+import java.io.InputStream;
+
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.SecurityContext;
+
+@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaResteasyServerCodegen", date = "2017-11-09T10:58:42.375+08:00")
+public abstract class V1ApiService {
+ public abstract Response getAllUsingGET(SecurityContext securityContext)
+ throws NotFoundException;
+ public abstract Response getBookByIdUsingGET(Integer id,SecurityContext securityContext)
+ throws NotFoundException;
+ public abstract Response getBooksByCategoryUsingGET(Integer id,SecurityContext securityContext)
+ throws NotFoundException;
+ public abstract Response getUsingGET(Integer id,SecurityContext securityContext)
+ throws NotFoundException;
+ public abstract Response updateUsingPOST(Integer id,SecurityContext securityContext)
+ throws NotFoundException;
+}
diff --git a/server/jaxrs-resteasy/src/gen/java/io/swagger/model/Book.java b/server/jaxrs-resteasy/src/gen/java/io/swagger/model/Book.java
new file mode 100644
index 0000000..044f23d
--- /dev/null
+++ b/server/jaxrs-resteasy/src/gen/java/io/swagger/model/Book.java
@@ -0,0 +1,114 @@
+package io.swagger.model;
+
+import java.util.Objects;
+import java.util.ArrayList;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import com.fasterxml.jackson.annotation.JsonCreator;
+import javax.validation.constraints.*;
+import io.swagger.annotations.*;
+
+
+@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaResteasyServerCodegen", date = "2017-11-09T10:58:42.375+08:00")
+public class Book {
+
+ private String author = null;
+ private Integer categoryId = null;
+ private Integer id = null;
+ private String name = null;
+
+ /**
+ * 作者
+ **/
+
+ @ApiModelProperty(value = "作者")
+ @JsonProperty("author")
+ public String getAuthor() {
+ return author;
+ }
+ public void setAuthor(String author) {
+ this.author = author;
+ }
+
+ /**
+ **/
+
+ @ApiModelProperty(value = "")
+ @JsonProperty("categoryId")
+ public Integer getCategoryId() {
+ return categoryId;
+ }
+ public void setCategoryId(Integer categoryId) {
+ this.categoryId = categoryId;
+ }
+
+ /**
+ **/
+
+ @ApiModelProperty(value = "")
+ @JsonProperty("id")
+ public Integer getId() {
+ return id;
+ }
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ /**
+ * 书名
+ **/
+
+ @ApiModelProperty(value = "书名")
+ @JsonProperty("name")
+ public String getName() {
+ return name;
+ }
+ public void setName(String name) {
+ this.name = name;
+ }
+
+
+ @Override
+ public boolean equals(java.lang.Object o) {
+ if (this == o) {
+ return true;
+ }
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
+ Book book = (Book) o;
+ return Objects.equals(author, book.author) &&
+ Objects.equals(categoryId, book.categoryId) &&
+ Objects.equals(id, book.id) &&
+ Objects.equals(name, book.name);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(author, categoryId, id, name);
+ }
+
+ @Override
+ public String toString() {
+ StringBuilder sb = new StringBuilder();
+ sb.append("class Book {\n");
+
+ sb.append(" author: ").append(toIndentedString(author)).append("\n");
+ sb.append(" categoryId: ").append(toIndentedString(categoryId)).append("\n");
+ sb.append(" id: ").append(toIndentedString(id)).append("\n");
+ sb.append(" name: ").append(toIndentedString(name)).append("\n");
+ sb.append("}");
+ return sb.toString();
+ }
+
+ /**
+ * Convert the given object to string with each line indented by 4 spaces
+ * (except the first line).
+ */
+ private String toIndentedString(java.lang.Object o) {
+ if (o == null) {
+ return "null";
+ }
+ return o.toString().replace("\n", "\n ");
+ }
+}
+
diff --git a/server/jaxrs-resteasy/src/gen/java/io/swagger/model/Category.java b/server/jaxrs-resteasy/src/gen/java/io/swagger/model/Category.java
new file mode 100644
index 0000000..99c435b
--- /dev/null
+++ b/server/jaxrs-resteasy/src/gen/java/io/swagger/model/Category.java
@@ -0,0 +1,82 @@
+package io.swagger.model;
+
+import java.util.Objects;
+import java.util.ArrayList;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import com.fasterxml.jackson.annotation.JsonCreator;
+import javax.validation.constraints.*;
+import io.swagger.annotations.*;
+
+
+@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaResteasyServerCodegen", date = "2017-11-09T10:58:42.375+08:00")
+public class Category {
+
+ private Integer id = null;
+ private String name = null;
+
+ /**
+ **/
+
+ @ApiModelProperty(value = "")
+ @JsonProperty("id")
+ public Integer getId() {
+ return id;
+ }
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ /**
+ **/
+
+ @ApiModelProperty(value = "")
+ @JsonProperty("name")
+ public String getName() {
+ return name;
+ }
+ public void setName(String name) {
+ this.name = name;
+ }
+
+
+ @Override
+ public boolean equals(java.lang.Object o) {
+ if (this == o) {
+ return true;
+ }
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
+ Category category = (Category) o;
+ return Objects.equals(id, category.id) &&
+ Objects.equals(name, category.name);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(id, name);
+ }
+
+ @Override
+ public String toString() {
+ StringBuilder sb = new StringBuilder();
+ sb.append("class Category {\n");
+
+ sb.append(" id: ").append(toIndentedString(id)).append("\n");
+ sb.append(" name: ").append(toIndentedString(name)).append("\n");
+ sb.append("}");
+ return sb.toString();
+ }
+
+ /**
+ * Convert the given object to string with each line indented by 4 spaces
+ * (except the first line).
+ */
+ private String toIndentedString(java.lang.Object o) {
+ if (o == null) {
+ return "null";
+ }
+ return o.toString().replace("\n", "\n ");
+ }
+}
+
diff --git a/server/jaxrs-resteasy/src/main/java/io/swagger/api/factories/V1ApiServiceFactory.java b/server/jaxrs-resteasy/src/main/java/io/swagger/api/factories/V1ApiServiceFactory.java
new file mode 100644
index 0000000..2a90ebf
--- /dev/null
+++ b/server/jaxrs-resteasy/src/main/java/io/swagger/api/factories/V1ApiServiceFactory.java
@@ -0,0 +1,15 @@
+package io.swagger.api.factories;
+
+import io.swagger.api.V1ApiService;
+import io.swagger.api.impl.V1ApiServiceImpl;
+
+@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaResteasyServerCodegen", date = "2017-11-09T10:58:42.375+08:00")
+public class V1ApiServiceFactory {
+
+ private final static V1ApiService service = new V1ApiServiceImpl();
+
+ public static V1ApiService getV1Api()
+ {
+ return service;
+ }
+}
diff --git a/server/jaxrs-resteasy/src/main/java/io/swagger/api/impl/V1ApiServiceImpl.java b/server/jaxrs-resteasy/src/main/java/io/swagger/api/impl/V1ApiServiceImpl.java
new file mode 100644
index 0000000..607c802
--- /dev/null
+++ b/server/jaxrs-resteasy/src/main/java/io/swagger/api/impl/V1ApiServiceImpl.java
@@ -0,0 +1,50 @@
+package io.swagger.api.impl;
+
+import io.swagger.api.*;
+import io.swagger.model.*;
+
+
+import io.swagger.model.Book;
+import io.swagger.model.Category;
+
+import java.util.List;
+import io.swagger.api.NotFoundException;
+
+import java.io.InputStream;
+
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.SecurityContext;
+
+@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaResteasyServerCodegen", date = "2017-11-09T10:58:42.375+08:00")
+public class V1ApiServiceImpl extends V1ApiService {
+ @Override
+ public Response getAllUsingGET(SecurityContext securityContext)
+ throws NotFoundException {
+ // do some magic!
+ return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build();
+ }
+ @Override
+ public Response getBookByIdUsingGET(Integer id,SecurityContext securityContext)
+ throws NotFoundException {
+ // do some magic!
+ return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build();
+ }
+ @Override
+ public Response getBooksByCategoryUsingGET(Integer id,SecurityContext securityContext)
+ throws NotFoundException {
+ // do some magic!
+ return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build();
+ }
+ @Override
+ public Response getUsingGET(Integer id,SecurityContext securityContext)
+ throws NotFoundException {
+ // do some magic!
+ return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build();
+ }
+ @Override
+ public Response updateUsingPOST(Integer id,SecurityContext securityContext)
+ throws NotFoundException {
+ // do some magic!
+ return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build();
+ }
+}
diff --git a/server/jaxrs-resteasy/src/main/webapp/WEB-INF/jboss-web.xml b/server/jaxrs-resteasy/src/main/webapp/WEB-INF/jboss-web.xml
new file mode 100644
index 0000000..63da3d6
--- /dev/null
+++ b/server/jaxrs-resteasy/src/main/webapp/WEB-INF/jboss-web.xml
@@ -0,0 +1,3 @@
+
+
+
\ No newline at end of file
diff --git a/server/jaxrs-resteasy/src/main/webapp/WEB-INF/web.xml b/server/jaxrs-resteasy/src/main/webapp/WEB-INF/web.xml
new file mode 100644
index 0000000..52a89e9
--- /dev/null
+++ b/server/jaxrs-resteasy/src/main/webapp/WEB-INF/web.xml
@@ -0,0 +1,14 @@
+
+
+
+
+ ApiOriginFilter
+ io.swagger.api.ApiOriginFilter
+
+
+ ApiOriginFilter
+ /*
+
+
diff --git a/server/spring/.swagger-codegen-ignore b/server/spring/.swagger-codegen-ignore
new file mode 100644
index 0000000..c5fa491
--- /dev/null
+++ b/server/spring/.swagger-codegen-ignore
@@ -0,0 +1,23 @@
+# Swagger Codegen Ignore
+# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen
+
+# Use this file to prevent files from being overwritten by the generator.
+# The patterns follow closely to .gitignore or .dockerignore.
+
+# As an example, the C# client generator defines ApiClient.cs.
+# You can make changes and tell Swagger Codgen to ignore just this file by uncommenting the following line:
+#ApiClient.cs
+
+# You can match any string of characters against a directory, file or extension with a single asterisk (*):
+#foo/*/qux
+# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux
+
+# You can recursively match patterns against a directory, file or extension with a double asterisk (**):
+#foo/**/qux
+# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux
+
+# You can also negate patterns with an exclamation (!).
+# For example, you can ignore all files in a docs folder with the file extension .md:
+#docs/*.md
+# Then explicitly reverse the ignore rule for a single file:
+#!docs/README.md
diff --git a/server/spring/.swagger-codegen/VERSION b/server/spring/.swagger-codegen/VERSION
new file mode 100644
index 0000000..717311e
--- /dev/null
+++ b/server/spring/.swagger-codegen/VERSION
@@ -0,0 +1 @@
+unset
\ No newline at end of file
diff --git a/server/spring/README.md b/server/spring/README.md
new file mode 100644
index 0000000..a2e8a9f
--- /dev/null
+++ b/server/spring/README.md
@@ -0,0 +1,18 @@
+# Swagger generated server
+
+Spring Boot Server
+
+
+## Overview
+This server was generated by the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project.
+By using the [OpenAPI-Spec](https://github.com/swagger-api/swagger-core), you can easily generate a server stub.
+This is an example of building a swagger-enabled server in Java using the SpringBoot framework.
+
+The underlying library integrating swagger to SpringBoot is [springfox](https://github.com/springfox/springfox)
+
+Start your server as an simple java application
+
+You can view the api documentation in swagger-ui by pointing to
+http://localhost:8080/
+
+Change default port value in application.properties
\ No newline at end of file
diff --git a/server/spring/pom.xml b/server/spring/pom.xml
new file mode 100644
index 0000000..404858d
--- /dev/null
+++ b/server/spring/pom.xml
@@ -0,0 +1,69 @@
+
+ 4.0.0
+ com.example
+ swagger-client-java
+ jar
+ swagger-client-java
+ 1.0.0
+
+ 1.8
+ ${java.version}
+ ${java.version}
+ 2.6.1
+
+
+ org.springframework.boot
+ spring-boot-starter-parent
+ 1.4.7.RELEASE
+
+
+ src/main/java
+
+
+ org.springframework.boot
+ spring-boot-maven-plugin
+
+
+
+ repackage
+
+
+
+
+
+
+
+
+ org.springframework.boot
+ spring-boot-starter-web
+
+
+ org.springframework.boot
+ spring-boot-starter-tomcat
+ provided
+
+
+
+ io.springfox
+ springfox-swagger2
+ ${springfox-version}
+
+
+ io.springfox
+ springfox-swagger-ui
+ ${springfox-version}
+
+
+
+ com.fasterxml.jackson.datatype
+ jackson-datatype-jsr310
+
+
+
+ javax.validation
+ validation-api
+ 1.1.0.Final
+ provided
+
+
+
diff --git a/server/spring/src/main/java/io/swagger/RFC3339DateFormat.java b/server/spring/src/main/java/io/swagger/RFC3339DateFormat.java
new file mode 100644
index 0000000..0c3d276
--- /dev/null
+++ b/server/spring/src/main/java/io/swagger/RFC3339DateFormat.java
@@ -0,0 +1,20 @@
+package io.swagger;
+
+import com.fasterxml.jackson.databind.util.ISO8601DateFormat;
+import com.fasterxml.jackson.databind.util.ISO8601Utils;
+
+import java.text.FieldPosition;
+import java.util.Date;
+
+
+public class RFC3339DateFormat extends ISO8601DateFormat {
+
+ // Same as ISO8601DateFormat but serializing milliseconds.
+ @Override
+ public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) {
+ String value = ISO8601Utils.format(date, true);
+ toAppendTo.append(value);
+ return toAppendTo;
+ }
+
+}
\ No newline at end of file
diff --git a/server/spring/src/main/java/io/swagger/Swagger2SpringBoot.java b/server/spring/src/main/java/io/swagger/Swagger2SpringBoot.java
new file mode 100644
index 0000000..b7b7bb3
--- /dev/null
+++ b/server/spring/src/main/java/io/swagger/Swagger2SpringBoot.java
@@ -0,0 +1,36 @@
+package io.swagger;
+
+import org.springframework.boot.CommandLineRunner;
+import org.springframework.boot.ExitCodeGenerator;
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+import org.springframework.context.annotation.ComponentScan;
+
+import springfox.documentation.swagger2.annotations.EnableSwagger2;
+
+@SpringBootApplication
+@EnableSwagger2
+@ComponentScan(basePackages = { "io.swagger", "io.swagger.api" })
+public class Swagger2SpringBoot implements CommandLineRunner {
+
+ @Override
+ public void run(String... arg0) throws Exception {
+ if (arg0.length > 0 && arg0[0].equals("exitcode")) {
+ throw new ExitException();
+ }
+ }
+
+ public static void main(String[] args) throws Exception {
+ new SpringApplication(Swagger2SpringBoot.class).run(args);
+ }
+
+ class ExitException extends RuntimeException implements ExitCodeGenerator {
+ private static final long serialVersionUID = 1L;
+
+ @Override
+ public int getExitCode() {
+ return 10;
+ }
+
+ }
+}
diff --git a/server/spring/src/main/java/io/swagger/api/ApiException.java b/server/spring/src/main/java/io/swagger/api/ApiException.java
new file mode 100644
index 0000000..5ed8a62
--- /dev/null
+++ b/server/spring/src/main/java/io/swagger/api/ApiException.java
@@ -0,0 +1,11 @@
+package io.swagger.api;
+
+@javax.annotation.Generated(value = "io.swagger.codegen.languages.SpringCodegen", date = "2017-11-09T10:58:41.434+08:00")
+
+public class ApiException extends Exception{
+ private int code;
+ public ApiException (int code, String msg) {
+ super(msg);
+ this.code = code;
+ }
+}
diff --git a/server/spring/src/main/java/io/swagger/api/ApiOriginFilter.java b/server/spring/src/main/java/io/swagger/api/ApiOriginFilter.java
new file mode 100644
index 0000000..6e74701
--- /dev/null
+++ b/server/spring/src/main/java/io/swagger/api/ApiOriginFilter.java
@@ -0,0 +1,28 @@
+package io.swagger.api;
+
+import java.io.IOException;
+
+import javax.servlet.*;
+import javax.servlet.http.HttpServletResponse;
+
+@javax.annotation.Generated(value = "io.swagger.codegen.languages.SpringCodegen", date = "2017-11-09T10:58:41.434+08:00")
+
+public class ApiOriginFilter implements javax.servlet.Filter {
+ @Override
+ public void doFilter(ServletRequest request, ServletResponse response,
+ FilterChain chain) throws IOException, ServletException {
+ HttpServletResponse res = (HttpServletResponse) response;
+ res.addHeader("Access-Control-Allow-Origin", "*");
+ res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
+ res.addHeader("Access-Control-Allow-Headers", "Content-Type");
+ chain.doFilter(request, response);
+ }
+
+ @Override
+ public void destroy() {
+ }
+
+ @Override
+ public void init(FilterConfig filterConfig) throws ServletException {
+ }
+}
diff --git a/server/spring/src/main/java/io/swagger/api/ApiResponseMessage.java b/server/spring/src/main/java/io/swagger/api/ApiResponseMessage.java
new file mode 100644
index 0000000..31d7f1b
--- /dev/null
+++ b/server/spring/src/main/java/io/swagger/api/ApiResponseMessage.java
@@ -0,0 +1,70 @@
+package io.swagger.api;
+
+import javax.xml.bind.annotation.XmlTransient;
+
+@javax.annotation.Generated(value = "io.swagger.codegen.languages.SpringCodegen", date = "2017-11-09T10:58:41.434+08:00")
+
+@javax.xml.bind.annotation.XmlRootElement
+public class ApiResponseMessage {
+ public static final int ERROR = 1;
+ public static final int WARNING = 2;
+ public static final int INFO = 3;
+ public static final int OK = 4;
+ public static final int TOO_BUSY = 5;
+
+ int code;
+ String type;
+ String message;
+
+ public ApiResponseMessage(){}
+
+ public ApiResponseMessage(int code, String message){
+ this.code = code;
+ switch(code){
+ case ERROR:
+ setType("error");
+ break;
+ case WARNING:
+ setType("warning");
+ break;
+ case INFO:
+ setType("info");
+ break;
+ case OK:
+ setType("ok");
+ break;
+ case TOO_BUSY:
+ setType("too busy");
+ break;
+ default:
+ setType("unknown");
+ break;
+ }
+ this.message = message;
+ }
+
+ @XmlTransient
+ public int getCode() {
+ return code;
+ }
+
+ public void setCode(int code) {
+ this.code = code;
+ }
+
+ public String getType() {
+ return type;
+ }
+
+ public void setType(String type) {
+ this.type = type;
+ }
+
+ public String getMessage() {
+ return message;
+ }
+
+ public void setMessage(String message) {
+ this.message = message;
+ }
+}
diff --git a/server/spring/src/main/java/io/swagger/api/NotFoundException.java b/server/spring/src/main/java/io/swagger/api/NotFoundException.java
new file mode 100644
index 0000000..cb469d7
--- /dev/null
+++ b/server/spring/src/main/java/io/swagger/api/NotFoundException.java
@@ -0,0 +1,11 @@
+package io.swagger.api;
+
+@javax.annotation.Generated(value = "io.swagger.codegen.languages.SpringCodegen", date = "2017-11-09T10:58:41.434+08:00")
+
+public class NotFoundException extends ApiException {
+ private int code;
+ public NotFoundException (int code, String msg) {
+ super(code, msg);
+ this.code = code;
+ }
+}
diff --git a/server/spring/src/main/java/io/swagger/api/V1Api.java b/server/spring/src/main/java/io/swagger/api/V1Api.java
new file mode 100644
index 0000000..378e888
--- /dev/null
+++ b/server/spring/src/main/java/io/swagger/api/V1Api.java
@@ -0,0 +1,122 @@
+/**
+ * NOTE: This class is auto generated by the swagger code generator program (unset).
+ * https://github.com/swagger-api/swagger-codegen
+ * Do not edit the class manually.
+ */
+package io.swagger.api;
+
+import io.swagger.model.Book;
+import io.swagger.model.Category;
+
+import io.swagger.annotations.*;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestHeader;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.bind.annotation.RequestParam;
+import org.springframework.web.bind.annotation.RequestPart;
+import org.springframework.web.multipart.MultipartFile;
+
+import java.util.List;
+import javax.validation.constraints.*;
+import javax.validation.Valid;
+@javax.annotation.Generated(value = "io.swagger.codegen.languages.SpringCodegen", date = "2017-11-09T10:58:41.434+08:00")
+
+@Api(value = "v1", description = "the v1 API")
+public interface V1Api {
+
+ @ApiOperation(value = "获取全部分类", notes = "", response = Category.class, responseContainer = "List", tags={ "category-api", })
+ @ApiResponses(value = {
+ @ApiResponse(code = 200, message = "OK", response = Category.class, responseContainer = "List"),
+ @ApiResponse(code = 401, message = "Unauthorized", response = Void.class),
+ @ApiResponse(code = 403, message = "Forbidden", response = Void.class),
+ @ApiResponse(code = 404, message = "Not Found", response = Void.class) })
+
+ @RequestMapping(value = "/v1/category/",
+ produces = { "*/*" },
+ consumes = { "application/json" },
+ method = RequestMethod.GET)
+ default ResponseEntity> getAllUsingGET() {
+ // do some magic!
+ return new ResponseEntity>(HttpStatus.OK);
+ }
+
+
+ @ApiOperation(value = "根据ID获取书籍", notes = "", response = Book.class, authorizations = {
+ @Authorization(value = "api_key")
+ }, tags={ "book-api", })
+ @ApiResponses(value = {
+ @ApiResponse(code = 200, message = "OK", response = Book.class),
+ @ApiResponse(code = 401, message = "Unauthorized", response = Void.class),
+ @ApiResponse(code = 403, message = "Forbidden", response = Void.class),
+ @ApiResponse(code = 404, message = "Not Found", response = Void.class) })
+
+ @RequestMapping(value = "/v1/book/{id}",
+ produces = { "*/*" },
+ consumes = { "application/json" },
+ method = RequestMethod.GET)
+ default ResponseEntity getBookByIdUsingGET(@ApiParam(value = "id",required=true ) @PathVariable("id") Integer id) {
+ // do some magic!
+ return new ResponseEntity(HttpStatus.OK);
+ }
+
+
+ @ApiOperation(value = "根据分类获取书籍", notes = "", response = Book.class, responseContainer = "List", authorizations = {
+ @Authorization(value = "api_key")
+ }, tags={ "book-api", })
+ @ApiResponses(value = {
+ @ApiResponse(code = 200, message = "OK", response = Book.class, responseContainer = "List"),
+ @ApiResponse(code = 401, message = "Unauthorized", response = Void.class),
+ @ApiResponse(code = 403, message = "Forbidden", response = Void.class),
+ @ApiResponse(code = 404, message = "Not Found", response = Void.class) })
+
+ @RequestMapping(value = "/v1/book/getByCategoryId",
+ produces = { "*/*" },
+ consumes = { "application/json" },
+ method = RequestMethod.GET)
+ default ResponseEntity> getBooksByCategoryUsingGET( @NotNull@ApiParam(value = "id", required = true) @RequestParam(value = "id", required = true) Integer id) {
+ // do some magic!
+ return new ResponseEntity>(HttpStatus.OK);
+ }
+
+
+ @ApiOperation(value = "根据ID获取分类", notes = "", response = Category.class, tags={ "category-api", })
+ @ApiResponses(value = {
+ @ApiResponse(code = 200, message = "OK", response = Category.class),
+ @ApiResponse(code = 401, message = "Unauthorized", response = Void.class),
+ @ApiResponse(code = 403, message = "Forbidden", response = Void.class),
+ @ApiResponse(code = 404, message = "Not Found", response = Void.class) })
+
+ @RequestMapping(value = "/v1/category/{id}",
+ produces = { "*/*" },
+ consumes = { "application/json" },
+ method = RequestMethod.GET)
+ default ResponseEntity getUsingGET(@ApiParam(value = "id",required=true ) @PathVariable("id") Integer id) {
+ // do some magic!
+ return new ResponseEntity(HttpStatus.OK);
+ }
+
+
+ @ApiOperation(value = "更新书籍", notes = "", response = Boolean.class, authorizations = {
+ @Authorization(value = "api_key")
+ }, tags={ "book-api", })
+ @ApiResponses(value = {
+ @ApiResponse(code = 200, message = "OK", response = Boolean.class),
+ @ApiResponse(code = 201, message = "Created", response = Void.class),
+ @ApiResponse(code = 401, message = "Unauthorized", response = Void.class),
+ @ApiResponse(code = 403, message = "Forbidden", response = Void.class),
+ @ApiResponse(code = 404, message = "Not Found", response = Void.class) })
+
+ @RequestMapping(value = "/v1/book/update",
+ produces = { "*/*" },
+ consumes = { "application/json" },
+ method = RequestMethod.POST)
+ default ResponseEntity updateUsingPOST(@ApiParam(value = "id" ) @Valid @RequestBody Integer id) {
+ // do some magic!
+ return new ResponseEntity(HttpStatus.OK);
+ }
+
+}
diff --git a/server/spring/src/main/java/io/swagger/api/V1ApiController.java b/server/spring/src/main/java/io/swagger/api/V1ApiController.java
new file mode 100644
index 0000000..8664a39
--- /dev/null
+++ b/server/spring/src/main/java/io/swagger/api/V1ApiController.java
@@ -0,0 +1,14 @@
+package io.swagger.api;
+
+import org.springframework.stereotype.Controller;
+
+import javax.validation.constraints.*;
+import javax.validation.Valid;
+@javax.annotation.Generated(value = "io.swagger.codegen.languages.SpringCodegen", date = "2017-11-09T10:58:41.434+08:00")
+
+@Controller
+public class V1ApiController implements V1Api {
+
+
+
+}
diff --git a/server/spring/src/main/java/io/swagger/configuration/HomeController.java b/server/spring/src/main/java/io/swagger/configuration/HomeController.java
new file mode 100644
index 0000000..f832809
--- /dev/null
+++ b/server/spring/src/main/java/io/swagger/configuration/HomeController.java
@@ -0,0 +1,16 @@
+package io.swagger.configuration;
+
+import org.springframework.stereotype.Controller;
+import org.springframework.web.bind.annotation.RequestMapping;
+
+/**
+ * Home redirection to swagger api documentation
+ */
+@Controller
+public class HomeController {
+ @RequestMapping(value = "/")
+ public String index() {
+ System.out.println("swagger-ui.html");
+ return "redirect:swagger-ui.html";
+ }
+}
diff --git a/server/spring/src/main/java/io/swagger/configuration/SwaggerDocumentationConfig.java b/server/spring/src/main/java/io/swagger/configuration/SwaggerDocumentationConfig.java
new file mode 100644
index 0000000..196d0b9
--- /dev/null
+++ b/server/spring/src/main/java/io/swagger/configuration/SwaggerDocumentationConfig.java
@@ -0,0 +1,41 @@
+package io.swagger.configuration;
+
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+
+import springfox.documentation.builders.ApiInfoBuilder;
+import springfox.documentation.builders.RequestHandlerSelectors;
+import springfox.documentation.service.ApiInfo;
+import springfox.documentation.service.Contact;
+import springfox.documentation.spi.DocumentationType;
+import springfox.documentation.spring.web.plugins.Docket;
+
+@javax.annotation.Generated(value = "io.swagger.codegen.languages.SpringCodegen", date = "2017-11-09T10:58:41.434+08:00")
+
+@Configuration
+public class SwaggerDocumentationConfig {
+
+ ApiInfo apiInfo() {
+ return new ApiInfoBuilder()
+ .title("Swagger Demo")
+ .description("Swagger的简单示例, 包括swagger-codegen, swagger2markup 和 asciidoctor.")
+ .license("Apache License")
+ .licenseUrl("http://www.apache.org/licenses/LICENSE-2.0.html")
+ .termsOfServiceUrl("http://www.google.com")
+ .version("v1")
+ .contact(new Contact("","", "damon.q@iv66.net"))
+ .build();
+ }
+
+ @Bean
+ public Docket customImplementation(){
+ return new Docket(DocumentationType.SWAGGER_2)
+ .select()
+ .apis(RequestHandlerSelectors.basePackage("io.swagger.api"))
+ .build()
+ .directModelSubstitute(java.time.LocalDate.class, java.sql.Date.class)
+ .directModelSubstitute(java.time.OffsetDateTime.class, java.util.Date.class)
+ .apiInfo(apiInfo());
+ }
+
+}
diff --git a/server/spring/src/main/java/io/swagger/model/Book.java b/server/spring/src/main/java/io/swagger/model/Book.java
new file mode 100644
index 0000000..f122e71
--- /dev/null
+++ b/server/spring/src/main/java/io/swagger/model/Book.java
@@ -0,0 +1,154 @@
+package io.swagger.model;
+
+import java.util.Objects;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import com.fasterxml.jackson.annotation.JsonCreator;
+import io.swagger.annotations.ApiModel;
+import io.swagger.annotations.ApiModelProperty;
+import javax.validation.Valid;
+import javax.validation.constraints.*;
+
+/**
+ * Book
+ */
+@javax.annotation.Generated(value = "io.swagger.codegen.languages.SpringCodegen", date = "2017-11-09T10:58:41.434+08:00")
+
+public class Book {
+ @JsonProperty("author")
+ private String author = null;
+
+ @JsonProperty("categoryId")
+ private Integer categoryId = null;
+
+ @JsonProperty("id")
+ private Integer id = null;
+
+ @JsonProperty("name")
+ private String name = null;
+
+ public Book author(String author) {
+ this.author = author;
+ return this;
+ }
+
+ /**
+ * 作者
+ * @return author
+ **/
+ @ApiModelProperty(value = "作者")
+
+
+ public String getAuthor() {
+ return author;
+ }
+
+ public void setAuthor(String author) {
+ this.author = author;
+ }
+
+ public Book categoryId(Integer categoryId) {
+ this.categoryId = categoryId;
+ return this;
+ }
+
+ /**
+ * Get categoryId
+ * @return categoryId
+ **/
+ @ApiModelProperty(value = "")
+
+
+ public Integer getCategoryId() {
+ return categoryId;
+ }
+
+ public void setCategoryId(Integer categoryId) {
+ this.categoryId = categoryId;
+ }
+
+ public Book id(Integer id) {
+ this.id = id;
+ return this;
+ }
+
+ /**
+ * Get id
+ * @return id
+ **/
+ @ApiModelProperty(value = "")
+
+
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public Book name(String name) {
+ this.name = name;
+ return this;
+ }
+
+ /**
+ * 书名
+ * @return name
+ **/
+ @ApiModelProperty(value = "书名")
+
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+
+ @Override
+ public boolean equals(java.lang.Object o) {
+ if (this == o) {
+ return true;
+ }
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
+ Book book = (Book) o;
+ return Objects.equals(this.author, book.author) &&
+ Objects.equals(this.categoryId, book.categoryId) &&
+ Objects.equals(this.id, book.id) &&
+ Objects.equals(this.name, book.name);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(author, categoryId, id, name);
+ }
+
+ @Override
+ public String toString() {
+ StringBuilder sb = new StringBuilder();
+ sb.append("class Book {\n");
+
+ sb.append(" author: ").append(toIndentedString(author)).append("\n");
+ sb.append(" categoryId: ").append(toIndentedString(categoryId)).append("\n");
+ sb.append(" id: ").append(toIndentedString(id)).append("\n");
+ sb.append(" name: ").append(toIndentedString(name)).append("\n");
+ sb.append("}");
+ return sb.toString();
+ }
+
+ /**
+ * Convert the given object to string with each line indented by 4 spaces
+ * (except the first line).
+ */
+ private String toIndentedString(java.lang.Object o) {
+ if (o == null) {
+ return "null";
+ }
+ return o.toString().replace("\n", "\n ");
+ }
+}
+
diff --git a/server/spring/src/main/java/io/swagger/model/Category.java b/server/spring/src/main/java/io/swagger/model/Category.java
new file mode 100644
index 0000000..151c6ca
--- /dev/null
+++ b/server/spring/src/main/java/io/swagger/model/Category.java
@@ -0,0 +1,104 @@
+package io.swagger.model;
+
+import java.util.Objects;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import com.fasterxml.jackson.annotation.JsonCreator;
+import io.swagger.annotations.ApiModel;
+import io.swagger.annotations.ApiModelProperty;
+import javax.validation.Valid;
+import javax.validation.constraints.*;
+
+/**
+ * Category
+ */
+@javax.annotation.Generated(value = "io.swagger.codegen.languages.SpringCodegen", date = "2017-11-09T10:58:41.434+08:00")
+
+public class Category {
+ @JsonProperty("id")
+ private Integer id = null;
+
+ @JsonProperty("name")
+ private String name = null;
+
+ public Category id(Integer id) {
+ this.id = id;
+ return this;
+ }
+
+ /**
+ * Get id
+ * @return id
+ **/
+ @ApiModelProperty(value = "")
+
+
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public Category name(String name) {
+ this.name = name;
+ return this;
+ }
+
+ /**
+ * Get name
+ * @return name
+ **/
+ @ApiModelProperty(value = "")
+
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+
+ @Override
+ public boolean equals(java.lang.Object o) {
+ if (this == o) {
+ return true;
+ }
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
+ Category category = (Category) o;
+ return Objects.equals(this.id, category.id) &&
+ Objects.equals(this.name, category.name);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(id, name);
+ }
+
+ @Override
+ public String toString() {
+ StringBuilder sb = new StringBuilder();
+ sb.append("class Category {\n");
+
+ sb.append(" id: ").append(toIndentedString(id)).append("\n");
+ sb.append(" name: ").append(toIndentedString(name)).append("\n");
+ sb.append("}");
+ return sb.toString();
+ }
+
+ /**
+ * Convert the given object to string with each line indented by 4 spaces
+ * (except the first line).
+ */
+ private String toIndentedString(java.lang.Object o) {
+ if (o == null) {
+ return "null";
+ }
+ return o.toString().replace("\n", "\n ");
+ }
+}
+
diff --git a/server/spring/src/main/resources/application.properties b/server/spring/src/main/resources/application.properties
new file mode 100644
index 0000000..12f1987
--- /dev/null
+++ b/server/spring/src/main/resources/application.properties
@@ -0,0 +1,5 @@
+springfox.documentation.swagger.v2.path=/api-docs
+server.contextPath=
+server.port=8080
+spring.jackson.date-format=io.swagger.RFC3339DateFormat
+spring.jackson.serialization.WRITE_DATES_AS_TIMESTAMPS=false
\ No newline at end of file
diff --git a/swagger-server/bin/generate-client-html-config.json b/swagger-server/bin/generate-client-html-config.json
new file mode 100644
index 0000000..58febd9
--- /dev/null
+++ b/swagger-server/bin/generate-client-html-config.json
@@ -0,0 +1,5 @@
+{
+ "groupId": "com.example",
+ "artifactId": "swagger-client-java",
+ "artifactVersion": "1.0.0"
+}
diff --git a/swagger-server/bin/generate-client-java-config.json b/swagger-server/bin/generate-client-java-config.json
new file mode 100644
index 0000000..f1ee5d9
--- /dev/null
+++ b/swagger-server/bin/generate-client-java-config.json
@@ -0,0 +1,8 @@
+{
+ "groupId": "com.example",
+ "artifactId": "swagger-client-java",
+ "artifactVersion": "1.0.0",
+ "library": "okhttp-gson",
+ "java8": true,
+ "dateLibrary": "java8"
+}
diff --git a/swagger-server/bin/generate-server-jaxrs-resteasy-config.json b/swagger-server/bin/generate-server-jaxrs-resteasy-config.json
new file mode 100644
index 0000000..a9a377e
--- /dev/null
+++ b/swagger-server/bin/generate-server-jaxrs-resteasy-config.json
@@ -0,0 +1,7 @@
+{
+ "groupId": "com.example",
+ "artifactId": "swagger-client-java",
+ "artifactVersion": "1.0.0",
+ "java8": true,
+ "dateLibrary": "java8"
+}
diff --git a/swagger-server/bin/generate-server-spring-config.json b/swagger-server/bin/generate-server-spring-config.json
new file mode 100644
index 0000000..bb1ae05
--- /dev/null
+++ b/swagger-server/bin/generate-server-spring-config.json
@@ -0,0 +1,8 @@
+{
+ "groupId": "com.example",
+ "artifactId": "swagger-client-java",
+ "artifactVersion": "1.0.0",
+ "library": "spring-boot",
+ "java8": true,
+ "dateLibrary": "java8"
+}
diff --git a/swagger-server/bin/install.sh b/swagger-server/bin/install.sh
new file mode 100644
index 0000000..4b4fc50
--- /dev/null
+++ b/swagger-server/bin/install.sh
@@ -0,0 +1,47 @@
+#!/bin/bash
+
+pwd=$(cd `dirname $0`; pwd);cd $pwd
+CLIENT_HOME=$pwd/../../client
+SERVER_HOME=$pwd/../../server
+ASCII_HOME=$pwd/../../asciidoc
+DOC_HOME=$pwd/../../docs
+
+echo "generated client source folder: $CLIENT_HOME"
+echo "generated server source folder: $SERVER_HOME"
+
+# do clean
+rm -rf $CLIENT_HOME $SERVER_HOME $ASCII_HOME $DOC_HOME
+
+# clients
+java -jar swagger-codegen-cli.jar generate \
+ -i $pwd/../src/main/resources/swagger.yml \
+ -l java \
+ -c generate-client-java-config.json \
+ -o $CLIENT_HOME/java
+
+java -jar swagger-codegen-cli.jar generate \
+ -i $pwd/../src/main/resources/swagger.yml \
+ -l go \
+ -o $CLIENT_HOME/go
+
+java -jar swagger-codegen-cli.jar generate \
+ -i $pwd/../src/main/resources/swagger.yml \
+ -l html2 \
+ -c generate-client-html-config.json \
+ -o $CLIENT_HOME/html2
+
+# servers
+java -jar swagger-codegen-cli.jar generate \
+ -i $pwd/../src/main/resources/swagger.yml \
+ -l spring \
+ -c generate-server-spring-config.json \
+ -o $SERVER_HOME/spring
+
+java -jar swagger-codegen-cli.jar generate \
+ -i $pwd/../src/main/resources/swagger.yml \
+ -l jaxrs-resteasy \
+ -c generate-server-jaxrs-resteasy-config.json \
+ -o $SERVER_HOME/jaxrs-resteasy
+
+cd $pwd/../..
+mvn clean install
diff --git a/swagger-server/bin/swagger-codegen-cli.jar b/swagger-server/bin/swagger-codegen-cli.jar
new file mode 100644
index 0000000..ef3cedb
Binary files /dev/null and b/swagger-server/bin/swagger-codegen-cli.jar differ
diff --git a/swagger-server/pom.xml b/swagger-server/pom.xml
new file mode 100644
index 0000000..7da2f4f
--- /dev/null
+++ b/swagger-server/pom.xml
@@ -0,0 +1,214 @@
+
+
+ 4.0.0
+
+ swagger-server
+ 1.0.0
+ jar
+
+ swagger-server
+ Demo project for Spring Boot
+
+
+ com.example
+ swagger-example
+ 1.0.0
+ ../
+
+
+
+ UTF-8
+ UTF-8
+ 1.8
+
+ 2.7.0
+ 1.3.3
+ 1.5.6
+ 1.5.0-alpha.16
+
+ ${project.basedir}/src/main/resources/swagger.yml
+ ${project.basedir}/../asciidoc/
+ ${project.basedir}/../docs
+
+
+
+
+ org.springframework.boot
+ spring-boot-starter-web
+
+
+
+ io.springfox
+ springfox-swagger2
+ ${springfox-swagger2.version}
+
+
+ io.springfox
+ springfox-swagger-ui
+ ${springfox-swagger2.version}
+
+
+
+ org.springframework.boot
+ spring-boot-starter-actuator
+
+
+
+ org.springframework.boot
+ spring-boot-starter-test
+ test
+
+
+
+
+
+
+ org.springframework.boot
+ spring-boot-maven-plugin
+
+
+
+ io.github.swagger2markup
+ swagger2markup-maven-plugin
+ ${swagger2markup-maven-plugin.version}
+
+ ${swagger.input}
+ ${generated.asciidoc.directory}/swagger-example
+
+ ASCIIDOC
+
+
+
+
+ generate-resources
+
+ convertSwagger2markup
+
+
+
+
+
+ org.asciidoctor
+ asciidoctor-maven-plugin
+ ${asciidoctor-maven-plugin.version}
+
+
+ org.asciidoctor
+ asciidoctorj-pdf
+ ${asciidoctorj-pdf.version}
+
+
+
+ ${generated.asciidoc.directory}
+ true
+ coderay
+ book
+
+ ${project.build.sourceDirectory}
+ http://example.org
+ ${project.version}
+ left
+ 3
+ true
+ ${project.version}
+ ${maven.build.timestamp}
+ google.com
+
+
+
+
+ output-html
+ generate-resources
+
+ process-asciidoc
+
+
+ ${asciidoctor.output.directory}
+ html5
+
+ ./images
+ left
+ font
+ true
+
+ -
+ true
+
+
+
+
+
+
+
+
+
diff --git a/swagger-server/src/main/java/com/example/server/SwaggerServerApplication.java b/swagger-server/src/main/java/com/example/server/SwaggerServerApplication.java
new file mode 100644
index 0000000..c663746
--- /dev/null
+++ b/swagger-server/src/main/java/com/example/server/SwaggerServerApplication.java
@@ -0,0 +1,12 @@
+package com.example.server;
+
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+
+@SpringBootApplication
+public class SwaggerServerApplication {
+
+ public static void main(String[] args) {
+ SpringApplication.run(SwaggerServerApplication.class, args);
+ }
+}
diff --git a/swagger-server/src/main/java/com/example/server/api/BookApi.java b/swagger-server/src/main/java/com/example/server/api/BookApi.java
new file mode 100644
index 0000000..a011618
--- /dev/null
+++ b/swagger-server/src/main/java/com/example/server/api/BookApi.java
@@ -0,0 +1,48 @@
+package com.example.server.api;
+
+import com.example.server.model.Book;
+import com.example.server.service.BookService;
+import io.swagger.annotations.ApiOperation;
+import java.util.List;
+import java.util.Random;
+import javax.websocket.server.PathParam;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestParam;
+import org.springframework.web.bind.annotation.RestController;
+
+/**
+ * Created by Damon.Q on 2017/10/27.
+ */
+@RestController
+@RequestMapping("/v1/book")
+public class BookApi {
+
+ private final BookService bookService;
+
+ @Autowired
+ public BookApi(BookService bookService) {
+ this.bookService = bookService;
+ }
+
+ @GetMapping("/{id}")
+ @ApiOperation(value = "根据ID获取书籍")
+ public Book getBookById(@PathVariable("id") Integer id) {
+ return bookService.getById(id);
+ }
+
+ @GetMapping("/getByCategoryId")
+ @ApiOperation(value = "根据分类获取书籍")
+ public List getBooksByCategory(@RequestParam("id") Integer id) {
+ return bookService.getByCategoryId(id);
+ }
+
+ @PostMapping("/update")
+ @ApiOperation(value = "更新书籍")
+ public boolean update(@PathParam("id") Integer id) {
+ return new Random().nextBoolean();
+ }
+}
diff --git a/swagger-server/src/main/java/com/example/server/api/CategoryApi.java b/swagger-server/src/main/java/com/example/server/api/CategoryApi.java
new file mode 100644
index 0000000..f762148
--- /dev/null
+++ b/swagger-server/src/main/java/com/example/server/api/CategoryApi.java
@@ -0,0 +1,38 @@
+package com.example.server.api;
+
+import com.example.server.model.Category;
+import com.example.server.service.CategoryService;
+import io.swagger.annotations.ApiOperation;
+import java.util.List;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+/**
+ * Created by Damon.Q on 2017/10/27.
+ */
+@RestController
+@RequestMapping("/v1/category")
+public class CategoryApi {
+
+ private final CategoryService categoryService;
+
+ @Autowired
+ public CategoryApi(CategoryService categoryService) {
+ this.categoryService = categoryService;
+ }
+
+ @GetMapping("/")
+ @ApiOperation(value = "获取全部分类")
+ public List getAll() {
+ return categoryService.getAll();
+ }
+
+ @GetMapping("/{id}")
+ @ApiOperation(value = "根据ID获取分类")
+ public Category get(@PathVariable("id") Integer id) {
+ return categoryService.get(id);
+ }
+}
diff --git a/swagger-server/src/main/java/com/example/server/config/SwaggerConfig.java b/swagger-server/src/main/java/com/example/server/config/SwaggerConfig.java
new file mode 100644
index 0000000..e47f572
--- /dev/null
+++ b/swagger-server/src/main/java/com/example/server/config/SwaggerConfig.java
@@ -0,0 +1,94 @@
+package com.example.server.config;
+
+import com.google.common.collect.Lists;
+import com.google.common.collect.Sets;
+import java.util.List;
+import org.springframework.boot.web.servlet.FilterRegistrationBean;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.web.cors.CorsConfiguration;
+import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
+import org.springframework.web.filter.CorsFilter;
+import springfox.documentation.builders.ApiInfoBuilder;
+import springfox.documentation.builders.PathSelectors;
+import springfox.documentation.builders.RequestHandlerSelectors;
+import springfox.documentation.service.ApiInfo;
+import springfox.documentation.service.ApiKey;
+import springfox.documentation.service.AuthorizationScope;
+import springfox.documentation.service.Contact;
+import springfox.documentation.service.SecurityReference;
+import springfox.documentation.spi.DocumentationType;
+import springfox.documentation.spi.service.contexts.SecurityContext;
+import springfox.documentation.spring.web.plugins.Docket;
+import springfox.documentation.swagger2.annotations.EnableSwagger2;
+
+/**
+ * Created by Damon.Q on 2017/10/27.
+ */
+@Configuration
+@EnableSwagger2
+public class SwaggerConfig {
+
+ @Bean
+ public Docket api() {
+ return new Docket(DocumentationType.SWAGGER_2)
+ .select()
+ .apis(RequestHandlerSelectors.any())
+ .paths(PathSelectors.regex("/v1/.*"))
+ .build()
+ .host("localhost:8080")
+ .protocols(Sets.newHashSet("http", "https"))
+ .securitySchemes(Lists.newArrayList(new ApiKey("api_key", "api_key", "header")))
+ .securityContexts(Lists.newArrayList(securityContext()))
+ .apiInfo(apiInfo())
+ //.useDefaultResponseMessages(false)
+ //.globalResponseMessage(RequestMethod.GET, Lists.newArrayList(
+ // new ResponseMessageBuilder()
+ // .code(500)
+ // .message("500 message")
+ // .responseModel(new ModelRef("Error"))
+ // .build(),
+ // new ResponseMessageBuilder()
+ // .code(403)
+ // .message("Forbidden!")
+ // .build()))
+ ;
+ }
+
+ @Bean
+ public FilterRegistrationBean corsFilter() {
+ UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
+ CorsConfiguration config = new CorsConfiguration();
+ config.setAllowCredentials(true);
+ config.setAllowedOrigins(Lists.newArrayList("*"));
+ config.setAllowedHeaders(Lists.newArrayList("*"));
+ config.setAllowedMethods(Lists.newArrayList("*"));
+ source.registerCorsConfiguration("/**", config);
+ FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
+ bean.setOrder(0);
+ return bean;
+ }
+
+ private SecurityContext securityContext() {
+ return SecurityContext.builder()
+ .securityReferences(defaultAuth())
+ .forPaths(PathSelectors.regex("/v1/book/.*"))
+ .build();
+ }
+
+ private List defaultAuth() {
+ return Lists.newArrayList(new SecurityReference("api_key", new AuthorizationScope[0]));
+ }
+
+ private ApiInfo apiInfo() {
+ return new ApiInfoBuilder()
+ .title("Swagger Demo")
+ .description("Swagger的简单示例, 包括swagger-codegen, swagger2markup 和 asciidoctor.")
+ .termsOfServiceUrl("http://www.apache.org/licenses/LICENSE-2.0.html")
+ .contact(new Contact("Damon", "http://www.google.com", "damon.q@iv66.net"))
+ .license("Apache License")
+ .licenseUrl("http://www.apache.org/licenses/LICENSE-2.0.html")
+ .version("v1")
+ .build();
+ }
+}
diff --git a/swagger-server/src/main/java/com/example/server/model/Book.java b/swagger-server/src/main/java/com/example/server/model/Book.java
new file mode 100644
index 0000000..9bf1f82
--- /dev/null
+++ b/swagger-server/src/main/java/com/example/server/model/Book.java
@@ -0,0 +1,57 @@
+package com.example.server.model;
+
+import io.swagger.annotations.ApiModel;
+import io.swagger.annotations.ApiModelProperty;
+
+/**
+ * Created by Damon.Q on 2017/10/27.
+ */
+@ApiModel
+public class Book {
+
+ private int id;
+ private int categoryId;
+ @ApiModelProperty("书名")
+ private String name;
+ @ApiModelProperty("作者")
+ private String author;
+
+ public Book(int id, int categoryId, String name, String author) {
+ this.id = id;
+ this.categoryId = categoryId;
+ this.name = name;
+ this.author = author;
+ }
+
+ public int getId() {
+ return id;
+ }
+
+ public void setId(int id) {
+ this.id = id;
+ }
+
+ public int getCategoryId() {
+ return categoryId;
+ }
+
+ public void setCategoryId(int categoryId) {
+ this.categoryId = categoryId;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getAuthor() {
+ return author;
+ }
+
+ public void setAuthor(String author) {
+ this.author = author;
+ }
+}
diff --git a/swagger-server/src/main/java/com/example/server/model/Category.java b/swagger-server/src/main/java/com/example/server/model/Category.java
new file mode 100644
index 0000000..f1441e9
--- /dev/null
+++ b/swagger-server/src/main/java/com/example/server/model/Category.java
@@ -0,0 +1,31 @@
+package com.example.server.model;
+
+/**
+ *
Created by Damon.Q on 2017/10/27.
+ */
+public class Category {
+
+ private int id;
+ private String name;
+
+ public Category(int id, String name) {
+ this.id = id;
+ this.name = name;
+ }
+
+ public int getId() {
+ return id;
+ }
+
+ public void setId(int id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+}
diff --git a/swagger-server/src/main/java/com/example/server/service/BookService.java b/swagger-server/src/main/java/com/example/server/service/BookService.java
new file mode 100644
index 0000000..eee399a
--- /dev/null
+++ b/swagger-server/src/main/java/com/example/server/service/BookService.java
@@ -0,0 +1,29 @@
+package com.example.server.service;
+
+import com.example.server.model.Book;
+import com.google.common.collect.Lists;
+import java.util.List;
+import java.util.stream.Collectors;
+import org.springframework.stereotype.Service;
+
+/**
+ *
Created by Damon.Q on 2017/10/27.
+ */
+@Service
+public class BookService {
+
+ private static final List BOOKS = Lists.newArrayList(
+ new Book(1, 1, "Clean Code", "Martin"),
+ new Book(2, 1, "Effective Java", "Joshua Bloch"),
+ new Book(3, 2, "挪威的森林", "村上春树")
+ );
+ private static final Book NOT_EXIST = new Book(-1, -1, "NOT EXIST", "NO AUTHOR");
+
+ public Book getById(int id) {
+ return BOOKS.stream().filter(b -> id == b.getId()).findAny().orElse(NOT_EXIST);
+ }
+
+ public List getByCategoryId(Integer categoryId) {
+ return BOOKS.stream().filter(b -> categoryId == b.getCategoryId()).collect(Collectors.toList());
+ }
+}
diff --git a/swagger-server/src/main/java/com/example/server/service/CategoryService.java b/swagger-server/src/main/java/com/example/server/service/CategoryService.java
new file mode 100644
index 0000000..5710d17
--- /dev/null
+++ b/swagger-server/src/main/java/com/example/server/service/CategoryService.java
@@ -0,0 +1,28 @@
+package com.example.server.service;
+
+import com.example.server.model.Category;
+import com.google.common.collect.Lists;
+import java.util.List;
+import org.springframework.stereotype.Service;
+
+/**
+ * Created by Damon.Q on 2017/10/27.
+ */
+@Service
+public class CategoryService {
+
+ private static final List CATEGORIES = Lists.newArrayList(
+ new Category(1, "技术"),
+ new Category(2, "文学")
+ );
+
+ private static final Category NOT_EXIST = new Category(-1, "NOT EXIST");
+
+ public List getAll() {
+ return CATEGORIES;
+ }
+
+ public Category get(Integer id) {
+ return CATEGORIES.stream().filter(c -> id == c.getId()).findAny().orElse(NOT_EXIST);
+ }
+}
diff --git a/swagger-server/src/main/resources/application.yml b/swagger-server/src/main/resources/application.yml
new file mode 100644
index 0000000..4dee154
--- /dev/null
+++ b/swagger-server/src/main/resources/application.yml
@@ -0,0 +1 @@
+debug: false
diff --git a/swagger-server/src/main/resources/openapi3.0.0.yml b/swagger-server/src/main/resources/openapi3.0.0.yml
new file mode 100644
index 0000000..924aa26
--- /dev/null
+++ b/swagger-server/src/main/resources/openapi3.0.0.yml
@@ -0,0 +1,26 @@
+openapi: 3.0.0
+info:
+ title: Sample API
+ description: Optional multiline or single-line description in [CommonMark](http://commonmark.org/help/) or HTML.
+ version: 0.1.9
+
+servers:
+ - url: http://api.example.com/v1
+ description: Optional server description, e.g. Main (production) server
+ - url: http://staging-api.example.com
+ description: Optional server description, e.g. Internal staging server for testing
+
+paths:
+ /users:
+ get:
+ summary: Returns a list of users.
+ description: Optional extended description in CommonMark or HTML.
+ responses:
+ '200': # status code
+ description: A JSON array of user names
+ content:
+ application/json:
+ schema:
+ type: array
+ items:
+ type: string
\ No newline at end of file
diff --git a/swagger-server/src/main/resources/swagger.yml b/swagger-server/src/main/resources/swagger.yml
new file mode 100644
index 0000000..444e1d6
--- /dev/null
+++ b/swagger-server/src/main/resources/swagger.yml
@@ -0,0 +1,199 @@
+swagger: '2.0'
+info:
+ description: 'Swagger的简单示例, 包括swagger-codegen, swagger2markup 和 asciidoctor.'
+ version: v1
+ title: Swagger Demo
+ termsOfService: 'http://www.apache.org/licenses/LICENSE-2.0.html'
+ contact:
+ name: Damon
+ url: 'http://www.google.com'
+ email: damon.q@iv66.net
+ license:
+ name: Apache License
+ url: 'http://www.apache.org/licenses/LICENSE-2.0.html'
+host: 'localhost:8080'
+basePath: /
+tags:
+ - name: category-api
+ description: Category Api
+ - name: book-api
+ description: Book Api
+schemes:
+ - http
+ - https
+paths:
+ /v1/book/getByCategoryId:
+ get:
+ tags:
+ - book-api
+ summary: 根据分类获取书籍
+ operationId: getBooksByCategoryUsingGET
+ consumes:
+ - application/json
+ produces:
+ - '*/*'
+ parameters:
+ - name: id
+ in: query
+ description: id
+ required: true
+ type: integer
+ format: int32
+ responses:
+ '200':
+ description: OK
+ schema:
+ type: array
+ items:
+ $ref: '#/definitions/Book'
+ '401':
+ description: Unauthorized
+ '403':
+ description: Forbidden
+ '404':
+ description: Not Found
+ security:
+ - api_key: []
+ /v1/book/update:
+ post:
+ tags:
+ - book-api
+ summary: 更新书籍
+ operationId: updateUsingPOST
+ consumes:
+ - application/json
+ produces:
+ - '*/*'
+ parameters:
+ - in: body
+ name: id
+ description: id
+ required: false
+ schema:
+ type: integer
+ format: int32
+ responses:
+ '200':
+ description: OK
+ schema:
+ type: boolean
+ '201':
+ description: Created
+ '401':
+ description: Unauthorized
+ '403':
+ description: Forbidden
+ '404':
+ description: Not Found
+ security:
+ - api_key: []
+ '/v1/book/{id}':
+ get:
+ tags:
+ - book-api
+ summary: 根据ID获取书籍
+ operationId: getBookByIdUsingGET
+ consumes:
+ - application/json
+ produces:
+ - '*/*'
+ parameters:
+ - name: id
+ in: path
+ description: id
+ required: true
+ type: integer
+ format: int32
+ responses:
+ '200':
+ description: OK
+ schema:
+ $ref: '#/definitions/Book'
+ '401':
+ description: Unauthorized
+ '403':
+ description: Forbidden
+ '404':
+ description: Not Found
+ security:
+ - api_key: []
+ /v1/category/:
+ get:
+ tags:
+ - category-api
+ summary: 获取全部分类
+ operationId: getAllUsingGET
+ consumes:
+ - application/json
+ produces:
+ - '*/*'
+ responses:
+ '200':
+ description: OK
+ schema:
+ type: array
+ items:
+ $ref: '#/definitions/Category'
+ '401':
+ description: Unauthorized
+ '403':
+ description: Forbidden
+ '404':
+ description: Not Found
+ '/v1/category/{id}':
+ get:
+ tags:
+ - category-api
+ summary: 根据ID获取分类
+ operationId: getUsingGET
+ consumes:
+ - application/json
+ produces:
+ - '*/*'
+ parameters:
+ - name: id
+ in: path
+ description: id
+ required: true
+ type: integer
+ format: int32
+ responses:
+ '200':
+ description: OK
+ schema:
+ $ref: '#/definitions/Category'
+ '401':
+ description: Unauthorized
+ '403':
+ description: Forbidden
+ '404':
+ description: Not Found
+securityDefinitions:
+ api_key:
+ type: apiKey
+ name: api_key
+ in: header
+definitions:
+ Book:
+ type: object
+ properties:
+ author:
+ type: string
+ description: 作者
+ categoryId:
+ type: integer
+ format: int32
+ id:
+ type: integer
+ format: int32
+ name:
+ type: string
+ description: 书名
+ Category:
+ type: object
+ properties:
+ id:
+ type: integer
+ format: int32
+ name:
+ type: string
diff --git a/swagger-server/src/test/java/com/example/server/SwaggerServerApplicationTests.java b/swagger-server/src/test/java/com/example/server/SwaggerServerApplicationTests.java
new file mode 100644
index 0000000..585db9d
--- /dev/null
+++ b/swagger-server/src/test/java/com/example/server/SwaggerServerApplicationTests.java
@@ -0,0 +1,22 @@
+package com.example.server;
+
+import com.example.server.api.BookApi;
+import org.assertj.core.api.Assertions;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.test.context.junit4.SpringRunner;
+
+@RunWith(SpringRunner.class)
+@SpringBootTest
+public class SwaggerServerApplicationTests {
+
+ @Autowired
+ private BookApi bookApi;
+
+ @Test
+ public void contextLoads() throws Exception {
+ Assertions.assertThat(bookApi).isNotNull();
+ }
+}
diff --git a/swagger-server/src/test/java/com/example/server/api/BookApiMockTest.java b/swagger-server/src/test/java/com/example/server/api/BookApiMockTest.java
new file mode 100644
index 0000000..649080c
--- /dev/null
+++ b/swagger-server/src/test/java/com/example/server/api/BookApiMockTest.java
@@ -0,0 +1,97 @@
+package com.example.server.api;
+
+import static org.hamcrest.Matchers.hasSize;
+import static org.hamcrest.Matchers.is;
+import static org.hamcrest.Matchers.isOneOf;
+import static org.mockito.Mockito.when;
+import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
+
+import com.example.server.model.Book;
+import com.example.server.service.BookService;
+import com.google.common.collect.Lists;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
+import org.springframework.boot.test.mock.mockito.MockBean;
+import org.springframework.http.MediaType;
+import org.springframework.test.context.junit4.SpringRunner;
+import org.springframework.test.web.servlet.MockMvc;
+import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
+
+/**
+ * Created by Damon on 2017/10/20.
+ */
+@RunWith(SpringRunner.class)
+@WebMvcTest(BookApi.class)
+public class BookApiMockTest {
+
+ @Autowired
+ private MockMvc mockMvc;
+
+ @MockBean
+ private BookService bookService;
+
+ @Test
+ public void getShouldReturnSpecifiedBook() throws Exception {
+ when(bookService.getById(1)).thenReturn(new Book(1, 1, "Clean Code", "Martin"));
+ mockMvc.perform(MockMvcRequestBuilders.get("/v1/book/1").accept(MediaType.ALL))
+ .andDo(print())
+ .andExpect(status().isOk())
+ .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
+ .andExpect(jsonPath("$.id", is(1)));
+ }
+
+ @Test
+ public void getByInvalidIdShouldReturnDefault() throws Exception {
+ when(bookService.getById(5)).thenReturn(new Book(-1, -1, "NOT EXIST", "NO AUTHOR"));
+ mockMvc.perform(MockMvcRequestBuilders.get("/v1/book/5").accept(MediaType.ALL))
+ .andDo(print())
+ .andExpect(status().isOk())
+ .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
+ .andExpect(jsonPath("$.id", is(-1)));
+ }
+
+ @Test
+ public void getByCategoryIdShouldReturnBooksOfThisCategory() throws Exception {
+ when(bookService.getByCategoryId(1)).thenReturn(Lists.newArrayList(
+ new Book(1, 1, "Clean Code", "Martin"),
+ new Book(2, 1, "Effective Java", "Joshua Bloch"),
+ new Book(3, 2, "挪威的森林", "村上春树")
+ ));
+ mockMvc.perform(MockMvcRequestBuilders
+ .get("/v1/book/getByCategoryId").param("id", "1").accept(MediaType.ALL))
+ .andDo(print())
+ .andExpect(status().isOk())
+ .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
+ .andExpect(jsonPath("$", hasSize(3)));
+ }
+
+ @Test
+ public void getByInvalidCategoryIdShouldReturnEmpty() throws Exception {
+ when(bookService.getByCategoryId(1)).thenReturn(Lists.newArrayList(
+ new Book(1, 1, "Clean Code", "Martin"),
+ new Book(2, 1, "Effective Java", "Joshua Bloch"),
+ new Book(3, 2, "挪威的森林", "村上春树")
+ ));
+ mockMvc.perform(MockMvcRequestBuilders
+ .get("/v1/book/getByCategoryId").param("id", "2").accept(MediaType.ALL))
+ .andDo(print())
+ .andExpect(status().isOk())
+ .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
+ .andExpect(jsonPath("$", hasSize(0)));
+ }
+
+ @Test
+ public void updateShouldReturnBoolean() throws Exception {
+ mockMvc.perform(MockMvcRequestBuilders
+ .post("/v1/book/update").param("id", "1").accept(MediaType.ALL))
+ .andDo(print())
+ .andExpect(status().isOk())
+ .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
+ .andExpect(content().string(isOneOf("true", "false")));
+ }
+}
diff --git a/swagger-server/src/test/java/com/example/server/api/CategoryApiMockTest.java b/swagger-server/src/test/java/com/example/server/api/CategoryApiMockTest.java
new file mode 100644
index 0000000..060823a
--- /dev/null
+++ b/swagger-server/src/test/java/com/example/server/api/CategoryApiMockTest.java
@@ -0,0 +1,82 @@
+package com.example.server.api;
+
+import static org.hamcrest.Matchers.hasSize;
+import static org.hamcrest.Matchers.is;
+import static org.mockito.Mockito.when;
+import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
+
+import com.example.server.model.Category;
+import com.example.server.service.CategoryService;
+import com.google.common.collect.Lists;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
+import org.springframework.boot.test.mock.mockito.MockBean;
+import org.springframework.http.MediaType;
+import org.springframework.test.context.junit4.SpringRunner;
+import org.springframework.test.web.servlet.MockMvc;
+import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
+
+/**
+ *
Created by Damon on 2017/10/20.
+ */
+@RunWith(SpringRunner.class)
+@WebMvcTest(CategoryApi.class)
+public class CategoryApiMockTest {
+
+ @Autowired
+ private MockMvc mockMvc;
+
+ @MockBean
+ private CategoryService categoryService;
+
+ @Test
+ public void getAllShouldReturnAllCategories() throws Exception {
+ when(categoryService.getAll()).thenReturn(Lists.newArrayList(
+ new Category(1, "技术"),
+ new Category(2, "文学")
+ ));
+ mockMvc.perform(MockMvcRequestBuilders.get("/v1/category/").accept(MediaType.ALL))
+ .andDo(print())
+ .andExpect(status().isOk())
+ .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
+ .andExpect(jsonPath("$", hasSize(2)));
+ }
+
+ @Test
+ public void getAllShouldReturnEmpty() throws Exception {
+ when(categoryService.getAll()).thenReturn(Lists.newArrayList());
+ mockMvc.perform(MockMvcRequestBuilders.get("/v1/category/").accept(MediaType.ALL))
+ .andDo(print())
+ .andExpect(status().isOk())
+ .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
+ .andExpect(jsonPath("$", hasSize(0)));
+ }
+
+
+ @Test
+ public void getShouldReturnSpecifiedCategory() throws Exception {
+ when(categoryService.get(1)).thenReturn(new Category(1, "技术"));
+ mockMvc.perform(MockMvcRequestBuilders
+ .get("/v1/category/1").accept(MediaType.ALL))
+ .andDo(print())
+ .andExpect(status().isOk())
+ .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
+ .andExpect(jsonPath("$.id", is(1)));
+ }
+
+ @Test
+ public void getByInvalidIdShouldReturnDefault() throws Exception {
+ when(categoryService.get(5)).thenReturn(new Category(-1, "NOT EXIST"));
+ mockMvc.perform(MockMvcRequestBuilders
+ .get("/v1/category/5").accept(MediaType.ALL))
+ .andDo(print())
+ .andExpect(status().isOk())
+ .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
+ .andExpect(jsonPath("$.id", is(-1)));
+ }
+}