added java petstore sample

This commit is contained in:
Tony Tam
2012-08-24 19:21:40 -07:00
parent 52587de715
commit 038402abb3
25 changed files with 1307 additions and 25 deletions

View File

@@ -42,6 +42,21 @@ cd samples/petstore/scala
mvn package mvn package
</pre> </pre>
Do the same for `java` by running `./bin/java-petstore.sh`
#### Generating a client from flat files
If you don't want to call your server, you can save the swagger spec files into a directory and pass an argument
to the code generator like this:
<pre>
-DfileMap=/path/to/files
</per>
Or for example:
License License
------- -------

6
bin/java-petstore-filemap.sh Executable file
View File

@@ -0,0 +1,6 @@
#!/bin/bash
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
export CLASSPATH="$DIR/../target/lib/*:$DIR/../target/*"
export JAVA_OPTS="${JAVA_OPTS} -Xmx1024M -DloggerPath=conf/log4j.properties -DfileMap=src/test/resources/petstore "
scala $WORDNIK_OPTS $JAVA_CONFIG_OPTIONS -cp $CLASSPATH "$@" src/main/scala/JavaPetstoreCodegen.scala http://petstore.swagger.wordnik.com/api/resources.json special-key

View File

@@ -1,16 +1,6 @@
#!/bin/bash #!/bin/bash
echo "" > classpath.txt DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
for file in `ls target/*.jar`;
do echo -n '' >> classpath.txt;
echo -n $file >> classpath.txt;
echo -n ':' >> classpath.txt;
done
for file in `ls target/lib`;
do echo -n 'target/lib/' >> classpath.txt;
echo -n $file >> classpath.txt;
echo -n ':' >> classpath.txt;
done
export CLASSPATH=$(cat classpath.txt) export CLASSPATH="$DIR/../target/lib/*:$DIR/../target/*"
export JAVA_OPTS="${JAVA_OPTS} -Xmx1024M -DloggerPath=conf/log4j.properties" export JAVA_OPTS="${JAVA_OPTS} -Xmx1024M -DloggerPath=conf/log4j.properties"
scala $WORDNIK_OPTS $JAVA_CONFIG_OPTIONS -cp $CLASSPATH "$@" src/main/scala/JavaPetstoreCodegen.scala http://petstore.swagger.wordnik.com/api/resources.json special-key scala $WORDNIK_OPTS $JAVA_CONFIG_OPTIONS -cp $CLASSPATH "$@" src/main/scala/JavaPetstoreCodegen.scala http://petstore.swagger.wordnik.com/api/resources.json special-key

View File

@@ -0,0 +1,225 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.wordnik</groupId>
<artifactId>swagger-client</artifactId>
<packaging>jar</packaging>
<name>swagger-client</name>
<version>1.0</version>
<scm>
<connection>scm:git:git@github.com:wordnik/swagger-mustache.git</connection>
<developerConnection>scm:git:git@github.com:wordnik/swagger-mustache.git</developerConnection>
<url>https://github.com/wordnik/swagger-mustache</url>
</scm>
<prerequisites>
<maven>2.2.0</maven>
</prerequisites>
<pluginRepositories>
<pluginRepository>
<id>scala-tools.org</id>
<name>Scala-Tools Maven2 Repository</name>
<url>http://scala-tools.org/repo-releases</url>
</pluginRepository>
<pluginRepository>
<id>maven-mongodb-plugin-repo</id>
<name>maven mongodb plugin repository</name>
<url>http://maven-mongodb-plugin.googlecode.com/svn/maven/repo</url>
<layout>default</layout>
</pluginRepository>
</pluginRepositories>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.12</version>
<configuration>
<systemProperties>
<property>
<name>loggerPath</name>
<value>conf/log4j.properties</value>
</property>
</systemProperties>
<argLine>-Xms512m -Xmx1500m</argLine>
<parallel>methods</parallel>
<forkMode>pertest</forkMode>
</configuration>
</plugin>
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}/lib</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
<!-- attach test jar -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.2</version>
<executions>
<execution>
<goals>
<goal>jar</goal>
<goal>test-jar</goal>
</goals>
</execution>
</executions>
<configuration>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<executions>
<execution>
<id>add_sources</id>
<phase>generate-sources</phase>
<goals>
<goal>add-source</goal>
</goals>
<configuration>
<sources>
<source>src/main/java</source>
</sources>
</configuration>
</execution>
<execution>
<id>add_test_sources</id>
<phase>generate-test-sources</phase>
<goals>
<goal>add-test-source</goal>
</goals>
<configuration>
<sources>
<source>src/test/java</source>
</sources>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
<plugin>
<groupId>org.scala-tools</groupId>
<artifactId>maven-scala-plugin</artifactId>
<version>2.15.2</version>
<executions>
<execution>
<id>scala-compile-first</id>
<phase>process-resources</phase>
<goals>
<goal>add-source</goal>
<goal>compile</goal>
</goals>
</execution>
<execution>
<id>scala-test-compile</id>
<phase>process-test-resources</phase>
<goals>
<goal>testCompile</goal>
</goals>
</execution>
</executions>
<configuration>
<jvmArgs>
<jvmArg>-Xms128m</jvmArg>
<jvmArg>-Xmx1500m</jvmArg>
</jvmArgs>
</configuration>
</plugin>
</plugins>
</build>
<reporting>
<plugins>
<plugin>
<groupId>org.scala-tools</groupId>
<artifactId>maven-scala-plugin</artifactId>
<configuration>
<scalaVersion>${scala-version}</scalaVersion>
</configuration>
</plugin>
</plugins>
</reporting>
<dependencies>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-client</artifactId>
<version>${jersey-version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.scala-lang</groupId>
<artifactId>scala-library</artifactId>
<version>${scala-version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.wordnik</groupId>
<artifactId>swagger-core_2.9.1</artifactId>
<version>${swagger-core-version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.scalatest</groupId>
<artifactId>scalatest_2.9.1</artifactId>
<version>${scala-test-version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit-version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<repositories>
<repository>
<id>scala-tools.org</id>
<name>Scala-Tools Maven2 Repository</name>
<url>http://scala-tools.org/repo-releases</url>
</repository>
<repository>
<id>wordnik-ci-aws</id>
<url>https://ci.aws.wordnik.com/artifactory/libs-snapshots/</url>
</repository>
<repository>
<id>wordnik-ci-aws-maven</id>
<url>https://ci.aws.wordnik.com/artifactory/m2-snapshots/</url>
</repository>
<repository>
<id>wordnik-ci-aws-remote</id>
<url>https://ci.aws.wordnik.com/artifactory/remote-repos/</url>
</repository>
</repositories>
<properties>
<jersey-version>1.7</jersey-version>
<swagger-core-version>1.02-SNAPSHOT</swagger-core-version>
<scala-version>2.9.1-1</scala-version>
<junit-version>4.8.1</junit-version>
<maven-plugin.version>1.0.0</maven-plugin.version>
<scala-test-version>1.6.1</scala-test-version>
<junit-version>4.8.1</junit-version>
<scala-test-version>1.6.1</scala-test-version>
</properties>
</project>

View File

@@ -0,0 +1,29 @@
package com.wordnik.client;
public class ApiException extends Exception {
int code = 0;
String message = null;
public ApiException() {}
public ApiException(int code, String message) {
this.code = code;
this.message = message;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}

View File

@@ -0,0 +1,131 @@
package com.wordnik.client;
import com.wordnik.swagger.core.util.JsonUtil;
import org.codehaus.jackson.type.JavaType;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.api.client.filter.LoggingFilter;
import com.sun.jersey.api.client.WebResource.Builder;
import javax.ws.rs.core.MediaType;
import java.util.Map;
import java.util.HashMap;
import java.util.List;
import java.io.IOException;
public class ApiInvoker {
private static ApiInvoker INSTANCE = new ApiInvoker();
private Map<String, Client> hostMap = new HashMap<String, Client>();
private Map<String, String> defaultHeaderMap = new HashMap<String, String>();
public static ApiInvoker getInstance() {
return INSTANCE;
}
public void addDefaultHeader(String key, String value) {
defaultHeaderMap.put(key, value);
}
public String escapeString(String str) {
return str;
}
public static Object deserialize(String json, String containerType, Class cls) throws ApiException {
try{
if("List".equals(containerType)) {
JavaType typeInfo = org.codehaus.jackson.map.type.TypeFactory.collectionType(List.class, cls);
List response = (List<?>) JsonUtil.getJsonMapper().readValue(json, typeInfo);
return response;
}
else if(String.class.equals(cls)) {
if(json != null && json.startsWith("\"") && json.endsWith("\"") && json.length() > 1) {
return json.substring(1, json.length() - 2);
}
else
return json;
}
else {
return JsonUtil.getJsonMapper().readValue(json, cls);
}
}
catch (IOException e) {
throw new ApiException(500, e.getMessage());
}
}
public static String serialize(Object obj) throws ApiException {
try {
if (obj != null) return JsonUtil.getJsonMapper().writeValueAsString(obj);
else return null;
}
catch (Exception e) {
throw new ApiException(500, e.getMessage());
}
}
public String invokeAPI(String host, String path, String method, Map<String, String> queryParams, Object body, Map<String, String> headerParams) throws ApiException {
Client client = getClient(host);
StringBuilder b = new StringBuilder();
for(String key : queryParams.keySet()) {
String value = queryParams.get(key);
if (value != null){
if(b.toString().length() == 0) b.append("?");
else b.append("&");
b.append(escapeString(key)).append("=").append(escapeString(value));
}
}
String querystring = b.toString();
Builder builder = client.resource(host + path + querystring).type("application/json");
for(String key : headerParams.keySet()) {
builder.header(key, headerParams.get(key));
}
for(String key : defaultHeaderMap.keySet()) {
if(!headerParams.containsKey(key)) {
builder.header(key, defaultHeaderMap.get(key));
}
}
ClientResponse response = null;
if("GET".equals(method)) {
response = (ClientResponse) builder.get(ClientResponse.class);
}
else if ("POST".equals(method)) {
response = builder.post(ClientResponse.class, serialize(body));
}
else if ("PUT".equals(method)) {
response = builder.put(ClientResponse.class, serialize(body));
}
else if ("DELETE".equals(method)) {
response = builder.delete(ClientResponse.class, serialize(body));
}
else {
throw new ApiException(500, "unknown method type " + method);
}
if(response.getClientResponseStatus() == ClientResponse.Status.OK) {
return (String) response.getEntity(String.class);
}
else {
throw new ApiException(
response.getClientResponseStatus().getStatusCode(),
response.getEntity(String.class));
}
}
private Client getClient(String host) {
if(!hostMap.containsKey(host)) {
Client client = Client.create();
client.addFilter(new LoggingFilter());
hostMap.put(host, client);
}
return hostMap.get(host);
}
}

View File

@@ -0,0 +1,174 @@
package com.wordnik.petstore.api;
import com.wordnik.client.ApiException;
import com.wordnik.client.ApiInvoker;
import com.wordnik.petstore.model.Pet;
import java.util.*;
public class PetApi {
String basePath = "http://petstore.swagger.wordnik.com/api";
ApiInvoker apiInvoker = ApiInvoker.getInstance();
public ApiInvoker getInvoker() {
return apiInvoker;
}
public void setBasePath(String basePath) {
this.basePath = basePath;
}
public String getBasePath() {
return basePath;
}
public Pet getPetById (String petId) throws ApiException {
// create path and map variables
String path = "/pet.{format}/{petId}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "petId" + "\\}", apiInvoker.escapeString(petId));
// query params
Map<String, String> queryParams = new HashMap<String, String>();
Map<String, String> headerParams = new HashMap<String, String>();
// verify required params are set
if(petId == null ) {
throw new ApiException(400, "missing required params");
}
try {
String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams);
if(response != null){
return (Pet) ApiInvoker.deserialize(response, "", Pet.class);
}
else {
return null;
}
} catch (ApiException ex) {
if(ex.getCode() == 404) {
return null;
}
else {
throw ex;
}
}
}
public void addPet (Pet body) throws ApiException {
// create path and map variables
String path = "/pet.{format}".replaceAll("\\{format\\}","json");
// query params
Map<String, String> queryParams = new HashMap<String, String>();
Map<String, String> headerParams = new HashMap<String, String>();
// verify required params are set
if(body == null ) {
throw new ApiException(400, "missing required params");
}
try {
String response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, body, headerParams);
if(response != null){
return ;
}
else {
return ;
}
} catch (ApiException ex) {
if(ex.getCode() == 404) {
return ;
}
else {
throw ex;
}
}
}
public void updatePet (Pet body) throws ApiException {
// create path and map variables
String path = "/pet.{format}".replaceAll("\\{format\\}","json");
// query params
Map<String, String> queryParams = new HashMap<String, String>();
Map<String, String> headerParams = new HashMap<String, String>();
// verify required params are set
if(body == null ) {
throw new ApiException(400, "missing required params");
}
try {
String response = apiInvoker.invokeAPI(basePath, path, "PUT", queryParams, body, headerParams);
if(response != null){
return ;
}
else {
return ;
}
} catch (ApiException ex) {
if(ex.getCode() == 404) {
return ;
}
else {
throw ex;
}
}
}
public List<Pet> findPetsByStatus (String status) throws ApiException {
// create path and map variables
String path = "/pet.{format}/findByStatus".replaceAll("\\{format\\}","json");
// query params
Map<String, String> queryParams = new HashMap<String, String>();
Map<String, String> headerParams = new HashMap<String, String>();
// verify required params are set
if(status == null ) {
throw new ApiException(400, "missing required params");
}
if(!"null".equals(String.valueOf(status)))
queryParams.put("status", String.valueOf(status));
try {
String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams);
if(response != null){
return (List<Pet>) ApiInvoker.deserialize(response, "List", Pet.class);
}
else {
return null;
}
} catch (ApiException ex) {
if(ex.getCode() == 404) {
return null;
}
else {
throw ex;
}
}
}
public List<Pet> findPetsByTags (String tags) throws ApiException {
// create path and map variables
String path = "/pet.{format}/findByTags".replaceAll("\\{format\\}","json");
// query params
Map<String, String> queryParams = new HashMap<String, String>();
Map<String, String> headerParams = new HashMap<String, String>();
// verify required params are set
if(tags == null ) {
throw new ApiException(400, "missing required params");
}
if(!"null".equals(String.valueOf(tags)))
queryParams.put("tags", String.valueOf(tags));
try {
String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams);
if(response != null){
return (List<Pet>) ApiInvoker.deserialize(response, "List", Pet.class);
}
else {
return null;
}
} catch (ApiException ex) {
if(ex.getCode() == 404) {
return null;
}
else {
throw ex;
}
}
}
}

View File

@@ -0,0 +1,112 @@
package com.wordnik.petstore.api;
import com.wordnik.client.ApiException;
import com.wordnik.client.ApiInvoker;
import com.wordnik.petstore.model.Order;
import java.util.*;
public class StoreApi {
String basePath = "http://petstore.swagger.wordnik.com/api";
ApiInvoker apiInvoker = ApiInvoker.getInstance();
public ApiInvoker getInvoker() {
return apiInvoker;
}
public void setBasePath(String basePath) {
this.basePath = basePath;
}
public String getBasePath() {
return basePath;
}
public Order getOrderById (String orderId) throws ApiException {
// create path and map variables
String path = "/store.{format}/order/{orderId}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "orderId" + "\\}", apiInvoker.escapeString(orderId));
// query params
Map<String, String> queryParams = new HashMap<String, String>();
Map<String, String> headerParams = new HashMap<String, String>();
// verify required params are set
if(orderId == null ) {
throw new ApiException(400, "missing required params");
}
try {
String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams);
if(response != null){
return (Order) ApiInvoker.deserialize(response, "", Order.class);
}
else {
return null;
}
} catch (ApiException ex) {
if(ex.getCode() == 404) {
return null;
}
else {
throw ex;
}
}
}
public void deleteOrder (String orderId) throws ApiException {
// create path and map variables
String path = "/store.{format}/order/{orderId}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "orderId" + "\\}", apiInvoker.escapeString(orderId));
// query params
Map<String, String> queryParams = new HashMap<String, String>();
Map<String, String> headerParams = new HashMap<String, String>();
// verify required params are set
if(orderId == null ) {
throw new ApiException(400, "missing required params");
}
try {
String response = apiInvoker.invokeAPI(basePath, path, "DELETE", queryParams, null, headerParams);
if(response != null){
return ;
}
else {
return ;
}
} catch (ApiException ex) {
if(ex.getCode() == 404) {
return ;
}
else {
throw ex;
}
}
}
public void placeOrder (Order body) throws ApiException {
// create path and map variables
String path = "/store.{format}/order".replaceAll("\\{format\\}","json");
// query params
Map<String, String> queryParams = new HashMap<String, String>();
Map<String, String> headerParams = new HashMap<String, String>();
// verify required params are set
if(body == null ) {
throw new ApiException(400, "missing required params");
}
try {
String response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, body, headerParams);
if(response != null){
return ;
}
else {
return ;
}
} catch (ApiException ex) {
if(ex.getCode() == 404) {
return ;
}
else {
throw ex;
}
}
}
}

View File

@@ -0,0 +1,257 @@
package com.wordnik.petstore.api;
import com.wordnik.client.ApiException;
import com.wordnik.client.ApiInvoker;
import com.wordnik.petstore.model.User;
import java.util.*;
public class UserApi {
String basePath = "http://petstore.swagger.wordnik.com/api";
ApiInvoker apiInvoker = ApiInvoker.getInstance();
public ApiInvoker getInvoker() {
return apiInvoker;
}
public void setBasePath(String basePath) {
this.basePath = basePath;
}
public String getBasePath() {
return basePath;
}
public void createUsersWithArrayInput (List<User> body) throws ApiException {
// create path and map variables
String path = "/user.{format}/createWithArray".replaceAll("\\{format\\}","json");
// query params
Map<String, String> queryParams = new HashMap<String, String>();
Map<String, String> headerParams = new HashMap<String, String>();
// verify required params are set
if(body == null ) {
throw new ApiException(400, "missing required params");
}
try {
String response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, body, headerParams);
if(response != null){
return ;
}
else {
return ;
}
} catch (ApiException ex) {
if(ex.getCode() == 404) {
return ;
}
else {
throw ex;
}
}
}
public void createUser (User body) throws ApiException {
// create path and map variables
String path = "/user.{format}".replaceAll("\\{format\\}","json");
// query params
Map<String, String> queryParams = new HashMap<String, String>();
Map<String, String> headerParams = new HashMap<String, String>();
// verify required params are set
if(body == null ) {
throw new ApiException(400, "missing required params");
}
try {
String response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, body, headerParams);
if(response != null){
return ;
}
else {
return ;
}
} catch (ApiException ex) {
if(ex.getCode() == 404) {
return ;
}
else {
throw ex;
}
}
}
public void createUsersWithListInput (List<User> body) throws ApiException {
// create path and map variables
String path = "/user.{format}/createWithList".replaceAll("\\{format\\}","json");
// query params
Map<String, String> queryParams = new HashMap<String, String>();
Map<String, String> headerParams = new HashMap<String, String>();
// verify required params are set
if(body == null ) {
throw new ApiException(400, "missing required params");
}
try {
String response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, body, headerParams);
if(response != null){
return ;
}
else {
return ;
}
} catch (ApiException ex) {
if(ex.getCode() == 404) {
return ;
}
else {
throw ex;
}
}
}
public void updateUser (String username, User body) throws ApiException {
// create path and map variables
String path = "/user.{format}/{username}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "username" + "\\}", apiInvoker.escapeString(username));
// query params
Map<String, String> queryParams = new HashMap<String, String>();
Map<String, String> headerParams = new HashMap<String, String>();
// verify required params are set
if(username == null || body == null ) {
throw new ApiException(400, "missing required params");
}
try {
String response = apiInvoker.invokeAPI(basePath, path, "PUT", queryParams, body, headerParams);
if(response != null){
return ;
}
else {
return ;
}
} catch (ApiException ex) {
if(ex.getCode() == 404) {
return ;
}
else {
throw ex;
}
}
}
public void deleteUser (String username) throws ApiException {
// create path and map variables
String path = "/user.{format}/{username}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "username" + "\\}", apiInvoker.escapeString(username));
// query params
Map<String, String> queryParams = new HashMap<String, String>();
Map<String, String> headerParams = new HashMap<String, String>();
// verify required params are set
if(username == null ) {
throw new ApiException(400, "missing required params");
}
try {
String response = apiInvoker.invokeAPI(basePath, path, "DELETE", queryParams, null, headerParams);
if(response != null){
return ;
}
else {
return ;
}
} catch (ApiException ex) {
if(ex.getCode() == 404) {
return ;
}
else {
throw ex;
}
}
}
public User getUserByName (String username) throws ApiException {
// create path and map variables
String path = "/user.{format}/{username}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "username" + "\\}", apiInvoker.escapeString(username));
// query params
Map<String, String> queryParams = new HashMap<String, String>();
Map<String, String> headerParams = new HashMap<String, String>();
// verify required params are set
if(username == null ) {
throw new ApiException(400, "missing required params");
}
try {
String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams);
if(response != null){
return (User) ApiInvoker.deserialize(response, "", User.class);
}
else {
return null;
}
} catch (ApiException ex) {
if(ex.getCode() == 404) {
return null;
}
else {
throw ex;
}
}
}
public String loginUser (String username, String password) throws ApiException {
// create path and map variables
String path = "/user.{format}/login".replaceAll("\\{format\\}","json");
// query params
Map<String, String> queryParams = new HashMap<String, String>();
Map<String, String> headerParams = new HashMap<String, String>();
// verify required params are set
if(username == null || password == null ) {
throw new ApiException(400, "missing required params");
}
if(!"null".equals(String.valueOf(username)))
queryParams.put("username", String.valueOf(username));
if(!"null".equals(String.valueOf(password)))
queryParams.put("password", String.valueOf(password));
try {
String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams);
if(response != null){
return (String) ApiInvoker.deserialize(response, "", String.class);
}
else {
return null;
}
} catch (ApiException ex) {
if(ex.getCode() == 404) {
return null;
}
else {
throw ex;
}
}
}
public void logoutUser () throws ApiException {
// create path and map variables
String path = "/user.{format}/logout".replaceAll("\\{format\\}","json");
// query params
Map<String, String> queryParams = new HashMap<String, String>();
Map<String, String> headerParams = new HashMap<String, String>();
try {
String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams);
if(response != null){
return ;
}
else {
return ;
}
} catch (ApiException ex) {
if(ex.getCode() == 404) {
return ;
}
else {
throw ex;
}
}
}
}

View File

@@ -0,0 +1,30 @@
package com.wordnik.petstore.model;
public class Category {
private Long id = null;
private String name = null;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class Category {\n");
sb.append(" id: ").append(id).append("\n");
sb.append(" name: ").append(name).append("\n");
sb.append("}\n");
return sb.toString();
}
}

View File

@@ -0,0 +1,59 @@
package com.wordnik.petstore.model;
import java.util.Date;
public class Order {
private Long id = null;
private Long petId = null;
/* Order Status */
private String status = null;
private Integer quantity = null;
private Date shipDate = null;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getPetId() {
return petId;
}
public void setPetId(Long petId) {
this.petId = petId;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Integer getQuantity() {
return quantity;
}
public void setQuantity(Integer quantity) {
this.quantity = quantity;
}
public Date getShipDate() {
return shipDate;
}
public void setShipDate(Date shipDate) {
this.shipDate = shipDate;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class Order {\n");
sb.append(" id: ").append(id).append("\n");
sb.append(" petId: ").append(petId).append("\n");
sb.append(" status: ").append(status).append("\n");
sb.append(" quantity: ").append(quantity).append("\n");
sb.append(" shipDate: ").append(shipDate).append("\n");
sb.append("}\n");
return sb.toString();
}
}

View File

@@ -0,0 +1,70 @@
package com.wordnik.petstore.model;
import java.util.*;
import com.wordnik.petstore.model.Category;
import com.wordnik.petstore.model.Tag;
public class Pet {
private Long id = null;
private List<Tag> tags = new ArrayList<Tag>();
private Category category = null;
/* pet status in the store */
private String status = null;
private String name = null;
private List<String> photoUrls = new ArrayList<String>();
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public List<Tag> getTags() {
return tags;
}
public void setTags(List<Tag> tags) {
this.tags = tags;
}
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<String> getPhotoUrls() {
return photoUrls;
}
public void setPhotoUrls(List<String> photoUrls) {
this.photoUrls = photoUrls;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class Pet {\n");
sb.append(" id: ").append(id).append("\n");
sb.append(" tags: ").append(tags).append("\n");
sb.append(" category: ").append(category).append("\n");
sb.append(" status: ").append(status).append("\n");
sb.append(" name: ").append(name).append("\n");
sb.append(" photoUrls: ").append(photoUrls).append("\n");
sb.append("}\n");
return sb.toString();
}
}

View File

@@ -0,0 +1,30 @@
package com.wordnik.petstore.model;
public class Tag {
private Long id = null;
private String name = null;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class Tag {\n");
sb.append(" id: ").append(id).append("\n");
sb.append(" name: ").append(name).append("\n");
sb.append("}\n");
return sb.toString();
}
}

View File

@@ -0,0 +1,85 @@
package com.wordnik.petstore.model;
public class User {
private Long id = null;
private String lastName = null;
private String username = null;
private String phone = null;
private String email = null;
/* User Status */
private Integer userStatus = null;
private String firstName = null;
private String password = null;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Integer getUserStatus() {
return userStatus;
}
public void setUserStatus(Integer userStatus) {
this.userStatus = userStatus;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class User {\n");
sb.append(" id: ").append(id).append("\n");
sb.append(" lastName: ").append(lastName).append("\n");
sb.append(" username: ").append(username).append("\n");
sb.append(" phone: ").append(phone).append("\n");
sb.append(" email: ").append(email).append("\n");
sb.append(" userStatus: ").append(userStatus).append("\n");
sb.append(" firstName: ").append(firstName).append("\n");
sb.append(" password: ").append(password).append("\n");
sb.append("}\n");
return sb.toString();
}
}

View File

@@ -0,0 +1,29 @@
package com.wordnik.client;
public class ApiException extends Exception {
int code = 0;
String message = null;
public ApiException() {}
public ApiException(int code, String message) {
this.code = code;
this.message = message;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}

View File

@@ -43,6 +43,10 @@ public class ApiInvoker {
return response; return response;
} }
else if(String.class.equals(cls)) { else if(String.class.equals(cls)) {
if(json != null && json.startsWith("\"") && json.endsWith("\"") && json.length() > 1) {
return json.substring(1, json.length() - 2);
}
else
return json; return json;
} }
else { else {

View File

@@ -0,0 +1,28 @@
import com.wordnik.swagger.codegen.BasicJavaGenerator
import com.wordnik.swagger.core._
object JavaPetstoreCodegen extends BasicJavaGenerator {
def main(args: Array[String]) = generateClient(args)
override def packageName = "com.wordnik.petstore"
// location of templates
override def templateDir = "javaTemplates/"
// where to write generated code
override def destinationDir = "samples/petstore/java/src/main/java"
// package for models
override def modelPackage = Some("com.wordnik.petstore.model")
// package for api classes
override def apiPackage = Some("com.wordnik.petstore.api")
// supporting classes
override def supportingFiles =
List(
("apiInvoker.mustache", "samples/petstore/java/src/main/java/com/wordnik/client", "ApiInvoker.java"),
("apiException.mustache", "samples/petstore/java/src/main/java/com/wordnik/client", "ApiException.java"),
("pom.mustache", "samples/petstore/java", "pom.xml"))
}

View File

@@ -14,15 +14,15 @@
* limitations under the License. * limitations under the License.
*/ */
import com.wordnik.swagger.codegen.BasicGenerator package com.wordnik.swagger.codegen
import com.wordnik.swagger.core._ import com.wordnik.swagger.core._
object JavaCodegen extends JavaCodegen { object BasicJavaGenerator extends BasicJavaGenerator {
def main(args: Array[String]) = generateClient(args) def main(args: Array[String]) = generateClient(args)
} }
class JavaCodegen extends BasicGenerator { class BasicJavaGenerator extends BasicGenerator {
override def defaultIncludes = Set( override def defaultIncludes = Set(
"double", "double",
"int", "int",
@@ -32,13 +32,17 @@ class JavaCodegen extends BasicGenerator {
"boolean") "boolean")
override def typeMapping = Map( override def typeMapping = Map(
"Int" -> "int", "string" -> "String",
"string" -> "String") "int" -> "Integer",
"float" -> "Float",
"long" -> "Long",
"double" -> "Double",
"object" -> "Object")
override def packageName = "com.wordnik.client" override def packageName = "com.wordnik.client"
// location of templates // location of templates
override def templateDir = "src/main/resources/java" override def templateDir = "javaTemplates"
// template used for models // template used for models
modelTemplateFiles += "model.mustache" -> ".java" modelTemplateFiles += "model.mustache" -> ".java"
@@ -57,10 +61,10 @@ class JavaCodegen extends BasicGenerator {
"List" -> "java.util.List") "List" -> "java.util.List")
// package for models // package for models
override def modelPackage = Some("com.wordnik.javaPetstore.model") override def modelPackage = Some("com.wordnik.model")
// package for api classes // package for api classes
override def apiPackage = Some("com.wordnik.javaPetstore.api") override def apiPackage = Some("com.wordnik.api")
// file suffix // file suffix
override def fileSuffix = ".java" override def fileSuffix = ".java"
@@ -69,14 +73,14 @@ class JavaCodegen extends BasicGenerator {
override def processResponseClass(responseClass: String): Option[String] = { override def processResponseClass(responseClass: String): Option[String] = {
responseClass match { responseClass match {
case "void" => None case "void" => None
case e: String => Some(e.replaceAll("\\[", "<").replaceAll("\\]", ">")) case e: String => Some(typeMapping.getOrElse(e, e.replaceAll("\\[", "<").replaceAll("\\]", ">")))
} }
} }
override def processResponseDeclaration(responseClass: String): Option[String] = { override def processResponseDeclaration(responseClass: String): Option[String] = {
responseClass match { responseClass match {
case "void" => None case "void" => None
case e: String => Some(e.replaceAll("\\[", "<").replaceAll("\\]", ">")) case e: String => Some(typeMapping.getOrElse(e, e.replaceAll("\\[", "<").replaceAll("\\]", ">")))
} }
} }
@@ -86,11 +90,11 @@ class JavaCodegen extends BasicGenerator {
case n: Int => { case n: Int => {
if (dt.substring(0, n) == "Array") { if (dt.substring(0, n) == "Array") {
"List" + dt.substring(n).replaceAll("\\[", "<").replaceAll("\\]", ">") "List" + dt.substring(n).replaceAll("\\[", "<").replaceAll("\\]", ">")
} else dt + dt.substring(1).replaceAll("\\[", "<").replaceAll("\\]", ">") }
else dt.replaceAll("\\[", "<").replaceAll("\\]", ">")
} }
case _ => dt case _ => dt
} }
println("mapping: ", declaredType, typeMapping.getOrElse(declaredType, declaredType))
typeMapping.getOrElse(declaredType, declaredType) typeMapping.getOrElse(declaredType, declaredType)
} }

View File

@@ -0,0 +1 @@
{"apiVersion":"0.2","swaggerVersion":"1.1","basePath":"http://petstore.swagger.wordnik.com/api","resourcePath":"/pet","apis":[{"path":"/pet.{format}/{petId}","description":"Operations about pets","operations":[{"httpMethod":"GET","summary":"Find pet by ID","notes":"Returns a pet based on ID","responseClass":"Pet","nickname":"getPetById","parameters":[{"name":"petId","description":"ID of pet that needs to be fetched","paramType":"path","required":true,"allowMultiple":false,"dataType":"string"}],"errorResponses":[{"code":400,"reason":"Invalid ID supplied"},{"code":404,"reason":"Pet not found"}]}]},{"path":"/pet.{format}","description":"Operations about pets","operations":[{"httpMethod":"POST","summary":"Add a new pet to the store","responseClass":"void","nickname":"addPet","parameters":[{"description":"Pet object that needs to be added to the store","paramType":"body","required":true,"allowMultiple":false,"dataType":"Pet"}],"errorResponses":[{"code":405,"reason":"Invalid input"}]},{"httpMethod":"PUT","summary":"Update an existing pet","responseClass":"void","nickname":"updatePet","parameters":[{"description":"Pet object that needs to be updated in the store","paramType":"body","required":true,"allowMultiple":false,"dataType":"Pet"}],"errorResponses":[{"code":400,"reason":"Invalid ID supplied"},{"code":404,"reason":"Pet not found"},{"code":405,"reason":"Validation exception"}]}]},{"path":"/pet.{format}/findByStatus","description":"Operations about pets","operations":[{"httpMethod":"GET","summary":"Finds Pets by status","notes":"Multiple status values can be provided with comma seperated strings","responseClass":"List[Pet]","nickname":"findPetsByStatus","parameters":[{"name":"status","description":"Status values that need to be considered for filter","paramType":"query","defaultValue":"available","allowableValues":{"valueType":"LIST","values":["available","pending","sold"],"valueType":"LIST"},"required":true,"allowMultiple":true,"dataType":"string"}],"errorResponses":[{"code":400,"reason":"Invalid status value"}]}]},{"path":"/pet.{format}/findByTags","description":"Operations about pets","operations":[{"httpMethod":"GET","summary":"Finds Pets by tags","notes":"Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.","deprecated":true,"responseClass":"List[Pet]","nickname":"findPetsByTags","parameters":[{"name":"tags","description":"Tags to filter by","paramType":"query","required":true,"allowMultiple":true,"dataType":"string"}],"errorResponses":[{"code":400,"reason":"Invalid tag value"}]}]}],"models":{"Category":{"id":"Category","properties":{"id":{"type":"long"},"name":{"type":"string"}}},"Pet":{"id":"Pet","properties":{"tags":{"items":{"$ref":"Tag"},"type":"Array"},"id":{"type":"long"},"category":{"type":"Category"},"status":{"allowableValues":{"valueType":"LIST","values":["available","pending","sold"],"valueType":"LIST"},"description":"pet status in the store","type":"string"},"name":{"type":"string"},"photoUrls":{"items":{"type":"string"},"type":"Array"}}},"Tag":{"id":"Tag","properties":{"id":{"type":"long"},"name":{"type":"string"}}}}}

View File

@@ -0,0 +1 @@
{"apiVersion":"0.2","swaggerVersion":"1.1","basePath":"http://petstore.swagger.wordnik.com/api","apis":[{"path":"/store.{format}","description":"Operations about store"},{"path":"/pet.{format}","description":"Operations about pets"},{"path":"/user.{format}","description":"Operations about user"}]}

View File

@@ -0,0 +1 @@
{"apiVersion":"0.2","swaggerVersion":"1.1","basePath":"http://petstore.swagger.wordnik.com/api","resourcePath":"/store","apis":[{"path":"/store.{format}/order/{orderId}","description":"Operations about store","operations":[{"httpMethod":"GET","summary":"Find purchase order by ID","notes":"For valid response try integer IDs with value <= 5. Anything above 5 or nonintegers will generate API errors","responseClass":"Order","nickname":"getOrderById","parameters":[{"name":"orderId","description":"ID of pet that needs to be fetched","paramType":"path","required":true,"allowMultiple":false,"dataType":"string"}],"errorResponses":[{"code":400,"reason":"Invalid ID supplied"},{"code":404,"reason":"Order not found"}]},{"httpMethod":"DELETE","summary":"Delete purchase order by ID","notes":"For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors","responseClass":"void","nickname":"deleteOrder","parameters":[{"name":"orderId","description":"ID of the order that needs to be deleted","paramType":"path","required":true,"allowMultiple":false,"dataType":"string"}],"errorResponses":[{"code":400,"reason":"Invalid ID supplied"},{"code":404,"reason":"Order not found"}]}]},{"path":"/store.{format}/order","description":"Operations about store","operations":[{"httpMethod":"POST","summary":"Place an order for a pet","responseClass":"void","nickname":"placeOrder","parameters":[{"description":"order placed for purchasing the pet","paramType":"body","required":true,"allowMultiple":false,"dataType":"Order"}],"errorResponses":[{"code":400,"reason":"Invalid order"}]}]}],"models":{"Order":{"id":"Order","properties":{"id":{"type":"long"},"petId":{"type":"long"},"status":{"allowableValues":{"valueType":"LIST","values":["placed"," approved"," delivered"],"valueType":"LIST"},"description":"Order Status","type":"string"},"quantity":{"type":"int"},"shipDate":{"type":"Date"}}}}}

View File

@@ -0,0 +1 @@
{"apiVersion":"0.2","swaggerVersion":"1.1","basePath":"http://petstore.swagger.wordnik.com/api","resourcePath":"/user","apis":[{"path":"/user.{format}/createWithArray","description":"Operations about user","operations":[{"httpMethod":"POST","summary":"Creates list of users with given input array","responseClass":"void","nickname":"createUsersWithArrayInput","parameters":[{"description":"List of user object","paramType":"body","required":true,"allowMultiple":false,"dataType":"Array[User]"}]}]},{"path":"/user.{format}","description":"Operations about user","operations":[{"httpMethod":"POST","summary":"Create user","notes":"This can only be done by the logged in user.","responseClass":"void","nickname":"createUser","parameters":[{"description":"Created user object","paramType":"body","required":true,"allowMultiple":false,"dataType":"User"}]}]},{"path":"/user.{format}/createWithList","description":"Operations about user","operations":[{"httpMethod":"POST","summary":"Creates list of users with given list input","responseClass":"void","nickname":"createUsersWithListInput","parameters":[{"description":"List of user object","paramType":"body","required":true,"allowMultiple":false,"dataType":"List[User]"}]}]},{"path":"/user.{format}/{username}","description":"Operations about user","operations":[{"httpMethod":"PUT","summary":"Updated user","notes":"This can only be done by the logged in user.","responseClass":"void","nickname":"updateUser","parameters":[{"name":"username","description":"name that need to be deleted","paramType":"path","required":true,"allowMultiple":false,"dataType":"string"},{"description":"Updated user object","paramType":"body","required":true,"allowMultiple":false,"dataType":"User"}],"errorResponses":[{"code":400,"reason":"Invalid username supplied"},{"code":404,"reason":"User not found"}]},{"httpMethod":"DELETE","summary":"Delete user","notes":"This can only be done by the logged in user.","responseClass":"void","nickname":"deleteUser","parameters":[{"name":"username","description":"The name that needs to be deleted","paramType":"path","required":true,"allowMultiple":false,"dataType":"string"}],"errorResponses":[{"code":400,"reason":"Invalid username supplied"},{"code":404,"reason":"User not found"}]},{"httpMethod":"GET","summary":"Get user by user name","responseClass":"User","nickname":"getUserByName","parameters":[{"name":"username","description":"The name that needs to be fetched. Use user1 for testing.","paramType":"path","required":true,"allowMultiple":false,"dataType":"string"}],"errorResponses":[{"code":400,"reason":"Invalid username supplied"},{"code":404,"reason":"User not found"}]}]},{"path":"/user.{format}/login","description":"Operations about user","operations":[{"httpMethod":"GET","summary":"Logs user into the system","responseClass":"string","nickname":"loginUser","parameters":[{"name":"username","description":"The user name for login","paramType":"query","required":true,"allowMultiple":false,"dataType":"string"},{"name":"password","description":"The password for login in clear text","paramType":"query","required":true,"allowMultiple":false,"dataType":"string"}],"errorResponses":[{"code":400,"reason":"Invalid username and password combination"}]}]},{"path":"/user.{format}/logout","description":"Operations about user","operations":[{"httpMethod":"GET","summary":"Logs out current logged in user session","responseClass":"void","nickname":"logoutUser"}]}],"models":{"User":{"id":"User","properties":{"id":{"type":"Long"},"lastName":{"type":"string"},"phone":{"type":"string"},"username":{"type":"string"},"email":{"type":"string"},"userStatus":{"allowableValues":{"valueType":"LIST","values":["1-registered","2-active","3-closed"],"valueType":"LIST"},"description":"User Status","type":"int"},"firstName":{"type":"string"},"password":{"type":"string"}}}}}