}
@Override
public void channelRead(final ChannelHandlerContext ctx, final Object msg) {
if (msg instanceof FullHttpRequest) {
final FullHttpRequest req = (FullHttpRequest) msg;
if (is100ContinueExpected(req)) {
ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE));
}
if (req.getMethod() != GET && req.getMethod() != POST) {
sendError(ctx, METHOD_NOT_ALLOWED, METHOD_NOT_ALLOWED.toString());
return;
}
final Triplet<String, Map<String,Object>, Optional<String>> requestArguments;
try {
requestArguments = getGremlinScript(req);
} catch (IllegalArgumentException iae) {
sendError(ctx, BAD_REQUEST, iae.getMessage());
return;
}
final String acceptString = Optional.ofNullable(req.headers().get("Accept")).orElse("application/json");
final String accept = acceptString.equals("*/*") ? "application/json" : acceptString;
final MessageTextSerializer serializer = (MessageTextSerializer) serializers.get(accept);
if (null == serializer) {
sendError(ctx, BAD_REQUEST, String.format("no serializer for requested Accept header: %s", accept));
return;
}
try {
logger.debug("Processing request containing script [{}] and bindings of [{}]", requestArguments.getValue0(), requestArguments.getValue1());
final Timer.Context timerContext = evalOpTimer.time();
final Object result = gremlinExecutor.eval(requestArguments.getValue0(), requestArguments.getValue2(), requestArguments.getValue1()).get();
timerContext.stop();
final ResponseMessage responseMessage = ResponseMessage.build(UUID.randomUUID())
.code(ResponseStatusCode.SUCCESS)
.result(IteratorUtil.convertToList(result)).create();
final FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(
serializer.serializeResponseAsString(responseMessage).getBytes(UTF8)));
response.headers().set(CONTENT_TYPE, accept);
response.headers().set(CONTENT_LENGTH, response.content().readableBytes());
// handle cors business
final String origin = req.headers().get(ORIGIN);
if (origin != null)
response.headers().set(ACCESS_CONTROL_ALLOW_ORIGIN, origin);
if (!isKeepAlive(req)) {
ctx.write(response).addListener(ChannelFutureListener.CLOSE);