Skip to content

Commit

Permalink
Completed initial ServerResponse implementation.
Browse files Browse the repository at this point in the history
  • Loading branch information
noboomu committed Apr 10, 2017
1 parent d69097b commit 501c4d4
Show file tree
Hide file tree
Showing 3 changed files with 170 additions and 25 deletions.
25 changes: 17 additions & 8 deletions src/main/java/com/wurrly/controllers/Users.java
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,7 @@
import java.util.Optional;
import java.util.UUID;

import javax.annotation.Nullable;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.POST;
Expand All @@ -24,19 +22,21 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.databind.JsonNode;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.google.inject.name.Named;
import com.jsoniter.any.Any;
import com.jsoniter.output.JsonStream;
import com.typesafe.config.Config;
import com.wurrly.models.User;
import com.wurrly.server.ServerRequest;
import com.wurrly.server.ServerResponse;

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

import io.undertow.util.HttpString;
import io.undertow.util.StatusCodes;
/**
* User API
*/
Expand Down Expand Up @@ -67,7 +67,7 @@ public Users()
@GET
@Path("/{userId}/type")
@ApiOperation(value = "Find users by id with type", httpMethod = "GET", response = User.class)
public Any userType(
public ServerResponse userType(
@ApiParam(hidden=true)final ServerRequest serverRequest, @PathParam("userId") final Long userId,
@QueryParam("optionalQueryString") Optional<String> optionalQueryString,
@QueryParam("optionalLong") Optional<Long> optionalLong,
Expand Down Expand Up @@ -99,7 +99,11 @@ public Any userType(
log.debug("optionalDate: " + optionalDate);


return Any.wrap(new User(232343L));
return ServerResponse.builder()
.ok()
.withEntity(new User(232343L))
.withHeader(HttpString.tryFromString("TestHeader"), "57475475")
.build();

}

Expand Down Expand Up @@ -129,7 +133,7 @@ public Any userForm(@ApiParam(hidden=true) final ServerRequest serverRequest,
@GET
@Path("/{userId}")
@ApiOperation(value = "Find users by id", httpMethod = "GET", response = User.class)
public Any user(@ApiParam(hidden=true)final ServerRequest serverRequest,
public ServerResponse 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
)
Expand All @@ -141,7 +145,12 @@ public Any user(@ApiParam(hidden=true)final ServerRequest serverRequest,
// log.debug("context: " + context);
//
//
return Any.wrap(new User(userId));
return ServerResponse.builder()
.ok()
.jsonType()
.withBody(JsonStream.serialize(new User(userId)))
.build();


}

Expand Down
140 changes: 131 additions & 9 deletions src/main/java/com/wurrly/server/ServerResponse.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,16 @@
*/
package com.wurrly.server;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jsoniter.output.JsonStream;

import io.undertow.io.IoCallback;
import io.undertow.server.HttpHandler;
import io.undertow.server.HttpServerExchange;
Expand All @@ -23,12 +29,15 @@
*/
public class ServerResponse
{
private static Logger log = LoggerFactory.getLogger(ServerResponse.class.getCanonicalName());

private ByteBuffer body;

private int status = -1;
private int status = StatusCodes.ACCEPTED;
private final HeaderMap headers = new HeaderMap();
private final Map<String,Cookie> cookies = new HashMap<>();
private String contentType;
private String contentType = org.apache.http.entity.ContentType.TEXT_PLAIN.getMimeType();
private Object entity;
private IoCallback callback;

public ServerResponse()
Expand Down Expand Up @@ -104,7 +113,7 @@ public void setContentType(String contentType)
this.contentType = contentType;
}

public void send( final HttpHandler currentHandler, final HttpServerExchange exchange )
public void send( final HttpHandler handler, final HttpServerExchange exchange )
{
long itr = this.headers.fastIterateNonEmpty();

Expand All @@ -114,22 +123,61 @@ public void send( final HttpHandler currentHandler, final HttpServerExchange exc

exchange.getResponseHeaders().putAll(values.getHeaderName(), values);

this.headers.fiNextNonEmpty(itr);
itr = this.headers.fiNextNonEmpty(itr);
}

exchange.getResponseCookies().putAll(this.cookies);

exchange.setStatusCode( this.status != -1 ? this.status : StatusCodes.ACCEPTED);
exchange.setStatusCode( this.status );

exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, this.contentType);

if( this.callback != null )
if( this.body == null && this.entity == null )
{
exchange.endExchange();
}
else if( this.body != null)
{
exchange.getResponseSender().send(this.body,this.callback);
if( this.callback != null )
{
exchange.getResponseSender().send(this.body,this.callback);
}
else
{
exchange.getResponseSender().send(this.body);
}
}
else
else if( this.entity != null)
{
exchange.getResponseSender().send(this.body);
if(exchange.isInIoThread()) {
exchange.dispatch(handler);
return;
}


exchange.startBlocking();

final int bufferSize = exchange.getConnection().getBufferSize();

final JsonStream stream = new JsonStream(exchange.getOutputStream(), bufferSize);

try
{
stream.writeVal(this.entity);
stream.close();

} catch (IOException e)
{

log.error(e.getMessage(),e);
exchange.setStatusCode(StatusCodes.INTERNAL_SERVER_ERROR);
exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "text/plain");
exchange.getResponseSender().send(e.getMessage());
}



exchange.endExchange();
}

}
Expand Down Expand Up @@ -160,6 +208,13 @@ public Builder withBody(ByteBuffer body)
return this;
}

public Builder withEntity(Object entity)
{
this.response.entity = entity;
jsonType();
return this;
}

public Builder withBody(String body)
{
this.response.body = ByteBuffer.wrap(body.getBytes());
Expand Down Expand Up @@ -196,6 +251,73 @@ public Builder withCallback(IoCallback callback)
this.response.callback = callback;
return this;
}

public Builder jsonType()
{
this.response.contentType = org.apache.http.entity.ContentType.APPLICATION_JSON.getMimeType();
return this;
}

public Builder htmlType()
{
this.response.contentType = org.apache.http.entity.ContentType.TEXT_HTML.getMimeType();
return this;
}

public Builder plainType()
{
this.response.contentType = org.apache.http.entity.ContentType.TEXT_PLAIN.getMimeType();
return this;
}

public Builder ok()
{
this.response.status = StatusCodes.ACCEPTED;
return this;
}

public Builder badRequest()
{
this.response.status = StatusCodes.BAD_REQUEST;
return this;
}

public Builder internalServerError()
{
this.response.status = StatusCodes.INTERNAL_SERVER_ERROR;
return this;
}

public Builder created()
{
this.response.status = StatusCodes.CREATED;
return this;
}

public Builder notFound()
{
this.response.status = StatusCodes.NOT_FOUND;
return this;
}

public Builder forbidden()
{
this.response.status = StatusCodes.FORBIDDEN;
return this;
}


public Builder found()
{
this.response.status = StatusCodes.FOUND;
return this;
}

public Builder noContent()
{
this.response.status = StatusCodes.NO_CONTENT;
return this;
}

public ServerResponse build()
{
Expand Down
30 changes: 22 additions & 8 deletions src/main/java/com/wurrly/server/handlers/HandlerGenerator.java
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@
import com.wurrly.modules.RoutingModule;
import com.wurrly.server.Extractors;
import com.wurrly.server.ServerRequest;
import com.wurrly.server.ServerResponse;
import com.wurrly.server.endpoints.EndpointInfo;

import io.swagger.annotations.Api;
Expand Down Expand Up @@ -702,7 +703,7 @@ else if (t.equals(TypeHandler.OptionalFromStringType) || t.equals(TypeHandler.Op
functionBlockBuilder.add("$T $L = $L.$L($L);", m.getReturnType(), "response", controllerName, m.getName(), controllerMethodArgs);

}

methodBuilder.addCode(functionBlockBuilder.build());

methodBuilder.addCode("$L", "\n");
Expand Down Expand Up @@ -748,20 +749,33 @@ else if (t.equals(TypeHandler.OptionalFromStringType) || t.equals(TypeHandler.Op
route.setConsumes(consumesContentType);

methodBuilder.addCode("$L", "\n");

methodBuilder.addStatement("exchange.getResponseHeaders().put($T.CONTENT_TYPE, $S)", Headers.class, producesContentType);

if (m.getReturnType().equals(String.class))

if( m.getReturnType().equals(ServerResponse.class))
{
methodBuilder.addStatement("exchange.getResponseHeaders().send($L)", "response");
methodBuilder.addStatement("$L.send(this,$L)","response","exchange");

}
else
{
methodBuilder.addStatement("exchange.getResponseSender().send(com.jsoniter.output.JsonStream.serialize($L))", "response");
}


methodBuilder.addStatement("exchange.getResponseHeaders().put($T.CONTENT_TYPE, $S)", Headers.class, producesContentType);

if (m.getReturnType().equals(String.class))
{
methodBuilder.addStatement("exchange.getResponseHeaders().send($L)", "response");
}
else
{
methodBuilder.addStatement("exchange.getResponseSender().send(com.jsoniter.output.JsonStream.serialize($L))", "response");
}


}

handlerClassBuilder.addMethod(methodBuilder.build());


FieldSpec handlerField = FieldSpec.builder(httpHandlerClass, methodName, Modifier.FINAL).initializer("$L", handlerClassBuilder.build()).build();

initBuilder.addCode("$L\n", handlerField.toString());
Expand Down

0 comments on commit 501c4d4

Please sign in to comment.