public static void main(String[] args) throws TTransportException, IOException, InterruptedException { TNonblockingServerSocket trans_svr = new TNonblockingServerSocket(9090); TMultiplexedProcessor proc = new TMultiplexedProcessor(); proc.registerProcessor("Message", new Message.Processor<>(new MessageHandler())); proc.registerProcessor("ServerTime", new ServerTime.Processor<>(new ServerTimeHandler())); TServer server = new TThreadedSelectorServer( new TThreadedSelectorServer.Args(trans_svr) .processor(proc) .protocolFactory(new TJSONProtocol.Factory()) .workerThreads(6) .selectorThreads(3)); Thread server_thread = new Thread(new RunnableServer(server), "server_thread"); server_thread.start(); System.out.println("[Server] press enter to shutdown> "); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); br.readLine(); System.out.println("[Server] shutting down..."); server.stop(); server_thread.join(); System.out.println("[Server] down, exiting"); }
@Override public TServiceClient makeObject() throws Exception { TSocket tsocket = new TSocket(server.getHost(), server.getPort()); tsocket.open(); // TTransport transport = new TFramedTransport(tsocket); TJSONProtocol protocol = new TJSONProtocol(tsocket); TMultiplexedProtocol uProtocol=new TMultiplexedProtocol(protocol, proccessName); TServiceClient client = this.clientFactory.getClient(uProtocol); if (callback != null) { try { callback.make(client); } catch (Exception e) { logger.warn("makeObject:{}", e); } } return client; }
protected TProtocol requestTransport(String url) throws TTransportException { // probably not thread safe, but we need it? Not atm. TTransport act; if (!activeTransports.containsKey(url)) { logger.log(Level.DEBUG ,"Creating new transport for: " + url); activeTransports.put(url, new THttpClient(url)); } act = activeTransports.get(url); if (!act.isOpen()) { act.open(); } // THINK: always create new protocol? return new TJSONProtocol(act); }
public void startServer1() throws Exception { Server server = new Server(9091); ServletHandler handler = new ServletHandler(); AwesomeService.Processor<AwesomeService.Iface> processor = new AwesomeService.Processor<>(referenceServer); ServletHolder holder = new ServletHolder(new TServlet(processor, new TJSONProtocol.Factory())); handler.addFilterWithMapping(CORSFilter.class, "/*", 0); handler.addServletWithMapping(holder, "/*"); server.setHandler(handler); server.start(); logger.info("Started JSON interface."); joinMethods.add(() -> { try { server.join(); } catch (InterruptedException ignored) { } }); }
@Before public void spawnServer() throws Exception { server = new Server(SERVER_PORT); ServletHandler handler = new ServletHandler(); mockedServer = Mockito.mock(AwesomeService.Iface.class); when(mockedServer.getData(any(Request.class))).thenReturn(new Response(Arrays.asList(new DataPoint(), new DataPoint()))); AwesomeService.Processor<AwesomeService.Iface> processor = new AwesomeService.Processor<>(mockedServer); ServletHolder holder = new ServletHolder(new TServlet(processor, new TJSONProtocol.Factory())); handler.addServletWithMapping(holder, "/*"); server.setHandler(handler); server.start(); }
/** * Returns the {@link SerializationFormat} for the specified {@link TProtocolFactory}. * * @throws IllegalArgumentException if the specified {@link TProtocolFactory} is not known by this class */ public static SerializationFormat toSerializationFormat(TProtocolFactory protoFactory) { requireNonNull(protoFactory, "protoFactory"); if (protoFactory instanceof TBinaryProtocol.Factory) { return ThriftSerializationFormats.BINARY; } else if (protoFactory instanceof TCompactProtocol.Factory) { return ThriftSerializationFormats.COMPACT; } else if (protoFactory instanceof TJSONProtocol.Factory) { return ThriftSerializationFormats.JSON; } else if (protoFactory instanceof TTextProtocol.Factory) { return ThriftSerializationFormats.TEXT; } else { throw new IllegalArgumentException( "unsupported TProtocolFactory: " + protoFactory.getClass().getName()); } }
public static void main(String[] args) throws TException { TTransport trans = new TFramedTransport(new TSocket("localhost", 9090)); TProtocol proto = new TJSONProtocol(trans); TMultiplexedProtocol proto_msg = new TMultiplexedProtocol(proto, "Message"); Message.Client client_msg = new Message.Client(proto_msg); TMultiplexedProtocol proto_time = new TMultiplexedProtocol(proto, "ServerTime"); ServerTime.Client client_time = new ServerTime.Client(proto_time); trans.open(); String line; do { System.out.println("Message from server: " + client_msg.motd()); System.out.println("Time at server: " + client_time.time_at_server((short)-1)); System.out.println("Enter to continue, 'q' to quit: "); line = System.console().readLine(); } while (0 != line.compareToIgnoreCase("q")); }
public static TProtocolFactory getProtocolFactory(ThriftProtocol protocol) { // TODO(ruibm): Check whether the Factories are thread safe so we can static initialize // them just once. switch (protocol) { case JSON: return new TJSONProtocol.Factory(); case COMPACT: return new TCompactProtocol.Factory(); case BINARY: return new TBinaryProtocol.Factory(); default: throw new IllegalArgumentException( String.format("Unknown ThriftProtocol [%s].", protocol.toString())); } }
private String thriftRequest(byte[] input){ try{ //Input TMemoryBuffer inbuffer = new TMemoryBuffer(input.length); inbuffer.write(input); TProtocol inprotocol = new TJSONProtocol(inbuffer); //Output TMemoryBuffer outbuffer = new TMemoryBuffer(100); TProtocol outprotocol = new TJSONProtocol(outbuffer); TProcessor processor = new Calculator.Processor(new CalculatorHandler()); processor.process(inprotocol, outprotocol); byte[] output = new byte[outbuffer.length()]; outbuffer.readAll(output, 0, output.length); return new String(output,"UTF-8"); }catch(Throwable t){ return "Error:"+t.getMessage(); } }
private String thriftRequest(byte[] input){ try{ //Input TMemoryBuffer inbuffer = new TMemoryBuffer(input.length); inbuffer.write(input); TProtocol inprotocol = new TJSONProtocol(inbuffer); //Output TMemoryBuffer outbuffer = new TMemoryBuffer(100); TProtocol outprotocol = new TJSONProtocol(outbuffer); TProcessor processor = new ThriftTest.Processor(new TestHandler()); processor.process(inprotocol, outprotocol); byte[] output = new byte[outbuffer.length()]; outbuffer.readAll(output, 0, output.length); return new String(output,"UTF-8"); }catch(Throwable t){ return "Error:"+t.getMessage(); } }
/** * 如果没有设置序列化协议,使用JSON协议 * * @return */ @Bean @ConditionalOnMissingBean(TProtocolFactory.class) public TProtocolFactory tProtocolFactory() { logger.info("init default TProtocol use TJSONProtocol"); return new TJSONProtocol.Factory(); }
public ProtocolFactorySelector(@SuppressWarnings("rawtypes") Class interfaceClass) { protocolFactoryMap.put((short) -32767, new TBinaryProtocol.Factory()); protocolFactoryMap.put((short) -32223, new TCompactProtocol.Factory()); protocolFactoryMap.put((short) 23345, new TJSONProtocol.Factory()); if (interfaceClass != null) { protocolFactoryMap.put((short) 23330, new TSimpleJSONProtocol.Factory(interfaceClass)); } }
private TProtocolFactory getProtocolFactory() { switch (protocol) { case BINARY: return new TBinaryProtocol.Factory(); case COMPACT: return new TCompactProtocol.Factory(); case JSON: return new TJSONProtocol.Factory(); default: throw new AssertionError("Invalid protocol value: " + protocol); } }
/** * Deserialize a Thrift object from JSON. * * @param serializedObject the JSON string representation of the object * @param obj the Thrift object to populate fields * * @throws MetadataException if there is an error deserializing */ public static <T extends TBase> void deserializeObject(String serializedObject, T obj) throws MetadataException { TDeserializer deserializer = new TDeserializer(new TJSONProtocol.Factory()); try { deserializer.deserialize(obj, serializedObject, "UTF-8"); } catch (TException e) { throw new MetadataException(e); } }
static byte[] serialize(AccessControlEntry ace) throws IOException { TMemoryBuffer transport = new TMemoryBuffer(BUFFER_SIZE); TJSONProtocol protocol = new TJSONProtocol(transport); try { ace.write(protocol); transport.flush(); return transport.toString(UTF_8.name()).getBytes(UTF_8); } catch (TException e) { throw new IOException("Failed to serialize access control entry : ", e); } catch (UnsupportedEncodingException uee) { throw new IOException("Failed to serialize acesss control entry : ", uee); } }
static AccessControlEntry deserialize(String zkPath, byte[] data) throws IOException { if (data.length == 0) { return DEFAULT_ACCESS_CONTROL_ENTRY; } AccessControlEntry ace = new AccessControlEntry(); TMemoryInputTransport transport = new TMemoryInputTransport(data); TJSONProtocol protocol = new TJSONProtocol(transport); try { ace.read(protocol); } catch (TException e) { throw new CorruptedAccessControlException(zkPath, e); } return ace; }
/** * 根据配置创建thrift管道的方法 * */ private TProtocol createTProtocol(TTransport transport) { if (tProtocolType == TProtocolType.BINARY) { return new TBinaryProtocol(transport); } else if (tProtocolType == TProtocolType.JSON) { return new TJSONProtocol(transport); } throw new IllegalStateException("暂不支持的管道类型:" + tProtocolType); }
private AwesomeService.Client createClient() throws TTransportException { URIBuilder uriBuilder = new URIBuilder(); uriBuilder.setScheme("http"); uriBuilder.setHost("localhost"); uriBuilder.setPort(SERVER_PORT); TTransport transport = new THttpClient(uriBuilder.toString()); transport.open(); TProtocol protocol = new TJSONProtocol(transport); return new AwesomeService.Client(protocol); }
public static void main(String[] args) throws TTransportException { TServerSocket trans_svr = new TServerSocket(9090); TProcessor proc = new Message.Processor<>(new MessageHandler()); TServer server = new TThreadPoolServer( new TThreadPoolServer.Args(trans_svr) .processor(proc) .protocolFactory(new TJSONProtocol.Factory()) .inputTransportFactory(new TFramedTransport.Factory()) .outputTransportFactory(new TWritelogTransportFactory(100))); server.serve(); }
public static void main(String[] args) throws TException { TTransport trans = new TFramedTransport(new TSocket("localhost", 9090)); TProtocol proto = new TJSONProtocol(trans); Message.Iface client = new Message.Client(proto); trans.open(); String line; do { System.out.println("Message from server: " + client.motd()); System.out.println("Enter to continue, 'q' to quit: "); line = System.console().readLine(); } while (0 != line.compareToIgnoreCase("q")); }
public static void main(String[] args) throws IOException, TException { THttpClient trans = new THttpClient("http://localhost:8080/thrift-servlet"); TJSONProtocol proto = new TJSONProtocol(trans); TradeHistory.Client client = new TradeHistory.Client(proto); for (int i = 0; i < 1000000; i++) { trans.open(); TradeReport tr = client.get_last_sale("AAPL"); trans.close(); } }
public static void main(String[] args) throws TTransportException, IOException { TradeHistory.Processor proc = new TradeHistory.Processor(new TradeHistoryHandler()); TServerSocket trans_svr = new TServerSocket(9090); TThreadPoolServer server = new TThreadPoolServer(new TThreadPoolServer.Args(trans_svr) .protocolFactory(new TJSONProtocol.Factory()) .processor(proc)); System.out.println("[Server] listening of port 9090"); server.serve(); }
public static void main(String[] args) throws IOException, TException { TSocket trans = new TSocket("localhost", 9090); TJSONProtocol proto = new TJSONProtocol(trans); TradeHistory.Client client = new TradeHistory.Client(proto); trans.open(); for (int i = 0; i < 1000000; i++) { TradeReport tr = client.get_last_sale("APPL"); } trans.close(); }
@Override public JobSpecT getJobSpec(UUID jobId) { final String json = jdbc.queryForObject("SELECT str_thrift_spec FROM job_history WHERE pk_job=?", String.class, jobId); final TDeserializer deserializer = new TDeserializer(new TJSONProtocol.Factory()); final JobSpecT spec = new JobSpecT(); try { deserializer.deserialize(spec, json.getBytes()); return spec; } catch (TException e) { throw new JobSpecException("Failed to parse job spec " + e, e); } }
/** * Gets the t protocol. * * @param connectionUrl the connection url * @param connectionTimeout the connection timeout * @return the t protocol * @throws Exception the exception */ private static TProtocol getTProtocol(String connectionUrl, int connectionTimeout) throws Exception { try { THttpClient client = new THttpClient(connectionUrl); client.setConnectTimeout(connectionTimeout); TTransport transport = client; transport.open(); TProtocol protocol = new TJSONProtocol(transport); return protocol; } catch(Exception ex) { logger.error(ex.getMessage(), ex); throw ex; } }
@Test public void testWriteWithValue() throws Exception { TTransport tTransport = new TMemoryBuffer(100); TProtocol tProtocol = new TJSONProtocol(tTransport); Foo foo = new Foo("foo", new ArrayList<String>(), new HashSet<String>(), new HashMap<String, String>()); foo.addToOptionalList("FOO-LIST"); foo.addToOptionalSet("FOO-SET"); foo.putToOptionalMap("FOO-MAP-KEY", "FOO-MAP-VALUE"); Bar bar = new Bar(); bar.setName("bar"); bar.addToBarList("BAR-LIST"); bar.addToBarSet("BAR-SET"); bar.putToBarMap("BAR-MAP-KEY", "BAR-MAP-VALUE"); foo.setBar(bar); Foo wrapped = makeNullSafe(foo); wrapped.write(tProtocol); Foo newFoo = new Foo("new-foo", new ArrayList<String>(), new HashSet<String>(), new HashMap<String, String>()); // read from message newFoo.read(tProtocol); assertThat(newFoo.getOptionalList(), hasItem("FOO-LIST")); assertThat(newFoo.getOptionalSet(), hasItem("FOO-SET")); assertThat(newFoo.getOptionalMap(), hasEntry("FOO-MAP-KEY", "FOO-MAP-VALUE")); assertThat(newFoo.getBar(), is(notNullValue())); assertThat(newFoo.getBar().getName(), is("bar")); assertThat(newFoo.getBar().getBarList(), hasItem("BAR-LIST")); assertThat(newFoo.getBar().getBarSet(), hasItem("BAR-SET")); assertThat(newFoo.getBar().getBarMap(), hasEntry("BAR-MAP-KEY", "BAR-MAP-VALUE")); assertThat(newFoo.getBar().getBaz(), is(nullValue())); }
@Test public void testWriteSetCollectionsToEmpty() throws Exception { TTransport tTransport = new TMemoryBuffer(100); TProtocol tProtocol = new TJSONProtocol(tTransport); // original object has values in collections Foo foo = new Foo("foo", new ArrayList<String>(), new HashSet<String>(), new HashMap<String, String>()); foo.addToOptionalList("FOO-LIST"); foo.addToOptionalSet("FOO-SET"); foo.putToOptionalMap("FOO-MAP-KEY", "FOO-MAP-VALUE"); // wrap it Foo wrapped = makeNullSafe(foo); // make collections empty wrapped.getOptionalList().clear(); wrapped.getOptionalSet().clear(); wrapped.getOptionalMap().clear(); // write wrapped.write(tProtocol); Foo newFoo = new Foo("new-foo", new ArrayList<String>(), new HashSet<String>(), new HashMap<String, String>()); // read from message newFoo.read(tProtocol); // now new object should have empty collections assertThat(newFoo.getName(), is("foo")); assertThat(newFoo.getOptionalList(), is(emptyCollectionOf(String.class))); assertThat(newFoo.getOptionalSet(), is(emptyCollectionOf(String.class))); assertThat(newFoo.getOptionalMap(), is(notNullValue())); assertThat(newFoo.getOptionalMap().size(), is(0)); }
protected TProtocol createThriftProtocol(TTransport transport) { switch(this.protocol) { case BINARY: return new TBinaryProtocol(transport); case JSON: return new TJSONProtocol(transport); case SIMPLE_JSON: return new TSimpleJSONProtocol(transport); default: throw new IllegalArgumentException("Unknown Thrift Protocol."); } }
@Provides @Singleton TServlet provideApiThriftServlet(AnnotatedAuroraAdmin schedulerThriftInterface) { return new TServlet( new AuroraAdmin.Processor<>(schedulerThriftInterface), new TJSONProtocol.Factory()); }
private AuroraAdmin.Client getClient(HttpClient httpClient) throws TTransportException { final TTransport httpClientTransport = new THttpClient(formatUrl(API_PATH), httpClient); addTearDown(httpClientTransport::close); return new AuroraAdmin.Client(new TJSONProtocol(httpClientTransport)); }
@Test public void test_TJSONProtocol() throws Exception { test(new TJSONProtocol.Factory()); }
@Test public void test_AsyncClient() throws Throwable { Random rnd = new Random(System.nanoTime()); TProtocolFactory[] protfacs = new TProtocolFactory[] { new TCompactProtocol.Factory(), new TBinaryProtocol.Factory(), new TJSONProtocol.Factory(), new TSimpleJSONProtocol.Factory(TCalculator.Iface.class, false) }; TProtocolFactory protocolFactory = protfacs[rnd.nextInt(protfacs.length)]; System.out.println("protocolFactory: " + protocolFactory); TAsyncClientManager clientManager = new TAsyncClientManager(); TNonblockingTransport transport = new TNonblockingSocket(HOST, PORT); TCalculator.AsyncClient client = new TCalculator.AsyncClient(protocolFactory, clientManager, transport); final int num1 = rnd.nextInt(Integer.MAX_VALUE / 2 - 1); final int num2 = rnd.nextInt(Integer.MAX_VALUE / 2 - 1); final CountDownLatch latch = new CountDownLatch(1); final Throwable[] exceptions = new Throwable[1]; AsyncMethodCallback<TCalculator.AsyncClient.add_call> resultHandler = new AsyncMethodCallback<TCalculator.AsyncClient.add_call>() { @Override public void onComplete(TCalculator.AsyncClient.add_call response) { System.out.println("onComplete!"); try { int result = response.getResult(); Assert.assertEquals(num1 + num2, result); } catch (Throwable e) { exceptions[0] = e; } finally { latch.countDown(); } } @Override public void onError(Exception exception) { System.err.println("onError!"); exception.printStackTrace(); latch.countDown(); } }; client.add(num1, num2, resultHandler); latch.await(); transport.close(); if (exceptions[0] != null) { throw exceptions[0]; } }
@Override public void deserialize(byte[] data) throws IOException { BKDLConfigFormat configFormat = new BKDLConfigFormat(); TMemoryInputTransport transport = new TMemoryInputTransport(data); TJSONProtocol protocol = new TJSONProtocol(transport); try { configFormat.read(protocol); } catch (TException e) { throw new IOException("Failed to deserialize data '" + new String(data, UTF_8) + "' : ", e); } // bookkeeper cluster settings if (configFormat.isSetBkZkServers()) { bkZkServersForWriter = configFormat.getBkZkServers(); } if (configFormat.isSetBkZkServersForReader()) { bkZkServersForReader = configFormat.getBkZkServersForReader(); } else { bkZkServersForReader = bkZkServersForWriter; } if (configFormat.isSetBkLedgersPath()) { bkLedgersPath = configFormat.getBkLedgersPath(); } // dl zookeeper cluster settings if (configFormat.isSetDlZkServersForWriter()) { dlZkServersForWriter = configFormat.getDlZkServersForWriter(); } if (configFormat.isSetDlZkServersForReader()) { dlZkServersForReader = configFormat.getDlZkServersForReader(); } else { dlZkServersForReader = dlZkServersForWriter; } // dl settings sanityCheckTxnID = !configFormat.isSetSanityCheckTxnID() || configFormat.isSanityCheckTxnID(); encodeRegionID = configFormat.isSetEncodeRegionID() && configFormat.isEncodeRegionID(); if (configFormat.isSetAclRootPath()) { aclRootPath = configFormat.getAclRootPath(); } if (configFormat.isSetFirstLogSegmentSeqNo()) { firstLogSegmentSeqNo = configFormat.getFirstLogSegmentSeqNo(); } isFederatedNamespace = configFormat.isSetFederatedNamespace() && configFormat.isFederatedNamespace(); // Validate the settings if (null == bkZkServersForWriter || null == bkZkServersForReader || null == bkLedgersPath || null == dlZkServersForWriter || null == dlZkServersForReader) { throw new IOException("Missing zk/bk settings in BKDL Config : " + new String(data, UTF_8)); } }
@Override public void open(InputStream is) throws IOException { protocol = new TJSONProtocol(new TIOStreamTransport(is)); }
@Override public void open(OutputStream os) throws IOException { protocol = new TJSONProtocol(new TIOStreamTransport(os)); }
public TJsonProtocolSerializer(boolean readStrict) { super(readStrict, new TJSONProtocol.Factory(), false, MEDIA_TYPE); }
@Test public void testTJsonProtocol() throws IOException, TException { testRecoding(new TJSONProtocol.Factory(), new TJsonProtocolSerializer()); }
public CloudAtlThriftServlet() throws Exception { super(new CloudATL.Processor<CloudATL.Iface>(new CloudATLIface()), new TJSONProtocol.Factory()); }
public UserServlet() throws Exception { super(new Users.Processor<Users.Iface>(new UsersIface()), new TJSONProtocol.Factory()); }