001package org.xbib.elasticsearch.http.netty; 002 003import org.elasticsearch.common.xcontent.XContentBuilder; 004import org.jboss.netty.handler.codec.http.websocketx.TextWebSocketFrame; 005import org.xbib.elasticsearch.websocket.InteractiveResponse; 006 007import java.io.IOException; 008import java.util.Map; 009 010import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; 011 012/** 013 * Netty implementation of an interactive response 014 */ 015public class NettyInteractiveResponse implements InteractiveResponse { 016 017 private final String type; 018 019 private final TextWebSocketFrame response; 020 021 public NettyInteractiveResponse(String type, XContentBuilder builder) throws IOException { 022 this.type = type; 023 XContentBuilder responseBuilder = jsonBuilder() 024 .startObject().field("success", true).field("type", type); 025 if (builder != null) { 026 responseBuilder.rawField("data", builder.bytes()); 027 } 028 responseBuilder.endObject(); 029 this.response = new TextWebSocketFrame(responseBuilder.string()); 030 } 031 032 public NettyInteractiveResponse(String type, Map<String, Object> map) throws IOException { 033 this.type = type; 034 XContentBuilder responseBuilder = jsonBuilder(); 035 responseBuilder.startObject().field("success", true).field("type", type).field("data", map).endObject(); 036 this.response = new TextWebSocketFrame(responseBuilder.string()); 037 } 038 039 public NettyInteractiveResponse(String type, Throwable t) { 040 this.type = type; 041 this.response = new TextWebSocketFrame("{\"success\":false,\"type\":\"" + type + "\",\"error\":\"" + t.getMessage() + "\""); 042 } 043 044 @Override 045 public String type() { 046 return type; 047 } 048 049 /** 050 * The response frame with content, ready for writing to a Channel 051 * 052 * @return a TextWebSocketFrame 053 * @throws IOException 054 */ 055 @Override 056 public TextWebSocketFrame response() throws IOException { 057 return response; 058 } 059}