Example usage for org.apache.thrift.transport TIOStreamTransport TIOStreamTransport

List of usage examples for org.apache.thrift.transport TIOStreamTransport TIOStreamTransport

Introduction

In this page you can find the example usage for org.apache.thrift.transport TIOStreamTransport TIOStreamTransport.

Prototype

public TIOStreamTransport(InputStream is, OutputStream os) 

Source Link

Document

Two-way stream constructor.

Usage

From source file:com.funtl.framework.rpc.thrift.spring.ThriftServiceExporter.java

License:Apache License

@Override
public void handleRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    if (!"POST".equals(request.getMethod())) {
        throw new HttpRequestMethodNotSupportedException(request.getMethod(), new String[] { "POST" },
                "ThriftServiceExporter only supports POST requests");
    }//from w w  w  . j  a v a  2  s  .  c o  m

    InputStream in = request.getInputStream();
    OutputStream out = response.getOutputStream();
    try {
        ThriftContextHolder.init();
        response.setContentType("application/x-thrift");
        TTransport transport = new TIOStreamTransport(in, out);

        TProtocol protocol = getProtocolFactory().getProtocol(transport);
        TProcessor processor = ThriftUtil.buildProcessor(getServiceInterface(), getProxyForService());
        processor.process(protocol, protocol);
    } catch (Throwable e) {
        response.setContentType("text/plain; charset=UTF-8");
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        e.printStackTrace(new PrintWriter(out, true));
        if (LOGGER.isErrorEnabled()) {
            LOGGER.error("Thrift server direct error", e);
        }
    } finally {
        ThriftContextHolder.reset();
    }
}

From source file:com.prolucid.thriftshell.ThriftSerializer.java

License:Apache License

public void initialize(OutputStream processIn, InputStream processOut) {
    this.protocol = new TBinaryProtocol(
            new TIOStreamTransport(new BufferedInputStream(processOut), new BufferedOutputStream(processIn)));
}

From source file:com.sample.HelloWorldWithUnity3d.PingVerticle.java

License:Apache License

void startHttpServer() {
    HttpServer server = vertx.createHttpServer();
    RouteMatcher routeMatcher = new RouteMatcher();

    routeMatcher.get("/", new Handler<HttpServerRequest>() {
        public void handle(HttpServerRequest req) {
            req.response().headers().set("Content-Type", "text/html; charset=UTF-8");
            System.out.println("Hello World!");

            TestReq fooBarMessage = new TestReq();
            fooBarMessage.key = 123456789;
            fooBarMessage.value = "abc";
            ByteArrayOutputStream outStream = new ByteArrayOutputStream(256);
            TProtocol tProtocol = new TBinaryProtocol(new TIOStreamTransport(null, outStream));

            try {
                fooBarMessage.write(tProtocol);
            } catch (TException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();/*from ww w.j a  va 2 s  .  c om*/
            }

            byte[] content = outStream.toByteArray();

            tProtocol = new TBinaryProtocol(new TIOStreamTransport(new ByteArrayInputStream(content), null));
            TestReq fooBarMessage2 = new TestReq();
            try {
                fooBarMessage2.read(tProtocol);
            } catch (TException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

            try {
                //  
                Session session = HibernateUtil.getCurrentSession();
                MyTestTable entity = (MyTestTable) session.get(MyTestTable.class, 1);
                entity.setName("bbb");
                Transaction tx = session.beginTransaction();
                session.update(entity);
                tx.commit();
                req.response().end("Hello World " + entity.getName());
            } catch (HibernateException e) {
                e.printStackTrace();
            } finally {
                //  
                HibernateUtil.closeSession();
            }
        }
    });

    routeMatcher.get("/login", new Handler<HttpServerRequest>() {
        public void handle(HttpServerRequest req) {

            try {

                String sid = GetSessionId(req);
                if (sid == null) {
                    req.response().headers().set("Set-Cookie",
                            ServerCookieEncoder.encode(new DefaultCookie("sessionId", generateSessionId())));
                }

                KeyPair keyPair = RSA.CreateKeyPair();

                PublicKey publicKey = keyPair.getPublic();
                PrivateKey privateKey = keyPair.getPrivate();

                RSAPublicKeySpec publicSpec = RSA.GetPublicKeySpec(keyPair);

                byte[] publicKeyModulus = publicSpec.getModulus().toByteArray();
                byte[] publicKeyExponent = publicSpec.getPublicExponent().toByteArray();

                // test
                byte[] encryptedData = RSA.Encrypt(publicKey, "haha!");
                String decryptedText = RSA.DecryptToString(privateKey, encryptedData);

                JsonObject json = new JsonObject();
                json.putBinary("publicKeyModulus", publicKeyModulus);
                json.putBinary("publicKeyExponent", publicKeyExponent);

                UserSession userSession = new UserSession();
                userSession.privateKey = privateKey;

                vertx.sharedData().getMap("1").put("userSession", userSession);
                req.response().end(json.toString());

            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
    });

    routeMatcher.post("/hello", new Handler<HttpServerRequest>() {
        public void handle(final HttpServerRequest req) {

            String sid = GetSessionId(req);

            req.bodyHandler(new Handler<Buffer>() {
                @Override
                public void handle(Buffer buff) {
                    String contentType = req.headers().get("Content-Type");
                    if ("application/octet-stream".equals(contentType)) {
                        /*
                         QueryStringDecoder qsd = new QueryStringDecoder(buff.toString(), false);
                         Map<String, List<String>> params = qsd.parameters();
                         System.out.println(params);
                         */

                        UserSession userSession = (UserSession) vertx.sharedData().getMap("1")
                                .get("userSession");

                        try {
                            String decryptedText = RSA.DecryptToString(userSession.privateKey, buff.getBytes());

                            JsonObject json = new JsonObject();
                            json.putString("decryptedText", decryptedText);

                            req.response().end(json.toString());
                        } catch (Exception e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                }
            });
        }
    });

    routeMatcher.post("/name/:name", new Handler<HttpServerRequest>() {
        public void handle(final HttpServerRequest req) {

            req.bodyHandler(new Handler<Buffer>() {
                @Override
                public void handle(Buffer buff) {

                    QueryStringDecoder qsd = new QueryStringDecoder(buff.toString(), false);
                    Map<String, List<String>> params = qsd.parameters();
                    System.out.println(params);

                    req.response().end("Your name is " + req.params().get("name"));
                }
            });

        }
    });

    routeMatcher.put("/age/:age", new Handler<HttpServerRequest>() {
        public void handle(final HttpServerRequest req) {

            req.bodyHandler(new Handler<Buffer>() {
                @Override
                public void handle(Buffer buff) {

                    QueryStringDecoder qsd = new QueryStringDecoder(buff.toString(), false);
                    Map<String, List<String>> params = qsd.parameters();
                    System.out.println(params);

                    if (params.size() > 0)
                        req.response()
                                .end("Your age is " + req.params().get("age") + params.get("name").get(0));
                    else
                        req.response().end("Your age is " + req.params().get("age"));
                }
            });

        }
    });

    routeMatcher.get("/json", new Handler<HttpServerRequest>() {
        public void handle(HttpServerRequest req) {
            JsonObject obj = new JsonObject().putString("name", "chope");
            req.response().end(obj.encode());
        }
    });

    server.requestHandler(routeMatcher).listen(808, "localhost");
}

From source file:com.sample.HelloWorldWithUnity3d.PingVerticle.java

License:Apache License

void startWebsocketServerWithThrift() {
    final EventBus eventBus = vertx.eventBus();
    final Pattern chatUrlPattern = Pattern.compile("/chat/(\\w+)");

    final ThriftHandler<Protocol, ServerWebSocket> thandler = new ThriftHandler<Protocol, ServerWebSocket>();
    thandler.AddHandler(TestReq.class, Protocol.Test1, new ThriftHandler.Handler<ServerWebSocket, TestReq>() {

        @Override//  w w w .j  a v a  2 s  .co  m
        public void DoHandler(ServerWebSocket ws, TestReq req) {
            // TODO Auto-generated method stub
            ByteArrayOutputStream outStream = new ByteArrayOutputStream(256);
            TBinaryProtocol tProtocol = new TBinaryProtocol(new TIOStreamTransport(null, outStream));

            try {
                TestAck testAck = new TestAck();
                testAck.header = new Header();
                testAck.header.key = Protocol.Test1;
                testAck.header.ok = 1;
                //testAck.setIvalue(true);
                testAck.value = "aa";

                testAck.write(tProtocol);
            } catch (TException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            ws.writeBinaryFrame(new Buffer(outStream.toByteArray()));
        }
    });

    thandler.AddHandler(TestReq.class, Protocol.Test2, new ThriftHandler.Handler<ServerWebSocket, TestReq2>() {

        @Override
        public void DoHandler(ServerWebSocket ws, TestReq2 req) {
            // TODO Auto-generated method stub
            ByteArrayOutputStream outStream = new ByteArrayOutputStream(256);
            TBinaryProtocol tProtocol = new TBinaryProtocol(new TIOStreamTransport(null, outStream));

            try {
                Test2Ack testAck = new Test2Ack();
                testAck.header = new Header();
                testAck.header.key = Protocol.Test1;
                testAck.header.ok = 1;
                //testAck.setIvalue(true);

                testAck.write(tProtocol);
            } catch (TException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            ws.writeBinaryFrame(new Buffer(outStream.toByteArray()));
        }
    });

    vertx.createHttpServer().websocketHandler(new Handler<ServerWebSocket>() {

        @Override
        public void handle(final ServerWebSocket ws) {
            final Matcher m = chatUrlPattern.matcher(ws.path());
            if (!m.matches()) {
                ws.reject();
                return;
            }

            final String chatRoom = m.group(1);
            final String id = ws.textHandlerID();
            System.out.println("registering new connection with id: " + id + " for chat-room: " + chatRoom);
            vertx.sharedData().getSet("chat.room." + chatRoom).add(id);

            ws.closeHandler(new Handler<Void>() {
                @Override
                public void handle(final Void event) {
                    System.out.println(
                            "un-registering connection with id: " + id + " from chat-room: " + chatRoom);
                    vertx.sharedData().getSet("chat.room." + chatRoom).remove(id);
                }
            });

            ws.dataHandler(new Handler<Buffer>() {
                @Override
                public void handle(final Buffer data) {

                    try {
                        ByteArrayInputStream stream = new ByteArrayInputStream(data.getBytes());
                        TProtocol tProtocol = new TBinaryProtocol(new TIOStreamTransport(stream, null));
                        tProtocol.readStructBegin();
                        tProtocol.readFieldBegin();
                        Header header = new Header();
                        header.read(tProtocol);
                        stream.reset();

                        thandler.DoHandle(ws, Protocol.Test1, tProtocol);

                    } catch (Exception e) {
                        ws.reject();
                    }
                }
            });

        }
    }).listen(8091);

}

From source file:com.sample.HelloWorldWithUnity3d.PingVerticle.java

License:Apache License

void startWebsocketServerWithThriftService() {
    MultiplicationHandler handler = new MultiplicationHandler();
    ;/*from  w  w  w .  j a v a2 s . c om*/

    final MultiplicationService.Processor processor = new MultiplicationService.Processor(handler);

    final EventBus eventBus = vertx.eventBus();
    final Pattern chatUrlPattern = Pattern.compile("/chat/(\\w+)");
    vertx.createHttpServer().websocketHandler(new Handler<ServerWebSocket>() {

        @Override
        public void handle(final ServerWebSocket ws) {
            final Matcher m = chatUrlPattern.matcher(ws.path());
            if (!m.matches()) {
                ws.reject();
                return;
            }

            final String chatRoom = m.group(1);
            final String id = ws.textHandlerID();
            System.out.println("registering new connection with id: " + id + " for chat-room: " + chatRoom);
            vertx.sharedData().getSet("chat.room." + chatRoom).add(id);

            ws.closeHandler(new Handler<Void>() {
                @Override
                public void handle(final Void event) {
                    System.out.println(
                            "un-registering connection with id: " + id + " from chat-room: " + chatRoom);
                    vertx.sharedData().getSet("chat.room." + chatRoom).remove(id);
                }
            });

            ws.dataHandler(new Handler<Buffer>() {
                @Override
                public void handle(final Buffer data) {

                    try {

                        TProtocol tInProtocol = new TBinaryProtocol(
                                new TIOStreamTransport(new ByteArrayInputStream(data.getBytes()), null));
                        ByteArrayOutputStream outStream = new ByteArrayOutputStream(data.length());
                        TProtocol tOutProtocol = new TBinaryProtocol(new TIOStreamTransport(null, outStream));

                        processor.process(tInProtocol, tOutProtocol);

                        TestReq fooBarMessage2 = new TestReq();
                        ws.writeBinaryFrame(new Buffer(outStream.toByteArray()));

                    } catch (Exception e) {
                        ws.reject();
                    }
                }
            });

        }
    }).listen(8092);
}

From source file:com.sleepycat.client.BdbServerConnection.java

License:Open Source License

/**
 * For unit test only.// www .j  a  v a  2s.c  o  m
 *
 * @param clientIn the input stream
 * @param clientOut the out stream
 */
BdbServerConnection(InputStream clientIn, OutputStream clientOut) {
    this.host = "test";
    this.port = 0;
    TProtocol protocol = new TCompactProtocol(new TIOStreamTransport(clientIn, clientOut));
    this.client = new BdbService.Client(protocol);
}

From source file:com.sleepycat.client.IOStreamServerTransport.java

License:Open Source License

public IOStreamServerTransport(InputStream in, OutputStream out) {
    this.transport = new TIOStreamTransport(in, out);
}

From source file:com.twitter.common.io.ThriftCodec.java

License:Apache License

@Override
public void serialize(T item, OutputStream sink) throws IOException {
    Preconditions.checkNotNull(item);/* w  w w .  ja va  2s  .com*/
    Preconditions.checkNotNull(sink);
    try {
        item.write(protocolFactory.apply(new TIOStreamTransport(null, sink)));
    } catch (TException e) {
        throw new IOException("Problem serializing thrift struct: " + item, e);
    }
}

From source file:com.twitter.common.io.ThriftCodec.java

License:Apache License

@Override
public T deserialize(InputStream source) throws IOException {
    Preconditions.checkNotNull(source);/*  w ww  .  java2 s  .  com*/
    T template = templateSupplier.get();
    try {
        template.read(protocolFactory.apply(new TIOStreamTransport(source, null)));
    } catch (TException e) {
        throw new IOException("Problem de-serializing thrift struct from stream", e);
    }
    return template;
}

From source file:org.apache.accumulo.core.rpc.TTimeoutTransport.java

License:Apache License

public static TTransport create(SocketAddress addr, long timeoutMillis) throws IOException {
    Socket socket = null;//  w w  w.j a  va  2 s .com
    try {
        socket = SelectorProvider.provider().openSocketChannel().socket();
        socket.setSoLinger(false, 0);
        socket.setTcpNoDelay(true);
        socket.connect(addr);
        InputStream input = new BufferedInputStream(getInputStream(socket, timeoutMillis), 1024 * 10);
        OutputStream output = new BufferedOutputStream(NetUtils.getOutputStream(socket, timeoutMillis),
                1024 * 10);
        return new TIOStreamTransport(input, output);
    } catch (IOException e) {
        try {
            if (socket != null)
                socket.close();
        } catch (IOException ioe) {
        }

        throw e;
    }
}