org.apache.thrift.protocol.TBinaryProtocol Java Examples

The following examples show how to use org.apache.thrift.protocol.TBinaryProtocol. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CoronaAdmin.java    From RDFS with Apache License 2.0 6 votes vote down vote up
/**
 * Persists the state of the ClusterManager
 * @return 0 if successful.
 * @throws IOException
 */
private int persistState() throws IOException {
  // Get the current configuration
  CoronaConf conf = new CoronaConf(getConf());

  InetSocketAddress address = NetUtils.createSocketAddr(conf
    .getClusterManagerAddress());
  TFramedTransport transport = new TFramedTransport(
    new TSocket(address.getHostName(), address.getPort()));
  ClusterManagerService.Client client = new ClusterManagerService.Client(
    new TBinaryProtocol(transport));

  try {
    transport.open();
    if (!client.persistState())  {
      System.err.println("Persisting Cluster Manager state failed. ");
    }
  } catch (TException e) {
    throw new IOException(e);
  }

  return 0;
}
 
Example #2
Source File: SimpleThriftLogger.java    From singer with Apache License 2.0 6 votes vote down vote up
/**
 * Simple implementation of log file rotation.
 * @throws java.io.IOException
 */
public void rotate() throws IOException {
  close();

  int i = 0;
  while (new File(String.format("%s.%d", fileName, ++i)).exists()) {
    ;
  }

  for (int j = i - 1; j >= 1; --j) {
    FileUtils.moveFile(
        new File(String.format("%s.%d", fileName, j)),
        new File(String.format("%s.%d", fileName, j + 1)));
  }
  FileUtils.moveFile(new File(fileName), new File(fileName + ".1"));
  bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(fileName, true));
  transport = new ByteOffsetTFramedTransport(new TIOStreamTransport(bufferedOutputStream));
  protocol = new TBinaryProtocol(transport);
}
 
Example #3
Source File: TriggersTest.java    From stratio-cassandra with Apache License 2.0 6 votes vote down vote up
@Test
public void executeTriggerOnThriftBatchUpdate() throws Exception
{
    Cassandra.Client client = new Cassandra.Client(
                                new TBinaryProtocol(
                                    new TFramedTransportFactory().openTransport(
                                        InetAddress.getLocalHost().getHostName(), 9170)));
    client.set_keyspace(ksName);
    org.apache.cassandra.thrift.Mutation mutation = new org.apache.cassandra.thrift.Mutation();
    ColumnOrSuperColumn cosc = new ColumnOrSuperColumn();
    cosc.setColumn(getColumnForInsert("v1", 3));
    mutation.setColumn_or_supercolumn(cosc);
    client.batch_mutate(
        Collections.singletonMap(bytes(3),
                                 Collections.singletonMap(cfName,
                                                          Collections.singletonList(mutation))),
        org.apache.cassandra.thrift.ConsistencyLevel.ONE);

    assertUpdateIsAugmented(3);
}
 
Example #4
Source File: rpcClient.java    From leaf-snowflake with Apache License 2.0 6 votes vote down vote up
public static void startClient(String ip ,int port ,int timeout) throws Exception
{
	TTransport transport = new TSocket(ip,port,timeout);
	TProtocol protocol = new TBinaryProtocol(transport);
	leafrpc.Client client = new leafrpc.Client(protocol);
	transport.open();

	int i = 0;
	while(i < 2000000)
	{
		 client.getID("");
		 ++i;
	}

	transport.close();
}
 
Example #5
Source File: rpcClient.java    From leaf-snowflake with Apache License 2.0 6 votes vote down vote up
public static void startClient2(String ip ,int port ,int timeout) throws Exception
{
	TTransport transport = new TFramedTransport(new TSocket(ip,port,timeout));
	TProtocol protocol = new TBinaryProtocol(transport);
	leafrpc.Client client = new leafrpc.Client(protocol);
	transport.open();

	for(int i = 0; i< 1000000; i++)
	{
		client.getID("");
		if (i % 100000 == 0)
		{
			System.out.println(Thread.currentThread().getName() + " " + client.getID(""));
		}
		//ai.incrementAndGet();
	}
	transport.close();
}
 
Example #6
Source File: ThriftProtocolFactories.java    From armeria with Apache License 2.0 6 votes vote down vote up
/**
 * 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 TTextProtocolFactory) {
        final TTextProtocolFactory factory = (TTextProtocolFactory) protoFactory;
        return factory.usesNamedEnums() ? ThriftSerializationFormats.TEXT_NAMED_ENUM
                                        : ThriftSerializationFormats.TEXT;
    } else {
        throw new IllegalArgumentException(
                "unsupported TProtocolFactory: " + protoFactory.getClass().getName());
    }
}
 
Example #7
Source File: HelloServerConfig.java    From jigsaw-payment with Apache License 2.0 6 votes vote down vote up
@Bean(name = "pool-server")
public TServer poolServer() throws Exception {
	TServerTransport transport = new TServerSocket(this.port());

	TThreadPoolServer.Args args = new TThreadPoolServer.Args(transport);
	args.transportFactory(new TTransportFactory());
	args.protocolFactory(new TBinaryProtocol.Factory());

	args.processor(this.processor());
	args.executorService(new ThreadPoolExecutor(env.getProperty(
			"rpc.server.min.worker.threads", Integer.class, 512), env
			.getProperty("rpc.server.max.worker.threads", Integer.class,
					65535), env.getProperty(
			"rpc.server.thread.keep.alive.time", Long.class, 600l),
			TimeUnit.SECONDS, new SynchronousQueue<Runnable>()));

	return new TThreadPoolServer(args);
}
 
Example #8
Source File: TestMappedTBinaryProtocol.java    From singer with Apache License 2.0 6 votes vote down vote up
@Test
public void testSimpleReadWrite() throws TException {
  LogMessage msg = new LogMessage();
  String key = "hellow world";
  msg.setKey(key.getBytes());
  String value = "abcdef";
  msg.setMessage(value.getBytes());
  long checksum = 1233432L;
  msg.setChecksum(checksum);
  long nanoTime = System.nanoTime();
  msg.setTimestampInNanos(nanoTime);
  byte[] serialize = ThriftCodec.getInstance().serialize(msg);

  TProtocol pr = new TBinaryProtocol(new TByteBuffer(ByteBuffer.wrap(serialize)));
  LogMessage lm = new LogMessage();
  lm.read(pr);
  assertEquals(nanoTime, lm.getTimestampInNanos());
  assertEquals(key, new String(lm.getKey()));
  assertEquals(value, new String(lm.getMessage()));
  assertEquals(checksum, lm.getChecksum());

}
 
Example #9
Source File: TestDriftNettyMethodInvoker.java    From drift with Apache License 2.0 6 votes vote down vote up
private static List<DriftLogEntry> testMethodInvoker(ServerMethodInvoker methodInvoker)
{
    int invocationCount = testMethodInvoker(methodInvoker, ImmutableList.of(
            address -> logThrift(address, MESSAGES, new TTransportFactory(), new TBinaryProtocol.Factory()),
            address -> logThrift(address, MESSAGES, new TTransportFactory(), new TCompactProtocol.Factory()),
            address -> logThrift(address, MESSAGES, new TFramedTransport.Factory(), new TBinaryProtocol.Factory()),
            address -> logThrift(address, MESSAGES, new TFramedTransport.Factory(), new TCompactProtocol.Factory()),
            address -> logThriftAsync(address, MESSAGES),
            address -> logNiftyInvocationHandler(address, DRIFT_MESSAGES, Transport.UNFRAMED, BINARY),
            address -> logNiftyInvocationHandler(address, DRIFT_MESSAGES, Transport.UNFRAMED, Protocol.COMPACT),
            address -> logNiftyInvocationHandler(address, DRIFT_MESSAGES, Transport.UNFRAMED, Protocol.FB_COMPACT),
            address -> logNiftyInvocationHandler(address, DRIFT_MESSAGES, FRAMED, BINARY),
            address -> logNiftyInvocationHandler(address, DRIFT_MESSAGES, FRAMED, Protocol.COMPACT),
            address -> logNiftyInvocationHandler(address, DRIFT_MESSAGES, FRAMED, Protocol.FB_COMPACT),
            address -> logNiftyInvocationHandler(address, DRIFT_MESSAGES, Transport.HEADER, BINARY),
            address -> logNiftyInvocationHandler(address, DRIFT_MESSAGES, Transport.HEADER, Protocol.FB_COMPACT)));

    return newArrayList(concat(nCopies(invocationCount, DRIFT_MESSAGES)));
}
 
Example #10
Source File: ColumnSerializationUtilTest.java    From SpinalTap with Apache License 2.0 6 votes vote down vote up
@Test
public void testDeserializeColumn() throws Exception {
  Mutation mutation =
      new Mutation(
          MutationType.DELETE,
          TIMESTAMP,
          SOURCE_ID,
          DATA_SOURCE,
          BINLOG_HEADER,
          TABLE,
          getEntity());

  TSerializer serializer = new TSerializer(new TBinaryProtocol.Factory());
  TDeserializer deserializer = new TDeserializer(new TBinaryProtocol.Factory());

  byte[] serialized = serializer.serialize(mutation);

  Mutation deserialized = new Mutation();
  deserializer.deserialize(deserialized, serialized);

  assertEquals(mutation, deserialized);
}
 
Example #11
Source File: TestThriftSpnegoHttpFallbackServer.java    From hbase with Apache License 2.0 6 votes vote down vote up
@Override
protected void talkToThriftServer(String url, int customHeaderSize) throws Exception {
  // Close httpClient and THttpClient automatically on any failures
  try (
    CloseableHttpClient httpClient = createHttpClient();
    THttpClient tHttpClient = new THttpClient(url, httpClient)
  ) {
    tHttpClient.open();
    if (customHeaderSize > 0) {
      StringBuilder sb = new StringBuilder();
      for (int i = 0; i < customHeaderSize; i++) {
        sb.append("a");
      }
      tHttpClient.setCustomHeader(HttpHeaders.USER_AGENT, sb.toString());
    }

    TProtocol prot = new TBinaryProtocol(tHttpClient);
    Hbase.Client client = new Hbase.Client(prot);
    TestThriftServer.createTestTables(client);
    TestThriftServer.checkTableList(client);
    TestThriftServer.dropTestTables(client);
  }
}
 
Example #12
Source File: SimpleTransportPlugin.java    From jstorm with Apache License 2.0 6 votes vote down vote up
@Override
public TServer getServer(TProcessor processor) throws IOException, TTransportException {
    int port = type.getPort(storm_conf);
    TNonblockingServerSocket serverTransport = new TNonblockingServerSocket(port);
    int numWorkerThreads = type.getNumThreads(storm_conf);
    int maxBufferSize = type.getMaxBufferSize(storm_conf);
    Integer queueSize = type.getQueueSize(storm_conf);

    THsHaServer.Args server_args =
            new THsHaServer.Args(serverTransport).processor(new SimpleWrapProcessor(processor)).workerThreads(numWorkerThreads)
                    .protocolFactory(new TBinaryProtocol.Factory(false, true, maxBufferSize, -1));

    if (queueSize != null) {
        server_args.executorService(new ThreadPoolExecutor(numWorkerThreads, numWorkerThreads, 60, TimeUnit.SECONDS, new ArrayBlockingQueue(queueSize)));
    }

    // construct THsHaServer
    return new THsHaServer(server_args);
}
 
Example #13
Source File: DKSearchService.java    From dk-fitting with Apache License 2.0 6 votes vote down vote up
/**
 *  线程池服务模型,使用标准的阻塞式IO,预先创建一组线程处理请求。
 */
public void startTThreadPoolServer() {
    try {
        System.out.println("UserInfoServiceDemo TThreadPoolServer start ....");
        TMultiplexedProcessor processor = new TMultiplexedProcessor();
        processor.registerProcessor( "DKSearchOutput",new DKSearchOutput.Processor<DKSearchOutput.Iface>( new DKSearchOutputImpl() ) );
        processor.registerProcessor( "DKSearchInput",new DKSearchInput.Processor<DKSearchInput.Iface>(new DKSearchInputImpl()  ) );
        processor.registerProcessor( "DKSearchService",new SearchService.Processor<SearchService.Iface>(new SearchServiceImpl() ) );
        //TProcessor tprocessor = new UserInfoService.Processor<UserInfoService.Iface>(new UserInfoServiceImpl());
        TServerSocket serverTransport = new TServerSocket( Integer.valueOf(prop.get("dkSearch.port")));
        TThreadPoolServer.Args ttpsArgs = new TThreadPoolServer.Args(serverTransport);
        ttpsArgs.processor(processor);
        ttpsArgs.protocolFactory(new TBinaryProtocol.Factory());
        // 线程池服务模型,使用标准的阻塞式IO,预先创建一组线程处理请求。
        TServer server = new TThreadPoolServer(ttpsArgs);
        server.serve();
    } catch (Exception e) {
        System.out.println("Server start error!!!");
        e.printStackTrace();

    }

}
 
Example #14
Source File: Drpc.java    From jstorm with Apache License 2.0 6 votes vote down vote up
private THsHaServer initHandlerServer(Map conf, final Drpc service) throws Exception {
    int port = JStormUtils.parseInt(conf.get(Config.DRPC_PORT));
    int workerThreadNum = JStormUtils.parseInt(conf.get(Config.DRPC_WORKER_THREADS));
    int queueSize = JStormUtils.parseInt(conf.get(Config.DRPC_QUEUE_SIZE));

    LOG.info("Begin to init DRPC handler server at port: " + port);

    TNonblockingServerSocket socket = new TNonblockingServerSocket(port);
    THsHaServer.Args targs = new THsHaServer.Args(socket);
    targs.workerThreads(64);
    targs.protocolFactory(new TBinaryProtocol.Factory());
    targs.processor(new DistributedRPC.Processor<DistributedRPC.Iface>(service));

    ThreadPoolExecutor executor = new ThreadPoolExecutor(
            workerThreadNum, workerThreadNum, 60, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(queueSize));
    targs.executorService(executor);

    THsHaServer handlerServer = new THsHaServer(targs);
    LOG.info("Successfully inited DRPC handler server at port: " + port);

    return handlerServer;
}
 
Example #15
Source File: ThriftServerTest.java    From ThriftJ with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args){
	ExecutorService es = Executors.newFixedThreadPool(2);
	for(int i=0; i<ports.length; i++){
		final int index = i;
		es.execute(new Runnable() {
			@Override
			public void run() {
				try{
					TNonblockingServerSocket socket = new TNonblockingServerSocket(ports[index]);
					TestThriftJ.Processor processor = new TestThriftJ.Processor(new QueryImp());
					TNonblockingServer.Args arg = new TNonblockingServer.Args(socket);
					arg.protocolFactory(new TBinaryProtocol.Factory());
					arg.transportFactory(new TFramedTransport.Factory());
					arg.processorFactory(new TProcessorFactory(processor));
					TServer server = new TNonblockingServer(arg);
					
					logger.info("127.0.0.1:" + ports[index] + " start");
					server.serve();
				}catch(Exception e){
					logger.error("127.0.0.1:" + ports[index] + " error");
				}
			}
		});
	}
}
 
Example #16
Source File: ThriftTest.java    From java-specialagent with Apache License 2.0 6 votes vote down vote up
@Test
public void test(final MockTracer tracer) throws Exception {
  startNewThreadPoolServer();

  final TTransport transport = new TSocket("localhost", port);
  transport.open();

  final TProtocol protocol = new TBinaryProtocol(transport);

  final CustomService.Client client = new CustomService.Client(protocol);
  assertEquals("Say Good bye World", client.say("Good bye", "World"));

  await().atMost(5, TimeUnit.SECONDS).until(TestUtil.reportedSpansSize(tracer), equalTo(2));

  final List<MockSpan> mockSpans = tracer.finishedSpans();
  assertEquals(2, mockSpans.size());

  assertTrue(mockSpans.get(0).parentId() != 0 || mockSpans.get(1).parentId() != 0);
  assertNull(tracer.activeSpan());
}
 
Example #17
Source File: ThriftQueueServer.java    From bigqueue with Apache License 2.0 6 votes vote down vote up
public void start() {
	try {
		System.out.println("Thrift queue server start ...");
		
		BigQueueService.Iface bigQueueSerivce = new ThriftQueueServiceImpl(QUEUE_DIR);
		TProcessor tprocessor = new BigQueueService.Processor(bigQueueSerivce);
		
		TNonblockingServerSocket tnbSocketTransport = new TNonblockingServerSocket(SERVER_PORT);
		TNonblockingServer.Args tnbArgs = new TNonblockingServer.Args(tnbSocketTransport);
		tnbArgs.processor(tprocessor);
		// Nonblocking server mode needs TFramedTransport
		tnbArgs.transportFactory(new TFramedTransport.Factory());
		tnbArgs.protocolFactory(new TBinaryProtocol.Factory());
		
		TServer server = new TNonblockingServer(tnbArgs);
		System.out.println("Thrift queue server started on port " + SERVER_PORT);
		server.serve();
	} catch (Exception e) {
		System.err.println("Server start error!!!");
		e.printStackTrace();
	}
}
 
Example #18
Source File: ConnectionPool.java    From suro with Apache License 2.0 6 votes vote down vote up
public void connect() throws Exception {
    TSocket socket = new TSocket(server.getHost(), server.getPort(), config.getConnectionTimeout());
    socket.getSocket().setTcpNoDelay(true);
    socket.getSocket().setKeepAlive(true);
    socket.getSocket().setSoLinger(true, 0);
    transport = new TFramedTransport(socket);
    transport.open();

    TProtocol protocol = new TBinaryProtocol(transport);

    client = new SuroServer.Client(protocol);
    ServiceStatus status = client.getStatus();
    if (status != ServiceStatus.ALIVE) {
        transport.close();
        throw new RuntimeException(server + " IS NOT ALIVE!!!");
    }
}
 
Example #19
Source File: AppClient.java    From rpcx-benchmark with Apache License 2.0 6 votes vote down vote up
public static Greeter.Client[] createClients(String host, int n, BenchmarkMessage msg) throws TException {
    TTransport[] transport = new TTransport[n];
    Greeter.Client[] clients = new Greeter.Client[n];

    //warmup
    for (int i = 0; i < n; i++) {
        transport[i] = new TFramedTransport(new TSocket(host, 8972));
        transport[i].open();

        TProtocol protocol = new TBinaryProtocol(transport[i]);
        clients[i] =  new Greeter.Client(protocol);
        clients[i].say(msg);
    }

    return clients;
}
 
Example #20
Source File: InternalScribeCodecTest.java    From zipkin-reporter-java with Apache License 2.0 5 votes vote down vote up
@Test
public void sendsSpanExpectedMetrics() throws Exception {
  byte[] thrift = SpanBytesEncoder.THRIFT.encode(CLIENT_SPAN);
  ByteArrayOutputStream out = new ByteArrayOutputStream();
  TBinaryProtocol prot = new TBinaryProtocol(new TIOStreamTransport(out));

  InternalScribeCodec.writeLogRequest(ScribeClient.category, Arrays.asList(thrift), 1, prot);

  assertThat(InternalScribeCodec.messageSizeInBytes(ScribeClient.category, Arrays.asList(thrift)))
      .isEqualTo(out.size());

  assertThat(InternalScribeCodec.messageSizeInBytes(ScribeClient.category, thrift.length))
      .isEqualTo(out.size());
}
 
Example #21
Source File: StormManagerServiceTestCase.java    From product-cep with Apache License 2.0 5 votes vote down vote up
private StormManagerService.Client createManagerServiceClient() throws TTransportException {
    TTransport transport = new TSocket("localhost", 8904);
    TProtocol protocol = new TBinaryProtocol(transport);
    transport.open();
    StormManagerService.Client client = new StormManagerService.Client(protocol);
    return client;

}
 
Example #22
Source File: AbstractTest.java    From dubbox with Apache License 2.0 5 votes vote down vote up
protected void init() throws Exception {
    TServerTransport serverTransport = new TServerSocket( PORT );

    TBinaryProtocol.Factory bFactory = new TBinaryProtocol.Factory();

    server = new TThreadPoolServer(
            new TThreadPoolServer.Args( serverTransport )
                    .inputProtocolFactory( bFactory )
                    .outputProtocolFactory( bFactory )
                    .inputTransportFactory( getTransportFactory() )
                    .outputTransportFactory( getTransportFactory() )
                    .processor( getProcessor() ) );

    Thread startTread = new Thread() {

        @Override
        public void run() {
            server.serve();
        }

    };

    startTread.setName( "thrift-server" );

    startTread.start();

    while( !server.isServing() ) {
        Thread.sleep( 100 );
    }

    protocol = ExtensionLoader.getExtensionLoader(Protocol.class)
            .getExtension( ThriftProtocol.NAME );

    invoker = protocol.refer( getInterface(), getUrl() );

}
 
Example #23
Source File: HealthCheck.java    From suro with Apache License 2.0 5 votes vote down vote up
private SuroServer.Client getClient(String host, int port, int timeout) throws SocketException, TTransportException {
    TSocket socket = new TSocket(host, port, timeout);
    socket.getSocket().setTcpNoDelay(true);
    socket.getSocket().setKeepAlive(true);
    socket.getSocket().setSoLinger(true, 0);
    TTransport transport = new TFramedTransport(socket);
    transport.open();

    TProtocol protocol = new TBinaryProtocol(transport);

    return new SuroServer.Client(protocol);
}
 
Example #24
Source File: rpcServer.java    From leaf-snowflake with Apache License 2.0 5 votes vote down vote up
public static void startRPCServer4(leafServer leafserver , String ip , int port) throws Exception
{
	TProcessor processor = new leafrpc.Processor<leafrpc.Iface>(new RPCService(leafserver));
	//传输通道,非阻塞模式
	InetSocketAddress address = new InetSocketAddress(InetAddress.getByName(ip),port);
	TNonblockingServerSocket serverTransport = new TNonblockingServerSocket(address,10000);
	THsHaServer.Args  args = new THsHaServer.Args(serverTransport);
	args.processor(processor);
	args.protocolFactory(new TBinaryProtocol.Factory());
	args.transportFactory(new TFramedTransport.Factory());
	TServer server = new THsHaServer(args);
	LOG.info("leaf RPCServer(type:THsHaServer) start at ip:port : "+ ip +":" + port );
	server.serve();
}
 
Example #25
Source File: FunctionCallTest.java    From Firefly with Apache License 2.0 5 votes vote down vote up
@Test
public void voidMethodReceiveObserableWithoutOneway() throws Exception {
    NotifyCheck notifyCheck = new NotifyCheck(100);
    final TestService.Processor<Iface> processor = new TestService.Processor<Iface>(notifyCheck);
    final TTransport transport = new FlushableMemoryBuffer(4096) {
        boolean flushed = false;

        @Override
        public void flush() throws TTransportException {
            if (!flushed) {
                flushed = true;
                try {
                    processor.process(new TBinaryProtocol(this), new TBinaryProtocol(this));
                } catch (TException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    };
    com.meituan.firefly.rx_testfirefly.TestService testService = thrift.create(com.meituan.firefly.rx_testfirefly.TestService.class, new Thrift.SimpleTProtocolFactory() {
        @Override
        public TProtocol get() {
            return new TBinaryProtocol(transport);
        }
    });
    TestSubscriber testSubscriber = new TestSubscriber();
    testService.notifyWithoutOneway(100).subscribe(testSubscriber);
    Assert.assertTrue(notifyCheck.notified);

}
 
Example #26
Source File: RemoteShaderDispatcher.java    From graphicsfuzz with Apache License 2.0 5 votes vote down vote up
private Iface getFuzzerServiceManagerProxy(CloseableHttpClient httpClient)
    throws TTransportException {
  TTransport transport = new THttpClient(url, httpClient);
  transport.open();
  TProtocol protocol = new TBinaryProtocol(transport);
  return new FuzzerServiceManager.Client(
      protocol);
}
 
Example #27
Source File: EmbeddedCassandraServiceTest.java    From stratio-cassandra with Apache License 2.0 5 votes vote down vote up
/**
 * Gets a connection to the localhost client
 *
 * @return
 * @throws TTransportException
 */
private Cassandra.Client getClient() throws TTransportException
{
    TTransport tr = new TFramedTransport(new TSocket("localhost", DatabaseDescriptor.getRpcPort()));
    TProtocol proto = new TBinaryProtocol(tr);
    Cassandra.Client client = new Cassandra.Client(proto);
    tr.open();
    return client;
}
 
Example #28
Source File: SyncClient.java    From incubator-iotdb with Apache License 2.0 5 votes vote down vote up
@Override
public void establishConnection(String serverIp, int serverPort) throws SyncConnectionException {
  transport = new TSocket(serverIp, serverPort, TIMEOUT_MS);
  TProtocol protocol = new TBinaryProtocol(transport);
  serviceClient = new SyncService.Client(protocol);
  try {
    if (!transport.isOpen()) {
      transport.open();
    }
  } catch (TTransportException e) {
    logger.error("Cannot connect to the receiver.");
    throw new SyncConnectionException(e);
  }
}
 
Example #29
Source File: ScribeTransport.java    From incubator-retired-htrace with Apache License 2.0 5 votes vote down vote up
private Scribe.Iface newScribe(String collectorHostname,
                               int collectorPort)
    throws IOException {

  TTransport transport = new TFramedTransport(
      new TSocket(collectorHostname, collectorPort));
  try {
    transport.open();
  } catch (TTransportException e) {
    throw new IOException(e);
  }
  TBinaryProtocol.Factory factory = new TBinaryProtocol.Factory();
  TProtocol protocol = factory.getProtocol(transport);
  return new Scribe.Client(protocol);
}
 
Example #30
Source File: FunctionCallTest.java    From Firefly with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldReceiveOnewayMethod() throws Exception {
    final TTransport transport = new FlushableMemoryBuffer(4096);
    com.meituan.firefly.testfirefly.TestService testService = thrift.create(com.meituan.firefly.testfirefly.TestService.class, new Thrift.SimpleTProtocolFactory() {
        @Override
        public TProtocol get() {
            return new TBinaryProtocol(transport);
        }
    });
    NotifyCheck notifyCheck = new NotifyCheck(100);
    TestService.Processor<Iface> processor = new TestService.Processor<Iface>(notifyCheck);
    testService.notify(100);
    processor.process(new TBinaryProtocol(transport), new TBinaryProtocol(transport));
    Assert.assertTrue(notifyCheck.notified);
}