Skip to content

Commit

Permalink
Swagger functioning as expected.
Browse files Browse the repository at this point in the history
  • Loading branch information
noboomu committed Apr 5, 2017
1 parent d2838dc commit e739eae
Show file tree
Hide file tree
Showing 25 changed files with 14,255 additions and 82 deletions.
55 changes: 53 additions & 2 deletions conf/application.conf
Original file line number Diff line number Diff line change
@@ -1,4 +1,54 @@

application {


env = dev

version = "1.0"
name="Wurrly API"




# tmpdir
tmpdir = ${java.io.tmpdir}/${application.name}

# path (a.k.a. as contextPath)
path = /

# localhost
host = "localhost"

# HTTP ports
port = 8090

# uncomment to enabled HTTPS
# securePort = 8443

# we do UTF-8
charset = UTF-8

# date format
dateFormat = dd-MMM-yyyy

# number format, system default. set it at runtime
# numberFormat = DecimalFormat.getInstance(${application.lang})).toPattern()

# comma separated list of locale using the language tag format. Default to: Locale.getDefault()
# lang = Locale.getDefault()

# timezone, system default. set it at runtime
# tz = ZoneId.systemDefault().getId()

# redirect to/force https
# example: https://my.domain.com/{0}
redirect_https = ""


}

api.version="v1"

# images
image.size.min=120
image.size.max=3200
Expand Down Expand Up @@ -93,7 +143,7 @@ twilio.number="+16467987759"
twilio.sid="AC8a33a9fc51927ccd980ac919cdadcba5"
twilio.token="de44558f9a980b337512eb60b812f31a"



#api

Expand Down Expand Up @@ -155,11 +205,12 @@ battle.voting.duration=48
sift.api.key="GT4cFVEZegH4N5jxq5rj"
sift.api.url="https://wur28vu8.pottymouthfilter.com/v1/"

include "swagger.conf"

# The application languages
# ~~~~~


# Router
# ~~~~~
# Define the Router object to use for this application.
Expand Down
17 changes: 17 additions & 0 deletions conf/swagger.conf
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@

swagger {
swagger: "2.0"
info {
title = ${application.name}
version = ${application.version}
}
theme="material"
basePath= "/"${api.version}"/swagger"
specFilename="swagger.json"
consumes: ["application/json"]
produces: ["application/json"]
schemes: ["http"]
logoUrl: "https://www.wurrly.com/images/wurrly-logo.svg"
stylesheet: "wurrly.css"
}

27 changes: 26 additions & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@
<artifactId>jackson-annotations</artifactId>
<version>2.8.7</version>
</dependency>

<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
Expand Down Expand Up @@ -150,5 +150,30 @@
<artifactId>compiler</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-parser</artifactId>
<version>1.0.28</version>
</dependency>
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-jaxrs</artifactId>
<version>1.5.12</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.6</version>
</dependency>
<dependency>
<groupId>com.mitchellbosecke</groupId>
<artifactId>pebble</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>swagger-ui</artifactId>
<version>3.0.4</version>
</dependency>
</dependencies>
</project>
52 changes: 43 additions & 9 deletions src/com/wurrly/BaseServer.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import java.nio.ByteBuffer;
import java.util.Deque;
import java.util.Optional;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
Expand All @@ -16,21 +17,29 @@
import com.google.inject.Injector;
import com.jsoniter.DecodingMode;
import com.jsoniter.JsonIterator;
import com.jsoniter.annotation.JacksonAnnotationSupport;
import com.jsoniter.annotation.JsoniterAnnotationSupport;
import com.jsoniter.any.Any;
import com.jsoniter.output.EncodingMode;
import com.jsoniter.output.JsonStream;
import com.typesafe.config.Config;
import com.wurrly.models.User;
import com.wurrly.modules.DIModule;
import com.wurrly.modules.ConfigModule;
import com.wurrly.modules.RoutingModule;
import com.wurrly.modules.SwaggerModule;
import com.wurrly.server.GeneratedRouteHandler;
import com.wurrly.server.ServerRequest;
import com.wurrly.tests.RestRouteGenerator;
import com.wurrly.server.generate.RestRouteGenerator;
import com.wurrly.utilities.JsonMapper;

import io.swagger.models.Swagger;
import io.undertow.Undertow;
import io.undertow.UndertowOptions;
import io.undertow.server.HttpHandler;
import io.undertow.server.HttpServerExchange;
import io.undertow.server.RoutingHandler;
import io.undertow.util.Headers;
import io.undertow.util.HttpString;
import io.undertow.util.Methods;

/**
Expand Down Expand Up @@ -119,7 +128,7 @@ public static void main(String[] args)
try
{

Injector injector = Guice.createInjector(new DIModule());
Injector injector = Guice.createInjector(new ConfigModule(),new RoutingModule());


// Users usersController = injector.getInstance(Users.class);
Expand All @@ -129,21 +138,42 @@ public static void main(String[] args)

JsonIterator.setMode(DecodingMode.DYNAMIC_MODE_AND_MATCH_FIELD_WITH_HASH);
JsonStream.setMode(EncodingMode.DYNAMIC_MODE);
JsoniterAnnotationSupport.enable();
JacksonAnnotationSupport.enable();


Set<Class<?>> classes = RestRouteGenerator.getApiClasses("com.wurrly.controllers",null);

RoutingHandler router = new RoutingHandler().setFallbackHandler(BaseHandlers::notFoundHandler);

RestRouteGenerator generator = new RestRouteGenerator("com.wurrly.controllers.handlers","RouteHandlers");
generator.generateRoutes();
generator.generateRoutes(classes);

StringBuilder sb = new StringBuilder();

generator.getRestRoutes().stream().forEachOrdered( r -> sb.append(r.toString() + "\n"));

Logger.info("\n\nRegistered the following endpoints: \n\n" + sb.toString());

Class<? extends GeneratedRouteHandler> handlerClass = generator.compileRoutes();

RoutingHandler router = injector.getInstance(RoutingHandler.class);

Logger.debug("New class: " + handlerClass);

GeneratedRouteHandler routeHandler = injector.getInstance(handlerClass);

routeHandler.addRouteHandlers(router);

SwaggerModule swaggerModule = injector.getInstance(SwaggerModule.class);

swaggerModule.generateSwaggerSpec(classes);

Logger.debug("swagger spec\n");

Swagger swagger = swaggerModule.getSwagger();

Logger.debug("swagger spec: " + JsonMapper.toPrettyJSON(swagger));

swaggerModule.addRouteHandlers();

// HttpHandler getUserHandler = null;
// GetUsersHandler getUserHandler = new GetUsersHandler(usersController);

Expand Down Expand Up @@ -185,6 +215,7 @@ public static void main(String[] args)
// }
// };


router.add(Methods.GET, "/", new HttpHandler(){

/* (non-Javadoc)
Expand All @@ -203,9 +234,10 @@ public void handleRequest(HttpServerExchange exchange) throws Exception

} );

Config rootConfig = injector.getInstance(Config.class);

Undertow server = Undertow.builder()
.addHttpListener(8090, "localhost")
.addHttpListener(rootConfig.getInt("application.port"), "localhost")
.setBufferSize(1024 * 16)
.setIoThreads(Runtime.getRuntime().availableProcessors())
.setServerOption(UndertowOptions.ENABLE_HTTP2, true)
Expand All @@ -227,7 +259,9 @@ public void handleRequest(final HttpServerExchange exchange) throws Exception
// return;
// }


exchange.getResponseHeaders().put(HttpString.tryFromString("Access-Control-Allow-Origin"), "*");
exchange.getResponseHeaders().put(HttpString.tryFromString("Access-Control-Allow-Methods"), "GET, POST, DELETE, PUT, PATCH, OPTIONS");
exchange.getResponseHeaders().put(HttpString.tryFromString("Access-Control-Allow-Headers"), "Content-Type, api_key, Authorization");
router.handleRequest(exchange);

} catch (Exception e)
Expand Down
40 changes: 26 additions & 14 deletions src/com/wurrly/controllers/Users.java
Original file line number Diff line number Diff line change
Expand Up @@ -33,11 +33,12 @@

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

/**
* User API
*/
@Api(tags="users",produces="application/json", consumes="application/json")
@Api(tags="users")
@Path("/api/users")
@Produces(("application/json"))
@Consumes(("application/json"))
Expand All @@ -63,8 +64,8 @@ public Users()

@GET
@Path("/{userId}/type")
@ApiOperation(value = "Find users by id with type", nickname = "user", httpMethod = "GET", response = User.class)
public Any userType(final ServerRequest serverRequest, @PathParam("userId") final Long userId, @QueryParam("context") Optional<String> context, @QueryParam("type") User.UserType type, @QueryParam("uuid") UUID uuid)
@ApiOperation(value = "Find users by id with type", httpMethod = "GET", response = User.class)
public Any userType(@ApiParam(hidden=true)final ServerRequest serverRequest, @PathParam("userId") final Long userId, @QueryParam("context") Optional<String> context, @QueryParam("type") User.UserType type, @QueryParam("uuid") Optional<UUID> uuid)
{
//
log.debug("uuid: " + uuid);
Expand All @@ -78,9 +79,15 @@ public Any userType(final ServerRequest serverRequest, @PathParam("userId") fina
}

@POST
@Path("/form")
@ApiOperation(value = "Find users by id with type", nickname = "user", httpMethod = "GET", response = User.class)
public Any userForm(final ServerRequest serverRequest, @PathParam("userId") final Long userId, @QueryParam("context") Optional<String> context, @FormParam("type") User.UserType type, ByteBuffer testFile)
@Path("/form/{userId}")
@Consumes("*/*")
@ApiOperation(value = "Post a complex form", httpMethod = "POST", response = User.class)
public Any userForm(@ApiParam(hidden=true) final ServerRequest serverRequest,
@ApiParam(name="userId",required=true) @PathParam("userId") final Long userId,
@ApiParam(name="context",required=false) @QueryParam("context") Optional<String> context,
@ApiParam(name="type",required=true) @QueryParam("type") User.UserType type,
ByteBuffer testFile
)
{
//
// log.debug("esIndexName: " + esIndexName);
Expand All @@ -96,8 +103,11 @@ public Any userForm(final ServerRequest serverRequest, @PathParam("userId") fina

@GET
@Path("/{userId}")
@ApiOperation(value = "Find users by id", nickname = "user", httpMethod = "GET", response = JsonNode.class)
public Any user(final ServerRequest serverRequest, @PathParam("userId") final Long userId, @QueryParam("context") Optional<String> context)
@ApiOperation(value = "Find users by id", httpMethod = "GET", response = User.class)
public Any user(@ApiParam(hidden=true)final ServerRequest serverRequest,
@ApiParam(name="userId", required=true) @PathParam("userId") final Long userId,
@ApiParam(name="context", required=false) @QueryParam("context") Optional<String> context
)
{
//
// log.debug("esIndexName: " + esIndexName);
Expand All @@ -113,27 +123,29 @@ public Any user(final ServerRequest serverRequest, @PathParam("userId") final Lo

@POST
@Path("/")
@Consumes("multipart/form-data")
// @ApiImplicitParams({ @ApiImplicitParam(dataType = "com.wurrly.models.User", name = "user", paramType = "body", required = false, allowMultiple = false) })
@ApiOperation(value = "Find users by id", nickname = "user", httpMethod = "POST", response = JsonNode.class)
public Any createUser(final ServerRequest serverRequest, @QueryParam("context") Optional<String> context, final List<User> user )
@ApiOperation(value = "Create a user", httpMethod = "POST", response = User.class)
public Any createUser(@ApiParam(hidden=true)final ServerRequest serverRequest, @QueryParam("context") Optional<String> context, final java.nio.file.Path filePath )
{
//

// log.debug("context: " + context);
// log.debug("request: " + serverRequest);
// log.debug("file: " + user);

return Any.wrap(user);
return Any.wrap(new User(34l));



}

@PUT
@Path("/{userId}/username")
@Path("/username")
@Consumes(("application/json"))
// @ApiImplicitParams({ @ApiImplicitParam(dataType = "com.wurrly.models.User", name = "user", paramType = "body", required = false, allowMultiple = false) })
@ApiOperation(value = "Update a user's name", nickname = "updateUsername", httpMethod = "PUT", response = JsonNode.class)
public Any updateUsername(final ServerRequest serverRequest, @QueryParam("context") Optional<String> context, final User user )
@ApiOperation(value = "Update a user's name", httpMethod = "PUT", response = User.class)
public Any updateUsername(@ApiParam(hidden=true)final ServerRequest serverRequest, @QueryParam("context") Optional<String> context, final User user )
{
//
log.debug("esIndexName: " + esIndexName);
Expand Down
Loading

0 comments on commit e739eae

Please sign in to comment.