Java Code Examples for org.apache.thrift.protocol.TBinaryProtocol

The following examples show how to use org.apache.thrift.protocol.TBinaryProtocol. These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: leaf-snowflake   Source File: rpcClient.java    License: 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 2
Source Project: stratio-cassandra   Source File: TriggersTest.java    License: 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 3
Source Project: singer   Source File: SimpleThriftLogger.java    License: 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 4
Source Project: singer   Source File: TestMappedTBinaryProtocol.java    License: 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 5
Source Project: hbase   Source File: TestThriftSpnegoHttpFallbackServer.java    License: 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 6
Source Project: dk-fitting   Source File: DKSearchService.java    License: 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 7
Source Project: rpcx-benchmark   Source File: AppClient.java    License: 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 8
Source Project: suro   Source File: ConnectionPool.java    License: 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 9
Source Project: bigqueue   Source File: ThriftQueueServer.java    License: 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 10
Source Project: java-specialagent   Source File: ThriftTest.java    License: 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 11
Source Project: ThriftJ   Source File: ThriftServerTest.java    License: 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 12
Source Project: jstorm   Source File: Drpc.java    License: 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 13
Source Project: jstorm   Source File: SimpleTransportPlugin.java    License: 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 14
Source Project: SpinalTap   Source File: ColumnSerializationUtilTest.java    License: 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 15
Source Project: RDFS   Source File: CoronaAdmin.java    License: 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 16
Source Project: jigsaw-payment   Source File: HelloServerConfig.java    License: 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 17
Source Project: drift   Source File: TestDriftNettyMethodInvoker.java    License: 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 18
Source Project: armeria   Source File: ThriftProtocolFactories.java    License: 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 19
Source Project: leaf-snowflake   Source File: rpcClient.java    License: 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 20
private EntitlementThriftClient.Client getThriftClient() throws Exception {

        TSSLTransportFactory.TSSLTransportParameters param = new TSSLTransportFactory.TSSLTransportParameters();
        param.setTrustStore(trustStore, trustStorePass);
        TTransport transport;
        transport = TSSLTransportFactory.getClientSocket(thriftHost, thriftPort, ProxyConstants.THRIFT_TIME_OUT, param);
        TProtocol protocol = new TBinaryProtocol(transport);
        return new EntitlementThriftClient.Client(protocol);
    }
 
Example 21
Source Project: thrift-mock   Source File: AsyncMockServerRuleTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testAsyncServerRule() throws Exception {
  String responseMsg = "asyncHello";
  Response expectHelloResponse = new Response(200, responseMsg);
  server.setExpectReturn("sayHello", expectHelloResponse);

  TNonblockingTransport transport = new TNonblockingSocket("127.0.0.1",
                                                           9999,
                                                           3000);
  HelloService.AsyncIface client = new HelloService.AsyncClient(new TBinaryProtocol.Factory(),
                                                                new TAsyncClientManager(),
                                                                transport);
  Request request = new Request();
  request.setMsg("hello async!");
  Response result = new Response();
  Stopwatch stopwatch = Stopwatch.createStarted();
  client.sayHello(request, new AsyncMethodCallback() {
    @Override
    public void onComplete(Object response) {
      System.out.println("cost:" + stopwatch.elapsed(TimeUnit.MILLISECONDS));
      result.setCode(((Response)response).getCode());
      result.setResponseMsg(((Response)response).getResponseMsg());
    }

    @Override
    public void onError(Exception exception) {
      System.out.println(exception.getMessage());
    }
  });
  Thread.sleep(50);
  System.out.println("final result:" + result);
  Assert.assertTrue(result.getCode() == 200);
  Assert.assertTrue(responseMsg.equals(result.getResponseMsg()));
}
 
Example 22
Source Project: zipkin-reporter-java   Source File: InternalScribeCodec.java    License: Apache License 2.0 5 votes vote down vote up
static void write(byte[] category, byte[] span, TBinaryProtocol oprot) throws TException {
  oprot.writeFieldBegin(CATEGORY_FIELD_DESC);
  oprot.writeI32(category.length);
  oprot.getTransport().write(category, 0, category.length);

  oprot.writeFieldBegin(MESSAGE_FIELD_DESC);
  byte[] base64 = base64(span);
  oprot.writeI32(base64.length);
  oprot.getTransport().write(base64, 0, base64.length);
  oprot.writeFieldStop();
}
 
Example 23
Source Project: distributedlog   Source File: Utils.java    License: Apache License 2.0 5 votes vote down vote up
public static Message parseMessage(byte[] data) throws TException {
    Message msg = new Message();
    TMemoryInputTransport transport = new TMemoryInputTransport(data);
    TBinaryProtocol protocol = new TBinaryProtocol(transport);
    msg.read(protocol);
    return msg;
}
 
Example 24
Source Project: tchannel-java   Source File: ThriftSerializer.java    License: MIT License 5 votes vote down vote up
@Override
public @Nullable ByteBuf encodeBody(@NotNull Object body) {
    try {
        TSerializer serializer = new TSerializer(new TBinaryProtocol.Factory());
        byte[] payloadBytes = serializer.serialize((TBase<?, ?>) body);
        return Unpooled.wrappedBuffer(payloadBytes);
    } catch (TException e) {
        logger.error("Failed to encode {} body", body.getClass().getName(), e);
    }
    return null;
}
 
Example 25
Source Project: singer   Source File: ThriftLogGenerator.java    License: Apache License 2.0 5 votes vote down vote up
public ThriftLogGenerator(
    String logDir,
    String logFileName,
    int bytesPerSecond,
    int maxNumOfMessages,
    int numOfBytesPerLogFile,
    int numOfLogFiles,
    int payloadSizeInBytes) throws Exception {
  UUID uuid = UUID.randomUUID();
  this.logGeneratorId = ByteBuffer.wrap(new byte[16])
      .putLong(uuid.getMostSignificantBits())
      .putLong(uuid.getLeastSignificantBits())
      .array();
  this.logDir = logDir;
  this.logFileName = logFileName;

  this.rateLimiter = RateLimiter.create(bytesPerSecond);
  this.logger = new SimpleThriftLogger<>(FilenameUtils.concat(logDir, logFileName));
  this.random = new Random();

  this.maxNumOfMessages = maxNumOfMessages;
  this.numOfBytesPerLogFile = numOfBytesPerLogFile;
  this.numOfLogFiles = numOfLogFiles;
  this.payloadSizeInBytes = payloadSizeInBytes;

  this.numOfLogMessageSequence = 100;
  this.nextSequenceNums = Lists.newArrayListWithExpectedSize(numOfLogMessageSequence);
  this.sequenceIds = Lists.newArrayListWithExpectedSize(numOfLogMessageSequence);

  this.serializer = new TSerializer(new TBinaryProtocol.Factory());
}
 
Example 26
Source Project: stratio-cassandra   Source File: PigTestBase.java    License: Apache License 2.0 5 votes vote down vote up
protected static Cassandra.Client getClient() throws TTransportException
{
    TTransport tr = new TFramedTransport(new TSocket("localhost", 9170));
    TProtocol proto = new TBinaryProtocol(tr);
    Cassandra.Client client = new Cassandra.Client(proto);
    tr.open();
    return client;
}
 
Example 27
Source Project: Firefly   Source File: StructBase.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public T createFromParcel(Parcel source) {
    byte[] bytes = source.createByteArray();
    TTransport transport = new TIOStreamTransport(new ByteArrayInputStream(bytes));
    TProtocol protocol = new TBinaryProtocol(transport);
    TypeAdapter<T> typeAdapter = Thrift.instance.getAdapter(tClass);
    try {
        return typeAdapter.read(protocol);
    } catch (TException e) {
        throw new RuntimeException(e);
    }
}
 
Example 28
Source Project: Hive-Cassandra   Source File: CassandraClientHolder.java    License: Apache License 2.0 5 votes vote down vote up
private void initClient() throws CassandraException
{
    try
    {
        transport.open();
    } catch (TTransportException e)
    {
        throw new CassandraException("unable to connect to server", e);
    }

    client = new Cassandra.Client(new TBinaryProtocol(transport));

    // connect to last known keyspace
    setKeyspace(keyspace);
}
 
Example 29
Source Project: ThriftBook   Source File: HelloClient.java    License: Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
    TSocket trans = new TSocket("localhost", 9090);
    TBinaryProtocol proto = new TBinaryProtocol(trans);
    helloSvc.Client client = new helloSvc.Client(proto);

    try {
        trans.open();
        String str = client.getMessage("world");
        System.out.println("[Client] received: " + str);
    } catch (TException ex) {
        System.out.println("Error: " + ex.toString());
    }
    trans.close();
}
 
Example 30
Source Project: Firefly   Source File: StructBase.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void writeToParcel(Parcel dest, int flags) {
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    TTransport transport = new TIOStreamTransport(stream);
    TProtocol protocol = new TBinaryProtocol(transport);
    TypeAdapter typeAdapter = Thrift.instance.getAdapter(this.getClass());
    try {
        typeAdapter.write(this, protocol);
    } catch (TException e) {
        throw new RuntimeException(e);
    }
    dest.writeByteArray(stream.toByteArray());
}