removed old files

This commit is contained in:
Tony Tam 2015-02-06 11:36:58 -08:00
parent 7315b0ce2c
commit 416c087be0
102 changed files with 1545 additions and 4890 deletions

36
bin/scalatra-petstore-server.sh Executable file
View File

@ -0,0 +1,36 @@
#!/bin/sh
SCRIPT="$0"
while [ -h "$SCRIPT" ] ; do
ls=`ls -ld "$SCRIPT"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
SCRIPT="$link"
else
SCRIPT=`dirname "$SCRIPT"`/"$link"
fi
done
if [ ! -d "${APP_DIR}" ]; then
APP_DIR=`dirname "$SCRIPT"`/..
APP_DIR=`cd "${APP_DIR}"; pwd`
fi
root=./modules/swagger-codegen-distribution/pom.xml
# gets version of swagger-codegen
version=$(sed '/<project>/,/<\/project>/d;/<version>/!d;s/ *<\/\?version> *//g' $root | sed -n '2p' | sed -e 's,.*<version>\([^<]*\)</version>.*,\1,g')
executable="./modules/swagger-codegen-distribution/target/swagger-codegen-distribution-$version.jar"
if [ ! -f "$executable" ]
then
mvn clean package
fi
# if you've executed sbt assembly previously it will use that instead.
export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="$@ -i http://petstore.swagger.wordnik.com/v2/swagger.json -l scalatra -o samples/server/petstore/scalatra"
java $JAVA_OPTS -jar $executable $ags

View File

@ -1,135 +0,0 @@
/**
* Copyright 2014 Wordnik, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import com.wordnik.swagger.codegen.BasicJavaGenerator
import scala.collection.mutable.{ HashMap, ListBuffer }
object JavaJaxRSServerGenerator extends BasicJavaGenerator {
def main(args: Array[String]) = generateClient(args)
override def templateDir = "samples/server-generator/java-jaxrs/templates"
val outputFolder = "samples/server-generator/java-jaxrs/output"
// where to write generated code
override def destinationDir = outputFolder + "/src/main/java"
override def modelPackage = Some("com.wordnik.client.model")
// template used for apis
apiTemplateFiles ++= Map("api.mustache" -> ".java")
modelTemplateFiles ++= Map("model.mustache" -> ".java")
override def apiPackage = Some("com.wordnik.api")
// supporting classes
override def supportingFiles = List(
("README.mustache", outputFolder, "README.md"),
("ApiException.mustache", destinationDir + "/" + apiPackage.get.replaceAll("\\.", "/"), "ApiException.java"),
("ApiOriginFilter.mustache", destinationDir + "/" + apiPackage.get.replaceAll("\\.", "/"), "ApiOriginFilter.java"),
("ApiResponse.mustache", destinationDir + "/" + apiPackage.get.replaceAll("\\.", "/"), "ApiResponse.java"),
("JacksonJsonProvider.mustache", destinationDir + "/" + apiPackage.get.replaceAll("\\.", "/"), "JacksonJsonProvider.java"),
("NotFoundException.mustache", destinationDir + "/" + apiPackage.get.replaceAll("\\.", "/"), "NotFoundException.java"),
("pom.xml", outputFolder, "pom.xml"),
("web.mustache", outputFolder + "/src/main/webapp/WEB-INF", "web.xml")
)
override def processApiMap(m: Map[String, AnyRef]): Map[String, AnyRef] = {
val mutable = scala.collection.mutable.Map() ++ m
mutable.map(k => {
k._1 match {
case "allParams" => {
val paramList = k._2.asInstanceOf[List[_]]
paramList.foreach(param => {
val map = param.asInstanceOf[scala.collection.mutable.HashMap[String, AnyRef]]
if(map.contains("dataType")){
val dataType = map("dataType")
map += "dataType" -> dataType.toString.replaceAll("Array\\[","List[")
}
if(map.contains("required")) {
if(map("required") == "false") map += "notRequired" -> "true"
}
if(map.contains("defaultValue")) {
// unquote default value
val defaultValue = {
map("defaultValue") match {
case Some(d) => {
val str = d.toString
if(str.startsWith("\"") && str.endsWith("\""))
Some(str.substring(1, str.length-1))
else Some(d)
}
case None => None
}
}
map += "defaultValue" -> defaultValue
}
if(map.contains("allowableValues")) {
val allowableValues = map("allowableValues")
val quote = map("swaggerDataType") match {
case "string" => "\""
case _ => ""
}
val pattern = "([A-Z]*)\\[(.*)\\]".r
val str = allowableValues match {
case pattern(valueType, values) => {
valueType match {
case "LIST" => {
val l = values.split(",").toList
Some("AllowableValues(" + l.mkString(quote, quote + "," + quote, quote + ")"))
}
case "RANGE" => {
val r = values.split(",")
Some("AllowableValues(Range(" + r(0) + "," + r(1) + ", 1))")
}
}
}
case _ => None
}
str match {
case Some(s) => map += "allowableValues" -> s
case _ =>
}
}
})
}
case "path" => {
val path = {
val arr = k._2.toString.split("/")
if (arr.length >= 2) {
mutable += "basePart" -> (arr.slice(2, arr.length).mkString("", "/", ""))
"/" + arr.slice(2, arr.length).mkString("", "/", "")
} else
k._2.toString
}
// rip out the root path
mutable += "path" -> path
}
case "returnType" => {
k._2 match {
case Some(returnType) =>
case None => mutable += "returnType" -> "void"
}
}
case _ =>
}
})
mutable.toMap
}
}

View File

@ -1,80 +0,0 @@
# Swagger generated server
## Overview
Using the swagger-codegen, you can not only generate clients but servers as well! The same spec can be used to drive your
development both ways. This is an example of generating a server for `JAX-RS`.
### Prerequisites
You need the following installed and available in your $PATH:
<li>Maven 3</li>
### Generating a server
You first need to build the `swagger-codegen` project--this is done by running this command at the root of the swagger-codegen project:
```
sbt assembly
```
You can now generate a server from any valid[**](https://github.com/wordnik/swagger-codegen/blob/master/README.md#validating-your-swagger-spec) swagger spec:
```
./bin/runscala.sh samples/server-generator/java-jaxrs/JavaJaxRSServerGenerator.scala http://petstore.swagger.wordnik.com/api/api-docs special-key
```
After executing this script, you will have an output directory with the server-generated files:
```
$ cd samples/server-generator/java-jaxrs/output
$ find .
./pom.xml
./README.md
./src
./src/main
./src/main/java
./src/main/java/com
./src/main/java/com/wordnik
./src/main/java/com/wordnik/api
./src/main/java/com/wordnik/api/ApiException.java
./src/main/java/com/wordnik/api/ApiResponse.java
./src/main/java/com/wordnik/api/JacksonJsonProvider.java
./src/main/java/com/wordnik/api/NotFoundException.java
./src/main/java/com/wordnik/api/PetApi.java
./src/main/java/com/wordnik/api/StoreApi.java
./src/main/java/com/wordnik/api/UserApi.java
./src/main/java/com/wordnik/client
./src/main/java/com/wordnik/client/model
./src/main/java/com/wordnik/client/model/Category.java
./src/main/java/com/wordnik/client/model/Order.java
./src/main/java/com/wordnik/client/model/Pet.java
./src/main/java/com/wordnik/client/model/Tag.java
./src/main/java/com/wordnik/client/model/User.java
./src/main/webapp
./src/main/webapp/WEB-INF
./src/main/webapp/WEB-INF/web.xml
```
To run the server, cd to the `samples/server-generator/java-jaxrs/output` folder and run:
```
mvn jetty:run
```
You can now load the swagger-ui against `http://localhost:8002/api/api-docs.json`. Of course this isn't a fully
runnable server! You have to add the logic in the **/api/*.java files. But that's the easy part.
### Making it your own
Running the sample is easy, but how about making your own server? Easy! Just modify the `samples/server-generator/java-jaxrs/JavaJaxRSServerGenerator.scala` file.
Don't like the templates? Don't worry, we're not offended! They're [mustache](http://mustache.github.com/) templates and are easy to modify.
Take a look at the sample templates here:
<li> - Generator for your api classes: [api.mustache](https://github.com/wordnik/swagger-codegen/blob/master/samples/server-generator/java-jaxrs/templates/api.mustache)
<li> - Generator for your models: [model.mustache](https://github.com/wordnik/swagger-codegen/blob/master/samples/server-generator/java-jaxrs/templates/model.mustache)
<li> - Your web.xml: [web.mustache](https://github.com/wordnik/swagger-codegen/blob/master/samples/server-generator/java-jaxrs/templates/web.mustache)
Sound easy? It is!

View File

@ -1,10 +0,0 @@
# Swagger generated server
## Overview
This server was generated by the [swagger-codegen](https://github.com/wordnik/swagger-codegen) project. By using the
[swagger-spec](https://github.com/wordnik/swagger-core/wiki) from a remote server, you can easily generate a server stub. This
is an example of building a swagger-enabled scalatra server.
This example uses the [scalatra](http://scalatra.org/) framework. To see how to make this your own, look here:
[README](https://github.com/wordnik/swagger-codegen/tree/master/samples/server-generator/scalatra)

View File

@ -1,109 +0,0 @@
<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-java-jaxrs-petstore</artifactId>
<packaging>war</packaging>
<name>swagger-java-jaxrs-petstore</name>
<version>1.0.0-SNAPSHOT</version>
<build>
<sourceDirectory>src/main/java</sourceDirectory>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.1.1</version>
</plugin>
<plugin>
<artifactId>maven-failsafe-plugin</artifactId>
<version>2.6</version>
<executions>
<execution>
<goals>
<goal>integration-test</goal>
<goal>verify</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.mortbay.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
<version>${jetty-version}</version>
<configuration>
<webAppConfig>
<contextPath>/api</contextPath>
</webAppConfig>
<webAppSourceDirectory>target/${project.artifactId}-${project.version}</webAppSourceDirectory>
<webDefaultXml>${project.basedir}/conf/jetty/webdefault.xml</webDefaultXml>
<stopPort>8079</stopPort>
<stopKey>stopit</stopKey>
<connectors>
<connector implementation="org.eclipse.jetty.server.nio.SelectChannelConnector">
<port>8002</port>
<maxIdleTime>60000</maxIdleTime>
<confidentialPort>8443</confidentialPort>
</connector>
</connectors>
</configuration>
<executions>
<execution>
<id>start-jetty</id>
<phase>pre-integration-test</phase>
<goals>
<goal>run</goal>
</goals>
<configuration>
<scanIntervalSeconds>0</scanIntervalSeconds>
<daemon>true</daemon>
</configuration>
</execution>
<execution>
<id>stop-jetty</id>
<phase>post-integration-test</phase>
<goals>
<goal>stop</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>com.wordnik</groupId>
<artifactId>swagger-jaxrs_2.9.1</artifactId>
<version>${swagger-core-version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${slf4j-version}</version>
</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>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>${servlet-api-version}</version>
</dependency>
</dependencies>
<properties>
<swagger-core-version>1.2.1</swagger-core-version>
<jetty-version>7.6.0.v20120127</jetty-version>
<slf4j-version>1.6.3</slf4j-version>
<scala-test-version>1.6.1</scala-test-version>
<junit-version>4.8.1</junit-version>
<servlet-api-version>2.5</servlet-api-version>
</properties>
</project>

View File

@ -1,10 +0,0 @@
package com.wordnik.api;
public class ApiException extends Exception{
private int code;
public ApiException (int code, String msg) {
super(msg);
this.code = code;
}
}

View File

@ -1,26 +0,0 @@
package com.wordnik.api;
import java.io.IOException;
import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
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 {
}
}

View File

@ -1,69 +0,0 @@
package com.wordnik.api;
import javax.xml.bind.annotation.XmlTransient;
@javax.xml.bind.annotation.XmlRootElement
public class ApiResponse {
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 ApiResponse(){}
public ApiResponse(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;
}
}

View File

@ -1,38 +0,0 @@
package com.wordnik.api;
import com.wordnik.swagger.core.util.JsonUtil;
import com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.core.JsonGenerator.Feature;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.annotation.*;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.ext.Provider;
@Provider
@Produces(MediaType.APPLICATION_JSON)
public class JacksonJsonProvider extends JacksonJaxbJsonProvider {
private static ObjectMapper commonMapper = null;
public JacksonJsonProvider() {
if(commonMapper == null){
ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
mapper.setSerializationInclusion(JsonInclude.Include.NON_DEFAULT);
mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
commonMapper = mapper;
}
super.setMapper(commonMapper);
}
}

View File

@ -1,10 +0,0 @@
package com.wordnik.api;
public class NotFoundException extends ApiException {
private int code;
public NotFoundException (int code, String msg) {
super(code, msg);
this.code = code;
}
}

View File

@ -1,87 +0,0 @@
package com.wordnik.api;
import com.wordnik.swagger.annotations.*;
import com.wordnik.client.model.Pet;
import java.util.List;
import com.wordnik.api.NotFoundException;
import javax.ws.rs.core.Response;
import javax.ws.rs.*;
@Path("/pet.json")
@Api(value = "/pet", description = "the pet API")
@Produces({"application/json"})
public class PetApi {
@GET
@Path("/{petId}")
@ApiOperation(value = "Find pet by ID", notes = "Returns a pet based on ID", responseClass = "Pet")
@ApiErrors(value = { @ApiError(code = 400, reason = "Invalid ID supplied"),
@ApiError(code = 404, reason = "Pet not found") })
public Response getPetById(
@ApiParam(value = "ID of pet that needs to be fetched"
,required=true)@PathParam("petId") String petId
)
throws NotFoundException {
// do some magic!
return Response.ok().entity(new ApiResponse(ApiResponse.OK, "magic!")).build();
}
@POST
@Path("/")
@ApiOperation(value = "Add a new pet to the store", notes = "", responseClass = "void")
@ApiErrors(value = { @ApiError(code = 400, reason = "Invalid ID supplied"),
@ApiError(code = 404, reason = "Pet not found") })
public Response addPet(
@ApiParam(value = "Pet object that needs to be added to the store"
,required=true) Pet body
)
throws NotFoundException {
// do some magic!
return Response.ok().entity(new ApiResponse(ApiResponse.OK, "magic!")).build();
}
@PUT
@Path("/")
@ApiOperation(value = "Update an existing pet", notes = "", responseClass = "void")
@ApiErrors(value = { @ApiError(code = 400, reason = "Invalid ID supplied"),
@ApiError(code = 404, reason = "Pet not found") })
public Response updatePet(
@ApiParam(value = "Pet object that needs to be updated in the store"
,required=true) Pet body
)
throws NotFoundException {
// do some magic!
return Response.ok().entity(new ApiResponse(ApiResponse.OK, "magic!")).build();
}
@GET
@Path("/findByStatus")
@ApiOperation(value = "Finds Pets by status", notes = "Multiple status values can be provided with comma seperated strings", responseClass = "List<Pet>")
@ApiErrors(value = { @ApiError(code = 400, reason = "Invalid ID supplied"),
@ApiError(code = 404, reason = "Pet not found") })
public Response findPetsByStatus(
@ApiParam(value = "Status values that need to be considered for filter"
,required=true, defaultValue="available")@QueryParam("status") String status
)
throws NotFoundException {
// do some magic!
return Response.ok().entity(new ApiResponse(ApiResponse.OK, "magic!")).build();
}
@GET
@Path("/findByTags")
@ApiOperation(value = "Finds Pets by tags", notes = "Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.", responseClass = "List<Pet>")
@ApiErrors(value = { @ApiError(code = 400, reason = "Invalid ID supplied"),
@ApiError(code = 404, reason = "Pet not found") })
public Response findPetsByTags(
@ApiParam(value = "Tags to filter by"
,required=true)@QueryParam("tags") String tags
)
throws NotFoundException {
// do some magic!
return Response.ok().entity(new ApiResponse(ApiResponse.OK, "magic!")).build();
}
}

View File

@ -1,59 +0,0 @@
package com.wordnik.api;
import com.wordnik.swagger.annotations.*;
import com.wordnik.client.model.Order;
import java.util.List;
import com.wordnik.api.NotFoundException;
import javax.ws.rs.core.Response;
import javax.ws.rs.*;
@Path("/store.json")
@Api(value = "/store", description = "the store API")
@Produces({"application/json"})
public class StoreApi {
@GET
@Path("/order/{orderId}")
@ApiOperation(value = "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")
@ApiErrors(value = { @ApiError(code = 400, reason = "Invalid ID supplied"),
@ApiError(code = 404, reason = "Pet not found") })
public Response getOrderById(
@ApiParam(value = "ID of pet that needs to be fetched"
,required=true)@PathParam("orderId") String orderId
)
throws NotFoundException {
// do some magic!
return Response.ok().entity(new ApiResponse(ApiResponse.OK, "magic!")).build();
}
@DELETE
@Path("/order/{orderId}")
@ApiOperation(value = "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")
@ApiErrors(value = { @ApiError(code = 400, reason = "Invalid ID supplied"),
@ApiError(code = 404, reason = "Pet not found") })
public Response deleteOrder(
@ApiParam(value = "ID of the order that needs to be deleted"
,required=true)@PathParam("orderId") String orderId
)
throws NotFoundException {
// do some magic!
return Response.ok().entity(new ApiResponse(ApiResponse.OK, "magic!")).build();
}
@POST
@Path("/order")
@ApiOperation(value = "Place an order for a pet", notes = "", responseClass = "void")
@ApiErrors(value = { @ApiError(code = 400, reason = "Invalid ID supplied"),
@ApiError(code = 404, reason = "Pet not found") })
public Response placeOrder(
@ApiParam(value = "order placed for purchasing the pet"
,required=true) Order body
)
throws NotFoundException {
// do some magic!
return Response.ok().entity(new ApiResponse(ApiResponse.OK, "magic!")).build();
}
}

View File

@ -1,131 +0,0 @@
package com.wordnik.api;
import com.wordnik.swagger.annotations.*;
import com.wordnik.client.model.User;
import java.util.List;
import com.wordnik.api.NotFoundException;
import javax.ws.rs.core.Response;
import javax.ws.rs.*;
@Path("/user.json")
@Api(value = "/user", description = "the user API")
@Produces({"application/json"})
public class UserApi {
@POST
@Path("/createWithArray")
@ApiOperation(value = "Creates list of users with given input array", notes = "", responseClass = "void")
@ApiErrors(value = { @ApiError(code = 400, reason = "Invalid ID supplied"),
@ApiError(code = 404, reason = "Pet not found") })
public Response createUsersWithArrayInput(
@ApiParam(value = "List of user object"
,required=true) List<User> body
)
throws NotFoundException {
// do some magic!
return Response.ok().entity(new ApiResponse(ApiResponse.OK, "magic!")).build();
}
@POST
@Path("/")
@ApiOperation(value = "Create user", notes = "This can only be done by the logged in user.", responseClass = "void")
@ApiErrors(value = { @ApiError(code = 400, reason = "Invalid ID supplied"),
@ApiError(code = 404, reason = "Pet not found") })
public Response createUser(
@ApiParam(value = "Created user object"
,required=true) User body
)
throws NotFoundException {
// do some magic!
return Response.ok().entity(new ApiResponse(ApiResponse.OK, "magic!")).build();
}
@POST
@Path("/createWithList")
@ApiOperation(value = "Creates list of users with given list input", notes = "", responseClass = "void")
@ApiErrors(value = { @ApiError(code = 400, reason = "Invalid ID supplied"),
@ApiError(code = 404, reason = "Pet not found") })
public Response createUsersWithListInput(
@ApiParam(value = "List of user object"
,required=true) List<User> body
)
throws NotFoundException {
// do some magic!
return Response.ok().entity(new ApiResponse(ApiResponse.OK, "magic!")).build();
}
@PUT
@Path("/{username}")
@ApiOperation(value = "Updated user", notes = "This can only be done by the logged in user.", responseClass = "void")
@ApiErrors(value = { @ApiError(code = 400, reason = "Invalid ID supplied"),
@ApiError(code = 404, reason = "Pet not found") })
public Response updateUser(
@ApiParam(value = "name that need to be deleted"
,required=true)@PathParam("username") String username
,@ApiParam(value = "Updated user object"
,required=true) User body
)
throws NotFoundException {
// do some magic!
return Response.ok().entity(new ApiResponse(ApiResponse.OK, "magic!")).build();
}
@DELETE
@Path("/{username}")
@ApiOperation(value = "Delete user", notes = "This can only be done by the logged in user.", responseClass = "void")
@ApiErrors(value = { @ApiError(code = 400, reason = "Invalid ID supplied"),
@ApiError(code = 404, reason = "Pet not found") })
public Response deleteUser(
@ApiParam(value = "The name that needs to be deleted"
,required=true)@PathParam("username") String username
)
throws NotFoundException {
// do some magic!
return Response.ok().entity(new ApiResponse(ApiResponse.OK, "magic!")).build();
}
@GET
@Path("/{username}")
@ApiOperation(value = "Get user by user name", notes = "", responseClass = "User")
@ApiErrors(value = { @ApiError(code = 400, reason = "Invalid ID supplied"),
@ApiError(code = 404, reason = "Pet not found") })
public Response getUserByName(
@ApiParam(value = "The name that needs to be fetched. Use user1 for testing."
,required=true)@PathParam("username") String username
)
throws NotFoundException {
// do some magic!
return Response.ok().entity(new ApiResponse(ApiResponse.OK, "magic!")).build();
}
@GET
@Path("/login")
@ApiOperation(value = "Logs user into the system", notes = "", responseClass = "String")
@ApiErrors(value = { @ApiError(code = 400, reason = "Invalid ID supplied"),
@ApiError(code = 404, reason = "Pet not found") })
public Response loginUser(
@ApiParam(value = "The user name for login"
,required=true)@QueryParam("username") String username
,@ApiParam(value = "The password for login in clear text"
,required=true)@QueryParam("password") String password
)
throws NotFoundException {
// do some magic!
return Response.ok().entity(new ApiResponse(ApiResponse.OK, "magic!")).build();
}
@GET
@Path("/logout")
@ApiOperation(value = "Logs out current logged in user session", notes = "", responseClass = "void")
@ApiErrors(value = { @ApiError(code = 400, reason = "Invalid ID supplied"),
@ApiError(code = 404, reason = "Pet not found") })
public Response logoutUser(
)
throws NotFoundException {
// do some magic!
return Response.ok().entity(new ApiResponse(ApiResponse.OK, "magic!")).build();
}
}

View File

@ -1,30 +0,0 @@
package com.wordnik.client.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

@ -1,59 +0,0 @@
package com.wordnik.client.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

@ -1,70 +0,0 @@
package com.wordnik.client.model;
import java.util.*;
import com.wordnik.client.model.Category;
import com.wordnik.client.model.Tag;
public class Pet {
private List<Tag> tags = new ArrayList<Tag>();
private Long id = null;
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 List<Tag> getTags() {
return tags;
}
public void setTags(List<Tag> tags) {
this.tags = tags;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
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(" tags: ").append(tags).append("\n");
sb.append(" id: ").append(id).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

@ -1,30 +0,0 @@
package com.wordnik.client.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

@ -1,85 +0,0 @@
package com.wordnik.client.model;
public class User {
private Long id = null;
private String lastName = null;
private String phone = null;
private String username = 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 getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
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(" phone: ").append(phone).append("\n");
sb.append(" username: ").append(username).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

@ -1,53 +0,0 @@
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:j2ee="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<servlet>
<servlet-name>jersey</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>com.wordnik.swagger.jaxrs.listing;com.wordnik.api</param-value>
</init-param>
<init-param>
<param-name>com.sun.jersey.spi.container.ContainerRequestFilters</param-name>
<param-value>com.sun.jersey.api.container.filter.PostReplaceFilter</param-value>
</init-param>
<init-param>
<param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>api.version</param-name>
<param-value>0.1</param-value>
</init-param>
<init-param>
<param-name>swagger.version</param-name>
<param-value>1.1</param-value>
</init-param>
<init-param>
<param-name>swagger.api.basepath</param-name>
<param-value>http://localhost:8002/api</param-value>
</init-param>
<init-param>
<param-name>swagger.security.filter</param-name>
<param-value>com.wordnik.swagger.sample.util.ApiAuthorizationFilterImpl</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>jersey</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<filter>
<filter-name>ApiOriginFilter</filter-name>
<filter-class>com.wordnik.api.ApiOriginFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>ApiOriginFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>

View File

@ -1,9 +0,0 @@
package {{apiPackage}};
public class ApiException extends Exception{
private int code;
public ApiException (int code, String msg) {
super(msg);
this.code = code;
}
}

View File

@ -1,26 +0,0 @@
package {{apiPackage}};
import java.io.IOException;
import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
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 {
}
}

View File

@ -1,68 +0,0 @@
package {{apiPackage}};
import javax.xml.bind.annotation.XmlTransient;
@javax.xml.bind.annotation.XmlRootElement
public class ApiResponse {
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 ApiResponse(){}
public ApiResponse(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;
}
}

View File

@ -1,38 +0,0 @@
package {{apiPackage}};
import com.wordnik.swagger.core.util.JsonUtil;
import com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.core.JsonGenerator.Feature;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.annotation.*;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.ext.Provider;
@Provider
@Produces(MediaType.APPLICATION_JSON)
public class JacksonJsonProvider extends JacksonJaxbJsonProvider {
private static ObjectMapper commonMapper = null;
public JacksonJsonProvider() {
if(commonMapper == null){
ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
mapper.setSerializationInclusion(JsonInclude.Include.NON_DEFAULT);
mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
commonMapper = mapper;
}
super.setMapper(commonMapper);
}
}

View File

@ -1,9 +0,0 @@
package {{apiPackage}};
public class NotFoundException extends ApiException {
private int code;
public NotFoundException (int code, String msg) {
super(code, msg);
this.code = code;
}
}

View File

@ -1,77 +0,0 @@
package {{package}};
import com.wordnik.swagger.annotations.*;
{{#imports}}import {{import}};
{{/imports}}
import java.util.List;
import {{package}}.NotFoundException;
import javax.ws.rs.core.Response;
import javax.ws.rs.*;
@Path("/{{baseName}}.json")
@Api(value = "/{{baseName}}", description = "the {{baseName}} API")
@Produces({"application/json"})
public class {{className}} {
{{#operations}}
{{#operation}}
@{{httpMethod}}
@Path("{{path}}")
@ApiOperation(value = "{{{summary}}}", notes = "{{{notes}}}", responseClass = "{{{returnType}}}")
@ApiErrors(value = { {{#errorList}} @ApiError(code = {{{code}}}, reason = "{{{reason}}}"){{#hasMore}},{{/hasMore}}
{{/errorList}}
})
public Response {{nickname}}(
{{#allParams}}
{{#queryParameter}}
@ApiParam(value = "{{{description}}}"
{{#required}},required=true{{newline}}{{/required}}
{{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{newline}}{{/allowableValues}}
{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{newline}}{{/defaultValue}}
)@QueryParam("{{paramName}}"){{newline}} {{{dataType}}} {{paramName}}
{{/queryParameter}}
{{#pathParameter}}
@ApiParam(value = "{{{description}}}"
{{#required}},required=true{{newline}}{{/required}}
{{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{newline}}{{/allowableValues}}
{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{newline}}{{/defaultValue}}
)@PathParam("{{paramName}}"){{newline}} {{{dataType}}} {{paramName}}
{{/pathParameter}}
{{#headerParameter}}
@ApiParam(value = "{{{description}}}"
{{#required}},required=true{{newline}}{{/required}}
{{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{newline}}{{/allowableValues}}
{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{newline}}{{/defaultValue}}
)@HeaderParam("{{paramName}}"){{newline}} {{{dataType}}} {{paramName}}
{{/headerParameter}}
{{#bodyParameter}}
@ApiParam(value = "{{{description}}}"
{{#required}},required=true{{newline}}{{/required}}
{{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{newline}}{{/allowableValues}}
{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{newline}}{{/defaultValue}}
) {{{dataType}}} {{paramName}}
{{/bodyParameter}}
{{#hasMore}},{{/hasMore}}
{{/allParams}}
)
throws NotFoundException {
// do some magic!
return Response.ok().entity(new ApiResponse(ApiResponse.OK, "magic!")).build();
}
{{/operation}}
{{/operations}}
}

View File

@ -1,38 +0,0 @@
package {{package}};
{{#imports}}import {{import}};
{{/imports}}
{{#models}}
{{#model}}
public class {{classname}} {
{{#vars}}
{{#description}}/* {{{description}}} */
{{/description}}
private {{{datatype}}} {{name}} = {{{defaultValue}}};
{{/vars}}
{{#vars}}
public {{{datatype}}} {{getter}}() {
return {{name}};
}
public void {{setter}}({{{datatype}}} {{name}}) {
this.{{name}} = {{name}};
}
{{/vars}}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class {{classname}} {\n");
{{#vars}}
sb.append(" {{name}}: ").append({{name}}).append("\n");
{{/vars}}
sb.append("}\n");
return sb.toString();
}
}
{{/model}}
{{/models}}

View File

@ -1,109 +0,0 @@
<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-java-jaxrs-petstore</artifactId>
<packaging>war</packaging>
<name>swagger-java-jaxrs-petstore</name>
<version>1.0.0-SNAPSHOT</version>
<build>
<sourceDirectory>src/main/java</sourceDirectory>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.1.1</version>
</plugin>
<plugin>
<artifactId>maven-failsafe-plugin</artifactId>
<version>2.6</version>
<executions>
<execution>
<goals>
<goal>integration-test</goal>
<goal>verify</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.mortbay.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
<version>${jetty-version}</version>
<configuration>
<webAppConfig>
<contextPath>/api</contextPath>
</webAppConfig>
<webAppSourceDirectory>target/${project.artifactId}-${project.version}</webAppSourceDirectory>
<webDefaultXml>${project.basedir}/conf/jetty/webdefault.xml</webDefaultXml>
<stopPort>8079</stopPort>
<stopKey>stopit</stopKey>
<connectors>
<connector implementation="org.eclipse.jetty.server.nio.SelectChannelConnector">
<port>8002</port>
<maxIdleTime>60000</maxIdleTime>
<confidentialPort>8443</confidentialPort>
</connector>
</connectors>
</configuration>
<executions>
<execution>
<id>start-jetty</id>
<phase>pre-integration-test</phase>
<goals>
<goal>run</goal>
</goals>
<configuration>
<scanIntervalSeconds>0</scanIntervalSeconds>
<daemon>true</daemon>
</configuration>
</execution>
<execution>
<id>stop-jetty</id>
<phase>post-integration-test</phase>
<goals>
<goal>stop</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>com.wordnik</groupId>
<artifactId>swagger-jaxrs_2.9.1</artifactId>
<version>${swagger-core-version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${slf4j-version}</version>
</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>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>${servlet-api-version}</version>
</dependency>
</dependencies>
<properties>
<swagger-core-version>1.2.1</swagger-core-version>
<jetty-version>7.6.0.v20120127</jetty-version>
<slf4j-version>1.6.3</slf4j-version>
<scala-test-version>1.6.1</scala-test-version>
<junit-version>4.8.1</junit-version>
<servlet-api-version>2.5</servlet-api-version>
</properties>
</project>

View File

@ -1 +0,0 @@
sbt.version=0.12.0

View File

@ -1,9 +0,0 @@
addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "0.8.4")
libraryDependencies <+= sbtVersion(v => v match {
case "0.11.0" => "com.github.siasia" %% "xsbt-web-plugin" % "0.11.0-0.2.8"
case "0.11.1" => "com.github.siasia" %% "xsbt-web-plugin" % "0.11.1-0.2.10"
case "0.11.2" => "com.github.siasia" %% "xsbt-web-plugin" % "0.11.2-0.2.11"
case "0.11.3" => "com.github.siasia" %% "xsbt-web-plugin" % "0.11.3-0.2.11.1"
case x if (x.startsWith("0.12")) => "com.github.siasia" %% "xsbt-web-plugin" % "0.12.0-0.2.11.1"
})

View File

@ -1,52 +0,0 @@
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:j2ee="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<servlet>
<servlet-name>jersey</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>com.wordnik.swagger.jaxrs.listing;{{apiPackage}}</param-value>
</init-param>
<init-param>
<param-name>com.sun.jersey.spi.container.ContainerRequestFilters</param-name>
<param-value>com.sun.jersey.api.container.filter.PostReplaceFilter</param-value>
</init-param>
<init-param>
<param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>api.version</param-name>
<param-value>0.1</param-value>
</init-param>
<init-param>
<param-name>swagger.version</param-name>
<param-value>1.1</param-value>
</init-param>
<init-param>
<param-name>swagger.api.basepath</param-name>
<param-value>http://localhost:8002/api</param-value>
</init-param>
<init-param>
<param-name>swagger.security.filter</param-name>
<param-value>com.wordnik.swagger.sample.util.ApiAuthorizationFilterImpl</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>jersey</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<filter>
<filter-name>ApiOriginFilter</filter-name>
<filter-class>{{apiPackage}}.ApiOriginFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>ApiOriginFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>

View File

@ -1,54 +0,0 @@
/**
* Copyright 2014 Wordnik, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import com.wordnik.swagger.codegen.BasicScalaGenerator
import scala.collection.mutable.{ HashMap, ListBuffer }
object NodeServerGenerator extends BasicScalaGenerator {
def main(args: Array[String]) = generateClient(args)
val codeDir = "app"
val apiDir = "apis"
override def templateDir = "samples/server-generator/node/templates"
val outputFolder = "samples/server-generator/node/output"
// where to write generated code
override def destinationDir = outputFolder + java.io.File.separator + codeDir
override def apiPackage = Option(apiDir)
// template used for apis
apiTemplateFiles ++= Map("api.mustache" -> ".js")
modelTemplateFiles.clear
additionalParams ++= Map(
"artifactId" -> "swagger-sample-app",
"artifactVersion" -> "1.0.0",
"homepage" -> "http://swagger.wordnik.com",
"codeDir" -> codeDir,
"apiFolder" -> apiDir
)
// supporting classes
override def supportingFiles = List(
("package.mustache", outputFolder, "package.json"),
("README.mustache", outputFolder, "README.md"),
("main.mustache", destinationDir, "main.js"),
("models.mustache", destinationDir, "models.js"))
}

View File

@ -1,106 +0,0 @@
# Swagger generated server
## Overview
Using the swagger-codegen, you can not only generate clients but servers as well! The same spec can be used to drive your
development both ways. This is an example of generating a server for `node.js`.
### Prerequisites
You need the following installed and available in your $PATH:
<li>- node (http://nodejs.org)
<li>- Scala 2.9.1 [available here](http://www.scala-lang.org)
You also need to add the scala binary to your PATH.
### Generating a server
You first need to build the `swagger-codegen` project--this is done by running this command at the root of the swagger-codegen project:
```
mvn package
```
You can now generate a server from any valid[**](https://github.com/wordnik/swagger-codegen/blob/master/README.md#validating-your-swagger-spec) swagger spec:
```
./bin/runscala.sh samples/server-generator/node/NodeServerFromSpec.scala http://petstore.swagger.wordnik.com/api/api-docs special-key
```
After executing this script, you will have an output directory with the server-generated files:
```
$ find samples/server-generator/node/output
samples/server-generator/node/output
samples/server-generator/node/output/App
samples/server-generator/node/output/App/apis
samples/server-generator/node/output/App/apis/PetApi.js
samples/server-generator/node/output/App/apis/StoreApi.js
samples/server-generator/node/output/App/apis/UserApi.js
samples/server-generator/node/output/App/Common
samples/server-generator/node/output/App/Common/node
samples/server-generator/node/output/App/Common/node/paramTypes.js
samples/server-generator/node/output/App/Common/node/randomizer.js
samples/server-generator/node/output/App/Common/node/swagger.js
samples/server-generator/node/output/App/main.js
samples/server-generator/node/output/App/models.js
samples/server-generator/node/output/package.json
```
To run the server, cd to the `samples/server-generator/node/output` folder and run:
```
# install the dependencies
npm install
node Apps/main.js
```
You can now load the swagger-ui against `http://localhost:8002/resources.json`. Of course this isn't a fully
runnable server! You have to add the logic in the apis/*.js files. But that's the easy part.
### Making it your own
Running the sample is easy, but how about making your own server? Easy! Just modify the `samples/server-generator/node/NodeServerFromSpec.scala` file.
See comments in below, in a copy of the script
```scala
object NodeServerGenerator extends BasicScalaGenerator {
def main(args: Array[String]) = generateClient(args)
// if you want to point to a different template directory, change this
override def templateDir = "samples/server-generator/node/templates"
// where the files are written
val outputFolder = "samples/server-generator/node/output"
// where to write generated code
override def destinationDir = outputFolder + "/App"
// template used for apis (writes one file per api)
apiTemplateFiles ++= Map("api.mustache" -> ".js")
modelTemplateFiles.clear
// puts the api files in a folder called `apis`
override def apiPackage = Some("apis")
// copies swagger files and processes any *.mustache files
override def supportingFiles = List(
("package.json", outputFolder, "package.json"),
("README.json", outputFolder, "README.md"),
("main.mustache", destinationDir, "main.js"),
("models.mustache", destinationDir, "models.js"))
}
```
Don't like the templates? Don't worry, we're not offended! They're [mustache](http://mustache.github.com/) templates and are easy to modify.
Take a look at the sample templates here:
<li> Generator for your api classes: [api.mustache](https://github.com/wordnik/swagger-codegen/blob/master/samples/server-generator/node/templates/api.mustache)
<li> Generator for your models: [models.mustache](https://github.com/wordnik/swagger-codegen/blob/master/samples/server-generator/node/templates/models.mustache)
<li> The main class to run your server: [main.mustache](https://github.com/wordnik/swagger-codegen/blob/master/samples/server-generator/node/templates/main.mustache)
Sound easy? It is!

View File

@ -1,193 +0,0 @@
var swagger = require("swagger-node-express");
var url = require("url");
var errors = swagger.errors;
var params = swagger.params;
/* add model includes */
function writeResponse (response, data) {
response.header('Access-Control-Allow-Origin', "*");
response.header("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
response.header("Access-Control-Allow-Headers", "Content-Type");
response.header("Content-Type", "application/json; charset=utf-8");
response.send(JSON.stringify(data));
}
exports.models = models = require("../models.js");
exports.getPetById = {
'spec': {
"description" : "Operations about pets",
"path" : "/pet/{petId}",
"notes" : "Returns a pet based on ID",
"summary" : "Find pet by ID",
"method": "GET",
"params" : [].concat([params.path("petId", "ID of pet that needs to be fetched")]).concat([]).concat([]),
"type" : "Pet",
"responseMessages" : [errors.invalid('id'), errors.notFound('Pet')],
"nickname" : "getPetById"
},
'action': function (req,res) {
if (!req.params.petId) {
throw errors.invalid('petId');
}
writeResponse(res, {message: "how about implementing getPetById as a GET method?"});
}
};
exports.deletePet = {
'spec': {
"description" : "Operations about pets",
"path" : "/pet/{petId}",
"notes" : "",
"summary" : "Deletes a pet",
"method": "DELETE",
"params" : [].concat([params.path("petId", "Pet id to delete")]).concat([]).concat([]),
"type" : "",
"responseMessages" : [errors.invalid('id'), errors.notFound('')],
"nickname" : "deletePet"
},
'action': function (req,res) {
if (!req.params.petId) {
throw errors.invalid('petId');
}
writeResponse(res, {message: "how about implementing deletePet as a DELETE method?"});
}
};
exports.partialUpdate = {
'spec': {
"description" : "Operations about pets",
"path" : "/pet/{petId}",
"notes" : "",
"summary" : "partial updates to a pet",
"method": "PATCH",
"params" : [].concat([params.path("petId", "ID of pet that needs to be fetched")]).concat([]).concat([params.body("body", "Pet", "Pet object that needs to be added to the store", true)
]),
"type" : "List[Pet]",
"responseMessages" : [errors.invalid('id'), errors.notFound('List[Pet]')],
"nickname" : "partialUpdate"
},
'action': function (req,res) {
if (!req.params.petId) {
throw errors.invalid('petId');
}
if (!req.params.body) {
throw errors.invalid('body');
}
writeResponse(res, {message: "how about implementing partialUpdate as a PATCH method?"});
}
};
exports.updatePetWithForm = {
'spec': {
"description" : "Operations about pets",
"path" : "/pet/{petId}",
"notes" : "",
"summary" : "Updates a pet in the store with form data",
"method": "POST",
"params" : [].concat([params.path("petId", "ID of pet that needs to be updated")]).concat([]).concat([]),
"type" : "",
"responseMessages" : [errors.invalid('id'), errors.notFound('')],
"nickname" : "updatePetWithForm"
},
'action': function (req,res) {
if (!req.params.petId) {
throw errors.invalid('petId');
}
writeResponse(res, {message: "how about implementing updatePetWithForm as a POST method?"});
}
};
exports.uploadFile = {
'spec': {
"description" : "Operations about pets",
"path" : "/pet/uploadImage",
"notes" : "",
"summary" : "uploads an image",
"method": "POST",
"params" : [].concat([]).concat([]).concat([params.body("body", "File", "file to upload", false)
]),
"type" : "",
"responseMessages" : [errors.invalid('id'), errors.notFound('')],
"nickname" : "uploadFile"
},
'action': function (req,res) {
writeResponse(res, {message: "how about implementing uploadFile as a POST method?"});
}
};
exports.addPet = {
'spec': {
"description" : "Operations about pets",
"path" : "/pet",
"notes" : "",
"summary" : "Add a new pet to the store",
"method": "POST",
"params" : [].concat([]).concat([]).concat([params.body("body", "Pet", "Pet object that needs to be added to the store", true)
]),
"type" : "",
"responseMessages" : [errors.invalid('id'), errors.notFound('')],
"nickname" : "addPet"
},
'action': function (req,res) {
if (!req.params.body) {
throw errors.invalid('body');
}
writeResponse(res, {message: "how about implementing addPet as a POST method?"});
}
};
exports.updatePet = {
'spec': {
"description" : "Operations about pets",
"path" : "/pet",
"notes" : "",
"summary" : "Update an existing pet",
"method": "PUT",
"params" : [].concat([]).concat([]).concat([params.body("body", "Pet", "Pet object that needs to be updated in the store", true)
]),
"type" : "",
"responseMessages" : [errors.invalid('id'), errors.notFound('')],
"nickname" : "updatePet"
},
'action': function (req,res) {
if (!req.params.body) {
throw errors.invalid('body');
}
writeResponse(res, {message: "how about implementing updatePet as a PUT method?"});
}
};
exports.findPetsByStatus = {
'spec': {
"description" : "Operations about pets",
"path" : "/pet/findByStatus",
"notes" : "Multiple status values can be provided with comma seperated strings",
"summary" : "Finds Pets by status",
"method": "GET",
"params" : [params.query("status", "Status values that need to be considered for filter", "string", true, true, "LIST[available,pending,sold]", "available")].concat([]).concat([]).concat([]),
"type" : "List[Pet]",
"responseMessages" : [errors.invalid('id'), errors.notFound('List[Pet]')],
"nickname" : "findPetsByStatus"
},
'action': function (req,res) {
if (!req.params.status) {
throw errors.invalid('status');
}
writeResponse(res, {message: "how about implementing findPetsByStatus as a GET method?"});
}
};
exports.findPetsByTags = {
'spec': {
"description" : "Operations about pets",
"path" : "/pet/findByTags",
"notes" : "Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.",
"summary" : "Finds Pets by tags",
"method": "GET",
"params" : [params.query("tags", "Tags to filter by", "string", true, true, "")].concat([]).concat([]).concat([]),
"type" : "List[Pet]",
"responseMessages" : [errors.invalid('id'), errors.notFound('List[Pet]')],
"nickname" : "findPetsByTags"
},
'action': function (req,res) {
if (!req.params.tags) {
throw errors.invalid('tags');
}
writeResponse(res, {message: "how about implementing findPetsByTags as a GET method?"});
}
};

View File

@ -1,76 +0,0 @@
var swagger = require("swagger-node-express");
var url = require("url");
var errors = swagger.errors;
var params = swagger.params;
/* add model includes */
function writeResponse (response, data) {
response.header('Access-Control-Allow-Origin', "*");
response.header("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
response.header("Access-Control-Allow-Headers", "Content-Type");
response.header("Content-Type", "application/json; charset=utf-8");
response.send(JSON.stringify(data));
}
exports.models = models = require("../models.js");
exports.getOrderById = {
'spec': {
"description" : "Operations about pets",
"path" : "/store/order/{orderId}",
"notes" : "For valid response try integer IDs with value <= 5. Anything above 5 or nonintegers will generate API errors",
"summary" : "Find purchase order by ID",
"method": "GET",
"params" : [].concat([params.path("orderId", "ID of pet that needs to be fetched")]).concat([]).concat([]),
"type" : "Order",
"responseMessages" : [errors.invalid('id'), errors.notFound('Order')],
"nickname" : "getOrderById"
},
'action': function (req,res) {
if (!req.params.orderId) {
throw errors.invalid('orderId');
}
writeResponse(res, {message: "how about implementing getOrderById as a GET method?"});
}
};
exports.deleteOrder = {
'spec': {
"description" : "Operations about pets",
"path" : "/store/order/{orderId}",
"notes" : "For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors",
"summary" : "Delete purchase order by ID",
"method": "DELETE",
"params" : [].concat([params.path("orderId", "ID of the order that needs to be deleted")]).concat([]).concat([]),
"type" : "",
"responseMessages" : [errors.invalid('id'), errors.notFound('')],
"nickname" : "deleteOrder"
},
'action': function (req,res) {
if (!req.params.orderId) {
throw errors.invalid('orderId');
}
writeResponse(res, {message: "how about implementing deleteOrder as a DELETE method?"});
}
};
exports.placeOrder = {
'spec': {
"description" : "Operations about pets",
"path" : "/store/order",
"notes" : "",
"summary" : "Place an order for a pet",
"method": "POST",
"params" : [].concat([]).concat([]).concat([params.body("body", "Order", "order placed for purchasing the pet", true)
]),
"type" : "",
"responseMessages" : [errors.invalid('id'), errors.notFound('')],
"nickname" : "placeOrder"
},
'action': function (req,res) {
if (!req.params.body) {
throw errors.invalid('body');
}
writeResponse(res, {message: "how about implementing placeOrder as a POST method?"});
}
};

View File

@ -1,177 +0,0 @@
var swagger = require("swagger-node-express");
var url = require("url");
var errors = swagger.errors;
var params = swagger.params;
/* add model includes */
function writeResponse (response, data) {
response.header('Access-Control-Allow-Origin', "*");
response.header("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
response.header("Access-Control-Allow-Headers", "Content-Type");
response.header("Content-Type", "application/json; charset=utf-8");
response.send(JSON.stringify(data));
}
exports.models = models = require("../models.js");
exports.updateUser = {
'spec': {
"description" : "Operations about pets",
"path" : "/user/{username}",
"notes" : "This can only be done by the logged in user.",
"summary" : "Updated user",
"method": "PUT",
"params" : [].concat([params.path("username", "name that need to be deleted")]).concat([]).concat([params.body("body", "User", "Updated user object", true)
]),
"type" : "",
"responseMessages" : [errors.invalid('id'), errors.notFound('')],
"nickname" : "updateUser"
},
'action': function (req,res) {
if (!req.params.username) {
throw errors.invalid('username');
}
if (!req.params.body) {
throw errors.invalid('body');
}
writeResponse(res, {message: "how about implementing updateUser as a PUT method?"});
}
};
exports.deleteUser = {
'spec': {
"description" : "Operations about pets",
"path" : "/user/{username}",
"notes" : "This can only be done by the logged in user.",
"summary" : "Delete user",
"method": "DELETE",
"params" : [].concat([params.path("username", "The name that needs to be deleted")]).concat([]).concat([]),
"type" : "",
"responseMessages" : [errors.invalid('id'), errors.notFound('')],
"nickname" : "deleteUser"
},
'action': function (req,res) {
if (!req.params.username) {
throw errors.invalid('username');
}
writeResponse(res, {message: "how about implementing deleteUser as a DELETE method?"});
}
};
exports.getUserByName = {
'spec': {
"description" : "Operations about pets",
"path" : "/user/{username}",
"notes" : "",
"summary" : "Get user by user name",
"method": "GET",
"params" : [].concat([params.path("username", "The name that needs to be fetched. Use user1 for testing.")]).concat([]).concat([]),
"type" : "User",
"responseMessages" : [errors.invalid('id'), errors.notFound('User')],
"nickname" : "getUserByName"
},
'action': function (req,res) {
if (!req.params.username) {
throw errors.invalid('username');
}
writeResponse(res, {message: "how about implementing getUserByName as a GET method?"});
}
};
exports.loginUser = {
'spec': {
"description" : "Operations about pets",
"path" : "/user/login",
"notes" : "",
"summary" : "Logs user into the system",
"method": "GET",
"params" : [params.query("username", "The user name for login", "string", true, false, ""),params.query("password", "The password for login in clear text", "string", true, false, "")].concat([]).concat([]).concat([]),
"type" : "String",
"responseMessages" : [errors.invalid('id'), errors.notFound('String')],
"nickname" : "loginUser"
},
'action': function (req,res) {
if (!req.params.username) {
throw errors.invalid('username');
}
if (!req.params.password) {
throw errors.invalid('password');
}
writeResponse(res, {message: "how about implementing loginUser as a GET method?"});
}
};
exports.logoutUser = {
'spec': {
"description" : "Operations about pets",
"path" : "/user/logout",
"notes" : "",
"summary" : "Logs out current logged in user session",
"method": "GET",
"params" : [].concat([]).concat([]).concat([]),
"type" : "",
"responseMessages" : [errors.invalid('id'), errors.notFound('')],
"nickname" : "logoutUser"
},
'action': function (req,res) {
writeResponse(res, {message: "how about implementing logoutUser as a GET method?"});
}
};
exports.createUser = {
'spec': {
"description" : "Operations about pets",
"path" : "/user",
"notes" : "This can only be done by the logged in user.",
"summary" : "Create user",
"method": "POST",
"params" : [].concat([]).concat([]).concat([params.body("body", "User", "Created user object", true)
]),
"type" : "",
"responseMessages" : [errors.invalid('id'), errors.notFound('')],
"nickname" : "createUser"
},
'action': function (req,res) {
if (!req.params.body) {
throw errors.invalid('body');
}
writeResponse(res, {message: "how about implementing createUser as a POST method?"});
}
};
exports.createUsersWithArrayInput = {
'spec': {
"description" : "Operations about pets",
"path" : "/user/createWithArray",
"notes" : "",
"summary" : "Creates list of users with given input array",
"method": "POST",
"params" : [].concat([]).concat([]).concat([params.body("body", "Array[User]", "List of user object", true)
]),
"type" : "",
"responseMessages" : [errors.invalid('id'), errors.notFound('')],
"nickname" : "createUsersWithArrayInput"
},
'action': function (req,res) {
if (!req.params.body) {
throw errors.invalid('body');
}
writeResponse(res, {message: "how about implementing createUsersWithArrayInput as a POST method?"});
}
};
exports.createUsersWithListInput = {
'spec': {
"description" : "Operations about pets",
"path" : "/user/createWithList",
"notes" : "",
"summary" : "Creates list of users with given list input",
"method": "POST",
"params" : [].concat([]).concat([]).concat([params.body("body", "Array[User]", "List of user object", true)
]),
"type" : "",
"responseMessages" : [errors.invalid('id'), errors.notFound('')],
"nickname" : "createUsersWithListInput"
},
'action': function (req,res) {
if (!req.params.body) {
throw errors.invalid('body');
}
writeResponse(res, {message: "how about implementing createUsersWithListInput as a POST method?"});
}
};

View File

@ -1,58 +0,0 @@
var express = require("express")
, url = require("url")
, cors = require("cors")
, swagger = require("swagger-node-express")
, db = false
var app = express();
app.use(express.bodyParser());
var corsOptions = {
credentials: true,
origin: function(origin,callback) {
if(origin===undefined) {
callback(null,false);
} else {
callback(null,true);
}
}
};
app.use(cors(corsOptions));
swagger.setAppHandler(app);
swagger.configureSwaggerPaths("", "api-docs", "")
var models = require("./models.js");
var UserApi = require("./apis/UserApi.js");
var PetApi = require("./apis/PetApi.js");
var StoreApi = require("./apis/StoreApi.js");
swagger.addModels(models)
.addPUT(UserApi.updateUser)
.addDELETE(UserApi.deleteUser)
.addGET(UserApi.getUserByName)
.addGET(UserApi.loginUser)
.addGET(UserApi.logoutUser)
.addPOST(UserApi.createUser)
.addPOST(UserApi.createUsersWithArrayInput)
.addPOST(UserApi.createUsersWithListInput)
.addGET(PetApi.getPetById)
.addDELETE(PetApi.deletePet)
.addPATCH(PetApi.partialUpdate)
.addPOST(PetApi.updatePetWithForm)
.addPOST(PetApi.uploadFile)
.addPOST(PetApi.addPet)
.addPUT(PetApi.updatePet)
.addGET(PetApi.findPetsByStatus)
.addGET(PetApi.findPetsByTags)
.addGET(StoreApi.getOrderById)
.addDELETE(StoreApi.deleteOrder)
.addPOST(StoreApi.placeOrder)
;
// configures the app
swagger.configure("http://localhost:8002", "0.1");
// start the server
app.listen(8002);

View File

@ -1,129 +0,0 @@
exports.models = {
"Tag": {
"id" : "Tag",
"name" : "",
"properties" : {
"id" : {
"type" : "integer",
"format" : "int64"
},
"name" : {
"type" : "string"
}
}
},
"User": {
"id" : "User",
"name" : "",
"properties" : {
"email" : {
"type" : "string"
},
"username" : {
"type" : "string"
},
"userStatus" : {
"type" : "integer",
"format" : "int32",
"description" : "User Status",
"enum" : [ "1-registered", "2-active", "3-closed" ]
},
"lastName" : {
"type" : "string"
},
"firstName" : {
"type" : "string"
},
"id" : {
"type" : "integer",
"format" : "int64"
},
"phone" : {
"type" : "string"
},
"password" : {
"type" : "string"
}
}
},
"Order": {
"id" : "Order",
"name" : "",
"properties" : {
"shipDate" : {
"type" : "string",
"format" : "date-time"
},
"quantity" : {
"type" : "integer",
"format" : "int32"
},
"petId" : {
"type" : "integer",
"format" : "int64"
},
"id" : {
"type" : "integer",
"format" : "int64"
},
"status" : {
"type" : "string",
"description" : "Order Status",
"enum" : [ "placed", " approved", " delivered" ]
}
}
},
"Category": {
"id" : "Category",
"name" : "",
"properties" : {
"id" : {
"type" : "integer",
"format" : "int64"
},
"name" : {
"type" : "string"
}
}
},
"Pet": {
"id" : "Pet",
"name" : "",
"required" : [ "id", "name" ],
"properties" : {
"name" : {
"type" : "string"
},
"tags" : {
"type" : "array",
"items" : {
"$ref" : "Tag"
}
},
"photoUrls" : {
"type" : "array",
"items" : {
"type" : "string"
}
},
"id" : {
"type" : "integer",
"format" : "int64",
"description" : "unique identifier for the pet"
},
"status" : {
"type" : "string",
"description" : "pet status in the store",
"enum" : [ "available", "pending", "sold" ]
},
"category" : {
"type" : "Category"
}
}
}
}

View File

@ -1,10 +0,0 @@
# Swagger generated server
## Overview
This server was generated by the [swagger-codegen](https://github.com/wordnik/swagger-codegen) project. By using the
[swagger-spec](https://github.com/wordnik/swagger-core/wiki) from a remote server, you can easily generate a server stub. This
is an example of building a node.js server.
This example uses the [expressjs](http://expressjs.com/) framework. To see how to make this your own, look here:
[README](https://github.com/wordnik/swagger-codegen/tree/master/samples/server-generator/node)

View File

@ -1,16 +0,0 @@
{
"name": "swagger-sample-app",
"description": "Wordnik node.js server generator",
"version": "1.0.0",
"homepage": "http://swagger.wordnik.com",
"main": "./app/main.js",
"engines": {
"node": ">= 0.8.x"
},
"dependencies": {
"swagger-node-express": ">= 2.0.x",
"connect": ">= 1.8.x",
"cors": "2.1.1",
"express": "3.x"
}
}

View File

@ -1,10 +0,0 @@
# Swagger generated server
## Overview
This server was generated by the [swagger-codegen](https://github.com/wordnik/swagger-codegen) project. By using the
[swagger-spec](https://github.com/wordnik/swagger-core/wiki) from a remote server, you can easily generate a server stub. This
is an example of building a node.js server.
This example uses the [expressjs](http://expressjs.com/) framework. To see how to make this your own, look here:
[README](https://github.com/wordnik/swagger-codegen/tree/master/samples/server-generator/node)

View File

@ -1,52 +0,0 @@
var swagger = require("swagger-node-express");
var url = require("url");
var errors = swagger.errors;
var params = swagger.params;
/* add model includes */
function writeResponse (response, data) {
response.header('Access-Control-Allow-Origin', "*");
response.header("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
response.header("Access-Control-Allow-Headers", "Content-Type");
response.header("Content-Type", "application/json; charset=utf-8");
response.send(JSON.stringify(data));
}
exports.models = models = require("../models.js");
{{#operations}}
{{#operation}}
exports.{{nickname}} = {
'spec': {
"description" : "Operations about pets",
"path" : "{{path}}",
"notes" : "{{{notes}}}",
"summary" : "{{{summary}}}",
"method": "{{httpMethod}}",
"params" : [{{#queryParams}}
params.query("{{paramName}}", "{{description}}", "{{swaggerDataType}}", {{required}}, {{allowMultiple}}, "{{{allowableValues}}}"{{#defaultValue}}, {{{defaultValue}}}{{/defaultValue}}){{#hasMore}},{{/hasMore}}
{{/queryParams}}].concat([{{#pathParams}}
params.path("{{paramName}}", "{{description}}"){{#hasMore}},{{/hasMore}}
{{/pathParams}}]).concat([{{#headerParams}}
params.header("{{paramName}}", "{{description}}"){{#hasMore}},{{/hasMore}}
{{/headerParams}}]).concat([{{#bodyParams}}
params.body("body", "{{swaggerDataType}}", "{{description}}", {{#required}}{{required}}{{/required}}{{^required}}false{{/required}})
{{/bodyParams}}]),
"type" : "{{returnType}}",
"responseMessages" : [errors.invalid('id'), errors.notFound('{{returnType}}')],
"nickname" : "{{nickname}}"
},
'action': function (req,res) {
{{#requiredParamCount}}
{{#requiredParams}}
if (!req.params.{{baseName}}) {
throw errors.invalid('{{baseName}}');
}
{{/requiredParams}}
{{/requiredParamCount}}
writeResponse(res, {message: "how about implementing {{nickname}} as a {{httpMethod}} method?"});
}
};
{{/operation}}
{{/operations}}

View File

@ -1,47 +0,0 @@
var express = require("express")
, url = require("url")
, cors = require("cors")
, swagger = require("swagger-node-express")
, db = false
var app = express();
app.use(express.bodyParser());
var corsOptions = {
credentials: true,
origin: function(origin,callback) {
if(origin===undefined) {
callback(null,false);
} else {
callback(null,true);
}
}
};
app.use(cors(corsOptions));
swagger.setAppHandler(app);
swagger.configureSwaggerPaths("", "api-docs", "")
var models = require("./models.js");
{{#apiInfo}}
{{#apis}}
var {{name}} = require("./{{apiFolder}}/{{classname}}.js");
{{/apis}}
{{/apiInfo}}
swagger.addModels(models)
{{#apiInfo}}
{{#apis}}
{{#operations}}
{{#operation}}.add{{httpMethod}}({{name}}.{{nickname}}){{newline}}{{/operation}}
{{/operations}}
{{/apis}};
{{/apiInfo}}
// configures the app
swagger.configure("http://localhost:8002", "0.1");
// start the server
app.listen(8002);

View File

@ -1,7 +0,0 @@
exports.models = {
{{#models}}
{{#model}}
"{{classVarName}}": {{{modelJson}}}{{#hasMoreModels}},{{/hasMoreModels}}{{newline}}
{{/model}}
{{/models}}
}

View File

@ -1,16 +0,0 @@
{
"name": "{{{artifactId}}}",
"description": "Wordnik node.js server generator",
"version": "{{{artifactVersion}}}",
"homepage": "{{{homepage}}}",
"main": "./{{codeDir}}/main.js",
"engines": {
"node": ">= 0.8.x"
},
"dependencies": {
"swagger-node-express": ">= 2.0.x",
"connect": ">= 1.8.x",
"cors": "2.1.1",
"express": "3.x"
}
}

View File

@ -1,76 +0,0 @@
# Swagger generated server
## Overview
Using the swagger-codegen, you can not only generate clients but servers as well! The same spec can be used to drive your
development both ways. This is an example of generating a server for `scalatra`.
### Prerequisites
You need the following installed and available in your $PATH:
<li>- sbt 0.12 (http://www.scala-sbt.org/)
<li>- Scala 2.10.0 [available here](http://www.scala-lang.org)
You also need to add the scala binary to your PATH.
### Generating a server
You first need to build the `swagger-codegen` project--this is done by running this command at the root of the swagger-codegen project:
```
./sbt assembly
```
You can now generate a server from any valid[**](https://github.com/wordnik/swagger-codegen/blob/master/README.md#validating-your-swagger-spec) swagger spec:
```
./bin/runscala.sh samples/server-generator/scalatra/ScalatraServerGenerator.scala http://petstore.swagger.wordnik.com/api/api-docs special-key
```
After executing this script, you will have an output directory with the server-generated files:
```
$ cd samples/server-generator/scalatra/output
$ find -type f
./project/build.properties
./project/plugins.sbt
./README.md
./src/main/scala/apis/PetApi.scala
./src/main/scala/apis/StoreApi.scala
./src/main/scala/apis/UserApi.scala
./src/main/scala/com/wordnik/client/model/Category.scala
./src/main/scala/com/wordnik/client/model/Order.scala
./src/main/scala/com/wordnik/client/model/Pet.scala
./src/main/scala/com/wordnik/client/model/Tag.scala
./src/main/scala/com/wordnik/client/model/User.scala
./src/main/scala/JsonUtil.scala
./src/main/scala/ServletApp.scala
```
To run the server, cd to the `samples/server-generator/scalatra/output` folder and run:
```
chmod a+x ./sbt
./sbt
> container:start
```
You can now load the swagger-ui against `http://localhost:8080/api-docs`. Of course this isn't a fully
runnable server! You have to add the logic in the apis/*.scala files. But that's the easy part.
### Making it your own
Running the sample is easy, but how about making your own server? Easy! Just modify the `samples/server-generator/scalatra/ScalatraServerGenerator.scala` file.
Don't like the templates? Don't worry, we're not offended! They're [mustache](http://mustache.github.com/) templates and are easy to modify.
Take a look at the sample templates here:
<li> - Generator for your api classes: [api.mustache](https://github.com/wordnik/swagger-codegen/blob/master/samples/server-generator/scalatra/templates/api.mustache)
<li> - Generator for your models: [model.mustache](https://github.com/wordnik/swagger-codegen/blob/master/samples/server-generator/scalatra/templates/model.mustache)
<li> - The main class to run your server: [ServletApp.mustache](https://github.com/wordnik/swagger-codegen/blob/master/samples/server-generator/scalatra/templates/ServletApp.mustache)
Sound easy? It is!

View File

@ -1,127 +0,0 @@
/**
* Copyright 2014 Wordnik, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import com.wordnik.swagger.codegen.BasicScalaGenerator
import scala.collection.mutable.{ HashMap, ListBuffer }
object ScalatraServerGenerator extends BasicScalaGenerator {
def main(args: Array[String]) = generateClient(args)
override def templateDir = "samples/server-generator/scalatra/templates"
val outputFolder = "samples/server-generator/scalatra/output"
// where to write generated code
override def destinationDir = outputFolder + "/src/main/scala"
override def modelPackage = Some("com.wordnik.client.model")
// template used for apis
apiTemplateFiles ++= Map("api.mustache" -> ".scala")
modelTemplateFiles ++= Map("model.mustache" -> ".scala")
override def apiPackage = Some("apis")
additionalParams ++= Map(
"appName" -> "Swagger Sample",
"appDescription" -> "A sample swagger server",
"infoUrl" -> "http://developers.helloreverb.com",
"infoEmail" -> "hello@helloreverb.com",
"licenseInfo" -> "All rights reserved",
"licenseUrl" -> "http://apache.org/licenses/LICENSE-2.0.html")
// supporting classes
override def supportingFiles = List(
("README.mustache", outputFolder, "README.md"),
("build.sbt", outputFolder, "build.sbt"),
("web.xml", outputFolder + "/src/main/webapp/WEB-INF", "web.xml"),
("JettyMain.scala", outputFolder + "/src/main/scala", "JettyMain.scala"),
("Bootstrap.mustache", destinationDir, "ScalatraBootstrap.scala"),
("ServletApp.mustache", destinationDir, "ServletApp.scala"),
("project/build.properties", outputFolder, "project/build.properties"),
("project/plugins.sbt", outputFolder, "project/plugins.sbt"),
("sbt", outputFolder, "sbt"))
override def processApiMap(m: Map[String, AnyRef]): Map[String, AnyRef] = {
val mutable = scala.collection.mutable.Map() ++ m
mutable.map(k => {
k._1 match {
case "allParams" => {
val paramList = k._2.asInstanceOf[List[_]]
paramList.foreach(param => {
val map = param.asInstanceOf[scala.collection.mutable.HashMap[String, AnyRef]]
if(map.contains("dataType")){
val dataType = map("dataType")
map += "dataType" -> dataType.toString.replaceAll("Array\\[","List[")
}
if(map.contains("required")) {
if(map("required") == "false") map += "notRequired" -> "true"
}
if(map.contains("allowableValues")) {
val allowableValues = map("allowableValues")
val quote = map("swaggerDataType") match {
case "string" => "\""
case _ => ""
}
val pattern = "([A-Z]*)\\[(.*)\\]".r
val str = allowableValues match {
case pattern(valueType, values) => {
valueType match {
case "LIST" => {
val l = values.split(",").toList
Some("AllowableValues(" + l.mkString(quote, quote + "," + quote, quote + ")"))
}
case "RANGE" => {
val r = values.split(",")
Some("AllowableValues(Range(" + r(0) + "," + r(1) + ", 1))")
}
}
}
case _ => None
}
str match {
case Some(s) => map += "allowableValues" -> s
case _ =>
}
}
})
}
// the scalatra templates like lower-case httpMethods
case "httpMethod" => mutable += "httpMethod" -> k._2.toString.toLowerCase
// convert path into ruby-ish syntax without basePart (i.e. /pet.{format}/{petId} => /:petId
case "path" => {
val path = {
val arr = k._2.toString.split("/")
if (arr.length >= 2) {
mutable += "basePart" -> (arr.slice(2, arr.length).mkString("", "/", ""))
"/" + arr.slice(2, arr.length).mkString("", "/", "")
} else
k._2.toString
}
// rip out the root path
mutable += "path" -> path.replaceAll("\\{", ":").replaceAll("\\}", "")
}
case _ =>
}
})
mutable.toMap
}
}

View File

@ -1,10 +0,0 @@
# Swagger generated server
## Overview
This server was generated by the [swagger-codegen](https://github.com/wordnik/swagger-codegen) project. By using the
[swagger-spec](https://github.com/wordnik/swagger-core/wiki) from a remote server, you can easily generate a server stub. This
is an example of building a swagger-enabled scalatra server.
This example uses the [scalatra](http://scalatra.org/) framework. To see how to make this your own, look here:
[README](https://github.com/wordnik/swagger-codegen/tree/master/samples/server-generator/scalatra)

View File

@ -1,59 +0,0 @@
import AssemblyKeys._ // put this at the top of the file
import NativePackagerKeys._
packageArchetype.java_server
assemblySettings
scalariformSettings
organization := "com.wordnik"
seq(webSettings :_*)
mainClass in assembly := Some("JettyMain")
name := "scalatra-sample"
version := "0.1.0-SNAPSHOT"
scalaVersion := "2.10.0"
libraryDependencies ++= Seq(
"org.scalatest" %% "scalatest" % "2.0" % "test",
"org.scalatra" %% "scalatra" % "2.3.0.RC3",
"org.scalatra" %% "scalatra-scalate" % "2.3.0.RC3",
"org.scalatra" %% "scalatra-json" % "2.3.0.RC3",
"org.scalatra" %% "scalatra-swagger" % "2.3.0.RC3",
"org.scalatra" %% "scalatra-swagger-ext" % "2.3.0.RC3",
"org.scalatra" %% "scalatra-slf4j" % "2.3.0.RC3",
"org.json4s" %% "json4s-jackson" % "3.1.0",
"org.json4s" %% "json4s-ext" % "3.1.0",
"commons-codec" % "commons-codec" % "1.7",
"net.databinder.dispatch" %% "dispatch-core" % "0.9.5",
"net.databinder.dispatch" %% "json4s-jackson" % "0.9.5",
"com.typesafe.akka" %% "akka-actor" % "2.1.0",
"org.eclipse.jetty" % "jetty-server" % "8.1.7.v20120910" % "container;provided",
"org.eclipse.jetty" % "jetty-webapp" % "8.1.7.v20120910" % "container;provided",
"org.eclipse.jetty.orbit" % "javax.servlet" % "3.0.0.v201112011016" % "container;compile;provided;test" artifacts (Artifact("javax.servlet", "jar", "jar"))
)
resolvers += "Local Maven Repository" at "file://"+Path.userHome.absolutePath+"/.m2/repository"
resolvers += "Sonatype OSS Snapshots" at "http://oss.sonatype.org/content/repositories/snapshots/"
resolvers += "Sonatype OSS Releases" at "http://oss.sonatype.org/content/repositories/releases/"
ivyXML := <dependencies>
<exclude module="slf4j-log4j12"/>
<exclude module="grizzled-slf4j_2.9.1"/>
<exclude module="jsr311-api" />
</dependencies>
mergeStrategy in assembly <<= (mergeStrategy in assembly) { (old) =>
{
case "about.html" => MergeStrategy.discard
case x => old(x)
}
}

View File

@ -1 +0,0 @@
sbt.version=0.13.0

View File

@ -1,7 +0,0 @@
addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "0.10.1")
addSbtPlugin("com.typesafe.sbt" % "sbt-native-packager" % "0.6.4")
addSbtPlugin("com.earldouglas" % "xsbt-web-plugin" % "0.6.0")
addSbtPlugin("com.typesafe.sbt" % "sbt-scalariform" % "1.2.1")

View File

@ -1,21 +0,0 @@
import apis._
import akka.actor.ActorSystem
import com.wordnik.swagger.app.{ ResourcesApp, SwaggerApp }
import javax.servlet.ServletContext
import org.scalatra.LifeCycle
class ScalatraBootstrap extends LifeCycle {
implicit val swagger = new SwaggerApp
override def init(context: ServletContext) {
implicit val system = ActorSystem("appActorSystem")
try {
context mount (new UserApi, "/user/*")
context mount (new PetApi, "/pet/*")
context mount (new StoreApi, "/store/*")
context mount (new ResourcesApp, "/api-docs/*")
} catch {
case e: Throwable => e.printStackTrace()
}
}
}

View File

@ -1,39 +0,0 @@
package com.wordnik.swagger.app
import _root_.akka.actor.ActorSystem
import org.scalatra.swagger.{ ApiInfo, SwaggerWithAuth, Swagger }
import org.scalatra.swagger.{ JacksonSwaggerBase, Swagger }
import org.scalatra.ScalatraServlet
import org.json4s.{ DefaultFormats, Formats }
class ResourcesApp(implicit protected val system: ActorSystem, val swagger: SwaggerApp)
extends ScalatraServlet with JacksonSwaggerBase {
before() {
response.headers += ("Access-Control-Allow-Origin" -> "*")
}
protected def buildFullUrl(path: String) = if (path.startsWith("http")) path else {
val port = request.getServerPort
val h = request.getServerName
val prot = if (port == 443) "https" else "http"
val (proto, host) = if (port != 80 && port != 443) ("http", h + ":" + port.toString) else (prot, h)
"%s://%s%s%s".format(
proto,
host,
request.getContextPath,
path)
}
}
class SwaggerApp extends Swagger(apiInfo = ApiSwagger.apiInfo, apiVersion = "1.0", swaggerVersion = "1.2")
object ApiSwagger {
val apiInfo = ApiInfo(
"Swagger Sample",
"A sample swagger server",
"http://developers.helloreverb.com",
"hello@helloreverb.com",
"All rights reserved",
"http://apache.org/licenses/LICENSE-2.0.html")
}

View File

@ -1,137 +0,0 @@
package apis
import com.wordnik.client.model.Pet
import java.io.File
import org.scalatra.{ TypedParamSupport, ScalatraServlet }
import org.scalatra.swagger._
import org.json4s._
import org.json4s.JsonDSL._
import org.scalatra.json.{ JValueResult, JacksonJsonSupport }
import org.scalatra.servlet.{ FileUploadSupport, MultipartConfig, SizeConstraintExceededException }
import scala.collection.JavaConverters._
class PetApi(implicit val swagger: Swagger) extends ScalatraServlet
with FileUploadSupport
with JacksonJsonSupport
with SwaggerSupport {
protected implicit val jsonFormats: Formats = DefaultFormats
protected val applicationDescription: String = "PetApi"
override protected val applicationName: Option[String] = Some("pet")
before() {
contentType = formats("json")
response.headers += ("Access-Control-Allow-Origin" -> "*")
}
val getPetByIdOperation = (apiOperation[Pet]("getPetById")
summary "Find pet by ID"
parameters (
pathParam[Long]("petId").description(""))
)
get("/:petId", operation(getPetByIdOperation)) {
val petId = params.getOrElse("petId", halt(400))
println("petId: " + petId)
}
val deletePetOperation = (apiOperation[Unit]("deletePet")
summary "Deletes a pet"
parameters (
pathParam[String]("petId").description(""))
)
delete("/:petId", operation(deletePetOperation)) {
val petId = params.getOrElse("petId", halt(400))
println("petId: " + petId)
}
val partialUpdateOperation = (apiOperation[List[Pet]]("partialUpdate")
summary "partial updates to a pet"
parameters (
pathParam[String]("petId").description(""), bodyParam[Pet]("body").description(""))
)
patch("/:petId", operation(partialUpdateOperation)) {
val petId = params.getOrElse("petId", halt(400))
println("petId: " + petId)
val body = parsedBody.extract[Pet]
println("body: " + body)
}
val updatePetWithFormOperation = (apiOperation[Unit]("updatePetWithForm")
summary "Updates a pet in the store with form data"
parameters (
pathParam[String]("petId").description(""), formParam[String]("name").description(""), formParam[String]("status").description(""))
)
post("/:petId", operation(updatePetWithFormOperation)) {
val petId = params.getOrElse("petId", halt(400))
println("petId: " + petId)
val name = params.getAs[String]("name")
println("name: " + name)
val status = params.getAs[String]("status")
println("status: " + status)
}
val uploadFileOperation = (apiOperation[Unit]("uploadFile")
summary "uploads an image"
parameters (
formParam[String]("additionalMetadata").description(""),
bodyParam[File]("body").description("").optional)
)
post("/uploadImage", operation(uploadFileOperation)) {
val additionalMetadata = params.getAs[String]("additionalMetadata")
println("additionalMetadata: " + additionalMetadata)
val body = fileParams("body")
println("body: " + body)
}
val addPetOperation = (apiOperation[Unit]("addPet")
summary "Add a new pet to the store"
parameters (
bodyParam[Pet]("body").description(""))
)
post("/", operation(addPetOperation)) {
val body = parsedBody.extract[Pet]
println("body: " + body)
}
val updatePetOperation = (apiOperation[Unit]("updatePet")
summary "Update an existing pet"
parameters (
bodyParam[Pet]("body").description(""))
)
put("/", operation(updatePetOperation)) {
val body = parsedBody.extract[Pet]
println("body: " + body)
}
val findPetsByStatusOperation = (apiOperation[List[Pet]]("findPetsByStatus")
summary "Finds Pets by status"
parameters (
queryParam[String]("status").description("").defaultValue("available"))
)
get("/findByStatus", operation(findPetsByStatusOperation)) {
val status = params.getAs[String]("status")
println("status: " + status)
}
val findPetsByTagsOperation = (apiOperation[List[Pet]]("findPetsByTags")
summary "Finds Pets by tags"
parameters (
queryParam[String]("tags").description(""))
)
get("/findByTags", operation(findPetsByTagsOperation)) {
val tags = params.getAs[String]("tags")
println("tags: " + tags)
}
}

View File

@ -1,62 +0,0 @@
package apis
import com.wordnik.client.model.Order
import java.io.File
import org.scalatra.{ TypedParamSupport, ScalatraServlet }
import org.scalatra.swagger._
import org.json4s._
import org.json4s.JsonDSL._
import org.scalatra.json.{ JValueResult, JacksonJsonSupport }
import org.scalatra.servlet.{ FileUploadSupport, MultipartConfig, SizeConstraintExceededException }
import scala.collection.JavaConverters._
class StoreApi(implicit val swagger: Swagger) extends ScalatraServlet
with FileUploadSupport
with JacksonJsonSupport
with SwaggerSupport {
protected implicit val jsonFormats: Formats = DefaultFormats
protected val applicationDescription: String = "StoreApi"
override protected val applicationName: Option[String] = Some("store")
before() {
contentType = formats("json")
response.headers += ("Access-Control-Allow-Origin" -> "*")
}
val getOrderByIdOperation = (apiOperation[Order]("getOrderById")
summary "Find purchase order by ID"
parameters (
pathParam[String]("orderId").description(""))
)
get("/order/:orderId", operation(getOrderByIdOperation)) {
val orderId = params.getOrElse("orderId", halt(400))
println("orderId: " + orderId)
}
val deleteOrderOperation = (apiOperation[Unit]("deleteOrder")
summary "Delete purchase order by ID"
parameters (
pathParam[String]("orderId").description(""))
)
delete("/order/:orderId", operation(deleteOrderOperation)) {
val orderId = params.getOrElse("orderId", halt(400))
println("orderId: " + orderId)
}
val placeOrderOperation = (apiOperation[Unit]("placeOrder")
summary "Place an order for a pet"
parameters (
bodyParam[Order]("body").description(""))
)
post("/order", operation(placeOrderOperation)) {
val body = parsedBody.extract[Order]
println("body: " + body)
}
}

View File

@ -1,118 +0,0 @@
package apis
import com.wordnik.client.model.User
import java.io.File
import org.scalatra.{ TypedParamSupport, ScalatraServlet }
import org.scalatra.swagger._
import org.json4s._
import org.json4s.JsonDSL._
import org.scalatra.json.{ JValueResult, JacksonJsonSupport }
import org.scalatra.servlet.{ FileUploadSupport, MultipartConfig, SizeConstraintExceededException }
import scala.collection.JavaConverters._
class UserApi(implicit val swagger: Swagger) extends ScalatraServlet
with FileUploadSupport
with JacksonJsonSupport
with SwaggerSupport {
protected implicit val jsonFormats: Formats = DefaultFormats
protected val applicationDescription: String = "UserApi"
override protected val applicationName: Option[String] = Some("user")
before() {
contentType = formats("json")
response.headers += ("Access-Control-Allow-Origin" -> "*")
}
val updateUserOperation = (apiOperation[Unit]("updateUser")
summary "Updated user"
parameters (
pathParam[String]("username").description(""), bodyParam[User]("body").description(""))
)
put("/:username", operation(updateUserOperation)) {
val username = params.getOrElse("username", halt(400))
println("username: " + username)
val body = parsedBody.extract[User]
println("body: " + body)
}
val deleteUserOperation = (apiOperation[Unit]("deleteUser")
summary "Delete user"
parameters (
pathParam[String]("username").description(""))
)
delete("/:username", operation(deleteUserOperation)) {
val username = params.getOrElse("username", halt(400))
println("username: " + username)
}
val getUserByNameOperation = (apiOperation[User]("getUserByName")
summary "Get user by user name"
parameters (
pathParam[String]("username").description(""))
)
get("/:username", operation(getUserByNameOperation)) {
val username = params.getOrElse("username", halt(400))
println("username: " + username)
}
val loginUserOperation = (apiOperation[String]("loginUser")
summary "Logs user into the system"
parameters (
queryParam[String]("username").description(""), queryParam[String]("password").description(""))
)
get("/login", operation(loginUserOperation)) {
val username = params.getAs[String]("username")
println("username: " + username)
val password = params.getAs[String]("password")
println("password: " + password)
}
val logoutUserOperation = (apiOperation[Unit]("logoutUser")
summary "Logs out current logged in user session"
parameters ()
)
get("/logout", operation(logoutUserOperation)) {
}
val createUserOperation = (apiOperation[Unit]("createUser")
summary "Create user"
parameters (
bodyParam[User]("body").description(""))
)
post("/", operation(createUserOperation)) {
val body = parsedBody.extract[User]
println("body: " + body)
}
val createUsersWithArrayInputOperation = (apiOperation[Unit]("createUsersWithArrayInput")
summary "Creates list of users with given input array"
parameters (
bodyParam[List[User]]("body").description(""))
)
post("/createWithArray", operation(createUsersWithArrayInputOperation)) {
val body = parsedBody.extract[List[User]]
println("body: " + body)
}
val createUsersWithListInputOperation = (apiOperation[Unit]("createUsersWithListInput")
summary "Creates list of users with given list input"
parameters (
bodyParam[List[User]]("body").description(""))
)
post("/createWithList", operation(createUsersWithListInputOperation)) {
val body = parsedBody.extract[List[User]]
println("body: " + body)
}
}

View File

@ -1,7 +0,0 @@
package com.wordnik.client.model
case class Category(
id: Option[Long],
name: Option[String])

View File

@ -1,14 +0,0 @@
package com.wordnik.client.model
import java.util.Date
case class Order(
id: Option[Long],
petId: Option[Long],
quantity: Option[Int],
status: Option[String], // Order Status
shipDate: Option[Date])

View File

@ -1,18 +0,0 @@
package com.wordnik.client.model
import com.wordnik.client.model.Category
import com.wordnik.client.model.Tag
case class Pet(
id: Long, // unique identifier for the pet
category: Option[Category],
name: String,
photoUrls: Option[List[String]],
tags: Option[List[Tag]],
status: Option[String] // pet status in the store
)

View File

@ -1,7 +0,0 @@
package com.wordnik.client.model
case class Tag(
id: Option[Long],
name: Option[String])

View File

@ -1,20 +0,0 @@
package com.wordnik.client.model
case class User(
id: Option[Long],
firstName: Option[String],
username: Option[String],
lastName: Option[String],
email: Option[String],
password: Option[String],
phone: Option[String],
userStatus: Option[Int] // User Status
)

View File

@ -1,32 +0,0 @@
import org.eclipse.jetty.server.nio.SelectChannelConnector
import org.eclipse.jetty.server.{ Server }
import org.eclipse.jetty.server.handler.ContextHandlerCollection
import org.eclipse.jetty.webapp.WebAppContext
import org.eclipse.jetty.servlet.{ DefaultServlet, ServletContextHandler, ServletHolder }
object JettyMain {
def main(args: Array[String]) = {
val server: Server = new Server
println("starting jetty")
server setGracefulShutdown 5000
server setSendServerVersion false
server setSendDateHeader true
server setStopAtShutdown true
val connector = new SelectChannelConnector
connector setPort sys.env.get("PORT").map(_.toInt).getOrElse(8080)
connector setMaxIdleTime 90000
server addConnector connector
val webapp = sys.env.get("PUBLIC") getOrElse "webapp"
val webApp = new WebAppContext
webApp setContextPath "/"
webApp setResourceBase webapp
webApp setDescriptor (webapp+"/WEB-INF/web.xml");
server setHandler webApp
server.start()
}
}

View File

@ -1,12 +0,0 @@
package json
import com.fasterxml.jackson.module.scala.DefaultScalaModule
import com.fasterxml.jackson.core.JsonGenerator.Feature
import com.fasterxml.jackson.databind._
object JsonUtil {
val mapper = new ObjectMapper()
mapper.registerModule(new DefaultScalaModule())
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
}

View File

@ -1,10 +0,0 @@
# Swagger generated server
## Overview
This server was generated by the [swagger-codegen](https://github.com/wordnik/swagger-codegen) project. By using the
[swagger-spec](https://github.com/wordnik/swagger-core/wiki) from a remote server, you can easily generate a server stub. This
is an example of building a swagger-enabled scalatra server.
This example uses the [scalatra](http://scalatra.org/) framework. To see how to make this your own, look here:
[README](https://github.com/wordnik/swagger-codegen/tree/master/samples/server-generator/scalatra)

View File

@ -1,89 +0,0 @@
package {{package}}
{{#imports}}import {{import}}
{{/imports}}
import java.io.File
import org.scalatra.{ TypedParamSupport, ScalatraServlet }
import org.scalatra.swagger._
import org.json4s._
import org.json4s.JsonDSL._
import org.scalatra.json.{ JValueResult, JacksonJsonSupport }
import org.scalatra.servlet.{FileUploadSupport, MultipartConfig, SizeConstraintExceededException}
import scala.collection.JavaConverters._
class {{classname}} (implicit val swagger: Swagger) extends ScalatraServlet
with FileUploadSupport
with JacksonJsonSupport
with SwaggerSupport {
protected implicit val jsonFormats: Formats = DefaultFormats
protected val applicationDescription: String = "{{classname}}"
override protected val applicationName: Option[String] = Some("{{baseName}}")
before() {
contentType = formats("json")
response.headers += ("Access-Control-Allow-Origin" -> "*")
}
{{#operations}}
{{#operation}}
{{newline}}
val {{nickname}}Operation = (apiOperation[{{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}Unit{{/returnType}}]("{{nickname}}")
summary "{{{summary}}}"
parameters(
{{#allParams}}
{{#queryParameter}}
queryParam[{{dataType}}]("{{paramName}}").description(""){{^required}}.optional{{/required}}{{#defaultValue}}.defaultValue({{{defaultValue}}}){{/defaultValue}}
{{/queryParameter}}
{{#pathParameter}}
pathParam[{{dataType}}]("{{paramName}}").description(""){{#defaultValue}}.defaultValue({{{defaultValue}}}){{/defaultValue}}
{{/pathParameter}}
{{#headerParameter}}
headerParam[{{dataType}}]("{{paramName}}").description(""){{^required}}.optional{{/required}}{{#defaultValue}}.defaultValue({{{defaultValue}}}){{/defaultValue}}
{{/headerParameter}}
{{#bodyParameter}}
bodyParam[{{dataType}}]("{{paramName}}").description(""){{^required}}.optional{{/required}}{{#defaultValue}}.defaultValue({{{defaultValue}}}){{/defaultValue}}
{{/bodyParameter}}
{{#formParameter}}
formParam[{{dataType}}]("{{paramName}}").description(""){{^required}}.optional{{/required}}{{#defaultValue}}.defaultValue({{{defaultValue}}}){{/defaultValue}}
{{/formParameter}}
{{#hasMore}},{{/hasMore}}
{{/allParams}})
)
{{httpMethod}}("{{path}}",operation({{nickname}}Operation)) {
{{#allParams}}
{{#isFile}}
val {{paramName}} = fileParams("{{paramName}}")
{{/isFile}}
{{#notFile}}
{{#pathParameter}}
val {{paramName}} = params.getOrElse("{{paramName}}", halt(400))
{{/pathParameter}}
{{#queryParameter}}
val {{paramName}} = params.getAs[{{dataType}}]("{{paramName}}")
{{/queryParameter}}
{{#headerParameter}}
val {{paramName}} = request.getHeader("{{paramName}}")
{{/headerParameter}}
{{#formParameter}}
val {{paramName}} = params.getAs[{{dataType}}]("{{paramName}}")
{{/formParameter}}
{{#bodyParameter}}
val {{paramName}} = parsedBody.extract[{{dataType}}]
{{/bodyParameter}}
{{/notFile}}
println("{{paramName}}: " + {{paramName}})
{{/allParams}}
}
{{/operation}}
{{/operations}}
}

View File

@ -1,16 +0,0 @@
package {{package}}
{{#imports}}import {{import}}
{{/imports}}
{{#models}}
{{#model}}
case class {{classname}} (
{{#vars}}
{{name}}: {{#isNotRequired}}Option[{{/isNotRequired}}{{datatype}}{{#isNotRequired}}]{{/isNotRequired}} {{#hasMore}},{{/hasMore}}{{#description}} // {{description}}{{/description}}{{newline}}
{{/vars}}
)
{{/model}}
{{/models}}

View File

@ -1 +0,0 @@
sbt.version=0.13.0

View File

@ -1,7 +0,0 @@
addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "0.10.1")
addSbtPlugin("com.typesafe.sbt" % "sbt-native-packager" % "0.6.4")
addSbtPlugin("com.earldouglas" % "xsbt-web-plugin" % "0.6.0")
addSbtPlugin("com.typesafe.sbt" % "sbt-scalariform" % "1.2.1")

View File

@ -1,518 +0,0 @@
#!/usr/bin/env bash
#
# A more capable sbt runner, coincidentally also called sbt.
# Author: Paul Phillips <paulp@typesafe.com>
# todo - make this dynamic
declare -r sbt_release_version=0.12.4
declare -r sbt_beta_version=0.13.0-RC4
declare -r sbt_snapshot_version=0.13.0-SNAPSHOT
declare sbt_jar sbt_dir sbt_create sbt_snapshot sbt_launch_dir
declare scala_version java_home sbt_explicit_version
declare verbose debug quiet noshare batch trace_level log_level
declare sbt_saved_stty
echoerr () { [[ -z $quiet ]] && echo "$@" >&2; }
vlog () { [[ -n "$verbose$debug" ]] && echoerr "$@"; }
dlog () { [[ -n $debug ]] && echoerr "$@"; }
# we'd like these set before we get around to properly processing arguments
for arg in "$@"; do
case $arg in
-q|-quiet) quiet=true ;;
-d|-debug) debug=true ;;
-v|-verbose) verbose=true ;;
*) ;;
esac
done
build_props_sbt () {
if [[ -r project/build.properties ]]; then
versionLine=$(grep ^sbt.version project/build.properties | tr -d '\r')
versionString=${versionLine##sbt.version=}
echo "$versionString"
fi
}
update_build_props_sbt () {
local ver="$1"
local old=$(build_props_sbt)
if [[ $ver == $old ]]; then
return
elif [[ -r project/build.properties ]]; then
perl -pi -e "s/^sbt\.version=.*\$/sbt.version=${ver}/" project/build.properties
grep -q '^sbt.version=' project/build.properties || echo "sbt.version=${ver}" >> project/build.properties
echoerr !!!
echoerr !!! Updated file project/build.properties setting sbt.version to: $ver
echoerr !!! Previous value was: $old
echoerr !!!
fi
}
sbt_version () {
if [[ -n $sbt_explicit_version ]]; then
echo $sbt_explicit_version
else
local v=$(build_props_sbt)
if [[ -n $v ]]; then
echo $v
else
echo $sbt_release_version
fi
fi
}
# restore stty settings (echo in particular)
onSbtRunnerExit() {
[[ -n $sbt_saved_stty ]] || return
dlog ""
dlog "restoring stty: $sbt_saved_stty"
stty $sbt_saved_stty
unset sbt_saved_stty
}
# save stty and trap exit, to ensure echo is reenabled if we are interrupted.
trap onSbtRunnerExit EXIT
sbt_saved_stty=$(stty -g 2>/dev/null)
dlog "Saved stty: $sbt_saved_stty"
# this seems to cover the bases on OSX, and someone will
# have to tell me about the others.
get_script_path () {
local path="$1"
[[ -L "$path" ]] || { echo "$path" ; return; }
local target=$(readlink "$path")
if [[ "${target:0:1}" == "/" ]]; then
echo "$target"
else
echo "$(dirname $path)/$target"
fi
}
die() {
echo "Aborting: $@"
exit 1
}
make_url () {
groupid="$1"
category="$2"
version="$3"
echo "http://typesafe.artifactoryonline.com/typesafe/ivy-$category/$groupid/sbt-launch/$version/sbt-launch.jar"
}
readarr () {
while read ; do
eval "$1+=(\"$REPLY\")"
done
}
init_default_option_file () {
local overriding_var=${!1}
local default_file=$2
if [[ ! -r "$default_file" && $overriding_var =~ ^@(.*)$ ]]; then
local envvar_file=${BASH_REMATCH[1]}
if [[ -r $envvar_file ]]; then
default_file=$envvar_file
fi
fi
echo $default_file
}
declare -r default_jvm_opts="-Dfile.encoding=UTF8 -XX:MaxPermSize=256m -Xms512m -Xmx1g -XX:+CMSClassUnloadingEnabled -XX:+UseConcMarkSweepGC"
declare -r noshare_opts="-Dsbt.global.base=project/.sbtboot -Dsbt.boot.directory=project/.boot -Dsbt.ivy.home=project/.ivy"
declare -r latest_28="2.8.2"
declare -r latest_29="2.9.3"
declare -r latest_210="2.10.0"
declare -r script_path=$(get_script_path "$BASH_SOURCE")
declare -r script_dir="$(dirname $script_path)"
declare -r script_name="$(basename $script_path)"
# some non-read-onlies set with defaults
declare java_cmd=java
declare sbt_opts_file=$(init_default_option_file SBT_OPTS .sbtopts)
declare jvm_opts_file=$(init_default_option_file JVM_OPTS .jvmopts)
# pull -J and -D options to give to java.
declare -a residual_args
declare -a java_args
declare -a scalac_args
declare -a sbt_commands
# args to jvm/sbt via files or environment variables
declare -a extra_jvm_opts extra_sbt_opts
# if set, use JAVA_HOME over java found in path
[[ -e "$JAVA_HOME/bin/java" ]] && java_cmd="$JAVA_HOME/bin/java"
# directory to store sbt launchers
declare sbt_launch_dir="$HOME/.sbt/launchers"
[[ -d "$sbt_launch_dir" ]] || mkdir -p "$sbt_launch_dir"
[[ -w "$sbt_launch_dir" ]] || sbt_launch_dir="$(mktemp -d -t sbt_extras_launchers)"
build_props_scala () {
if [[ -r project/build.properties ]]; then
versionLine=$(grep ^build.scala.versions project/build.properties)
versionString=${versionLine##build.scala.versions=}
echo ${versionString%% .*}
fi
}
execRunner () {
# print the arguments one to a line, quoting any containing spaces
[[ $verbose || $debug ]] && echo "# Executing command line:" && {
for arg; do
if [[ -n "$arg" ]]; then
if printf "%s\n" "$arg" | grep -q ' '; then
printf "\"%s\"\n" "$arg"
else
printf "%s\n" "$arg"
fi
fi
done
echo ""
}
if [[ -n $batch ]]; then
# the only effective way I've found to avoid sbt hanging when backgrounded.
exec 0<&-
( "$@" & )
# I'm sure there's some way to get our hands on the pid and wait for it
# but it exceeds my present level of ambition.
else
{ "$@"; }
fi
}
sbt_groupid () {
case $(sbt_version) in
0.7.*) echo org.scala-tools.sbt ;;
0.10.*) echo org.scala-tools.sbt ;;
0.11.[12]) echo org.scala-tools.sbt ;;
*) echo org.scala-sbt ;;
esac
}
sbt_artifactory_list () {
local version0=$(sbt_version)
local version=${version0%-SNAPSHOT}
local url="http://typesafe.artifactoryonline.com/typesafe/ivy-snapshots/$(sbt_groupid)/sbt-launch/"
dlog "Looking for snapshot list at: $url "
curl -s --list-only "$url" | \
grep -F $version | \
perl -e 'print reverse <>' | \
perl -pe 's#^<a href="([^"/]+).*#$1#;'
}
make_release_url () {
make_url $(sbt_groupid) releases $(sbt_version)
}
# argument is e.g. 0.13.0-SNAPSHOT
# finds the actual version (with the build id) at artifactory
make_snapshot_url () {
for ver in $(sbt_artifactory_list); do
local url=$(make_url $(sbt_groupid) snapshots $ver)
dlog "Testing $url"
curl -s --head "$url" >/dev/null
dlog "curl returned: $?"
echo "$url"
return
done
}
jar_url () {
case $(sbt_version) in
0.7.*) echo "http://simple-build-tool.googlecode.com/files/sbt-launch-0.7.7.jar" ;;
*-SNAPSHOT) make_snapshot_url ;;
*) make_release_url ;;
esac
}
jar_file () {
case $1 in
0.13.*) echo "$sbt_launch_dir/$1/sbt-launch.jar" ;;
*) echo "$sbt_launch_dir/$sbt_release_version/sbt-launch.jar" ;;
esac
}
download_url () {
local url="$1"
local jar="$2"
echo "Downloading sbt launcher $(sbt_version):"
echo " From $url"
echo " To $jar"
mkdir -p $(dirname "$jar") && {
if which curl >/dev/null; then
curl --fail --silent "$url" --output "$jar"
elif which wget >/dev/null; then
wget --quiet -O "$jar" "$url"
fi
} && [[ -r "$jar" ]]
}
acquire_sbt_jar () {
sbt_url="$(jar_url)"
sbt_jar="$(jar_file $(sbt_version))"
[[ -r "$sbt_jar" ]] || download_url "$sbt_url" "$sbt_jar"
}
usage () {
cat <<EOM
Usage: $script_name [options]
-h | -help print this message
-v | -verbose this runner is chattier
-d | -debug set sbt log level to Debug
-q | -quiet set sbt log level to Error
-trace <level> display stack traces with a max of <level> frames (default: -1, traces suppressed)
-no-colors disable ANSI color codes
-sbt-create start sbt even if current directory contains no sbt project
-sbt-dir <path> path to global settings/plugins directory (default: ~/.sbt/<version>)
-sbt-boot <path> path to shared boot directory (default: ~/.sbt/boot in 0.11+)
-ivy <path> path to local Ivy repository (default: ~/.ivy2)
-no-share use all local caches; no sharing
-offline put sbt in offline mode
-jvm-debug <port> Turn on JVM debugging, open at the given port.
-batch Disable interactive mode
-prompt <expr> Set the sbt prompt; in expr, 's' is the State and 'e' is Extracted
# sbt version (default: from project/build.properties if present, else latest release)
!!! The only way to accomplish this pre-0.12.0 if there is a build.properties file which
!!! contains an sbt.version property is to update the file on disk. That's what this does.
-sbt-version <version> use the specified version of sbt (default: $sbt_release_version)
-sbt-jar <path> use the specified jar as the sbt launcher
-sbt-beta use a beta version of sbt (currently: $sbt_beta_version)
-sbt-snapshot use a snapshot version of sbt (currently: $sbt_snapshot_version)
-sbt-launch-dir <path> directory to hold sbt launchers (default: $sbt_launch_dir)
# scala version (default: as chosen by sbt)
-28 use $latest_28
-29 use $latest_29
-210 use $latest_210
-scala-home <path> use the scala build at the specified directory
-scala-version <version> use the specified version of scala
-binary-version <version> use the specified scala version when searching for dependencies
# java version (default: java from PATH, currently $(java -version 2>&1 | grep version))
-java-home <path> alternate JAVA_HOME
# passing options to the jvm - note it does NOT use JAVA_OPTS due to pollution
# The default set is used if JVM_OPTS is unset and no -jvm-opts file is found
<default> $default_jvm_opts
JVM_OPTS environment variable holding either the jvm args directly, or
the reference to a file containing jvm args if given path is prepended by '@' (e.g. '@/etc/jvmopts')
Note: "@"-file is overridden by local '.jvmopts' or '-jvm-opts' argument.
-jvm-opts <path> file containing jvm args (if not given, .jvmopts in project root is used if present)
-Dkey=val pass -Dkey=val directly to the jvm
-J-X pass option -X directly to the jvm (-J is stripped)
# passing options to sbt, OR to this runner
SBT_OPTS environment variable holding either the sbt args directly, or
the reference to a file containing sbt args if given path is prepended by '@' (e.g. '@/etc/sbtopts')
Note: "@"-file is overridden by local '.sbtopts' or '-sbt-opts' argument.
-sbt-opts <path> file containing sbt args (if not given, .sbtopts in project root is used if present)
-S-X add -X to sbt's scalacOptions (-S is stripped)
EOM
}
addJava () {
dlog "[addJava] arg = '$1'"
java_args=( "${java_args[@]}" "$1" )
}
addSbt () {
dlog "[addSbt] arg = '$1'"
sbt_commands=( "${sbt_commands[@]}" "$1" )
}
addScalac () {
dlog "[addScalac] arg = '$1'"
scalac_args=( "${scalac_args[@]}" "$1" )
}
addResidual () {
dlog "[residual] arg = '$1'"
residual_args=( "${residual_args[@]}" "$1" )
}
addResolver () {
addSbt "set resolvers in ThisBuild += $1"
}
addDebugger () {
addJava "-Xdebug"
addJava "-Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=$1"
}
setScalaVersion () {
addSbt "set scalaVersion in ThisBuild := \"$1\""
if [[ "$1" == *SNAPSHOT* ]]; then
addResolver Opts.resolver.sonatypeSnapshots
fi
}
process_args ()
{
require_arg () {
local type="$1"
local opt="$2"
local arg="$3"
if [[ -z "$arg" ]] || [[ "${arg:0:1}" == "-" ]]; then
die "$opt requires <$type> argument"
fi
}
while [[ $# -gt 0 ]]; do
case "$1" in
-h|-help) usage; exit 1 ;;
-v|-verbose) verbose=true && log_level=Info && shift ;;
-d|-debug) debug=true && log_level=Debug && shift ;;
-q|-quiet) quiet=true && log_level=Error && shift ;;
-trace) require_arg integer "$1" "$2" && trace_level=$2 && shift 2 ;;
-ivy) require_arg path "$1" "$2" && addJava "-Dsbt.ivy.home=$2" && shift 2 ;;
-no-colors) addJava "-Dsbt.log.noformat=true" && shift ;;
-no-share) noshare=true && shift ;;
-sbt-boot) require_arg path "$1" "$2" && addJava "-Dsbt.boot.directory=$2" && shift 2 ;;
-sbt-dir) require_arg path "$1" "$2" && sbt_dir="$2" && shift 2 ;;
-debug-inc) addJava "-Dxsbt.inc.debug=true" && shift ;;
-offline) addSbt "set offline := true" && shift ;;
-jvm-debug) require_arg port "$1" "$2" && addDebugger $2 && shift 2 ;;
-batch) batch=true && shift ;;
-prompt) require_arg "expr" "$1" "$2" && addSbt "set shellPrompt in ThisBuild := (s => { val e = Project.extract(s) ; $2 })" && shift 2 ;;
-sbt-create) sbt_create=true && shift ;;
-sbt-snapshot) sbt_explicit_version=$sbt_snapshot_version && shift ;;
-sbt-beta) sbt_explicit_version=$sbt_beta_version && shift ;;
-sbt-jar) require_arg path "$1" "$2" && sbt_jar="$2" && shift 2 ;;
-sbt-version) require_arg version "$1" "$2" && sbt_explicit_version="$2" && shift 2 ;;
-sbt-launch-dir) require_arg path "$1" "$2" && sbt_launch_dir="$2" && shift 2 ;;
-scala-version) require_arg version "$1" "$2" && setScalaVersion "$2" && shift 2 ;;
-binary-version) require_arg version "$1" "$2" && addSbt "set scalaBinaryVersion in ThisBuild := \"$2\"" && shift 2 ;;
-scala-home) require_arg path "$1" "$2" && addSbt "set every scalaHome := Some(file(\"$2\"))" && shift 2 ;;
-java-home) require_arg path "$1" "$2" && java_cmd="$2/bin/java" && shift 2 ;;
-sbt-opts) require_arg path "$1" "$2" && sbt_opts_file="$2" && shift 2 ;;
-jvm-opts) require_arg path "$1" "$2" && jvm_opts_file="$2" && shift 2 ;;
-D*) addJava "$1" && shift ;;
-J*) addJava "${1:2}" && shift ;;
-S*) addScalac "${1:2}" && shift ;;
-28) addSbt "++ $latest_28" && shift ;;
-29) addSbt "++ $latest_29" && shift ;;
-210) addSbt "++ $latest_210" && shift ;;
*) addResidual "$1" && shift ;;
esac
done
}
# process the direct command line arguments
process_args "$@"
# skip #-styled comments
readConfigFile() {
while read line; do echo ${line/\#*/} | grep -vE '^\s*$'; done < $1
}
# if there are file/environment sbt_opts, process again so we
# can supply args to this runner
if [[ -r "$sbt_opts_file" ]]; then
vlog "Using sbt options defined in file $sbt_opts_file"
readarr extra_sbt_opts < <(readConfigFile "$sbt_opts_file")
elif [[ -n "$SBT_OPTS" && !($SBT_OPTS =~ ^@.*) ]]; then
vlog "Using sbt options defined in variable \$SBT_OPTS"
extra_sbt_opts=( $SBT_OPTS )
else
vlog "No extra sbt options have been defined"
fi
[[ -n $extra_sbt_opts ]] && process_args "${extra_sbt_opts[@]}"
# reset "$@" to the residual args
set -- "${residual_args[@]}"
argumentCount=$#
# only exists in 0.12+
setTraceLevel() {
case $(sbt_version) in
0.{7,10,11}.*) echoerr "Cannot set trace level in sbt version $(sbt_version)" ;;
*) addSbt "set every traceLevel := $trace_level" ;;
esac
}
# set scalacOptions if we were given any -S opts
[[ ${#scalac_args[@]} -eq 0 ]] || addSbt "set scalacOptions in ThisBuild += \"${scalac_args[@]}\""
# Update build.properties no disk to set explicit version - sbt gives us no choice
[[ -n "$sbt_explicit_version" ]] && update_build_props_sbt "$sbt_explicit_version"
vlog "Detected sbt version $(sbt_version)"
[[ -n "$scala_version" ]] && echoerr "Overriding scala version to $scala_version"
# no args - alert them there's stuff in here
(( $argumentCount > 0 )) || vlog "Starting $script_name: invoke with -help for other options"
# verify this is an sbt dir or -create was given
[[ -r ./build.sbt || -d ./project || -n "$sbt_create" ]] || {
cat <<EOM
$(pwd) doesn't appear to be an sbt project.
If you want to start sbt anyway, run:
$0 -sbt-create
EOM
exit 1
}
# pick up completion if present; todo
[[ -r .sbt_completion.sh ]] && source .sbt_completion.sh
# no jar? download it.
[[ -r "$sbt_jar" ]] || acquire_sbt_jar || {
# still no jar? uh-oh.
echo "Download failed. Obtain the jar manually and place it at $sbt_jar"
exit 1
}
if [[ -n $noshare ]]; then
addJava "$noshare_opts"
else
[[ -n "$sbt_dir" ]] || {
sbt_dir=~/.sbt/$(sbt_version)
vlog "Using $sbt_dir as sbt dir, -sbt-dir to override."
}
addJava "-Dsbt.global.base=$sbt_dir"
fi
if [[ -r "$jvm_opts_file" ]]; then
vlog "Using jvm options defined in file $jvm_opts_file"
readarr extra_jvm_opts < <(readConfigFile "$jvm_opts_file")
elif [[ -n "$JVM_OPTS" && !($JVM_OPTS =~ ^@.*) ]]; then
vlog "Using jvm options defined in \$JVM_OPTS variable"
extra_jvm_opts=( $JVM_OPTS )
else
vlog "Using default jvm options"
extra_jvm_opts=( $default_jvm_opts )
fi
# since sbt 0.7 doesn't understand iflast
[[ ${#residual_args[@]} -eq 0 ]] && [[ -z "$batch" ]] && residual_args=( "shell" )
# traceLevel is 0.12+
[[ -n $trace_level ]] && setTraceLevel
[[ -n $log_level ]] && [[ $log_level != Info ]] && logLevalArg="set logLevel in Global := Level.$log_level"
# run sbt
execRunner "$java_cmd" \
"${extra_jvm_opts[@]}" \
"${java_args[@]}" \
-jar "$sbt_jar" \
"$logLevalArg" \
"${sbt_commands[@]}" \
"${residual_args[@]}"

View File

@ -1,17 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<listener>
<listener-class>org.scalatra.servlet.ScalatraListener</listener-class>
</listener>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>/*.html</url-pattern>
<url-pattern>/css/*</url-pattern>
<url-pattern>/js/*.js</url-pattern>
<url-pattern>/images/*</url-pattern>
</servlet-mapping>
</web-app>

View File

@ -1,64 +0,0 @@
# Swagger generated server
## Overview
Using the swagger-codegen, you can not only generate clients but servers as well! The same spec can be used to drive your
development both ways. This is an example of generating a server for `node.js`.
### Prerequisites
You need the following installed and available in your $PATH:
<li>- Scala 2.9.1 [available here](http://www.scala-lang.org)
You also need to add scala binary to your PATH.
### Generating a server
You first need to build the `swagger-codegen` project--this is done by running this command at the root of the swagger-codegen project:
```
mvn package
```
You can now generate a server from any valid[**](https://github.com/wordnik/swagger-codegen/blob/master/README.md#validating-your-swagger-spec) swagger spec:
```
./bin/runscala.sh samples/server-generator/sinatra/SinatraServerGenerator.scala http://petstore.swagger.wordnik.com/api/api-docs special-key
```
After executing this script, you will have an output directory with the server-generated files:
```
$ cd samples/server-generator/sinatra/output
$ find . -type f
./config.ru
./Gemfile
./Gemfile.lock
./lib/pet_api.rb
./lib/store_api.rb
./lib/swaggering.rb
./lib/user_api.rb
./my_app.rb
./README.md
```
To run the server, cd to the `samples/server-generator/sinatra/output` folder and run:
```
rackup -p 4567
```
You can now load the swagger-ui against `http://localhost:4567/resources.json`. Of course this isn't a fully
runnable server! You have to add the logic in the lib/*.rb files. But that's the easy part.
### Making it your own
Running the sample is easy, but how about making your own server? Easy! Just modify the `samples/server-generator/sinatra/SinatraServerGenerator.scala` file.
Don't like the templates? Don't worry, we're not offended! They're [mustache](http://mustache.github.com/) templates and are easy to modify.
Take a look at the sample templates here:
<li> - Generator for your api classes: [api.mustache](https://github.com/wordnik/swagger-codegen/blob/master/samples/server-generator/sinatra/templates/api.mustache)
<li> - The main class to run your server: [my_app.mustache](https://github.com/wordnik/swagger-codegen/blob/master/samples/server-generator/sinatra/templates/my_app.mustache)
Sound easy? It is!

View File

@ -1,81 +0,0 @@
/**
* Copyright 2014 Wordnik, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import com.wordnik.swagger.codegen.BasicRubyGenerator
import java.io.File
import scala.collection.mutable.{ HashMap, ListBuffer }
object SinatraServerGenerator extends BasicRubyGenerator {
def main(args: Array[String]) = generateClient(args)
override def toApiName(name: String): String = name + "_api"
// undo the ruby-ish conversions in the BasicRubyGenerator
override def toVarName(name: String): String = name
override def toMethodName(name: String): String = name
override def templateDir = "samples/server-generator/sinatra/templates"
val outputFolder = "samples/server-generator/sinatra/output"
// where to write generated code
override def destinationDir = outputFolder + ""
override def modelPackage = Some("com.wordnik.client.model")
// template used for apis
apiTemplateFiles ++= Map("api.mustache" -> ".rb")
modelTemplateFiles.clear
override def apiPackage = Some("lib")
// supporting classes
override def supportingFiles = List(
("README.md", outputFolder, "README.md"),
("config.ru", outputFolder, "config.ru"),
("Gemfile", outputFolder, "Gemfile"),
("my_app.mustache", outputFolder, "my_app.rb"),
("lib/swaggering.rb", outputFolder + File.separator + "lib", "swaggering.rb"))
override def processApiMap(m: Map[String, AnyRef]): Map[String, AnyRef] = {
val mutable = scala.collection.mutable.Map() ++ m
mutable.map(k => {
k._1 match {
// the sinatra templates like lower-case httpMethods
case e: String if (e == "httpMethod") => mutable += "httpMethod" -> k._2.toString.toLowerCase
// convert path into ruby-ish syntax without basePart (i.e. /pet.{format}/{petId} => /:petId
case e: String if (e == "path") => {
val path = {
val arr = k._2.toString.split("/")
if (arr.length >= 2) {
mutable += "basePart" -> (arr.slice(2, arr.length).mkString("", "/", ""))
"/" + arr.slice(2, arr.length).mkString("", "/", "")
} else
k._2.toString
}
mutable += "path" -> path.replaceAll("\\{", ":").replaceAll("\\}", "")
}
case _ =>
}
})
mutable.toMap
}
}

View File

@ -1,4 +0,0 @@
source 'https://rubygems.org'
gem "sinatra"
gem "sinatra-cross_origin"

View File

@ -1,29 +0,0 @@
# Swagger for Sinatra
## Overview
This is a project to provide Swagger support inside the [Sinatra](http://www.sinatrarb.com/) framework. You can find
out more about both the spec and the framework at http://swagger.wordnik.com. For more information about
Wordnik's APIs, please visit http://developer.wordnik.com.
## Prerequisites
You need to install ruby 1.9.3 and the following gems:
```
sinatra
sinatra-cross_origin
```
## Getting started
This sample was generated with the [swagger-codegen](https://github.com/wordnik/swagger-codegen) project.
```
rackup -p 4567 config.ru
```
In your [swagger ui](https://github.com/wordnik/swagger-ui), put in the following URL:
```
http://localhost:4567/resources.json
```
Voila!

View File

@ -1,2 +0,0 @@
require './my_app'
run MyApp

View File

@ -1,154 +0,0 @@
require 'json'
require 'sinatra/base'
require 'sinatra/cross_origin'
class Configuration
attr_accessor :base_path, :api_version, :swagger_version, :format_specifier
def initialize
@api_version = '1.0'
@base_path = 'http://localhost:4567'
@swagger_version = '1.1'
@format_specifier = ".json"
end
end
class Swaggering < Sinatra::Base
register Sinatra::CrossOrigin
@@routes = {}
@@configuration = Configuration.new
attr_accessor :configuration
def self.configure
get("/resources" + @@configuration.format_specifier) {
cross_origin
Swaggering.to_resource_listing
}
@@configuration ||= Configuration.new
yield(@@configuration) if block_given?
end
def self.add_route(method, path, swag={}, opts={}, &block)
fullPath = swag["resourcePath"].to_s + @@configuration.format_specifier + path
accepted = case method
when 'get'
get(fullPath, opts, &block)
true
when 'post'
post(fullPath, opts, &block)
true
when 'delete'
delete(fullPath, opts, &block)
true
when 'put'
put(fullPath, opts, &block)
true
else
false
end
if accepted then
resourcePath = swag["resourcePath"].to_s
ops = @@routes[resourcePath]
if ops.nil?
ops = Array.new
@@routes.merge!(resourcePath => ops)
get(resourcePath + @@configuration.format_specifier) do
cross_origin
Swaggering.to_api(resourcePath)
end
end
swag.merge!("httpMethod" => method.to_s.upcase)
ops.push(swag)
end
end
def self.to_resource_listing
apis = Array.new
(@@routes.keys).each do |key|
api = {
"path" => (key + ".{format}"),
"description" => "no description"
}
apis.push api
end
resource = {
"apiVersion" => @@configuration.api_version,
"swaggerVersion" => @@configuration.swagger_version,
"apis" => apis
}
resource.to_json
end
def self.to_api(resourcePath)
apis = {}
models = []
@@routes[resourcePath].each do |route|
endpoint = route["endpoint"].gsub(/:(\w+)(\/?)/,'{\1}\2')
path = (resourcePath + ".{format}" + endpoint)
api = apis[path]
if api.nil?
api = {"path" => path, "description" => "description", "operations" => []}
apis.merge!(path => api)
end
parameters = route["parameters"]
unless parameters.nil? then
parameters.each do |param|
av_string = param["allowableValues"]
unless av_string.nil?
if av_string.count('[') > 0
pattern = /^([A-Z]*)\[(.*)\]/
match = pattern.match av_string
case match.to_a[1]
when "LIST"
allowables = match.to_a[2].split(',')
param["allowableValues"] = {
"valueType" => "LIST",
"values" => allowables
}
when "RANGE"
allowables = match.to_a[2].split(',')
param["allowableValues"] = {
"valueType" => "RANGE",
"min" => allowables[0],
"max" => allowables[1]
}
end
end
end
end
end
op = {
"httpMethod" => route["httpMethod"],
"description" => route["summary"],
"responseClass" => route["responseClass"],
"notes" => route["notes"],
"nickname" => route["nickname"],
"summary" => route["summary"],
"parameters" => route["parameters"]
}
api["operations"].push(op)
end
api_listing = {
"apiVersion" => @@configuration.api_version,
"swaggerVersion" => @@configuration.swagger_version,
"basePath" => @@configuration.base_path,
"resourcePath" => resourcePath,
"apis" => apis.values,
"models" => models
}
api_listing.to_json
end
end

View File

@ -1,112 +0,0 @@
require 'json'
MyApp.add_route('get', '/:petId', {
"resourcePath" => "/pet",
"summary" => "Find pet by ID",
"nickname" => "getPetById",
"responseClass" => "Pet",
"endpoint" => "/:petId",
"notes" => "Returns a pet based on ID",
"parameters" => [
{
"name" => "petId",
"description" => "ID of pet that needs to be fetched",
"dataType" => "string",
"paramType" => "path",
},
]}) do
cross_origin
# the guts live here
{"message" => "yes, it worked"}.to_json
end
MyApp.add_route('post', '/', {
"resourcePath" => "/pet",
"summary" => "Add a new pet to the store",
"nickname" => "addPet",
"responseClass" => "void",
"endpoint" => "/",
"notes" => "",
"parameters" => [
{
"name" => "body",
"description" => "Pet object that needs to be added to the store",
"dataType" => "Pet",
"paramType" => "body",
}
]}) do
cross_origin
# the guts live here
{"message" => "yes, it worked"}.to_json
end
MyApp.add_route('put', '/', {
"resourcePath" => "/pet",
"summary" => "Update an existing pet",
"nickname" => "updatePet",
"responseClass" => "void",
"endpoint" => "/",
"notes" => "",
"parameters" => [
{
"name" => "body",
"description" => "Pet object that needs to be updated in the store",
"dataType" => "Pet",
"paramType" => "body",
}
]}) do
cross_origin
# the guts live here
{"message" => "yes, it worked"}.to_json
end
MyApp.add_route('get', '/findByStatus', {
"resourcePath" => "/pet",
"summary" => "Finds Pets by status",
"nickname" => "findPetsByStatus",
"responseClass" => "List[Pet]",
"endpoint" => "/findByStatus",
"notes" => "Multiple status values can be provided with comma seperated strings",
"parameters" => [
{
"name" => "status",
"description" => "Status values that need to be considered for filter",
"dataType" => "string",
"paramType" => "query",
"allowMultiple" => true,
"allowableValues" => "LIST[available,pending,sold]",
"defaultValue" => "available"},
]}) do
cross_origin
# the guts live here
{"message" => "yes, it worked"}.to_json
end
MyApp.add_route('get', '/findByTags', {
"resourcePath" => "/pet",
"summary" => "Finds Pets by tags",
"nickname" => "findPetsByTags",
"responseClass" => "List[Pet]",
"endpoint" => "/findByTags",
"notes" => "Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.",
"parameters" => [
{
"name" => "tags",
"description" => "Tags to filter by",
"dataType" => "string",
"paramType" => "query",
"allowMultiple" => true,
"allowableValues" => "",
},
]}) do
cross_origin
# the guts live here
{"message" => "yes, it worked"}.to_json
end

View File

@ -1,66 +0,0 @@
require 'json'
MyApp.add_route('get', '/order/:orderId', {
"resourcePath" => "/store",
"summary" => "Find purchase order by ID",
"nickname" => "getOrderById",
"responseClass" => "Order",
"endpoint" => "/order/:orderId",
"notes" => "For valid response try integer IDs with value <= 5. Anything above 5 or nonintegers will generate API errors",
"parameters" => [
{
"name" => "orderId",
"description" => "ID of pet that needs to be fetched",
"dataType" => "string",
"paramType" => "path",
},
]}) do
cross_origin
# the guts live here
{"message" => "yes, it worked"}.to_json
end
MyApp.add_route('delete', '/order/:orderId', {
"resourcePath" => "/store",
"summary" => "Delete purchase order by ID",
"nickname" => "deleteOrder",
"responseClass" => "void",
"endpoint" => "/order/:orderId",
"notes" => "For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors",
"parameters" => [
{
"name" => "orderId",
"description" => "ID of the order that needs to be deleted",
"dataType" => "string",
"paramType" => "path",
},
]}) do
cross_origin
# the guts live here
{"message" => "yes, it worked"}.to_json
end
MyApp.add_route('post', '/order', {
"resourcePath" => "/store",
"summary" => "Place an order for a pet",
"nickname" => "placeOrder",
"responseClass" => "void",
"endpoint" => "/order",
"notes" => "",
"parameters" => [
{
"name" => "body",
"description" => "order placed for purchasing the pet",
"dataType" => "Order",
"paramType" => "body",
}
]}) do
cross_origin
# the guts live here
{"message" => "yes, it worked"}.to_json
end

View File

@ -1,181 +0,0 @@
require 'json'
MyApp.add_route('post', '/createWithArray', {
"resourcePath" => "/user",
"summary" => "Creates list of users with given input array",
"nickname" => "createUsersWithArrayInput",
"responseClass" => "void",
"endpoint" => "/createWithArray",
"notes" => "",
"parameters" => [
{
"name" => "body",
"description" => "List of user object",
"dataType" => "Array[User]",
"paramType" => "body",
}
]}) do
cross_origin
# the guts live here
{"message" => "yes, it worked"}.to_json
end
MyApp.add_route('post', '/', {
"resourcePath" => "/user",
"summary" => "Create user",
"nickname" => "createUser",
"responseClass" => "void",
"endpoint" => "/",
"notes" => "This can only be done by the logged in user.",
"parameters" => [
{
"name" => "body",
"description" => "Created user object",
"dataType" => "User",
"paramType" => "body",
}
]}) do
cross_origin
# the guts live here
{"message" => "yes, it worked"}.to_json
end
MyApp.add_route('post', '/createWithList', {
"resourcePath" => "/user",
"summary" => "Creates list of users with given list input",
"nickname" => "createUsersWithListInput",
"responseClass" => "void",
"endpoint" => "/createWithList",
"notes" => "",
"parameters" => [
{
"name" => "body",
"description" => "List of user object",
"dataType" => "List[User]",
"paramType" => "body",
}
]}) do
cross_origin
# the guts live here
{"message" => "yes, it worked"}.to_json
end
MyApp.add_route('put', '/:username', {
"resourcePath" => "/user",
"summary" => "Updated user",
"nickname" => "updateUser",
"responseClass" => "void",
"endpoint" => "/:username",
"notes" => "This can only be done by the logged in user.",
"parameters" => [
{
"name" => "username",
"description" => "name that need to be deleted",
"dataType" => "string",
"paramType" => "path",
},
{
"name" => "body",
"description" => "Updated user object",
"dataType" => "User",
"paramType" => "body",
}
]}) do
cross_origin
# the guts live here
{"message" => "yes, it worked"}.to_json
end
MyApp.add_route('delete', '/:username', {
"resourcePath" => "/user",
"summary" => "Delete user",
"nickname" => "deleteUser",
"responseClass" => "void",
"endpoint" => "/:username",
"notes" => "This can only be done by the logged in user.",
"parameters" => [
{
"name" => "username",
"description" => "The name that needs to be deleted",
"dataType" => "string",
"paramType" => "path",
},
]}) do
cross_origin
# the guts live here
{"message" => "yes, it worked"}.to_json
end
MyApp.add_route('get', '/:username', {
"resourcePath" => "/user",
"summary" => "Get user by user name",
"nickname" => "getUserByName",
"responseClass" => "User",
"endpoint" => "/:username",
"notes" => "",
"parameters" => [
{
"name" => "username",
"description" => "The name that needs to be fetched. Use user1 for testing.",
"dataType" => "string",
"paramType" => "path",
},
]}) do
cross_origin
# the guts live here
{"message" => "yes, it worked"}.to_json
end
MyApp.add_route('get', '/login', {
"resourcePath" => "/user",
"summary" => "Logs user into the system",
"nickname" => "loginUser",
"responseClass" => "string",
"endpoint" => "/login",
"notes" => "",
"parameters" => [
{
"name" => "username",
"description" => "The user name for login",
"dataType" => "string",
"paramType" => "query",
"allowMultiple" => false,
"allowableValues" => "",
},
{
"name" => "password",
"description" => "The password for login in clear text",
"dataType" => "string",
"paramType" => "query",
"allowMultiple" => false,
"allowableValues" => "",
},
]}) do
cross_origin
# the guts live here
{"message" => "yes, it worked"}.to_json
end
MyApp.add_route('get', '/logout', {
"resourcePath" => "/user",
"summary" => "Logs out current logged in user session",
"nickname" => "logoutUser",
"responseClass" => "void",
"endpoint" => "/logout",
"notes" => "",
"parameters" => [
]}) do
cross_origin
# the guts live here
{"message" => "yes, it worked"}.to_json
end

View File

@ -1,13 +0,0 @@
require './lib/swaggering'
# only need to extend if you want special configuration!
class MyApp < Swaggering
self.configure do |config|
config.api_version = '0.2'
end
end
require './lib/store_api.rb'
require './lib/pet_api.rb'
require './lib/user_api.rb'

View File

@ -1,4 +0,0 @@
source 'https://rubygems.org'
gem "sinatra"
gem "sinatra-cross_origin"

View File

@ -1,29 +0,0 @@
# Swagger for Sinatra
## Overview
This is a project to provide Swagger support inside the [Sinatra](http://www.sinatrarb.com/) framework. You can find
out more about both the spec and the framework at http://swagger.wordnik.com. For more information about
Wordnik's APIs, please visit http://developer.wordnik.com.
## Prerequisites
You need to install ruby 1.9.3 and the following gems:
```
sinatra
sinatra-cross_origin
```
## Getting started
This sample was generated with the [swagger-codegen](https://github.com/wordnik/swagger-codegen) project.
```
rackup -p 4567 config.ru
```
In your [swagger ui](https://github.com/wordnik/swagger-ui), put in the following URL:
```
http://localhost:4567/resources.json
```
Voila!

View File

@ -1,57 +0,0 @@
require 'json'
{{#operations}}
{{#operation}}
MyApp.add_route('{{httpMethod}}', '{{path}}', {
"resourcePath" => "/{{baseName}}",
"summary" => "{{{summary}}}",
"nickname" => "{{nickname}}",
"responseClass" => "{{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}void{{/returnType}}",
"endpoint" => "{{path}}",
"notes" => "{{{notes}}}",
"parameters" => [
{{#queryParams}}
{
"name" => "{{paramName}}",
"description" => "{{description}}",
"dataType" => "{{swaggerDataType}}",
"paramType" => "query",
"allowMultiple" => {{allowMultiple}},
"allowableValues" => "{{allowableValues}}",
{{#defaultValue}}"defaultValue" => {{{defaultValue}}}{{/defaultValue}}
},
{{/queryParams}}
{{#pathParams}}
{
"name" => "{{paramName}}",
"description" => "{{description}}",
"dataType" => "{{swaggerDataType}}",
"paramType" => "path",
},
{{/pathParams}}
{{#headerParams}}
{
"name" => "{{paramName}}",
"description" => "{{description}}",
"dataType" => "{{swaggerDataType}}",
"paramType" => "header",
},
{{/headerParams}}
{{#bodyParams}}
{
"name" => "body",
"description" => "{{description}}",
"dataType" => "{{swaggerDataType}}",
"paramType" => "body",
}
{{/bodyParams}}
]}) do
cross_origin
# the guts live here
{"message" => "yes, it worked"}.to_json
end
{{/operation}}
{{/operations}}

View File

@ -1,2 +0,0 @@
require './my_app'
run MyApp

View File

@ -1,154 +0,0 @@
require 'json'
require 'sinatra/base'
require 'sinatra/cross_origin'
class Configuration
attr_accessor :base_path, :api_version, :swagger_version, :format_specifier
def initialize
@api_version = '1.0'
@base_path = 'http://localhost:4567'
@swagger_version = '1.1'
@format_specifier = ".json"
end
end
class Swaggering < Sinatra::Base
register Sinatra::CrossOrigin
@@routes = {}
@@configuration = Configuration.new
attr_accessor :configuration
def self.configure
get("/resources" + @@configuration.format_specifier) {
cross_origin
Swaggering.to_resource_listing
}
@@configuration ||= Configuration.new
yield(@@configuration) if block_given?
end
def self.add_route(method, path, swag={}, opts={}, &block)
fullPath = swag["resourcePath"].to_s + @@configuration.format_specifier + path
accepted = case method
when 'get'
get(fullPath, opts, &block)
true
when 'post'
post(fullPath, opts, &block)
true
when 'delete'
delete(fullPath, opts, &block)
true
when 'put'
put(fullPath, opts, &block)
true
else
false
end
if accepted then
resourcePath = swag["resourcePath"].to_s
ops = @@routes[resourcePath]
if ops.nil?
ops = Array.new
@@routes.merge!(resourcePath => ops)
get(resourcePath + @@configuration.format_specifier) do
cross_origin
Swaggering.to_api(resourcePath)
end
end
swag.merge!("httpMethod" => method.to_s.upcase)
ops.push(swag)
end
end
def self.to_resource_listing
apis = Array.new
(@@routes.keys).each do |key|
api = {
"path" => (key + ".{format}"),
"description" => "no description"
}
apis.push api
end
resource = {
"apiVersion" => @@configuration.api_version,
"swaggerVersion" => @@configuration.swagger_version,
"apis" => apis
}
resource.to_json
end
def self.to_api(resourcePath)
apis = {}
models = []
@@routes[resourcePath].each do |route|
endpoint = route["endpoint"].gsub(/:(\w+)(\/?)/,'{\1}\2')
path = (resourcePath + ".{format}" + endpoint)
api = apis[path]
if api.nil?
api = {"path" => path, "description" => "description", "operations" => []}
apis.merge!(path => api)
end
parameters = route["parameters"]
unless parameters.nil? then
parameters.each do |param|
av_string = param["allowableValues"]
unless av_string.nil?
if av_string.count('[') > 0
pattern = /^([A-Z]*)\[(.*)\]/
match = pattern.match av_string
case match.to_a[1]
when "LIST"
allowables = match.to_a[2].split(',')
param["allowableValues"] = {
"valueType" => "LIST",
"values" => allowables
}
when "RANGE"
allowables = match.to_a[2].split(',')
param["allowableValues"] = {
"valueType" => "RANGE",
"min" => allowables[0],
"max" => allowables[1]
}
end
end
end
end
end
op = {
"httpMethod" => route["httpMethod"],
"description" => route["summary"],
"responseClass" => route["responseClass"],
"notes" => route["notes"],
"nickname" => route["nickname"],
"summary" => route["summary"],
"parameters" => route["parameters"]
}
api["operations"].push(op)
end
api_listing = {
"apiVersion" => @@configuration.api_version,
"swaggerVersion" => @@configuration.swagger_version,
"basePath" => @@configuration.base_path,
"resourcePath" => resourcePath,
"apis" => apis.values,
"models" => models
}
api_listing.to_json
end
end

View File

@ -1,12 +0,0 @@
require './lib/swaggering'
# only need to extend if you want special configuration!
class MyApp < Swaggering
self.configure do |config|
config.api_version = '0.2'
end
end
{{#apis}}
require './lib/{{className}}.rb'
{{/apis}}

View File

@ -18,24 +18,27 @@ name := "scalatra-sample"
version := "0.1.0-SNAPSHOT"
scalaVersion := "2.10.0"
scalaVersion := "2.11.2"
scalacOptions += "-language:postfixOps"
libraryDependencies ++= Seq(
"org.scalatest" %% "scalatest" % "2.0" % "test",
"org.scalatest" %% "scalatest" % "2.2.1" % "test",
"org.scalatra" %% "scalatra" % "2.3.0.RC3",
"org.scalatra" %% "scalatra-scalate" % "2.3.0.RC3",
"org.scalatra" %% "scalatra-json" % "2.3.0.RC3",
"org.scalatra" %% "scalatra-swagger" % "2.3.0.RC3",
"org.scalatra" %% "scalatra-swagger-ext" % "2.3.0.RC3",
"org.scalatra" %% "scalatra-slf4j" % "2.3.0.RC3",
"org.json4s" %% "json4s-jackson" % "3.1.0",
"org.json4s" %% "json4s-ext" % "3.1.0",
"org.json4s" %% "json4s-jackson" % "3.2.10",
"org.json4s" %% "json4s-ext" % "3.2.10",
"commons-codec" % "commons-codec" % "1.7",
"net.databinder.dispatch" %% "dispatch-core" % "0.9.5",
"net.databinder.dispatch" %% "json4s-jackson" % "0.9.5",
"com.typesafe.akka" %% "akka-actor" % "2.1.0",
"org.eclipse.jetty" % "jetty-server" % "8.1.7.v20120910" % "container;provided",
"org.eclipse.jetty" % "jetty-webapp" % "8.1.7.v20120910" % "container;provided",
"net.databinder.dispatch" %% "dispatch-core" % "0.11.2",
//"net.databinder.dispatch" %% "json4s-jackson" % "0.11.2",
"net.databinder.dispatch" %% "dispatch-json4s-jackson" % "0.11.2",
"com.typesafe.akka" %% "akka-actor" % "2.3.6",
"org.eclipse.jetty" % "jetty-server" % "9.2.3.v20140905" % "container;compile;test",
"org.eclipse.jetty" % "jetty-webapp" % "9.2.3.v20140905" % "container;compile;test",
"org.eclipse.jetty.orbit" % "javax.servlet" % "3.0.0.v201112011016" % "container;compile;provided;test" artifacts (Artifact("javax.servlet", "jar", "jar"))
)
@ -51,9 +54,11 @@ ivyXML := <dependencies>
<exclude module="jsr311-api" />
</dependencies>
mergeStrategy in assembly <<= (mergeStrategy in assembly) { (old) =>
{
mergeStrategy in assembly <<= (mergeStrategy in assembly) {
(old) => {
case "about.html" => MergeStrategy.discard
case x => old(x)
}
}
net.virtualvoid.sbt.graph.Plugin.graphSettings

View File

@ -0,0 +1 @@
sbt.version=0.13.5

View File

@ -0,0 +1,9 @@
addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "0.10.1")
addSbtPlugin("com.typesafe.sbt" % "sbt-native-packager" % "0.7.5")
addSbtPlugin("com.earldouglas" % "xsbt-web-plugin" % "0.9.0")
addSbtPlugin("com.typesafe.sbt" % "sbt-scalariform" % "1.3.0")
addSbtPlugin("net.virtual-void" % "sbt-dependency-graph" % "0.7.4")

View File

@ -0,0 +1,525 @@
#!/usr/bin/env bash
#
# A more capable sbt runner, coincidentally also called sbt.
# Author: Paul Phillips <paulp@typesafe.com>
# todo - make this dynamic
declare -r sbt_release_version="0.13.6"
declare -r sbt_unreleased_version="0.13.6"
declare -r buildProps="project/build.properties"
declare sbt_jar sbt_dir sbt_create sbt_version
declare scala_version sbt_explicit_version
declare verbose noshare batch trace_level log_level
declare sbt_saved_stty debugUs
echoerr () { echo >&2 "$@"; }
vlog () { [[ -n "$verbose" ]] && echoerr "$@"; }
# spaces are possible, e.g. sbt.version = 0.13.0
build_props_sbt () {
[[ -r "$buildProps" ]] && \
grep '^sbt\.version' "$buildProps" | tr '=' ' ' | awk '{ print $2; }'
}
update_build_props_sbt () {
local ver="$1"
local old="$(build_props_sbt)"
[[ -r "$buildProps" ]] && [[ "$ver" != "$old" ]] && {
perl -pi -e "s/^sbt\.version\b.*\$/sbt.version=${ver}/" "$buildProps"
grep -q '^sbt.version[ =]' "$buildProps" || printf "\nsbt.version=%s\n" "$ver" >> "$buildProps"
vlog "!!!"
vlog "!!! Updated file $buildProps setting sbt.version to: $ver"
vlog "!!! Previous value was: $old"
vlog "!!!"
}
}
set_sbt_version () {
sbt_version="${sbt_explicit_version:-$(build_props_sbt)}"
[[ -n "$sbt_version" ]] || sbt_version=$sbt_release_version
export sbt_version
}
# restore stty settings (echo in particular)
onSbtRunnerExit() {
[[ -n "$sbt_saved_stty" ]] || return
vlog ""
vlog "restoring stty: $sbt_saved_stty"
stty "$sbt_saved_stty"
unset sbt_saved_stty
}
# save stty and trap exit, to ensure echo is reenabled if we are interrupted.
trap onSbtRunnerExit EXIT
sbt_saved_stty="$(stty -g 2>/dev/null)"
vlog "Saved stty: $sbt_saved_stty"
# this seems to cover the bases on OSX, and someone will
# have to tell me about the others.
get_script_path () {
local path="$1"
[[ -L "$path" ]] || { echo "$path" ; return; }
local target="$(readlink "$path")"
if [[ "${target:0:1}" == "/" ]]; then
echo "$target"
else
echo "${path%/*}/$target"
fi
}
die() {
echo "Aborting: $@"
exit 1
}
make_url () {
version="$1"
case "$version" in
0.7.*) echo "http://simple-build-tool.googlecode.com/files/sbt-launch-0.7.7.jar" ;;
0.10.* ) echo "$sbt_launch_repo/org.scala-tools.sbt/sbt-launch/$version/sbt-launch.jar" ;;
0.11.[12]) echo "$sbt_launch_repo/org.scala-tools.sbt/sbt-launch/$version/sbt-launch.jar" ;;
*) echo "$sbt_launch_repo/org.scala-sbt/sbt-launch/$version/sbt-launch.jar" ;;
esac
}
init_default_option_file () {
local overriding_var="${!1}"
local default_file="$2"
if [[ ! -r "$default_file" && "$overriding_var" =~ ^@(.*)$ ]]; then
local envvar_file="${BASH_REMATCH[1]}"
if [[ -r "$envvar_file" ]]; then
default_file="$envvar_file"
fi
fi
echo "$default_file"
}
declare -r cms_opts="-XX:+CMSClassUnloadingEnabled -XX:+UseConcMarkSweepGC"
declare -r jit_opts="-XX:ReservedCodeCacheSize=256m -XX:+TieredCompilation"
declare -r default_jvm_opts_common="-Xms512m -Xmx1536m -Xss2m $jit_opts $cms_opts"
declare -r noshare_opts="-Dsbt.global.base=project/.sbtboot -Dsbt.boot.directory=project/.boot -Dsbt.ivy.home=project/.ivy"
declare -r latest_28="2.8.2"
declare -r latest_29="2.9.3"
declare -r latest_210="2.10.4"
declare -r latest_211="2.11.2"
declare -r script_path="$(get_script_path "$BASH_SOURCE")"
declare -r script_name="${script_path##*/}"
# some non-read-onlies set with defaults
declare java_cmd="java"
declare sbt_opts_file="$(init_default_option_file SBT_OPTS .sbtopts)"
declare jvm_opts_file="$(init_default_option_file JVM_OPTS .jvmopts)"
declare sbt_launch_repo="http://typesafe.artifactoryonline.com/typesafe/ivy-releases"
# pull -J and -D options to give to java.
declare -a residual_args
declare -a java_args
declare -a scalac_args
declare -a sbt_commands
# args to jvm/sbt via files or environment variables
declare -a extra_jvm_opts extra_sbt_opts
# if set, use JAVA_HOME over java found in path
[[ -e "$JAVA_HOME/bin/java" ]] && java_cmd="$JAVA_HOME/bin/java"
# directory to store sbt launchers
declare sbt_launch_dir="$HOME/.sbt/launchers"
[[ -d "$sbt_launch_dir" ]] || mkdir -p "$sbt_launch_dir"
[[ -w "$sbt_launch_dir" ]] || sbt_launch_dir="$(mktemp -d -t sbt_extras_launchers.XXXXXX)"
java_version () {
local version=$("$java_cmd" -version 2>&1 | grep -e 'java version' | awk '{ print $3 }' | tr -d \")
vlog "Detected Java version: $version"
echo "${version:2:1}"
}
# MaxPermSize critical on pre-8 jvms but incurs noisy warning on 8+
default_jvm_opts () {
local v="$(java_version)"
if [[ $v -ge 8 ]]; then
echo "$default_jvm_opts_common"
else
echo "-XX:MaxPermSize=384m $default_jvm_opts_common"
fi
}
build_props_scala () {
if [[ -r "$buildProps" ]]; then
versionLine="$(grep '^build.scala.versions' "$buildProps")"
versionString="${versionLine##build.scala.versions=}"
echo "${versionString%% .*}"
fi
}
execRunner () {
# print the arguments one to a line, quoting any containing spaces
vlog "# Executing command line:" && {
for arg; do
if [[ -n "$arg" ]]; then
if printf "%s\n" "$arg" | grep -q ' '; then
printf >&2 "\"%s\"\n" "$arg"
else
printf >&2 "%s\n" "$arg"
fi
fi
done
vlog ""
}
[[ -n "$batch" ]] && exec </dev/null
exec "$@"
}
jar_url () {
make_url "$1"
}
jar_file () {
echo "$sbt_launch_dir/$1/sbt-launch.jar"
}
download_url () {
local url="$1"
local jar="$2"
echoerr "Downloading sbt launcher for $sbt_version:"
echoerr " From $url"
echoerr " To $jar"
mkdir -p "${jar%/*}" && {
if which curl >/dev/null; then
curl --fail --silent "$url" --output "$jar"
elif which wget >/dev/null; then
wget --quiet -O "$jar" "$url"
fi
} && [[ -r "$jar" ]]
}
acquire_sbt_jar () {
sbt_url="$(jar_url "$sbt_version")"
sbt_jar="$(jar_file "$sbt_version")"
[[ -r "$sbt_jar" ]] || download_url "$sbt_url" "$sbt_jar"
}
usage () {
cat <<EOM
Usage: $script_name [options]
Note that options which are passed along to sbt begin with -- whereas
options to this runner use a single dash. Any sbt command can be scheduled
to run first by prefixing the command with --, so --warn, --error and so on
are not special.
Output filtering: if there is a file in the home directory called .sbtignore
and this is not an interactive sbt session, the file is treated as a list of
bash regular expressions. Output lines which match any regex are not echoed.
One can see exactly which lines would have been suppressed by starting this
runner with the -x option.
-h | -help print this message
-v verbose operation (this runner is chattier)
-d, -w, -q aliases for --debug, --warn, --error (q means quiet)
-x debug this script
-trace <level> display stack traces with a max of <level> frames (default: -1, traces suppressed)
-debug-inc enable debugging log for the incremental compiler
-no-colors disable ANSI color codes
-sbt-create start sbt even if current directory contains no sbt project
-sbt-dir <path> path to global settings/plugins directory (default: ~/.sbt/<version>)
-sbt-boot <path> path to shared boot directory (default: ~/.sbt/boot in 0.11+)
-ivy <path> path to local Ivy repository (default: ~/.ivy2)
-no-share use all local caches; no sharing
-offline put sbt in offline mode
-jvm-debug <port> Turn on JVM debugging, open at the given port.
-batch Disable interactive mode
-prompt <expr> Set the sbt prompt; in expr, 's' is the State and 'e' is Extracted
# sbt version (default: sbt.version from $buildProps if present, otherwise $sbt_release_version)
-sbt-force-latest force the use of the latest release of sbt: $sbt_release_version
-sbt-version <version> use the specified version of sbt (default: $sbt_release_version)
-sbt-dev use the latest pre-release version of sbt: $sbt_unreleased_version
-sbt-jar <path> use the specified jar as the sbt launcher
-sbt-launch-dir <path> directory to hold sbt launchers (default: ~/.sbt/launchers)
-sbt-launch-repo <url> repo url for downloading sbt launcher jar (default: $sbt_launch_repo)
# scala version (default: as chosen by sbt)
-28 use $latest_28
-29 use $latest_29
-210 use $latest_210
-211 use $latest_211
-scala-home <path> use the scala build at the specified directory
-scala-version <version> use the specified version of scala
-binary-version <version> use the specified scala version when searching for dependencies
# java version (default: java from PATH, currently $(java -version 2>&1 | grep version))
-java-home <path> alternate JAVA_HOME
# passing options to the jvm - note it does NOT use JAVA_OPTS due to pollution
# The default set is used if JVM_OPTS is unset and no -jvm-opts file is found
<default> $(default_jvm_opts)
JVM_OPTS environment variable holding either the jvm args directly, or
the reference to a file containing jvm args if given path is prepended by '@' (e.g. '@/etc/jvmopts')
Note: "@"-file is overridden by local '.jvmopts' or '-jvm-opts' argument.
-jvm-opts <path> file containing jvm args (if not given, .jvmopts in project root is used if present)
-Dkey=val pass -Dkey=val directly to the jvm
-J-X pass option -X directly to the jvm (-J is stripped)
# passing options to sbt, OR to this runner
SBT_OPTS environment variable holding either the sbt args directly, or
the reference to a file containing sbt args if given path is prepended by '@' (e.g. '@/etc/sbtopts')
Note: "@"-file is overridden by local '.sbtopts' or '-sbt-opts' argument.
-sbt-opts <path> file containing sbt args (if not given, .sbtopts in project root is used if present)
-S-X add -X to sbt's scalacOptions (-S is stripped)
EOM
}
addJava () {
vlog "[addJava] arg = '$1'"
java_args=( "${java_args[@]}" "$1" )
}
addSbt () {
vlog "[addSbt] arg = '$1'"
sbt_commands=( "${sbt_commands[@]}" "$1" )
}
setThisBuild () {
vlog "[addBuild] args = '$@'"
local key="$1" && shift
addSbt "set $key in ThisBuild := $@"
}
addScalac () {
vlog "[addScalac] arg = '$1'"
scalac_args=( "${scalac_args[@]}" "$1" )
}
addResidual () {
vlog "[residual] arg = '$1'"
residual_args=( "${residual_args[@]}" "$1" )
}
addResolver () {
addSbt "set resolvers += $1"
}
addDebugger () {
addJava "-Xdebug"
addJava "-Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=$1"
}
setScalaVersion () {
[[ "$1" == *"-SNAPSHOT" ]] && addResolver 'Resolver.sonatypeRepo("snapshots")'
addSbt "++ $1"
}
process_args ()
{
require_arg () {
local type="$1"
local opt="$2"
local arg="$3"
if [[ -z "$arg" ]] || [[ "${arg:0:1}" == "-" ]]; then
die "$opt requires <$type> argument"
fi
}
while [[ $# -gt 0 ]]; do
case "$1" in
-h|-help) usage; exit 1 ;;
-v) verbose=true && shift ;;
-d) addSbt "--debug" && shift ;;
-w) addSbt "--warn" && shift ;;
-q) addSbt "--error" && shift ;;
-x) debugUs=true && shift ;;
-trace) require_arg integer "$1" "$2" && trace_level="$2" && shift 2 ;;
-ivy) require_arg path "$1" "$2" && addJava "-Dsbt.ivy.home=$2" && shift 2 ;;
-no-colors) addJava "-Dsbt.log.noformat=true" && shift ;;
-no-share) noshare=true && shift ;;
-sbt-boot) require_arg path "$1" "$2" && addJava "-Dsbt.boot.directory=$2" && shift 2 ;;
-sbt-dir) require_arg path "$1" "$2" && sbt_dir="$2" && shift 2 ;;
-debug-inc) addJava "-Dxsbt.inc.debug=true" && shift ;;
-offline) addSbt "set offline := true" && shift ;;
-jvm-debug) require_arg port "$1" "$2" && addDebugger "$2" && shift 2 ;;
-batch) batch=true && shift ;;
-prompt) require_arg "expr" "$1" "$2" && setThisBuild shellPrompt "(s => { val e = Project.extract(s) ; $2 })" && shift 2 ;;
-sbt-create) sbt_create=true && shift ;;
-sbt-jar) require_arg path "$1" "$2" && sbt_jar="$2" && shift 2 ;;
-sbt-version) require_arg version "$1" "$2" && sbt_explicit_version="$2" && shift 2 ;;
-sbt-force-latest) sbt_explicit_version="$sbt_release_version" && shift ;;
-sbt-dev) sbt_explicit_version="$sbt_unreleased_version" && shift ;;
-sbt-launch-dir) require_arg path "$1" "$2" && sbt_launch_dir="$2" && shift 2 ;;
-sbt-launch-repo) require_arg path "$1" "$2" && sbt_launch_repo="$2" && shift 2 ;;
-scala-version) require_arg version "$1" "$2" && setScalaVersion "$2" && shift 2 ;;
-binary-version) require_arg version "$1" "$2" && setThisBuild scalaBinaryVersion "\"$2\"" && shift 2 ;;
-scala-home) require_arg path "$1" "$2" && setThisBuild scalaHome "Some(file(\"$2\"))" && shift 2 ;;
-java-home) require_arg path "$1" "$2" && java_cmd="$2/bin/java" && shift 2 ;;
-sbt-opts) require_arg path "$1" "$2" && sbt_opts_file="$2" && shift 2 ;;
-jvm-opts) require_arg path "$1" "$2" && jvm_opts_file="$2" && shift 2 ;;
-D*) addJava "$1" && shift ;;
-J*) addJava "${1:2}" && shift ;;
-S*) addScalac "${1:2}" && shift ;;
-28) setScalaVersion "$latest_28" && shift ;;
-29) setScalaVersion "$latest_29" && shift ;;
-210) setScalaVersion "$latest_210" && shift ;;
-211) setScalaVersion "$latest_211" && shift ;;
*) addResidual "$1" && shift ;;
esac
done
}
# process the direct command line arguments
process_args "$@"
# skip #-styled comments and blank lines
readConfigFile() {
while read line; do
[[ $line =~ ^# ]] || [[ -z $line ]] || echo "$line"
done < "$1"
}
# if there are file/environment sbt_opts, process again so we
# can supply args to this runner
if [[ -r "$sbt_opts_file" ]]; then
vlog "Using sbt options defined in file $sbt_opts_file"
while read opt; do extra_sbt_opts+=("$opt"); done < <(readConfigFile "$sbt_opts_file")
elif [[ -n "$SBT_OPTS" && ! ("$SBT_OPTS" =~ ^@.*) ]]; then
vlog "Using sbt options defined in variable \$SBT_OPTS"
extra_sbt_opts=( $SBT_OPTS )
else
vlog "No extra sbt options have been defined"
fi
[[ -n "${extra_sbt_opts[*]}" ]] && process_args "${extra_sbt_opts[@]}"
# reset "$@" to the residual args
set -- "${residual_args[@]}"
argumentCount=$#
# set sbt version
set_sbt_version
# only exists in 0.12+
setTraceLevel() {
case "$sbt_version" in
"0.7."* | "0.10."* | "0.11."* ) echoerr "Cannot set trace level in sbt version $sbt_version" ;;
*) setThisBuild traceLevel $trace_level ;;
esac
}
# set scalacOptions if we were given any -S opts
[[ ${#scalac_args[@]} -eq 0 ]] || addSbt "set scalacOptions in ThisBuild += \"${scalac_args[@]}\""
# Update build.properties on disk to set explicit version - sbt gives us no choice
[[ -n "$sbt_explicit_version" ]] && update_build_props_sbt "$sbt_explicit_version"
vlog "Detected sbt version $sbt_version"
[[ -n "$scala_version" ]] && vlog "Overriding scala version to $scala_version"
# no args - alert them there's stuff in here
(( argumentCount > 0 )) || {
vlog "Starting $script_name: invoke with -help for other options"
residual_args=( shell )
}
# verify this is an sbt dir or -create was given
[[ -r ./build.sbt || -d ./project || -n "$sbt_create" ]] || {
cat <<EOM
$(pwd) doesn't appear to be an sbt project.
If you want to start sbt anyway, run:
$0 -sbt-create
EOM
exit 1
}
# pick up completion if present; todo
[[ -r .sbt_completion.sh ]] && source .sbt_completion.sh
# no jar? download it.
[[ -r "$sbt_jar" ]] || acquire_sbt_jar || {
# still no jar? uh-oh.
echo "Download failed. Obtain the jar manually and place it at $sbt_jar"
exit 1
}
if [[ -n "$noshare" ]]; then
for opt in ${noshare_opts}; do
addJava "$opt"
done
else
case "$sbt_version" in
"0.7."* | "0.10."* | "0.11."* | "0.12."* )
[[ -n "$sbt_dir" ]] || {
sbt_dir="$HOME/.sbt/$sbt_version"
vlog "Using $sbt_dir as sbt dir, -sbt-dir to override."
}
;;
esac
if [[ -n "$sbt_dir" ]]; then
addJava "-Dsbt.global.base=$sbt_dir"
fi
fi
if [[ -r "$jvm_opts_file" ]]; then
vlog "Using jvm options defined in file $jvm_opts_file"
while read opt; do extra_jvm_opts+=("$opt"); done < <(readConfigFile "$jvm_opts_file")
elif [[ -n "$JVM_OPTS" && ! ("$JVM_OPTS" =~ ^@.*) ]]; then
vlog "Using jvm options defined in \$JVM_OPTS variable"
extra_jvm_opts=( $JVM_OPTS )
else
vlog "Using default jvm options"
extra_jvm_opts=( $(default_jvm_opts) )
fi
# traceLevel is 0.12+
[[ -n "$trace_level" ]] && setTraceLevel
main () {
execRunner "$java_cmd" \
"${extra_jvm_opts[@]}" \
"${java_args[@]}" \
-jar "$sbt_jar" \
"${sbt_commands[@]}" \
"${residual_args[@]}"
}
# sbt inserts this string on certain lines when formatting is enabled:
# val OverwriteLine = "\r\u001BM\u001B[2K"
# ...in order not to spam the console with a million "Resolving" lines.
# Unfortunately that makes it that much harder to work with when
# we're not going to print those lines anyway. We strip that bit of
# line noise, but leave the other codes to preserve color.
mainFiltered () {
local ansiOverwrite='\r\x1BM\x1B[2K'
local excludeRegex=$(egrep -v '^#|^$' ~/.sbtignore | paste -sd'|' -)
echoLine () {
local line="$1"
local line1="$(echo "$line" | sed -r 's/\r\x1BM\x1B\[2K//g')" # This strips the OverwriteLine code.
local line2="$(echo "$line1" | sed -r 's/\x1B\[[0-9;]*[JKmsu]//g')" # This strips all codes - we test regexes against this.
if [[ $line2 =~ $excludeRegex ]]; then
[[ -n $debugUs ]] && echo "[X] $line1"
else
[[ -n $debugUs ]] && echo " $line1" || echo "$line1"
fi
}
echoLine "Starting sbt with output filtering enabled."
main | while read -r line; do echoLine "$line"; done
}
# Only filter if there's a filter file and we don't see a known interactive command.
# Obviously this is super ad hoc but I don't know how to improve on it. Testing whether
# stdin is a terminal is useless because most of my use cases for this filtering are
# exactly when I'm at a terminal, running sbt non-interactively.
shouldFilter () { [[ -f ~/.sbtignore ]] && ! egrep -q '\b(shell|console|consoleProject)\b' <<<"${residual_args[@]}"; }
# run sbt
if shouldFilter; then mainFiltered; else main; fi

View File

@ -0,0 +1,43 @@
import org.eclipse.jetty.server._
import org.eclipse.jetty.webapp.WebAppContext
import org.scalatra.servlet.ScalatraListener
object JettyMain {
object conf {
val port = sys.env.get("PORT") map (_.toInt) getOrElse (8080)
val stopTimeout = sys.env.get("STOP_TIMEOUT") map (_.toInt) getOrElse (5000)
val connectorIdleTimeout = sys.env.get("CONNECTOR_IDLE_TIMEOUT") map (_.toInt) getOrElse (90000)
val webapp = sys.env.get("PUBLIC") getOrElse "webapp"
val contextPath = sys.env.get("CONTEXT_PATH") getOrElse "/"
}
def main(args: Array[String]) = {
val server: Server = new Server
println("starting jetty")
server setStopTimeout conf.stopTimeout
//server setDumpAfterStart true
server setStopAtShutdown true
val httpConfig = new HttpConfiguration()
httpConfig setSendDateHeader true
httpConfig setSendServerVersion false
val connector = new NetworkTrafficServerConnector(server, new HttpConnectionFactory(httpConfig))
connector setPort conf.port
connector setSoLingerTime 0
connector setIdleTimeout conf.connectorIdleTimeout
server addConnector connector
val webapp = conf.webapp
val webApp = new WebAppContext
webApp setContextPath conf.contextPath
webApp setResourceBase conf.webapp
webApp setEventListeners Array(new ScalatraListener)
server setHandler webApp
server.start()
}
}

View File

@ -1,4 +1,4 @@
import {{apiPackage}}._
import com.wordnik.client.api._
import akka.actor.ActorSystem
import com.wordnik.swagger.app.{ResourcesApp, SwaggerApp}
import javax.servlet.ServletContext
@ -10,11 +10,10 @@ class ScalatraBootstrap extends LifeCycle {
override def init(context: ServletContext) {
implicit val system = ActorSystem("appActorSystem")
try {
{{#apiInfo}}
{{#apis}}
context mount (new {{classname}}, "/{{baseName}}/*")
{{/apis}}
{{/apiInfo}}
context mount (new UserApi, "/User/*")
context mount (new PetApi, "/Pet/*")
context mount (new StoreApi, "/Store/*")
context mount (new ResourcesApp, "/api-docs/*")
} catch {
case e: Throwable => e.printStackTrace()

View File

@ -30,10 +30,10 @@ class SwaggerApp extends Swagger(apiInfo = ApiSwagger.apiInfo, apiVersion = "1.0
object ApiSwagger {
val apiInfo = ApiInfo(
"{{{appName}}}",
"{{{appDescription}}}",
"{{{infoUrl}}}",
"{{{infoEmail}}}",
"{{{licenseInfo}}}",
"{{{licenseUrl}}}")
"""Swagger Petstore""",
"""This is a sample server Petstore server. You can find out more about Swagger at <a href="http://swagger.wordnik.com">http://swagger.wordnik.com</a> or on irc.freenode.net, #swagger. For this sample, you can use the api key "special-key" to test the authorization filters""",
"""""",
"""hello@helloreverb.com""",
"""Apache 2.0""",
"""http://www.apache.org/licenses/LICENSE-2.0.html""")
}

View File

@ -0,0 +1,365 @@
package com.wordnik.client.api
import com.wordnik.client.model.Pet
import java.io.File
import org.scalatra.{ TypedParamSupport, ScalatraServlet }
import org.scalatra.swagger._
import org.json4s._
import org.json4s.JsonDSL._
import org.scalatra.json.{ JValueResult, JacksonJsonSupport }
import org.scalatra.servlet.{FileUploadSupport, MultipartConfig, SizeConstraintExceededException}
import scala.collection.JavaConverters._
class PetApi (implicit val swagger: Swagger) extends ScalatraServlet
with FileUploadSupport
with JacksonJsonSupport
with SwaggerSupport {
protected implicit val jsonFormats: Formats = DefaultFormats
protected val applicationDescription: String = "PetApi"
override protected val applicationName: Option[String] = Some("Pet")
before() {
contentType = formats("json")
response.headers += ("Access-Control-Allow-Origin" -> "*")
}
val updatePetOperation = (apiOperation[Unit]("updatePet")
summary "Update an existing pet"
parameters(
bodyParam[Pet]("body").description("").optional
)
)
put("/pet",operation(updatePetOperation)) {
val body = parsedBody.extract[Pet]
println("body: " + body)
}
val addPetOperation = (apiOperation[Unit]("addPet")
summary "Add a new pet to the store"
parameters(
bodyParam[Pet]("body").description("").optional
)
)
post("/pet",operation(addPetOperation)) {
val body = parsedBody.extract[Pet]
println("body: " + body)
}
val findPetsByStatusOperation = (apiOperation[List[Pet]]("findPetsByStatus")
summary "Finds Pets by status"
parameters(
queryParam[List[String]]("status").description("").optional
)
)
get("/pet/findByStatus",operation(findPetsByStatusOperation)) {
val statusString = params.getAs[String]("status")
val status = if("multi".equals("default")) {
statusString match {
case Some(str) => str.split(",")
case None => List()
}
}
else
List()
println("status: " + status)
}
val findPetsByTagsOperation = (apiOperation[List[Pet]]("findPetsByTags")
summary "Finds Pets by tags"
parameters(
queryParam[List[String]]("tags").description("").optional
)
)
get("/pet/findByTags",operation(findPetsByTagsOperation)) {
val tagsString = params.getAs[String]("tags")
val tags = if("multi".equals("default")) {
tagsString match {
case Some(str) => str.split(",")
case None => List()
}
}
else
List()
println("tags: " + tags)
}
val getPetByIdOperation = (apiOperation[Pet]("getPetById")
summary "Find pet by ID"
parameters(
pathParam[Long]("petId").description("")
)
)
get("/pet/{petId}",operation(getPetByIdOperation)) {
val petId = params.getOrElse("petId", halt(400))
println("petId: " + petId)
}
val updatePetWithFormOperation = (apiOperation[Unit]("updatePetWithForm")
summary "Updates a pet in the store with form data"
parameters(
pathParam[String]("petId").description("")
,
formParam[String]("name").description("").optional
,
formParam[String]("status").description("").optional
)
)
post("/pet/{petId}",operation(updatePetWithFormOperation)) {
val petId = params.getOrElse("petId", halt(400))
println("petId: " + petId)
val name = params.getAs[String]("name")
println("name: " + name)
val status = params.getAs[String]("status")
println("status: " + status)
}
val deletePetOperation = (apiOperation[Unit]("deletePet")
summary "Deletes a pet"
parameters(
headerParam[String]("api_key").description("").optional
,
pathParam[Long]("petId").description("")
)
)
delete("/pet/{petId}",operation(deletePetOperation)) {
val api_key = request.getHeader("api_key")
println("api_key: " + api_key)
val petId = params.getOrElse("petId", halt(400))
println("petId: " + petId)
}
}

View File

@ -0,0 +1,146 @@
package com.wordnik.client.api
import com.wordnik.client.model.Order
import java.io.File
import org.scalatra.{ TypedParamSupport, ScalatraServlet }
import org.scalatra.swagger._
import org.json4s._
import org.json4s.JsonDSL._
import org.scalatra.json.{ JValueResult, JacksonJsonSupport }
import org.scalatra.servlet.{FileUploadSupport, MultipartConfig, SizeConstraintExceededException}
import scala.collection.JavaConverters._
class StoreApi (implicit val swagger: Swagger) extends ScalatraServlet
with FileUploadSupport
with JacksonJsonSupport
with SwaggerSupport {
protected implicit val jsonFormats: Formats = DefaultFormats
protected val applicationDescription: String = "StoreApi"
override protected val applicationName: Option[String] = Some("Store")
before() {
contentType = formats("json")
response.headers += ("Access-Control-Allow-Origin" -> "*")
}
val getInventoryOperation = (apiOperation[Map[String, Int]]("getInventory")
summary "Returns pet inventories by status"
parameters(
)
)
get("/store/inventory",operation(getInventoryOperation)) {
}
val placeOrderOperation = (apiOperation[Order]("placeOrder")
summary "Place an order for a pet"
parameters(
bodyParam[Order]("body").description("").optional
)
)
post("/store/order",operation(placeOrderOperation)) {
val body = parsedBody.extract[Order]
println("body: " + body)
}
val getOrderByIdOperation = (apiOperation[Order]("getOrderById")
summary "Find purchase order by ID"
parameters(
pathParam[String]("orderId").description("")
)
)
get("/store/order/{orderId}",operation(getOrderByIdOperation)) {
val orderId = params.getOrElse("orderId", halt(400))
println("orderId: " + orderId)
}
val deleteOrderOperation = (apiOperation[Unit]("deleteOrder")
summary "Delete purchase order by ID"
parameters(
pathParam[String]("orderId").description("")
)
)
delete("/store/order/{orderId}",operation(deleteOrderOperation)) {
val orderId = params.getOrElse("orderId", halt(400))
println("orderId: " + orderId)
}
}

View File

@ -0,0 +1,336 @@
package com.wordnik.client.api
import com.wordnik.client.model.User
import java.io.File
import org.scalatra.{ TypedParamSupport, ScalatraServlet }
import org.scalatra.swagger._
import org.json4s._
import org.json4s.JsonDSL._
import org.scalatra.json.{ JValueResult, JacksonJsonSupport }
import org.scalatra.servlet.{FileUploadSupport, MultipartConfig, SizeConstraintExceededException}
import scala.collection.JavaConverters._
class UserApi (implicit val swagger: Swagger) extends ScalatraServlet
with FileUploadSupport
with JacksonJsonSupport
with SwaggerSupport {
protected implicit val jsonFormats: Formats = DefaultFormats
protected val applicationDescription: String = "UserApi"
override protected val applicationName: Option[String] = Some("User")
before() {
contentType = formats("json")
response.headers += ("Access-Control-Allow-Origin" -> "*")
}
val createUserOperation = (apiOperation[Unit]("createUser")
summary "Create user"
parameters(
bodyParam[User]("body").description("").optional
)
)
post("/user",operation(createUserOperation)) {
val body = parsedBody.extract[User]
println("body: " + body)
}
val createUsersWithArrayInputOperation = (apiOperation[Unit]("createUsersWithArrayInput")
summary "Creates list of users with given input array"
parameters(
bodyParam[List[User]]("body").description("").optional
)
)
post("/user/createWithArray",operation(createUsersWithArrayInputOperation)) {
val body = parsedBody.extract[List[User]]
println("body: " + body)
}
val createUsersWithListInputOperation = (apiOperation[Unit]("createUsersWithListInput")
summary "Creates list of users with given input array"
parameters(
bodyParam[List[User]]("body").description("").optional
)
)
post("/user/createWithList",operation(createUsersWithListInputOperation)) {
val body = parsedBody.extract[List[User]]
println("body: " + body)
}
val loginUserOperation = (apiOperation[String]("loginUser")
summary "Logs user into the system"
parameters(
queryParam[String]("username").description("").optional
,
queryParam[String]("password").description("").optional
)
)
get("/user/login",operation(loginUserOperation)) {
val username = params.getAs[String]("username")
println("username: " + username)
val password = params.getAs[String]("password")
println("password: " + password)
}
val logoutUserOperation = (apiOperation[Unit]("logoutUser")
summary "Logs out current logged in user session"
parameters(
)
)
get("/user/logout",operation(logoutUserOperation)) {
}
val getUserByNameOperation = (apiOperation[User]("getUserByName")
summary "Get user by user name"
parameters(
pathParam[String]("username").description("")
)
)
get("/user/{username}",operation(getUserByNameOperation)) {
val username = params.getOrElse("username", halt(400))
println("username: " + username)
}
val updateUserOperation = (apiOperation[Unit]("updateUser")
summary "Updated user"
parameters(
pathParam[String]("username").description("")
,
bodyParam[User]("body").description("").optional
)
)
put("/user/{username}",operation(updateUserOperation)) {
val username = params.getOrElse("username", halt(400))
println("username: " + username)
val body = parsedBody.extract[User]
println("body: " + body)
}
val deleteUserOperation = (apiOperation[Unit]("deleteUser")
summary "Delete user"
parameters(
pathParam[String]("username").description("")
)
)
delete("/user/{username}",operation(deleteUserOperation)) {
val username = params.getOrElse("username", halt(400))
println("username: " + username)
}
}

View File

@ -0,0 +1,8 @@
package com.wordnik.client.model
case class Category (
id: Long,
name: String
)

View File

@ -0,0 +1,13 @@
package com.wordnik.client.model
import java.util.Date
case class Order (
id: Long,
petId: Long,
quantity: Int,
shipDate: Date,
status: String,
complete: Boolean
)

View File

@ -0,0 +1,14 @@
package com.wordnik.client.model
import com.wordnik.client.model.Category
import com.wordnik.client.model.Tag
case class Pet (
id: Long,
category: Category,
name: String,
photoUrls: List[String],
tags: List[Tag],
status: String
)

View File

@ -0,0 +1,8 @@
package com.wordnik.client.model
case class Tag (
id: Long,
name: String
)

Some files were not shown because too many files have changed in this diff Show More