@Config(name="datasource")
@ConfigScope
public class DataSourceConfig {

    private String password = "westty";
    private String user = "westty";
    private String driver = "org.apache.derby.jdbc.EmbeddedDriver";
    private String url  ="jdbc:derby:memory:westty;create=true";

    public DataSourceConfig() {
    }

    public String getPassword() {
        return password;
    }

    public String getUser() {
        return user;
    }

    public String getDriver() {
        return driver;
    }

    public String getUrl() {
        return url;
    }
} @ConfigScope
@Config(name = "protobuf",
        desc = "Protobuf configuration. Changes requires server restart.")
public class ProtobufConfig {

    @Id(desc="Name of this server")
    private String serverName = ServerConfig.DEFAULT_SERVER_NAME;

    public ProtobufConfig(){
    }

    public ProtobufConfig(String serverName){
        this.serverName = serverName;
    }

    @Config(desc = "Protobuf listening port.")
    @NotNull
    @Min(0)
    @Max(65535)
    private Integer port = 7777;

    @Config(desc = "Specify the worker count to use. "
            + "See netty javadoc NioServerSocketChannelFactory.")
    @Min(1)
    @NotNull
    private Integer ioWorkerCount = Runtime.getRuntime().availableProcessors() * 2;

    public Integer getIoWorkerCount() {
        return ioWorkerCount;
    }

    public int getPort() {
        return port;
    }

    public void setPort(Integer port) {
        this.port = port;
    }

    public void setIoWorkerCount(Integer ioWorkerCount) {
        this.ioWorkerCount = ioWorkerCount;
    }
} @ConfigScope
@Config(name = "servers",
        desc = "Server engine configuration. Changes requires server restart.")
public class ServerConfig {

    public static final String DEFAULT_SERVER_NAME = "server";
    public static final String DEFAULT_CONF_DIR = "conf";
    public static final String DEFAULT_LIB_DIR = "lib";
    public static final String DEFAULT_BIN_DIR = "bin";
    public static final String DEFAULT_HTML_DIR = "html";
    public static final String DEFAULT_IP_ADDRESS = "127.0.0.1";
    public static final int DEFAULT_HTTP_PORT = 8080;
    public static final int DEFAULT_CLUSTER_PORT = 5701;

    @Id(desc="Name of this server")
    private String name = DEFAULT_SERVER_NAME;

    @Config(desc = "Public Ip Address.")
    private String publicIp = DEFAULT_IP_ADDRESS;

    @Config(desc = "Private Ip Address.")
    private String privateIp = DEFAULT_IP_ADDRESS;

    @Config(desc="Port that this server uses for the cluster.")
    private Integer clusterPort = DEFAULT_CLUSTER_PORT;

    @Config(desc="Ip address that this server uses for the cluster.")
    private String clusterIp = DEFAULT_IP_ADDRESS;

    @Config(desc = "Root directory.")
    private String rootDir = System.getProperty("root.dir");

    @Config(desc = "Location of the conf directory relative to the root directory.")
    private String confDir = DEFAULT_CONF_DIR;

    @Config(desc = "Location of the lib directory relative to the root directory.")
    private String libDir = DEFAULT_LIB_DIR;

    @Config(desc = "Location of the bin directory relative to the root directory.")
    private String binDir = DEFAULT_BIN_DIR;

    @Config(desc = "Location of the html directory relative to the root directory.")
    private String htmlDir = DEFAULT_HTML_DIR;


    @Config(desc = "Http listening port.")
    @NotNull
    @Min(0)
    @Max(65535)
    private Integer httpPort = DEFAULT_HTTP_PORT;

    @Config(desc = "Specify the worker count to use. "
            + "See netty javadoc NioServerSocketChannelFactory.")
    @Min(1)
    @NotNull
    private Integer ioWorkerCount = Runtime.getRuntime().availableProcessors() * 2;

    @Config(desc = "Set the max request size in bytes. If this size exceeded "
            + "\"413 Request Entity Too Large\" willl be sent to the client.")
    @NotNull
    @Min(4096)
    private Integer maxRequestSize = 1024 * 1024 * 10;

    @Config(desc = "Maximum byte length of aggregated http content. "
            + "TooLongFrameException raised if length exceeded.")
    @NotNull
    @Min(16384)
    private Integer maxHttpContentChunkLength = 65536;

    public ServerConfig() {

    }

    public ServerConfig(String serverName) {
        this.name = serverName;
    }

    public Integer getIoWorkerCount() {
        return ioWorkerCount;
    }

    public Integer getMaxRequestSize() {
        return maxRequestSize;
    }

    public Integer getHttpPort() {
        return httpPort;
    }

    public Integer getMaxHttpContentChunkLength() {
        return maxHttpContentChunkLength;
    }

    public String getPublicIp() {
        return publicIp;
    }

    public String getPrivateIp() {
        return privateIp;
    }

    public int getClusterPort() {
        return clusterPort;
    }

    public File getLibDir() {
        return new File(rootDir, libDir);
    }

    public File getConfDir() {
        return new File(rootDir, confDir);
    }

    public File getBinDir() {
        return new File(rootDir, binDir);
    }

    public File getHtmlDir() {
        return new File(rootDir, htmlDir);
    }

    public void setHttpPort(Integer httpPort) {
        this.httpPort = httpPort;
    }

    public void setServerName(String serverName) {
        this.name = serverName;
    }

    public void setPublicIp(String publicIp) {
        this.publicIp = publicIp;
    }

    public void setPrivateIp(String privateIp) {
        this.privateIp = privateIp;
    }

    public void setClusterPort(Integer clusterPort) {
        this.clusterPort = clusterPort;
    }

    public void setClusterIpAddress(String clusterIpAddress) {
        this.clusterIp = clusterIpAddress;
    }

} @Singleton
@ApplicationPath(JaxrsApplication.JAXRS_CONTEXT_URI)
public class JaxrsApplication extends Application {
    /** relative uri for jaxrs endpoint for "see other" and "redirects" */
    public static final String JAXRS_CONTEXT_URI = "/jaxrs";

    @Inject
    private JaxrsCdiExtension jaxrsExtension;

    @Inject
    private BeanManager bm;

    @Override
    public Set<Class<?>> getClasses() {
        return new HashSet<Class<?>>();
    }

    @SuppressWarnings({ "rawtypes", "unchecked" })
    @Override
    public Set<Object> getSingletons() {
        HashSet<Object> instances = new HashSet<>();
        for (Class<?> cls : jaxrsExtension.getJaxrsClasses()) {
            Set<Bean<?>> beans = bm.getBeans(cls);
            for (Bean<?> bean : beans) {
                CreationalContext cc = bm.createCreationalContext(null);
                Object jaxrs = bean.create(cc);
                instances.add(jaxrs);
            }
        }
        return instances;
    }
} @Singleton
public class ProtobufClient {
    private static final Logger log = LoggerFactory.getLogger(ProtobufClient.class);

    public static final int MESSAGE_LENGTH = 4;
    public static final int MESSAGE_MAX_SIZE_10MB = 10485760;
    private final ProtobufSerializer serializer;
    private final Lock lock = new ReentrantLock();
    private final ConcurrentHashMap<Integer, ConcurrentLinkedQueue<Callback>> callbacks = new ConcurrentHashMap<>();
    private final ChannelFactory factory;
    private final ChannelGroup channelGroup = new DefaultChannelGroup("channels");
    private final ClientProtobufDecoder decoder;
    private final ClientProtobufEncoder encoder;
    private final LengthFieldPrepender lengthPrepender = new LengthFieldPrepender(MESSAGE_LENGTH);
    private final ClientHandler clientHandler = new ClientHandler();
    private final ProtobufConfig config;
    @Inject
    public ProtobufClient(IoExecutors excutors,
                          ProtobufSerializer serializer, ProtobufConfig config) {
        this.factory = new NioClientSocketChannelFactory(excutors.getBoss(), excutors.getWorker());
        this.serializer = serializer;
        this.decoder = new ClientProtobufDecoder(serializer);
        this.encoder = new ClientProtobufEncoder();
        this.config = config;
    }

    public int connect() throws IOException {
        return connect(new InetSocketAddress(config.getPort()));
    }

    public int connect(InetSocketAddress address) throws IOException {
        ClientBootstrap bootstrap = new ClientBootstrap(factory);
        bootstrap.setPipelineFactory(new ChannelPipelineFactory() {

            @Override
            public ChannelPipeline getPipeline() throws Exception {
                ChannelPipeline pipeline = Channels.pipeline();
                pipeline.addLast("lengthFrameDecoder", new LengthFieldBasedFrameDecoder(
                        MESSAGE_MAX_SIZE_10MB, 0, MESSAGE_LENGTH, 0, MESSAGE_LENGTH));
                pipeline.addLast("decoder", decoder);
                pipeline.addLast("lengthPrepender", lengthPrepender);
                pipeline.addLast("encoder", encoder);
                pipeline.addLast("handler", clientHandler);
                return pipeline;
            }
        });

        ChannelFuture future = bootstrap.connect(address);

        if (!future.awaitUninterruptibly().isSuccess()) {
            bootstrap.releaseExternalResources();
            throw new IllegalArgumentException("Could not connect to " + address);
        }

        Channel channel = future.getChannel();

        if (!channel.isConnected()) {
            bootstrap.releaseExternalResources();
            throw new IllegalStateException("Channel could not connect to " + address);
        }
        channelGroup.add(channel);
        return channel.getId();
    }

    public void registerResource(String protodesc) {
        serializer.registerResource(protodesc);
    }

    public ChannelFuture callAsync(Integer channelId, Object protoMsg) throws IOException {
        Channel channel = channelGroup.find(channelId);
        byte[] bytes = serializer.write(protoMsg);
        if (channel == null || !channel.isOpen()) {
            throw new IOException("Channel is not open");
        }
        return channel.write(ChannelBuffers.wrappedBuffer(bytes));
    }

    public Object callSync(int id, Object protoMsg) throws IOException, FailureMessageException {
        Preconditions.checkNotNull(protoMsg);
        Channel channel = channelGroup.find(id);
        if(channel == null){
            throw new IllegalArgumentException("Channel not found ["+id+"]");
        }
        byte[] bytes = serializer.write(protoMsg);
        Callback callback = new Callback();
        lock.lock();
        try {
            if (!channel.isOpen()) {
                throw new IOException("Channel is not open");
            }
            ConcurrentLinkedQueue<Callback> callbackQueue = callbacks.get(id);
            if(callbackQueue == null){
                callbackQueue = new ConcurrentLinkedQueue<>();
                callbacks.put(id, callbackQueue);
            }
            callbackQueue.add(callback);
            channel.write(ChannelBuffers.wrappedBuffer(bytes));
        } finally {
            lock.unlock();
        }
        Object res = callback.get();
        if (res instanceof Failure) {
            Failure failure = (Failure) res;
            throw new FailureMessageException(failure);
        }
        if(res instanceof VoidMessage.Void){
            return null;
        }
        return res;
    }

    public void disconnect(Integer id) {
        Channel channel = channelGroup.find(id);
        if (channel != null && channel.isConnected()) {
            channel.close().awaitUninterruptibly();
        }

    }

    public void shutdown() {
        channelGroup.close().awaitUninterruptibly();
        final class ShutdownNetty extends Thread {
            public void run() {
                factory.releaseExternalResources();
            }
        }
        new ShutdownNetty().start();
    }

    class ClientHandler extends SimpleChannelHandler {

        @Override
        public void handleUpstream(final ChannelHandlerContext ctx, final ChannelEvent e)
                throws Exception {
            if (e instanceof ChannelStateEvent) {
                log.debug(e.toString());
            }
            super.handleUpstream(ctx, e);
        }

        @Override
        public void channelClosed(ChannelHandlerContext ctx, final ChannelStateEvent e)
                throws Exception {
            disconnect(e.getChannel().getId());
        }

        @Override
        public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
            ConcurrentLinkedQueue<Callback> callbackQueue = callbacks.get(e.getChannel().getId());
            if(callbackQueue == null){
                return;
            }
            Callback callback = callbackQueue.poll();
            if (callback != null) {
                callback.handle(e.getMessage());
            }
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
            final Throwable cause = e.getCause();
            final Channel ch = ctx.getChannel();
            if (cause instanceof ClosedChannelException) {
                log.warn("Attempt to write to closed channel." + ch);

                disconnect(e.getChannel().getId());
            } else if (cause instanceof IOException
                    && "Connection reset by peer".equals(cause.getMessage())) {
                disconnect(e.getChannel().getId());
            } else if (cause instanceof ConnectException
                    && "Connection refused".equals(cause.getMessage())) {
                // server not up, nothing to do
            } else {
                log.error("Unexpected exception.", e.getCause());
                disconnect(e.getChannel().getId());
            }
        }
    }

    @Sharable
    static class ClientProtobufDecoder extends OneToOneDecoder {
        private final ProtobufSerializer serializer;

        public ClientProtobufDecoder(ProtobufSerializer serializer) {
            this.serializer = serializer;
        }

        @Override
        protected Object decode(ChannelHandlerContext ctx, Channel channel, Object msg)
                throws Exception {
            if (!(msg instanceof ChannelBuffer)) {
                return msg;
            }
            ChannelBuffer buf = (ChannelBuffer) msg;
            return serializer.read(buf.array());
        }
    }

    @Sharable
    static class ClientProtobufEncoder extends OneToOneEncoder {
        @Override
        protected Object encode(ChannelHandlerContext ctx, Channel channel, Object msg)
                throws Exception {
            if (msg instanceof MessageLite) {
                return wrappedBuffer(((MessageLite) msg).toByteArray());
            }
            if (msg instanceof MessageLite.Builder) {
                return wrappedBuffer(((MessageLite.Builder) msg).build().toByteArray());
            }
            return msg;
        }
    }

    static class Callback {
        private final CountDownLatch latch = new CountDownLatch(1);
        private Object response;

        Object get() {
            try {
                latch.await();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            return response;
        }

        void handle(Object response) {
            this.response = response;
            latch.countDown();
        }
    }
} @Alternative
public class ProtobufSerializer {
    private static final Logger log = LoggerFactory.getLogger(ProtobufSerializer.class);
    private HashMap<Integer, Method> numToMethod = new HashMap<>();
    private HashMap<String, Integer> protoToNum = new HashMap<>();
    private static final String UNRECOGNIZED_PROTOCOL_MSG = "Unrecognized protocol.";

    public ProtobufSerializer() {
        registerResource("META-INF/failure.desc");
        registerResource("META-INF/void.desc");
    }

    public void register(URL protodesc) {
        try {
            registerDesc(protodesc.getFile(), protodesc.openStream());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public void register(File protodesc) {
        try {
            registerDesc(protodesc.getName(), new FileInputStream(protodesc));
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    public void registerResource(String protodesc) {
        URL url = Thread.currentThread().getContextClassLoader().getResource(protodesc);
        register(url);
    }

    private void registerDesc(String name, InputStream in) {
        try {
            FileDescriptorSet descriptorSet = FileDescriptorSet.parseFrom(in);
            for (FileDescriptorProto fdp : descriptorSet.getFileList()) {
                FileDescriptor fd = FileDescriptor.buildFrom(fdp, new FileDescriptor[] {});

                for (Descriptor desc : fd.getMessageTypes()) {
                    FieldDescriptor fdesc = desc.findFieldByName("protoType");
                    if (fdesc == null) {
                        throw new IllegalArgumentException(name
                                + ".proto file must define protoType field "
                                + "with unqiue number that identify proto type");
                    }
                    String packageName = fdp.getOptions().getJavaPackage();

                    if (Strings.isNullOrEmpty(packageName)) {
                        throw new IllegalArgumentException(name
                                + ".proto file must define java_package");
                    }
                    String simpleClassName = fdp.getOptions().getJavaOuterClassname();
                    if (Strings.isNullOrEmpty(simpleClassName)) {
                        throw new IllegalArgumentException(name
                                + " .proto file must define java_outer_classname");
                    }

                    String className = packageName + "." + simpleClassName + "$" + desc.getName();
                    Class<?> cls = Thread.currentThread().getContextClassLoader()
                            .loadClass(className);
                    protoToNum.put(desc.getFullName(), fdesc.getNumber());
                    numToMethod.put(fdesc.getNumber(), cls.getMethod("parseFrom", byte[].class));
                    log.debug("Registered protobuf resource {}.", name);
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public Object read(byte[] bytes) throws Exception {
        try {
            ByteBuffer buf = ByteBuffer.wrap(bytes);
            Varint32 vint = new Varint32(buf);
            int protoTypeNum = vint.read();
            buf = vint.getByteBuffer();
            byte[] message = new byte[buf.remaining()];
            buf.get(message);
            Method m = numToMethod.get(protoTypeNum);
            if (m == null) {
                return Failure.newBuilder().setCode(BAD_REQUEST.getCode())
                        .setMsg("proto_type=" + protoTypeNum).build();
            }
            return m.invoke(null, message);
        } catch (Exception e) {
            return Failure.newBuilder().setCode(BAD_REQUEST.getCode())
                    .setMsg(UNRECOGNIZED_PROTOCOL_MSG).build();
        }
    }

    public byte[] write(Object proto) throws IOException {
        Message msg = (Message) proto;
        String protoName = msg.getDescriptorForType().getFullName();
        Integer num = protoToNum.get(protoName);
        if(num == null){
            throw new IllegalArgumentException("Could not find protoType mapping for " + protoName);
        }
        byte[] msgBytes = msg.toByteArray();
        Varint32 vint = new Varint32(num);
        int vsize = vint.getSize();
        byte[] bytes = new byte[vsize + msgBytes.length];
        System.arraycopy(vint.write(), 0, bytes, 0, vsize);
        System.arraycopy(msgBytes, 0, bytes, vsize, msgBytes.length);
        return bytes;
    }
} @Singleton
public class IoExecutors {

    private ExecutorService bossExecutor = Executors.newCachedThreadPool();
    private ExecutorService ioExecutor = Executors.newCachedThreadPool();

    public ExecutorService getBoss() {
        return bossExecutor;
    }

    public ExecutorService getWorker() {
        return ioExecutor;
    }

} @Singleton
public class SQLExec {
    private DataSource datasource;

    private String username;
    private String password;
    private String url;

    public SQLExec(){

    }

    public SQLExec(String username, String password, String url) {
        this.username = username;
        this.password = password;
        this.url = url;
    }

    public void executeResource(String ddl, boolean ignoreSqlEx) throws SQLException, IOException {
        ClassLoader cl = Thread.currentThread().getContextClassLoader();

        URL ddlUrl = cl.getResource(ddl);
        List<String> lines = Resources.readLines(ddlUrl, Charsets.UTF_8);
        execute(lines, ignoreSqlEx);
    }

    public void execute(File file, boolean ignoreSqlEx) throws SQLException, IOException {
        execute(file, ignoreSqlEx);
    }

    public void execute(List<String> commands, boolean ignoreSqlEx) throws SQLException,
            IOException {
        Connection c = getConnection();
        execute(commands, c, ignoreSqlEx);
    }

    public void execute(File file, String url, String username, String password, boolean ignoreSqlEx)
            throws SQLException, IOException {
        Connection c = getConnection();
        execute(file, c, ignoreSqlEx);
    }

    public Connection getConnection() throws SQLException {
        Connection c = null;
        if (datasource != null) {
            c = datasource.getConnection();
        } else {
            Properties connectionProps = new Properties();
            connectionProps.put("user", username);
            connectionProps.put("password", password);
            c = DriverManager.getConnection(url, connectionProps);
        }
        c.setAutoCommit(true);
        return c;
    }

    private void execute(File f, Connection c, boolean ignoreSqlEx) throws SQLException,
            IOException {
        execute(Files.readLines(f, Charset.defaultCharset()), c, ignoreSqlEx);
    }
    public void execute(String... lines) throws SQLException, IOException {
        execute(Arrays.asList(lines), getConnection(), false);
    }
    private void execute(List<String> lines, Connection c, boolean ignoreSqlEx)
            throws SQLException, IOException {
        try {
            List<String> sqlStmts = new ArrayList<>();
            StringBuilder sb = new StringBuilder();
            for (String input : lines) {
                if (input == null || "".equals(input.trim()) || input.startsWith("--")
                        || input.startsWith("#")) {
                    continue;
                }
                sb.append(input);
                if (input.endsWith(";")) {
                    sqlStmts.add(sb.substring(0, sb.length() - 1));
                    sb = new StringBuilder();
                }
            }
            for (String sql : sqlStmts) {
                PreparedStatement stmt = c.prepareStatement(sql);
                stmt.execute();
            }

        } catch (SQLException e) {
            if (!ignoreSqlEx) {
                throw e;
            }
        } finally {
            if (c != null) {
                try {
                    c.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
} public class WesttyJUnit4Runner extends BlockJUnit4ClassRunner {

    private final Class<?> cls;
    private Westty westty;
    public WesttyJUnit4Runner(final Class<?> cls) throws Exception {
        super(cls);
        this.cls = cls;
        for (Method m : cls.getDeclaredMethods()) {
            TestBootstrap bootstrap = m.getAnnotation(TestBootstrap.class);
            if (bootstrap == null) {
                continue;
            }
            if (!Modifier.isStatic(m.getModifiers())) {
                throw new IllegalStateException("TestBootstrap methods must be static.");
            }
            if (m.getParameterTypes().length > 0) {
                throw new IllegalStateException(
                        "TestBootstrap methods must not have parameters.");
            }
            m.setAccessible(true);
            m.invoke(null, null);
        }
        if (westty == null) {
            this.westty = new Westty();
            try {
                westty.startup();
            } catch (Throwable e) {
                e.printStackTrace();
                throw new InitializationError(e);
            }
        }
    }

    @Override
    protected Object createTest() throws Exception {
        try {
            if (westty == null) {
                this.westty = new Westty();
                try {
                    westty.startup();
                } catch (Throwable e) {
                    e.printStackTrace();
                    throw new InitializationError(e);
                }
            }
            return westty.getInstance(cls);
        } catch (Throwable e) {
            e.printStackTrace();
            throw new Exception(e);
        }
    }
} public static enum Protocol {
    PROTOBUF, JAXRS, EVENTBUS;
} public static final class CreateRequest extends
    com.google.protobuf.GeneratedMessage
    implements CreateRequestOrBuilder {
  // Use CreateRequest.newBuilder() to construct.
  private CreateRequest(Builder builder) {
    super(builder);
  }
  private CreateRequest(boolean noInit) {}
    
  private static final CreateRequest defaultInstance;
  public static CreateRequest getDefaultInstance() {
    return defaultInstance;
  }
    
  public CreateRequest getDefaultInstanceForType() {
    return defaultInstance;
  }
    
  public static final com.google.protobuf.Descriptors.Descriptor
      getDescriptor() {
    return org.deephacks.westty.tests.ServerMessages.internal_static_westty_tests_CreateRequest_descriptor;
  }
    
  protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
      internalGetFieldAccessorTable() {
    return org.deephacks.westty.tests.ServerMessages.internal_static_westty_tests_CreateRequest_fieldAccessorTable;
  }
    
  private int bitField0_;
  // optional uint32 protoType = 301;
  public static final int PROTOTYPE_FIELD_NUMBER = 301;
  private int protoType_;
  public boolean hasProtoType() {
    return ((bitField0_ & 0x00000001) == 0x00000001);
  }
  public int getProtoType() {
    return protoType_;
  }
    
  // required .westty.tests.JsonMessage json = 1;
  public static final int JSON_FIELD_NUMBER = 1;
  private org.deephacks.westty.tests.ServerMessages.JsonMessage json_;
  public boolean hasJson() {
    return ((bitField0_ & 0x00000002) == 0x00000002);
  }
  public org.deephacks.westty.tests.ServerMessages.JsonMessage getJson() {
    return json_;
  }
  public org.deephacks.westty.tests.ServerMessages.JsonMessageOrBuilder getJsonOrBuilder() {
    return json_;
  }
    
  private void initFields() {
    protoType_ = 0;
    json_ = org.deephacks.westty.tests.ServerMessages.JsonMessage.getDefaultInstance();
  }
  private byte memoizedIsInitialized = -1;
  public final boolean isInitialized() {
    byte isInitialized = memoizedIsInitialized;
    if (isInitialized != -1) return isInitialized == 1;
      
    if (!hasJson()) {
      memoizedIsInitialized = 0;
      return false;
    }
    if (!getJson().isInitialized()) {
      memoizedIsInitialized = 0;
      return false;
    }
    memoizedIsInitialized = 1;
    return true;
  }
    
  public void writeTo(com.google.protobuf.CodedOutputStream output)
                      throws java.io.IOException {
    getSerializedSize();
    if (((bitField0_ & 0x00000002) == 0x00000002)) {
      output.writeMessage(1, json_);
    }
    if (((bitField0_ & 0x00000001) == 0x00000001)) {
      output.writeUInt32(301, protoType_);
    }
    getUnknownFields().writeTo(output);
  }
    
  private int memoizedSerializedSize = -1;
  public int getSerializedSize() {
    int size = memoizedSerializedSize;
    if (size != -1) return size;
    
    size = 0;
    if (((bitField0_ & 0x00000002) == 0x00000002)) {
      size += com.google.protobuf.CodedOutputStream
        .computeMessageSize(1, json_);
    }
    if (((bitField0_ & 0x00000001) == 0x00000001)) {
      size += com.google.protobuf.CodedOutputStream
        .computeUInt32Size(301, protoType_);
    }
    size += getUnknownFields().getSerializedSize();
    memoizedSerializedSize = size;
    return size;
  }
    
  private static final long serialVersionUID = 0L;
  @java.lang.Override
  protected java.lang.Object writeReplace()
      throws java.io.ObjectStreamException {
    return super.writeReplace();
  }
    
  public static org.deephacks.westty.tests.ServerMessages.CreateRequest parseFrom(
      com.google.protobuf.ByteString data)
      throws com.google.protobuf.InvalidProtocolBufferException {
    return newBuilder().mergeFrom(data).buildParsed();
  }
  public static org.deephacks.westty.tests.ServerMessages.CreateRequest parseFrom(
      com.google.protobuf.ByteString data,
      com.google.protobuf.ExtensionRegistryLite extensionRegistry)
      throws com.google.protobuf.InvalidProtocolBufferException {
    return newBuilder().mergeFrom(data, extensionRegistry)
             .buildParsed();
  }
  public static org.deephacks.westty.tests.ServerMessages.CreateRequest parseFrom(byte[] data)
      throws com.google.protobuf.InvalidProtocolBufferException {
    return newBuilder().mergeFrom(data).buildParsed();
  }
  public static org.deephacks.westty.tests.ServerMessages.CreateRequest parseFrom(
      byte[] data,
      com.google.protobuf.ExtensionRegistryLite extensionRegistry)
      throws com.google.protobuf.InvalidProtocolBufferException {
    return newBuilder().mergeFrom(data, extensionRegistry)
             .buildParsed();
  }
  public static org.deephacks.westty.tests.ServerMessages.CreateRequest parseFrom(java.io.InputStream input)
      throws java.io.IOException {
    return newBuilder().mergeFrom(input).buildParsed();
  }
  public static org.deephacks.westty.tests.ServerMessages.CreateRequest parseFrom(
      java.io.InputStream input,
      com.google.protobuf.ExtensionRegistryLite extensionRegistry)
      throws java.io.IOException {
    return newBuilder().mergeFrom(input, extensionRegistry)
             .buildParsed();
  }
  public static org.deephacks.westty.tests.ServerMessages.CreateRequest parseDelimitedFrom(java.io.InputStream input)
      throws java.io.IOException {
    Builder builder = newBuilder();
    if (builder.mergeDelimitedFrom(input)) {
      return builder.buildParsed();
    } else {
      return null;
    }
  }
  public static org.deephacks.westty.tests.ServerMessages.CreateRequest parseDelimitedFrom(
      java.io.InputStream input,
      com.google.protobuf.ExtensionRegistryLite extensionRegistry)
      throws java.io.IOException {
    Builder builder = newBuilder();
    if (builder.mergeDelimitedFrom(input, extensionRegistry)) {
      return builder.buildParsed();
    } else {
      return null;
    }
  }
  public static org.deephacks.westty.tests.ServerMessages.CreateRequest parseFrom(
      com.google.protobuf.CodedInputStream input)
      throws java.io.IOException {
    return newBuilder().mergeFrom(input).buildParsed();
  }
  public static org.deephacks.westty.tests.ServerMessages.CreateRequest parseFrom(
      com.google.protobuf.CodedInputStream input,
      com.google.protobuf.ExtensionRegistryLite extensionRegistry)
      throws java.io.IOException {
    return newBuilder().mergeFrom(input, extensionRegistry)
             .buildParsed();
  }
    
  public static Builder newBuilder() { return Builder.create(); }
  public Builder newBuilderForType() { return newBuilder(); }
  public static Builder newBuilder(org.deephacks.westty.tests.ServerMessages.CreateRequest prototype) {
    return newBuilder().mergeFrom(prototype);
  }
  public Builder toBuilder() { return newBuilder(this); }
    
  @java.lang.Override
  protected Builder newBuilderForType(
      com.google.protobuf.GeneratedMessage.BuilderParent parent) {
    Builder builder = new Builder(parent);
    return builder;
  }
  public static final class Builder extends
      com.google.protobuf.GeneratedMessage.Builder<Builder>
     implements org.deephacks.westty.tests.ServerMessages.CreateRequestOrBuilder {
    public static final com.google.protobuf.Descriptors.Descriptor
        getDescriptor() {
      return org.deephacks.westty.tests.ServerMessages.internal_static_westty_tests_CreateRequest_descriptor;
    }
      
    protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
        internalGetFieldAccessorTable() {
      return org.deephacks.westty.tests.ServerMessages.internal_static_westty_tests_CreateRequest_fieldAccessorTable;
    }
      
    // Construct using org.deephacks.westty.tests.ServerMessages.CreateRequest.newBuilder()
    private Builder() {
      maybeForceBuilderInitialization();
    }
      
    private Builder(BuilderParent parent) {
      super(parent);
      maybeForceBuilderInitialization();
    }
    private void maybeForceBuilderInitialization() {
      if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {
        getJsonFieldBuilder();
      }
    }
    private static Builder create() {
      return new Builder();
    }
      
    public Builder clear() {
      super.clear();
      protoType_ = 0;
      bitField0_ = (bitField0_ & ~0x00000001);
      if (jsonBuilder_ == null) {
        json_ = org.deephacks.westty.tests.ServerMessages.JsonMessage.getDefaultInstance();
      } else {
        jsonBuilder_.clear();
      }
      bitField0_ = (bitField0_ & ~0x00000002);
      return this;
    }
      
    public Builder clone() {
      return create().mergeFrom(buildPartial());
    }
      
    public com.google.protobuf.Descriptors.Descriptor
        getDescriptorForType() {
      return org.deephacks.westty.tests.ServerMessages.CreateRequest.getDescriptor();
    }
      
    public org.deephacks.westty.tests.ServerMessages.CreateRequest getDefaultInstanceForType() {
      return org.deephacks.westty.tests.ServerMessages.CreateRequest.getDefaultInstance();
    }
      
    public org.deephacks.westty.tests.ServerMessages.CreateRequest build() {
      org.deephacks.westty.tests.ServerMessages.CreateRequest result = buildPartial();
      if (!result.isInitialized()) {
        throw newUninitializedMessageException(result);
      }
      return result;
    }
      
    private org.deephacks.westty.tests.ServerMessages.CreateRequest buildParsed()
        throws com.google.protobuf.InvalidProtocolBufferException {
      org.deephacks.westty.tests.ServerMessages.CreateRequest result = buildPartial();
      if (!result.isInitialized()) {
        throw newUninitializedMessageException(
          result).asInvalidProtocolBufferException();
      }
      return result;
    }
      
    public org.deephacks.westty.tests.ServerMessages.CreateRequest buildPartial() {
      org.deephacks.westty.tests.ServerMessages.CreateRequest result = new org.deephacks.westty.tests.ServerMessages.CreateRequest(this);
      int from_bitField0_ = bitField0_;
      int to_bitField0_ = 0;
      if (((from_bitField0_ & 0x00000001) == 0x00000001)) {
        to_bitField0_ |= 0x00000001;
      }
      result.protoType_ = protoType_;
      if (((from_bitField0_ & 0x00000002) == 0x00000002)) {
        to_bitField0_ |= 0x00000002;
      }
      if (jsonBuilder_ == null) {
        result.json_ = json_;
      } else {
        result.json_ = jsonBuilder_.build();
      }
      result.bitField0_ = to_bitField0_;
      onBuilt();
      return result;
    }
      
    public Builder mergeFrom(com.google.protobuf.Message other) {
      if (other instanceof org.deephacks.westty.tests.ServerMessages.CreateRequest) {
        return mergeFrom((org.deephacks.westty.tests.ServerMessages.CreateRequest)other);
      } else {
        super.mergeFrom(other);
        return this;
      }
    }
      
    public Builder mergeFrom(org.deephacks.westty.tests.ServerMessages.CreateRequest other) {
      if (other == org.deephacks.westty.tests.ServerMessages.CreateRequest.getDefaultInstance()) return this;
      if (other.hasProtoType()) {
        setProtoType(other.getProtoType());
      }
      if (other.hasJson()) {
        mergeJson(other.getJson());
      }
      this.mergeUnknownFields(other.getUnknownFields());
      return this;
    }
      
    public final boolean isInitialized() {
      if (!hasJson()) {
          
        return false;
      }
      if (!getJson().isInitialized()) {
          
        return false;
      }
      return true;
    }
      
    public Builder mergeFrom(
        com.google.protobuf.CodedInputStream input,
        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
        throws java.io.IOException {
      com.google.protobuf.UnknownFieldSet.Builder unknownFields =
        com.google.protobuf.UnknownFieldSet.newBuilder(
          this.getUnknownFields());
      while (true) {
        int tag = input.readTag();
        switch (tag) {
          case 0:
            this.setUnknownFields(unknownFields.build());
            onChanged();
            return this;
          default: {
            if (!parseUnknownField(input, unknownFields,
                                   extensionRegistry, tag)) {
              this.setUnknownFields(unknownFields.build());
              onChanged();
              return this;
            }
            break;
          }
          case 10: {
            org.deephacks.westty.tests.ServerMessages.JsonMessage.Builder subBuilder = org.deephacks.westty.tests.ServerMessages.JsonMessage.newBuilder();
            if (hasJson()) {
              subBuilder.mergeFrom(getJson());
            }
            input.readMessage(subBuilder, extensionRegistry);
            setJson(subBuilder.buildPartial());
            break;
          }
          case 2408: {
            bitField0_ |= 0x00000001;
            protoType_ = input.readUInt32();
            break;
          }
        }
      }
    }
      
    private int bitField0_;
      
    // optional uint32 protoType = 301;
    private int protoType_ ;
    public boolean hasProtoType() {
      return ((bitField0_ & 0x00000001) == 0x00000001);
    }
    public int getProtoType() {
      return protoType_;
    }
    public Builder setProtoType(int value) {
      bitField0_ |= 0x00000001;
      protoType_ = value;
      onChanged();
      return this;
    }
    public Builder clearProtoType() {
      bitField0_ = (bitField0_ & ~0x00000001);
      protoType_ = 0;
      onChanged();
      return this;
    }
      
    // required .westty.tests.JsonMessage json = 1;
    private org.deephacks.westty.tests.ServerMessages.JsonMessage json_ = org.deephacks.westty.tests.ServerMessages.JsonMessage.getDefaultInstance();
    private com.google.protobuf.SingleFieldBuilder<
        org.deephacks.westty.tests.ServerMessages.JsonMessage, org.deephacks.westty.tests.ServerMessages.JsonMessage.Builder, org.deephacks.westty.tests.ServerMessages.JsonMessageOrBuilder> jsonBuilder_;
    public boolean hasJson() {
      return ((bitField0_ & 0x00000002) == 0x00000002);
    }
    public org.deephacks.westty.tests.ServerMessages.JsonMessage getJson() {
      if (jsonBuilder_ == null) {
        return json_;
      } else {
        return jsonBuilder_.getMessage();
      }
    }
    public Builder setJson(org.deephacks.westty.tests.ServerMessages.JsonMessage value) {
      if (jsonBuilder_ == null) {
        if (value == null) {
          throw new NullPointerException();
        }
        json_ = value;
        onChanged();
      } else {
        jsonBuilder_.setMessage(value);
      }
      bitField0_ |= 0x00000002;
      return this;
    }
    public Builder setJson(
        org.deephacks.westty.tests.ServerMessages.JsonMessage.Builder builderForValue) {
      if (jsonBuilder_ == null) {
        json_ = builderForValue.build();
        onChanged();
      } else {
        jsonBuilder_.setMessage(builderForValue.build());
      }
      bitField0_ |= 0x00000002;
      return this;
    }
    public Builder mergeJson(org.deephacks.westty.tests.ServerMessages.JsonMessage value) {
      if (jsonBuilder_ == null) {
        if (((bitField0_ & 0x00000002) == 0x00000002) &&
            json_ != org.deephacks.westty.tests.ServerMessages.JsonMessage.getDefaultInstance()) {
          json_ =
            org.deephacks.westty.tests.ServerMessages.JsonMessage.newBuilder(json_).mergeFrom(value).buildPartial();
        } else {
          json_ = value;
        }
        onChanged();
      } else {
        jsonBuilder_.mergeFrom(value);
      }
      bitField0_ |= 0x00000002;
      return this;
    }
    public Builder clearJson() {
      if (jsonBuilder_ == null) {
        json_ = org.deephacks.westty.tests.ServerMessages.JsonMessage.getDefaultInstance();
        onChanged();
      } else {
        jsonBuilder_.clear();
      }
      bitField0_ = (bitField0_ & ~0x00000002);
      return this;
    }
    public org.deephacks.westty.tests.ServerMessages.JsonMessage.Builder getJsonBuilder() {
      bitField0_ |= 0x00000002;
      onChanged();
      return getJsonFieldBuilder().getBuilder();
    }
    public org.deephacks.westty.tests.ServerMessages.JsonMessageOrBuilder getJsonOrBuilder() {
      if (jsonBuilder_ != null) {
        return jsonBuilder_.getMessageOrBuilder();
      } else {
        return json_;
      }
    }
    private com.google.protobuf.SingleFieldBuilder<
        org.deephacks.westty.tests.ServerMessages.JsonMessage, org.deephacks.westty.tests.ServerMessages.JsonMessage.Builder, org.deephacks.westty.tests.ServerMessages.JsonMessageOrBuilder> 
        getJsonFieldBuilder() {
      if (jsonBuilder_ == null) {
        jsonBuilder_ = new com.google.protobuf.SingleFieldBuilder<
            org.deephacks.westty.tests.ServerMessages.JsonMessage, org.deephacks.westty.tests.ServerMessages.JsonMessage.Builder, org.deephacks.westty.tests.ServerMessages.JsonMessageOrBuilder>(
                json_,
                getParentForChildren(),
                isClean());
        json_ = null;
      }
      return jsonBuilder_;
    }
      
    // @@protoc_insertion_point(builder_scope:westty.tests.CreateRequest)
  }
    
  static {
    defaultInstance = new CreateRequest(true);
    defaultInstance.initFields();
  }
    
  // @@protoc_insertion_point(class_scope:westty.tests.CreateRequest)
} public static final class JsonMessage extends
    com.google.protobuf.GeneratedMessage
    implements JsonMessageOrBuilder {
  // Use JsonMessage.newBuilder() to construct.
  private JsonMessage(Builder builder) {
    super(builder);
  }
  private JsonMessage(boolean noInit) {}
    
  private static final JsonMessage defaultInstance;
  public static JsonMessage getDefaultInstance() {
    return defaultInstance;
  }
    
  public JsonMessage getDefaultInstanceForType() {
    return defaultInstance;
  }
    
  public static final com.google.protobuf.Descriptors.Descriptor
      getDescriptor() {
    return org.deephacks.westty.tests.ServerMessages.internal_static_westty_tests_JsonMessage_descriptor;
  }
    
  protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
      internalGetFieldAccessorTable() {
    return org.deephacks.westty.tests.ServerMessages.internal_static_westty_tests_JsonMessage_fieldAccessorTable;
  }
    
  private int bitField0_;
  // optional uint32 protoType = 300;
  public static final int PROTOTYPE_FIELD_NUMBER = 300;
  private int protoType_;
  public boolean hasProtoType() {
    return ((bitField0_ & 0x00000001) == 0x00000001);
  }
  public int getProtoType() {
    return protoType_;
  }
    
  // required string id = 1;
  public static final int ID_FIELD_NUMBER = 1;
  private java.lang.Object id_;
  public boolean hasId() {
    return ((bitField0_ & 0x00000002) == 0x00000002);
  }
  public String getId() {
    java.lang.Object ref = id_;
    if (ref instanceof String) {
      return (String) ref;
    } else {
      com.google.protobuf.ByteString bs = 
          (com.google.protobuf.ByteString) ref;
      String s = bs.toStringUtf8();
      if (com.google.protobuf.Internal.isValidUtf8(bs)) {
        id_ = s;
      }
      return s;
    }
  }
  private com.google.protobuf.ByteString getIdBytes() {
    java.lang.Object ref = id_;
    if (ref instanceof String) {
      com.google.protobuf.ByteString b = 
          com.google.protobuf.ByteString.copyFromUtf8((String) ref);
      id_ = b;
      return b;
    } else {
      return (com.google.protobuf.ByteString) ref;
    }
  }
    
  // required string json = 2;
  public static final int JSON_FIELD_NUMBER = 2;
  private java.lang.Object json_;
  public boolean hasJson() {
    return ((bitField0_ & 0x00000004) == 0x00000004);
  }
  public String getJson() {
    java.lang.Object ref = json_;
    if (ref instanceof String) {
      return (String) ref;
    } else {
      com.google.protobuf.ByteString bs = 
          (com.google.protobuf.ByteString) ref;
      String s = bs.toStringUtf8();
      if (com.google.protobuf.Internal.isValidUtf8(bs)) {
        json_ = s;
      }
      return s;
    }
  }
  private com.google.protobuf.ByteString getJsonBytes() {
    java.lang.Object ref = json_;
    if (ref instanceof String) {
      com.google.protobuf.ByteString b = 
          com.google.protobuf.ByteString.copyFromUtf8((String) ref);
      json_ = b;
      return b;
    } else {
      return (com.google.protobuf.ByteString) ref;
    }
  }
    
  private void initFields() {
    protoType_ = 0;
    id_ = "";
    json_ = "";
  }
  private byte memoizedIsInitialized = -1;
  public final boolean isInitialized() {
    byte isInitialized = memoizedIsInitialized;
    if (isInitialized != -1) return isInitialized == 1;
      
    if (!hasId()) {
      memoizedIsInitialized = 0;
      return false;
    }
    if (!hasJson()) {
      memoizedIsInitialized = 0;
      return false;
    }
    memoizedIsInitialized = 1;
    return true;
  }
    
  public void writeTo(com.google.protobuf.CodedOutputStream output)
                      throws java.io.IOException {
    getSerializedSize();
    if (((bitField0_ & 0x00000002) == 0x00000002)) {
      output.writeBytes(1, getIdBytes());
    }
    if (((bitField0_ & 0x00000004) == 0x00000004)) {
      output.writeBytes(2, getJsonBytes());
    }
    if (((bitField0_ & 0x00000001) == 0x00000001)) {
      output.writeUInt32(300, protoType_);
    }
    getUnknownFields().writeTo(output);
  }
    
  private int memoizedSerializedSize = -1;
  public int getSerializedSize() {
    int size = memoizedSerializedSize;
    if (size != -1) return size;
    
    size = 0;
    if (((bitField0_ & 0x00000002) == 0x00000002)) {
      size += com.google.protobuf.CodedOutputStream
        .computeBytesSize(1, getIdBytes());
    }
    if (((bitField0_ & 0x00000004) == 0x00000004)) {
      size += com.google.protobuf.CodedOutputStream
        .computeBytesSize(2, getJsonBytes());
    }
    if (((bitField0_ & 0x00000001) == 0x00000001)) {
      size += com.google.protobuf.CodedOutputStream
        .computeUInt32Size(300, protoType_);
    }
    size += getUnknownFields().getSerializedSize();
    memoizedSerializedSize = size;
    return size;
  }
    
  private static final long serialVersionUID = 0L;
  @java.lang.Override
  protected java.lang.Object writeReplace()
      throws java.io.ObjectStreamException {
    return super.writeReplace();
  }
    
  public static org.deephacks.westty.tests.ServerMessages.JsonMessage parseFrom(
      com.google.protobuf.ByteString data)
      throws com.google.protobuf.InvalidProtocolBufferException {
    return newBuilder().mergeFrom(data).buildParsed();
  }
  public static org.deephacks.westty.tests.ServerMessages.JsonMessage parseFrom(
      com.google.protobuf.ByteString data,
      com.google.protobuf.ExtensionRegistryLite extensionRegistry)
      throws com.google.protobuf.InvalidProtocolBufferException {
    return newBuilder().mergeFrom(data, extensionRegistry)
             .buildParsed();
  }
  public static org.deephacks.westty.tests.ServerMessages.JsonMessage parseFrom(byte[] data)
      throws com.google.protobuf.InvalidProtocolBufferException {
    return newBuilder().mergeFrom(data).buildParsed();
  }
  public static org.deephacks.westty.tests.ServerMessages.JsonMessage parseFrom(
      byte[] data,
      com.google.protobuf.ExtensionRegistryLite extensionRegistry)
      throws com.google.protobuf.InvalidProtocolBufferException {
    return newBuilder().mergeFrom(data, extensionRegistry)
             .buildParsed();
  }
  public static org.deephacks.westty.tests.ServerMessages.JsonMessage parseFrom(java.io.InputStream input)
      throws java.io.IOException {
    return newBuilder().mergeFrom(input).buildParsed();
  }
  public static org.deephacks.westty.tests.ServerMessages.JsonMessage parseFrom(
      java.io.InputStream input,
      com.google.protobuf.ExtensionRegistryLite extensionRegistry)
      throws java.io.IOException {
    return newBuilder().mergeFrom(input, extensionRegistry)
             .buildParsed();
  }
  public static org.deephacks.westty.tests.ServerMessages.JsonMessage parseDelimitedFrom(java.io.InputStream input)
      throws java.io.IOException {
    Builder builder = newBuilder();
    if (builder.mergeDelimitedFrom(input)) {
      return builder.buildParsed();
    } else {
      return null;
    }
  }
  public static org.deephacks.westty.tests.ServerMessages.JsonMessage parseDelimitedFrom(
      java.io.InputStream input,
      com.google.protobuf.ExtensionRegistryLite extensionRegistry)
      throws java.io.IOException {
    Builder builder = newBuilder();
    if (builder.mergeDelimitedFrom(input, extensionRegistry)) {
      return builder.buildParsed();
    } else {
      return null;
    }
  }
  public static org.deephacks.westty.tests.ServerMessages.JsonMessage parseFrom(
      com.google.protobuf.CodedInputStream input)
      throws java.io.IOException {
    return newBuilder().mergeFrom(input).buildParsed();
  }
  public static org.deephacks.westty.tests.ServerMessages.JsonMessage parseFrom(
      com.google.protobuf.CodedInputStream input,
      com.google.protobuf.ExtensionRegistryLite extensionRegistry)
      throws java.io.IOException {
    return newBuilder().mergeFrom(input, extensionRegistry)
             .buildParsed();
  }
    
  public static Builder newBuilder() { return Builder.create(); }
  public Builder newBuilderForType() { return newBuilder(); }
  public static Builder newBuilder(org.deephacks.westty.tests.ServerMessages.JsonMessage prototype) {
    return newBuilder().mergeFrom(prototype);
  }
  public Builder toBuilder() { return newBuilder(this); }
    
  @java.lang.Override
  protected Builder newBuilderForType(
      com.google.protobuf.GeneratedMessage.BuilderParent parent) {
    Builder builder = new Builder(parent);
    return builder;
  }
  public static final class Builder extends
      com.google.protobuf.GeneratedMessage.Builder<Builder>
     implements org.deephacks.westty.tests.ServerMessages.JsonMessageOrBuilder {
    public static final com.google.protobuf.Descriptors.Descriptor
        getDescriptor() {
      return org.deephacks.westty.tests.ServerMessages.internal_static_westty_tests_JsonMessage_descriptor;
    }
      
    protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
        internalGetFieldAccessorTable() {
      return org.deephacks.westty.tests.ServerMessages.internal_static_westty_tests_JsonMessage_fieldAccessorTable;
    }
      
    // Construct using org.deephacks.westty.tests.ServerMessages.JsonMessage.newBuilder()
    private Builder() {
      maybeForceBuilderInitialization();
    }
      
    private Builder(BuilderParent parent) {
      super(parent);
      maybeForceBuilderInitialization();
    }
    private void maybeForceBuilderInitialization() {
      if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {
      }
    }
    private static Builder create() {
      return new Builder();
    }
      
    public Builder clear() {
      super.clear();
      protoType_ = 0;
      bitField0_ = (bitField0_ & ~0x00000001);
      id_ = "";
      bitField0_ = (bitField0_ & ~0x00000002);
      json_ = "";
      bitField0_ = (bitField0_ & ~0x00000004);
      return this;
    }
      
    public Builder clone() {
      return create().mergeFrom(buildPartial());
    }
      
    public com.google.protobuf.Descriptors.Descriptor
        getDescriptorForType() {
      return org.deephacks.westty.tests.ServerMessages.JsonMessage.getDescriptor();
    }
      
    public org.deephacks.westty.tests.ServerMessages.JsonMessage getDefaultInstanceForType() {
      return org.deephacks.westty.tests.ServerMessages.JsonMessage.getDefaultInstance();
    }
      
    public org.deephacks.westty.tests.ServerMessages.JsonMessage build() {
      org.deephacks.westty.tests.ServerMessages.JsonMessage result = buildPartial();
      if (!result.isInitialized()) {
        throw newUninitializedMessageException(result);
      }
      return result;
    }
      
    private org.deephacks.westty.tests.ServerMessages.JsonMessage buildParsed()
        throws com.google.protobuf.InvalidProtocolBufferException {
      org.deephacks.westty.tests.ServerMessages.JsonMessage result = buildPartial();
      if (!result.isInitialized()) {
        throw newUninitializedMessageException(
          result).asInvalidProtocolBufferException();
      }
      return result;
    }
      
    public org.deephacks.westty.tests.ServerMessages.JsonMessage buildPartial() {
      org.deephacks.westty.tests.ServerMessages.JsonMessage result = new org.deephacks.westty.tests.ServerMessages.JsonMessage(this);
      int from_bitField0_ = bitField0_;
      int to_bitField0_ = 0;
      if (((from_bitField0_ & 0x00000001) == 0x00000001)) {
        to_bitField0_ |= 0x00000001;
      }
      result.protoType_ = protoType_;
      if (((from_bitField0_ & 0x00000002) == 0x00000002)) {
        to_bitField0_ |= 0x00000002;
      }
      result.id_ = id_;
      if (((from_bitField0_ & 0x00000004) == 0x00000004)) {
        to_bitField0_ |= 0x00000004;
      }
      result.json_ = json_;
      result.bitField0_ = to_bitField0_;
      onBuilt();
      return result;
    }
      
    public Builder mergeFrom(com.google.protobuf.Message other) {
      if (other instanceof org.deephacks.westty.tests.ServerMessages.JsonMessage) {
        return mergeFrom((org.deephacks.westty.tests.ServerMessages.JsonMessage)other);
      } else {
        super.mergeFrom(other);
        return this;
      }
    }
      
    public Builder mergeFrom(org.deephacks.westty.tests.ServerMessages.JsonMessage other) {
      if (other == org.deephacks.westty.tests.ServerMessages.JsonMessage.getDefaultInstance()) return this;
      if (other.hasProtoType()) {
        setProtoType(other.getProtoType());
      }
      if (other.hasId()) {
        setId(other.getId());
      }
      if (other.hasJson()) {
        setJson(other.getJson());
      }
      this.mergeUnknownFields(other.getUnknownFields());
      return this;
    }
      
    public final boolean isInitialized() {
      if (!hasId()) {
          
        return false;
      }
      if (!hasJson()) {
          
        return false;
      }
      return true;
    }
      
    public Builder mergeFrom(
        com.google.protobuf.CodedInputStream input,
        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
        throws java.io.IOException {
      com.google.protobuf.UnknownFieldSet.Builder unknownFields =
        com.google.protobuf.UnknownFieldSet.newBuilder(
          this.getUnknownFields());
      while (true) {
        int tag = input.readTag();
        switch (tag) {
          case 0:
            this.setUnknownFields(unknownFields.build());
            onChanged();
            return this;
          default: {
            if (!parseUnknownField(input, unknownFields,
                                   extensionRegistry, tag)) {
              this.setUnknownFields(unknownFields.build());
              onChanged();
              return this;
            }
            break;
          }
          case 10: {
            bitField0_ |= 0x00000002;
            id_ = input.readBytes();
            break;
          }
          case 18: {
            bitField0_ |= 0x00000004;
            json_ = input.readBytes();
            break;
          }
          case 2400: {
            bitField0_ |= 0x00000001;
            protoType_ = input.readUInt32();
            break;
          }
        }
      }
    }
      
    private int bitField0_;
      
    // optional uint32 protoType = 300;
    private int protoType_ ;
    public boolean hasProtoType() {
      return ((bitField0_ & 0x00000001) == 0x00000001);
    }
    public int getProtoType() {
      return protoType_;
    }
    public Builder setProtoType(int value) {
      bitField0_ |= 0x00000001;
      protoType_ = value;
      onChanged();
      return this;
    }
    public Builder clearProtoType() {
      bitField0_ = (bitField0_ & ~0x00000001);
      protoType_ = 0;
      onChanged();
      return this;
    }
      
    // required string id = 1;
    private java.lang.Object id_ = "";
    public boolean hasId() {
      return ((bitField0_ & 0x00000002) == 0x00000002);
    }
    public String getId() {
      java.lang.Object ref = id_;
      if (!(ref instanceof String)) {
        String s = ((com.google.protobuf.ByteString) ref).toStringUtf8();
        id_ = s;
        return s;
      } else {
        return (String) ref;
      }
    }
    public Builder setId(String value) {
      if (value == null) {
  throw new NullPointerException();
}
bitField0_ |= 0x00000002;
      id_ = value;
      onChanged();
      return this;
    }
    public Builder clearId() {
      bitField0_ = (bitField0_ & ~0x00000002);
      id_ = getDefaultInstance().getId();
      onChanged();
      return this;
    }
    void setId(com.google.protobuf.ByteString value) {
      bitField0_ |= 0x00000002;
      id_ = value;
      onChanged();
    }
      
    // required string json = 2;
    private java.lang.Object json_ = "";
    public boolean hasJson() {
      return ((bitField0_ & 0x00000004) == 0x00000004);
    }
    public String getJson() {
      java.lang.Object ref = json_;
      if (!(ref instanceof String)) {
        String s = ((com.google.protobuf.ByteString) ref).toStringUtf8();
        json_ = s;
        return s;
      } else {
        return (String) ref;
      }
    }
    public Builder setJson(String value) {
      if (value == null) {
  throw new NullPointerException();
}
bitField0_ |= 0x00000004;
      json_ = value;
      onChanged();
      return this;
    }
    public Builder clearJson() {
      bitField0_ = (bitField0_ & ~0x00000004);
      json_ = getDefaultInstance().getJson();
      onChanged();
      return this;
    }
    void setJson(com.google.protobuf.ByteString value) {
      bitField0_ |= 0x00000004;
      json_ = value;
      onChanged();
    }
      
    // @@protoc_insertion_point(builder_scope:westty.tests.JsonMessage)
  }
    
  static {
    defaultInstance = new JsonMessage(true);
    defaultInstance.initFields();
  }
    
  // @@protoc_insertion_point(class_scope:westty.tests.JsonMessage)
} public static final class ListRequest extends
    com.google.protobuf.GeneratedMessage
    implements ListRequestOrBuilder {
  // Use ListRequest.newBuilder() to construct.
  private ListRequest(Builder builder) {
    super(builder);
  }
  private ListRequest(boolean noInit) {}
    
  private static final ListRequest defaultInstance;
  public static ListRequest getDefaultInstance() {
    return defaultInstance;
  }
    
  public ListRequest getDefaultInstanceForType() {
    return defaultInstance;
  }
    
  public static final com.google.protobuf.Descriptors.Descriptor
      getDescriptor() {
    return org.deephacks.westty.tests.ServerMessages.internal_static_westty_tests_ListRequest_descriptor;
  }
    
  protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
      internalGetFieldAccessorTable() {
    return org.deephacks.westty.tests.ServerMessages.internal_static_westty_tests_ListRequest_fieldAccessorTable;
  }
    
  private int bitField0_;
  // optional uint32 protoType = 302;
  public static final int PROTOTYPE_FIELD_NUMBER = 302;
  private int protoType_;
  public boolean hasProtoType() {
    return ((bitField0_ & 0x00000001) == 0x00000001);
  }
  public int getProtoType() {
    return protoType_;
  }
    
  private void initFields() {
    protoType_ = 0;
  }
  private byte memoizedIsInitialized = -1;
  public final boolean isInitialized() {
    byte isInitialized = memoizedIsInitialized;
    if (isInitialized != -1) return isInitialized == 1;
      
    memoizedIsInitialized = 1;
    return true;
  }
    
  public void writeTo(com.google.protobuf.CodedOutputStream output)
                      throws java.io.IOException {
    getSerializedSize();
    if (((bitField0_ & 0x00000001) == 0x00000001)) {
      output.writeUInt32(302, protoType_);
    }
    getUnknownFields().writeTo(output);
  }
    
  private int memoizedSerializedSize = -1;
  public int getSerializedSize() {
    int size = memoizedSerializedSize;
    if (size != -1) return size;
    
    size = 0;
    if (((bitField0_ & 0x00000001) == 0x00000001)) {
      size += com.google.protobuf.CodedOutputStream
        .computeUInt32Size(302, protoType_);
    }
    size += getUnknownFields().getSerializedSize();
    memoizedSerializedSize = size;
    return size;
  }
    
  private static final long serialVersionUID = 0L;
  @java.lang.Override
  protected java.lang.Object writeReplace()
      throws java.io.ObjectStreamException {
    return super.writeReplace();
  }
    
  public static org.deephacks.westty.tests.ServerMessages.ListRequest parseFrom(
      com.google.protobuf.ByteString data)
      throws com.google.protobuf.InvalidProtocolBufferException {
    return newBuilder().mergeFrom(data).buildParsed();
  }
  public static org.deephacks.westty.tests.ServerMessages.ListRequest parseFrom(
      com.google.protobuf.ByteString data,
      com.google.protobuf.ExtensionRegistryLite extensionRegistry)
      throws com.google.protobuf.InvalidProtocolBufferException {
    return newBuilder().mergeFrom(data, extensionRegistry)
             .buildParsed();
  }
  public static org.deephacks.westty.tests.ServerMessages.ListRequest parseFrom(byte[] data)
      throws com.google.protobuf.InvalidProtocolBufferException {
    return newBuilder().mergeFrom(data).buildParsed();
  }
  public static org.deephacks.westty.tests.ServerMessages.ListRequest parseFrom(
      byte[] data,
      com.google.protobuf.ExtensionRegistryLite extensionRegistry)
      throws com.google.protobuf.InvalidProtocolBufferException {
    return newBuilder().mergeFrom(data, extensionRegistry)
             .buildParsed();
  }
  public static org.deephacks.westty.tests.ServerMessages.ListRequest parseFrom(java.io.InputStream input)
      throws java.io.IOException {
    return newBuilder().mergeFrom(input).buildParsed();
  }
  public static org.deephacks.westty.tests.ServerMessages.ListRequest parseFrom(
      java.io.InputStream input,
      com.google.protobuf.ExtensionRegistryLite extensionRegistry)
      throws java.io.IOException {
    return newBuilder().mergeFrom(input, extensionRegistry)
             .buildParsed();
  }
  public static org.deephacks.westty.tests.ServerMessages.ListRequest parseDelimitedFrom(java.io.InputStream input)
      throws java.io.IOException {
    Builder builder = newBuilder();
    if (builder.mergeDelimitedFrom(input)) {
      return builder.buildParsed();
    } else {
      return null;
    }
  }
  public static org.deephacks.westty.tests.ServerMessages.ListRequest parseDelimitedFrom(
      java.io.InputStream input,
      com.google.protobuf.ExtensionRegistryLite extensionRegistry)
      throws java.io.IOException {
    Builder builder = newBuilder();
    if (builder.mergeDelimitedFrom(input, extensionRegistry)) {
      return builder.buildParsed();
    } else {
      return null;
    }
  }
  public static org.deephacks.westty.tests.ServerMessages.ListRequest parseFrom(
      com.google.protobuf.CodedInputStream input)
      throws java.io.IOException {
    return newBuilder().mergeFrom(input).buildParsed();
  }
  public static org.deephacks.westty.tests.ServerMessages.ListRequest parseFrom(
      com.google.protobuf.CodedInputStream input,
      com.google.protobuf.ExtensionRegistryLite extensionRegistry)
      throws java.io.IOException {
    return newBuilder().mergeFrom(input, extensionRegistry)
             .buildParsed();
  }
    
  public static Builder newBuilder() { return Builder.create(); }
  public Builder newBuilderForType() { return newBuilder(); }
  public static Builder newBuilder(org.deephacks.westty.tests.ServerMessages.ListRequest prototype) {
    return newBuilder().mergeFrom(prototype);
  }
  public Builder toBuilder() { return newBuilder(this); }
    
  @java.lang.Override
  protected Builder newBuilderForType(
      com.google.protobuf.GeneratedMessage.BuilderParent parent) {
    Builder builder = new Builder(parent);
    return builder;
  }
  public static final class Builder extends
      com.google.protobuf.GeneratedMessage.Builder<Builder>
     implements org.deephacks.westty.tests.ServerMessages.ListRequestOrBuilder {
    public static final com.google.protobuf.Descriptors.Descriptor
        getDescriptor() {
      return org.deephacks.westty.tests.ServerMessages.internal_static_westty_tests_ListRequest_descriptor;
    }
      
    protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
        internalGetFieldAccessorTable() {
      return org.deephacks.westty.tests.ServerMessages.internal_static_westty_tests_ListRequest_fieldAccessorTable;
    }
      
    // Construct using org.deephacks.westty.tests.ServerMessages.ListRequest.newBuilder()
    private Builder() {
      maybeForceBuilderInitialization();
    }
      
    private Builder(BuilderParent parent) {
      super(parent);
      maybeForceBuilderInitialization();
    }
    private void maybeForceBuilderInitialization() {
      if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {
      }
    }
    private static Builder create() {
      return new Builder();
    }
      
    public Builder clear() {
      super.clear();
      protoType_ = 0;
      bitField0_ = (bitField0_ & ~0x00000001);
      return this;
    }
      
    public Builder clone() {
      return create().mergeFrom(buildPartial());
    }
      
    public com.google.protobuf.Descriptors.Descriptor
        getDescriptorForType() {
      return org.deephacks.westty.tests.ServerMessages.ListRequest.getDescriptor();
    }
      
    public org.deephacks.westty.tests.ServerMessages.ListRequest getDefaultInstanceForType() {
      return org.deephacks.westty.tests.ServerMessages.ListRequest.getDefaultInstance();
    }
      
    public org.deephacks.westty.tests.ServerMessages.ListRequest build() {
      org.deephacks.westty.tests.ServerMessages.ListRequest result = buildPartial();
      if (!result.isInitialized()) {
        throw newUninitializedMessageException(result);
      }
      return result;
    }
      
    private org.deephacks.westty.tests.ServerMessages.ListRequest buildParsed()
        throws com.google.protobuf.InvalidProtocolBufferException {
      org.deephacks.westty.tests.ServerMessages.ListRequest result = buildPartial();
      if (!result.isInitialized()) {
        throw newUninitializedMessageException(
          result).asInvalidProtocolBufferException();
      }
      return result;
    }
      
    public org.deephacks.westty.tests.ServerMessages.ListRequest buildPartial() {
      org.deephacks.westty.tests.ServerMessages.ListRequest result = new org.deephacks.westty.tests.ServerMessages.ListRequest(this);
      int from_bitField0_ = bitField0_;
      int to_bitField0_ = 0;
      if (((from_bitField0_ & 0x00000001) == 0x00000001)) {
        to_bitField0_ |= 0x00000001;
      }
      result.protoType_ = protoType_;
      result.bitField0_ = to_bitField0_;
      onBuilt();
      return result;
    }
      
    public Builder mergeFrom(com.google.protobuf.Message other) {
      if (other instanceof org.deephacks.westty.tests.ServerMessages.ListRequest) {
        return mergeFrom((org.deephacks.westty.tests.ServerMessages.ListRequest)other);
      } else {
        super.mergeFrom(other);
        return this;
      }
    }
      
    public Builder mergeFrom(org.deephacks.westty.tests.ServerMessages.ListRequest other) {
      if (other == org.deephacks.westty.tests.ServerMessages.ListRequest.getDefaultInstance()) return this;
      if (other.hasProtoType()) {
        setProtoType(other.getProtoType());
      }
      this.mergeUnknownFields(other.getUnknownFields());
      return this;
    }
      
    public final boolean isInitialized() {
      return true;
    }
      
    public Builder mergeFrom(
        com.google.protobuf.CodedInputStream input,
        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
        throws java.io.IOException {
      com.google.protobuf.UnknownFieldSet.Builder unknownFields =
        com.google.protobuf.UnknownFieldSet.newBuilder(
          this.getUnknownFields());
      while (true) {
        int tag = input.readTag();
        switch (tag) {
          case 0:
            this.setUnknownFields(unknownFields.build());
            onChanged();
            return this;
          default: {
            if (!parseUnknownField(input, unknownFields,
                                   extensionRegistry, tag)) {
              this.setUnknownFields(unknownFields.build());
              onChanged();
              return this;
            }
            break;
          }
          case 2416: {
            bitField0_ |= 0x00000001;
            protoType_ = input.readUInt32();
            break;
          }
        }
      }
    }
      
    private int bitField0_;
      
    // optional uint32 protoType = 302;
    private int protoType_ ;
    public boolean hasProtoType() {
      return ((bitField0_ & 0x00000001) == 0x00000001);
    }
    public int getProtoType() {
      return protoType_;
    }
    public Builder setProtoType(int value) {
      bitField0_ |= 0x00000001;
      protoType_ = value;
      onChanged();
      return this;
    }
    public Builder clearProtoType() {
      bitField0_ = (bitField0_ & ~0x00000001);
      protoType_ = 0;
      onChanged();
      return this;
    }
      
    // @@protoc_insertion_point(builder_scope:westty.tests.ListRequest)
  }
    
  static {
    defaultInstance = new ListRequest(true);
    defaultInstance.initFields();
  }
    
  // @@protoc_insertion_point(class_scope:westty.tests.ListRequest)
} public static final class ListResponse extends
    com.google.protobuf.GeneratedMessage
    implements ListResponseOrBuilder {
  // Use ListResponse.newBuilder() to construct.
  private ListResponse(Builder builder) {
    super(builder);
  }
  private ListResponse(boolean noInit) {}
    
  private static final ListResponse defaultInstance;
  public static ListResponse getDefaultInstance() {
    return defaultInstance;
  }
    
  public ListResponse getDefaultInstanceForType() {
    return defaultInstance;
  }
    
  public static final com.google.protobuf.Descriptors.Descriptor
      getDescriptor() {
    return org.deephacks.westty.tests.ServerMessages.internal_static_westty_tests_ListResponse_descriptor;
  }
    
  protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
      internalGetFieldAccessorTable() {
    return org.deephacks.westty.tests.ServerMessages.internal_static_westty_tests_ListResponse_fieldAccessorTable;
  }
    
  private int bitField0_;
  // optional uint32 protoType = 303;
  public static final int PROTOTYPE_FIELD_NUMBER = 303;
  private int protoType_;
  public boolean hasProtoType() {
    return ((bitField0_ & 0x00000001) == 0x00000001);
  }
  public int getProtoType() {
    return protoType_;
  }
    
  // repeated .westty.tests.JsonMessage json = 1;
  public static final int JSON_FIELD_NUMBER = 1;
  private java.util.List<org.deephacks.westty.tests.ServerMessages.JsonMessage> json_;
  public java.util.List<org.deephacks.westty.tests.ServerMessages.JsonMessage> getJsonList() {
    return json_;
  }
  public java.util.List<? extends org.deephacks.westty.tests.ServerMessages.JsonMessageOrBuilder> 
      getJsonOrBuilderList() {
    return json_;
  }
  public int getJsonCount() {
    return json_.size();
  }
  public org.deephacks.westty.tests.ServerMessages.JsonMessage getJson(int index) {
    return json_.get(index);
  }
  public org.deephacks.westty.tests.ServerMessages.JsonMessageOrBuilder getJsonOrBuilder(
      int index) {
    return json_.get(index);
  }
    
  private void initFields() {
    protoType_ = 0;
    json_ = java.util.Collections.emptyList();
  }
  private byte memoizedIsInitialized = -1;
  public final boolean isInitialized() {
    byte isInitialized = memoizedIsInitialized;
    if (isInitialized != -1) return isInitialized == 1;
      
    for (int i = 0; i < getJsonCount(); i++) {
      if (!getJson(i).isInitialized()) {
        memoizedIsInitialized = 0;
        return false;
      }
    }
    memoizedIsInitialized = 1;
    return true;
  }
    
  public void writeTo(com.google.protobuf.CodedOutputStream output)
                      throws java.io.IOException {
    getSerializedSize();
    for (int i = 0; i < json_.size(); i++) {
      output.writeMessage(1, json_.get(i));
    }
    if (((bitField0_ & 0x00000001) == 0x00000001)) {
      output.writeUInt32(303, protoType_);
    }
    getUnknownFields().writeTo(output);
  }
    
  private int memoizedSerializedSize = -1;
  public int getSerializedSize() {
    int size = memoizedSerializedSize;
    if (size != -1) return size;
    
    size = 0;
    for (int i = 0; i < json_.size(); i++) {
      size += com.google.protobuf.CodedOutputStream
        .computeMessageSize(1, json_.get(i));
    }
    if (((bitField0_ & 0x00000001) == 0x00000001)) {
      size += com.google.protobuf.CodedOutputStream
        .computeUInt32Size(303, protoType_);
    }
    size += getUnknownFields().getSerializedSize();
    memoizedSerializedSize = size;
    return size;
  }
    
  private static final long serialVersionUID = 0L;
  @java.lang.Override
  protected java.lang.Object writeReplace()
      throws java.io.ObjectStreamException {
    return super.writeReplace();
  }
    
  public static org.deephacks.westty.tests.ServerMessages.ListResponse parseFrom(
      com.google.protobuf.ByteString data)
      throws com.google.protobuf.InvalidProtocolBufferException {
    return newBuilder().mergeFrom(data).buildParsed();
  }
  public static org.deephacks.westty.tests.ServerMessages.ListResponse parseFrom(
      com.google.protobuf.ByteString data,
      com.google.protobuf.ExtensionRegistryLite extensionRegistry)
      throws com.google.protobuf.InvalidProtocolBufferException {
    return newBuilder().mergeFrom(data, extensionRegistry)
             .buildParsed();
  }
  public static org.deephacks.westty.tests.ServerMessages.ListResponse parseFrom(byte[] data)
      throws com.google.protobuf.InvalidProtocolBufferException {
    return newBuilder().mergeFrom(data).buildParsed();
  }
  public static org.deephacks.westty.tests.ServerMessages.ListResponse parseFrom(
      byte[] data,
      com.google.protobuf.ExtensionRegistryLite extensionRegistry)
      throws com.google.protobuf.InvalidProtocolBufferException {
    return newBuilder().mergeFrom(data, extensionRegistry)
             .buildParsed();
  }
  public static org.deephacks.westty.tests.ServerMessages.ListResponse parseFrom(java.io.InputStream input)
      throws java.io.IOException {
    return newBuilder().mergeFrom(input).buildParsed();
  }
  public static org.deephacks.westty.tests.ServerMessages.ListResponse parseFrom(
      java.io.InputStream input,
      com.google.protobuf.ExtensionRegistryLite extensionRegistry)
      throws java.io.IOException {
    return newBuilder().mergeFrom(input, extensionRegistry)
             .buildParsed();
  }
  public static org.deephacks.westty.tests.ServerMessages.ListResponse parseDelimitedFrom(java.io.InputStream input)
      throws java.io.IOException {
    Builder builder = newBuilder();
    if (builder.mergeDelimitedFrom(input)) {
      return builder.buildParsed();
    } else {
      return null;
    }
  }
  public static org.deephacks.westty.tests.ServerMessages.ListResponse parseDelimitedFrom(
      java.io.InputStream input,
      com.google.protobuf.ExtensionRegistryLite extensionRegistry)
      throws java.io.IOException {
    Builder builder = newBuilder();
    if (builder.mergeDelimitedFrom(input, extensionRegistry)) {
      return builder.buildParsed();
    } else {
      return null;
    }
  }
  public static org.deephacks.westty.tests.ServerMessages.ListResponse parseFrom(
      com.google.protobuf.CodedInputStream input)
      throws java.io.IOException {
    return newBuilder().mergeFrom(input).buildParsed();
  }
  public static org.deephacks.westty.tests.ServerMessages.ListResponse parseFrom(
      com.google.protobuf.CodedInputStream input,
      com.google.protobuf.ExtensionRegistryLite extensionRegistry)
      throws java.io.IOException {
    return newBuilder().mergeFrom(input, extensionRegistry)
             .buildParsed();
  }
    
  public static Builder newBuilder() { return Builder.create(); }
  public Builder newBuilderForType() { return newBuilder(); }
  public static Builder newBuilder(org.deephacks.westty.tests.ServerMessages.ListResponse prototype) {
    return newBuilder().mergeFrom(prototype);
  }
  public Builder toBuilder() { return newBuilder(this); }
    
  @java.lang.Override
  protected Builder newBuilderForType(
      com.google.protobuf.GeneratedMessage.BuilderParent parent) {
    Builder builder = new Builder(parent);
    return builder;
  }
  public static final class Builder extends
      com.google.protobuf.GeneratedMessage.Builder<Builder>
     implements org.deephacks.westty.tests.ServerMessages.ListResponseOrBuilder {
    public static final com.google.protobuf.Descriptors.Descriptor
        getDescriptor() {
      return org.deephacks.westty.tests.ServerMessages.internal_static_westty_tests_ListResponse_descriptor;
    }
      
    protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
        internalGetFieldAccessorTable() {
      return org.deephacks.westty.tests.ServerMessages.internal_static_westty_tests_ListResponse_fieldAccessorTable;
    }
      
    // Construct using org.deephacks.westty.tests.ServerMessages.ListResponse.newBuilder()
    private Builder() {
      maybeForceBuilderInitialization();
    }
      
    private Builder(BuilderParent parent) {
      super(parent);
      maybeForceBuilderInitialization();
    }
    private void maybeForceBuilderInitialization() {
      if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {
        getJsonFieldBuilder();
      }
    }
    private static Builder create() {
      return new Builder();
    }
      
    public Builder clear() {
      super.clear();
      protoType_ = 0;
      bitField0_ = (bitField0_ & ~0x00000001);
      if (jsonBuilder_ == null) {
        json_ = java.util.Collections.emptyList();
        bitField0_ = (bitField0_ & ~0x00000002);
      } else {
        jsonBuilder_.clear();
      }
      return this;
    }
      
    public Builder clone() {
      return create().mergeFrom(buildPartial());
    }
      
    public com.google.protobuf.Descriptors.Descriptor
        getDescriptorForType() {
      return org.deephacks.westty.tests.ServerMessages.ListResponse.getDescriptor();
    }
      
    public org.deephacks.westty.tests.ServerMessages.ListResponse getDefaultInstanceForType() {
      return org.deephacks.westty.tests.ServerMessages.ListResponse.getDefaultInstance();
    }
      
    public org.deephacks.westty.tests.ServerMessages.ListResponse build() {
      org.deephacks.westty.tests.ServerMessages.ListResponse result = buildPartial();
      if (!result.isInitialized()) {
        throw newUninitializedMessageException(result);
      }
      return result;
    }
      
    private org.deephacks.westty.tests.ServerMessages.ListResponse buildParsed()
        throws com.google.protobuf.InvalidProtocolBufferException {
      org.deephacks.westty.tests.ServerMessages.ListResponse result = buildPartial();
      if (!result.isInitialized()) {
        throw newUninitializedMessageException(
          result).asInvalidProtocolBufferException();
      }
      return result;
    }
      
    public org.deephacks.westty.tests.ServerMessages.ListResponse buildPartial() {
      org.deephacks.westty.tests.ServerMessages.ListResponse result = new org.deephacks.westty.tests.ServerMessages.ListResponse(this);
      int from_bitField0_ = bitField0_;
      int to_bitField0_ = 0;
      if (((from_bitField0_ & 0x00000001) == 0x00000001)) {
        to_bitField0_ |= 0x00000001;
      }
      result.protoType_ = protoType_;
      if (jsonBuilder_ == null) {
        if (((bitField0_ & 0x00000002) == 0x00000002)) {
          json_ = java.util.Collections.unmodifiableList(json_);
          bitField0_ = (bitField0_ & ~0x00000002);
        }
        result.json_ = json_;
      } else {
        result.json_ = jsonBuilder_.build();
      }
      result.bitField0_ = to_bitField0_;
      onBuilt();
      return result;
    }
      
    public Builder mergeFrom(com.google.protobuf.Message other) {
      if (other instanceof org.deephacks.westty.tests.ServerMessages.ListResponse) {
        return mergeFrom((org.deephacks.westty.tests.ServerMessages.ListResponse)other);
      } else {
        super.mergeFrom(other);
        return this;
      }
    }
      
    public Builder mergeFrom(org.deephacks.westty.tests.ServerMessages.ListResponse other) {
      if (other == org.deephacks.westty.tests.ServerMessages.ListResponse.getDefaultInstance()) return this;
      if (other.hasProtoType()) {
        setProtoType(other.getProtoType());
      }
      if (jsonBuilder_ == null) {
        if (!other.json_.isEmpty()) {
          if (json_.isEmpty()) {
            json_ = other.json_;
            bitField0_ = (bitField0_ & ~0x00000002);
          } else {
            ensureJsonIsMutable();
            json_.addAll(other.json_);
          }
          onChanged();
        }
      } else {
        if (!other.json_.isEmpty()) {
          if (jsonBuilder_.isEmpty()) {
            jsonBuilder_.dispose();
            jsonBuilder_ = null;
            json_ = other.json_;
            bitField0_ = (bitField0_ & ~0x00000002);
            jsonBuilder_ = 
              com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ?
                 getJsonFieldBuilder() : null;
          } else {
            jsonBuilder_.addAllMessages(other.json_);
          }
        }
      }
      this.mergeUnknownFields(other.getUnknownFields());
      return this;
    }
      
    public final boolean isInitialized() {
      for (int i = 0; i < getJsonCount(); i++) {
        if (!getJson(i).isInitialized()) {
            
          return false;
        }
      }
      return true;
    }
      
    public Builder mergeFrom(
        com.google.protobuf.CodedInputStream input,
        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
        throws java.io.IOException {
      com.google.protobuf.UnknownFieldSet.Builder unknownFields =
        com.google.protobuf.UnknownFieldSet.newBuilder(
          this.getUnknownFields());
      while (true) {
        int tag = input.readTag();
        switch (tag) {
          case 0:
            this.setUnknownFields(unknownFields.build());
            onChanged();
            return this;
          default: {
            if (!parseUnknownField(input, unknownFields,
                                   extensionRegistry, tag)) {
              this.setUnknownFields(unknownFields.build());
              onChanged();
              return this;
            }
            break;
          }
          case 10: {
            org.deephacks.westty.tests.ServerMessages.JsonMessage.Builder subBuilder = org.deephacks.westty.tests.ServerMessages.JsonMessage.newBuilder();
            input.readMessage(subBuilder, extensionRegistry);
            addJson(subBuilder.buildPartial());
            break;
          }
          case 2424: {
            bitField0_ |= 0x00000001;
            protoType_ = input.readUInt32();
            break;
          }
        }
      }
    }
      
    private int bitField0_;
      
    // optional uint32 protoType = 303;
    private int protoType_ ;
    public boolean hasProtoType() {
      return ((bitField0_ & 0x00000001) == 0x00000001);
    }
    public int getProtoType() {
      return protoType_;
    }
    public Builder setProtoType(int value) {
      bitField0_ |= 0x00000001;
      protoType_ = value;
      onChanged();
      return this;
    }
    public Builder clearProtoType() {
      bitField0_ = (bitField0_ & ~0x00000001);
      protoType_ = 0;
      onChanged();
      return this;
    }
      
    // repeated .westty.tests.JsonMessage json = 1;
    private java.util.List<org.deephacks.westty.tests.ServerMessages.JsonMessage> json_ =
      java.util.Collections.emptyList();
    private void ensureJsonIsMutable() {
      if (!((bitField0_ & 0x00000002) == 0x00000002)) {
        json_ = new java.util.ArrayList<org.deephacks.westty.tests.ServerMessages.JsonMessage>(json_);
        bitField0_ |= 0x00000002;
       }
    }
      
    private com.google.protobuf.RepeatedFieldBuilder<
        org.deephacks.westty.tests.ServerMessages.JsonMessage, org.deephacks.westty.tests.ServerMessages.JsonMessage.Builder, org.deephacks.westty.tests.ServerMessages.JsonMessageOrBuilder> jsonBuilder_;
      
    public java.util.List<org.deephacks.westty.tests.ServerMessages.JsonMessage> getJsonList() {
      if (jsonBuilder_ == null) {
        return java.util.Collections.unmodifiableList(json_);
      } else {
        return jsonBuilder_.getMessageList();
      }
    }
    public int getJsonCount() {
      if (jsonBuilder_ == null) {
        return json_.size();
      } else {
        return jsonBuilder_.getCount();
      }
    }
    public org.deephacks.westty.tests.ServerMessages.JsonMessage getJson(int index) {
      if (jsonBuilder_ == null) {
        return json_.get(index);
      } else {
        return jsonBuilder_.getMessage(index);
      }
    }
    public Builder setJson(
        int index, org.deephacks.westty.tests.ServerMessages.JsonMessage value) {
      if (jsonBuilder_ == null) {
        if (value == null) {
          throw new NullPointerException();
        }
        ensureJsonIsMutable();
        json_.set(index, value);
        onChanged();
      } else {
        jsonBuilder_.setMessage(index, value);
      }
      return this;
    }
    public Builder setJson(
        int index, org.deephacks.westty.tests.ServerMessages.JsonMessage.Builder builderForValue) {
      if (jsonBuilder_ == null) {
        ensureJsonIsMutable();
        json_.set(index, builderForValue.build());
        onChanged();
      } else {
        jsonBuilder_.setMessage(index, builderForValue.build());
      }
      return this;
    }
    public Builder addJson(org.deephacks.westty.tests.ServerMessages.JsonMessage value) {
      if (jsonBuilder_ == null) {
        if (value == null) {
          throw new NullPointerException();
        }
        ensureJsonIsMutable();
        json_.add(value);
        onChanged();
      } else {
        jsonBuilder_.addMessage(value);
      }
      return this;
    }
    public Builder addJson(
        int index, org.deephacks.westty.tests.ServerMessages.JsonMessage value) {
      if (jsonBuilder_ == null) {
        if (value == null) {
          throw new NullPointerException();
        }
        ensureJsonIsMutable();
        json_.add(index, value);
        onChanged();
      } else {
        jsonBuilder_.addMessage(index, value);
      }
      return this;
    }
    public Builder addJson(
        org.deephacks.westty.tests.ServerMessages.JsonMessage.Builder builderForValue) {
      if (jsonBuilder_ == null) {
        ensureJsonIsMutable();
        json_.add(builderForValue.build());
        onChanged();
      } else {
        jsonBuilder_.addMessage(builderForValue.build());
      }
      return this;
    }
    public Builder addJson(
        int index, org.deephacks.westty.tests.ServerMessages.JsonMessage.Builder builderForValue) {
      if (jsonBuilder_ == null) {
        ensureJsonIsMutable();
        json_.add(index, builderForValue.build());
        onChanged();
      } else {
        jsonBuilder_.addMessage(index, builderForValue.build());
      }
      return this;
    }
    public Builder addAllJson(
        java.lang.Iterable<? extends org.deephacks.westty.tests.ServerMessages.JsonMessage> values) {
      if (jsonBuilder_ == null) {
        ensureJsonIsMutable();
        super.addAll(values, json_);
        onChanged();
      } else {
        jsonBuilder_.addAllMessages(values);
      }
      return this;
    }
    public Builder clearJson() {
      if (jsonBuilder_ == null) {
        json_ = java.util.Collections.emptyList();
        bitField0_ = (bitField0_ & ~0x00000002);
        onChanged();
      } else {
        jsonBuilder_.clear();
      }
      return this;
    }
    public Builder removeJson(int index) {
      if (jsonBuilder_ == null) {
        ensureJsonIsMutable();
        json_.remove(index);
        onChanged();
      } else {
        jsonBuilder_.remove(index);
      }
      return this;
    }
    public org.deephacks.westty.tests.ServerMessages.JsonMessage.Builder getJsonBuilder(
        int index) {
      return getJsonFieldBuilder().getBuilder(index);
    }
    public org.deephacks.westty.tests.ServerMessages.JsonMessageOrBuilder getJsonOrBuilder(
        int index) {
      if (jsonBuilder_ == null) {
        return json_.get(index);  } else {
        return jsonBuilder_.getMessageOrBuilder(index);
      }
    }
    public java.util.List<? extends org.deephacks.westty.tests.ServerMessages.JsonMessageOrBuilder> 
         getJsonOrBuilderList() {
      if (jsonBuilder_ != null) {
        return jsonBuilder_.getMessageOrBuilderList();
      } else {
        return java.util.Collections.unmodifiableList(json_);
      }
    }
    public org.deephacks.westty.tests.ServerMessages.JsonMessage.Builder addJsonBuilder() {
      return getJsonFieldBuilder().addBuilder(
          org.deephacks.westty.tests.ServerMessages.JsonMessage.getDefaultInstance());
    }
    public org.deephacks.westty.tests.ServerMessages.JsonMessage.Builder addJsonBuilder(
        int index) {
      return getJsonFieldBuilder().addBuilder(
          index, org.deephacks.westty.tests.ServerMessages.JsonMessage.getDefaultInstance());
    }
    public java.util.List<org.deephacks.westty.tests.ServerMessages.JsonMessage.Builder> 
         getJsonBuilderList() {
      return getJsonFieldBuilder().getBuilderList();
    }
    private com.google.protobuf.RepeatedFieldBuilder<
        org.deephacks.westty.tests.ServerMessages.JsonMessage, org.deephacks.westty.tests.ServerMessages.JsonMessage.Builder, org.deephacks.westty.tests.ServerMessages.JsonMessageOrBuilder> 
        getJsonFieldBuilder() {
      if (jsonBuilder_ == null) {
        jsonBuilder_ = new com.google.protobuf.RepeatedFieldBuilder<
            org.deephacks.westty.tests.ServerMessages.JsonMessage, org.deephacks.westty.tests.ServerMessages.JsonMessage.Builder, org.deephacks.westty.tests.ServerMessages.JsonMessageOrBuilder>(
                json_,
                ((bitField0_ & 0x00000002) == 0x00000002),
                getParentForChildren(),
                isClean());
        json_ = null;
      }
      return jsonBuilder_;
    }
      
    // @@protoc_insertion_point(builder_scope:westty.tests.ListResponse)
  }
    
  static {
    defaultInstance = new ListResponse(true);
    defaultInstance.initFields();
  }
    
  // @@protoc_insertion_point(class_scope:westty.tests.ListResponse)
}
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import org.deephacks.confit.ConfigContext;
import org.deephacks.confit.admin.AdminContext;
import org.deephacks.confit.jaxrs.AdminContextJaxrsProxy;
import org.deephacks.westty.config.DataSourceConfig;
import org.deephacks.westty.config.ProtobufConfig;
import org.deephacks.westty.config.ServerConfig;
import org.deephacks.westty.internal.jaxrs.JaxrsApplication;
import org.deephacks.westty.protobuf.ProtobufClient;
import org.deephacks.westty.protobuf.ProtobufSerializer;
import org.deephacks.westty.spi.IoExecutors;
import org.deephacks.westty.test.SQLExec;
import org.deephacks.westty.test.TestBootstrap;
import org.deephacks.westty.test.WesttyJUnit4Runner;
import org.deephacks.westty.tests.JsonEntity.Protocol;
import org.deephacks.westty.tests.ServerMessages.CreateRequest;
import org.deephacks.westty.tests.ServerMessages.JsonMessage;
import org.deephacks.westty.tests.ServerMessages.ListRequest;
import org.deephacks.westty.tests.ServerMessages.ListResponse;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.LoggerFactory;
import org.vertx.java.core.Handler;
import org.vertx.java.core.eventbus.EventBus;
import org.vertx.java.core.eventbus.Message;
import javax.inject.Inject;
import java.util.List;
import java.util.UUID;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import static org.junit.matchers.JUnitMatchers.hasItem;
package org.deephacks.westty.tests;




@RunWith(WesttyJUnit4Runner.class)
public class ServerIntegrationTest {
    private static final ProtobufSerializer serializer = new ProtobufSerializer();
    private static final String TABLE = "CREATE TABLE JSON (ID varchar(255), JSON varchar(1024), PROTOCOL varchar(255));";
    private static final ProtobufClient protobuf = new ProtobufClient(new IoExecutors(), serializer, new ProtobufConfig());
    private static final JaxrsClient jaxrs = new JaxrsClient();
    private static final String URI_PREFIX = JaxrsApplication.JAXRS_CONTEXT_URI + ServerEndpoint.JAXRS_PATH;
    private static final ConfigContext config = ConfigContext.get();

    @Inject
    private EventBus bus;

    @TestBootstrap
    public static void bootstrap() throws Exception {
        Logger root = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
        root.setLevel(Level.DEBUG);
        serializer.registerResource("META-INF/server.desc");
        DataSourceConfig dataSourceConfig = config.get(DataSourceConfig.class);
        SQLExec sql = new SQLExec(dataSourceConfig.getUser(), dataSourceConfig.getPassword(), dataSourceConfig.getUrl());
        sql.execute(TABLE);
        sql.executeResource("META-INF/install_config_derby.ddl", false);
    }

    /**
     * Test that jpa can be used from a jaxrs endpoint.
     */
    @Test
    public void test_jaxrs_and_jpa() {
        AdminContext admin = AdminContextJaxrsProxy.get(ServerConfig.DEFAULT_IP_ADDRESS, ServerConfig.DEFAULT_HTTP_PORT, "jaxrs");
        admin.list(ServerConfig.class);
        JsonEntity entity = new JsonEntity(UUID.randomUUID().toString(), Protocol.JAXRS, "test");
        jaxrs.posthttp(URI_PREFIX + "/create", JsonUtil.toJson(entity));
        List<JsonEntity> list = JsonUtil.fromJsonList(jaxrs.gethttp(URI_PREFIX + "/list"));
        assertThat(list, hasItem(entity));
    }
    /**
     * Test that multiple jpa transactionl methods can
     * be executed and rollbacked as one transaction.
     */
    @Test
    public void test_nested_jpa_transaction(){
        JsonEntity entity = new JsonEntity(UUID.randomUUID().toString(), Protocol.JAXRS, "test");
        jaxrs.posthttp(URI_PREFIX + "/nested", JsonUtil.toJson(entity));
        List<JsonEntity> list = JsonUtil.fromJsonList(jaxrs.gethttp(URI_PREFIX + "/list"));
        assertThat(list, not(hasItem(entity)));
    }
    /**
     * Test that jpa can be used from a protobuf endpoint.
     */
    @Test
    public void test_protobuf_and_jpa() throws Exception {
        String id = UUID.randomUUID().toString();
        JsonMessage msg = JsonMessage.newBuilder().setId(id).setJson("msg").build();