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

The following examples show how to use org.apache.thrift.protocol.TProtocol. 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 check out the related API usage on the sidebar.
Example 1
Source Project: parquet-mr   Source File: ThriftRecordConverter.java    License: Apache License 2.0 6 votes vote down vote up
private Converter newConverter(List<TProtocol> events, Type type, ThriftField field) {
  switch (field.getType().getType()) {
  case LIST:
    return new ListConverter(events, type.asGroupType(), field);
  case SET:
    return new SetConverter(events, type.asGroupType(), field);
  case MAP:
    return new MapConverter(events, type.asGroupType(), field);
  case STRUCT:
    return new StructConverter(events, type.asGroupType(), field);
  case STRING:
    return new FieldStringConverter(events, field);
  case ENUM:
    return new FieldEnumConverter(events, field);
  default:
    return new FieldPrimitiveConverter(events, field);
  }
}
 
Example 2
Source Project: hbase   Source File: ThriftConnection.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Pair<THBaseService.Client, TTransport> getClient() throws IOException {
  Preconditions.checkArgument(connection.getHost().startsWith("http"),
      "http client host must start with http or https");
  String url = connection.getHost() + ":" + connection.getPort();
  try {
    THttpClient httpClient = new THttpClient(url, connection.getHttpClient());
    for (Map.Entry<String, String> header : customHeader.entrySet()) {
      httpClient.setCustomHeader(header.getKey(), header.getValue());
    }
    httpClient.open();
    TProtocol prot = new TBinaryProtocol(httpClient);
    THBaseService.Client client = new THBaseService.Client(prot);
    return new Pair<>(client, httpClient);
  } catch (TTransportException e) {
    throw new IOException(e);
  }

}
 
Example 3
@Test
public void testFixedResponse() throws Exception {
  ThriftMockServer server = new ThriftMockServer(9999);
  Thread t = new Thread(server::start);
  t.start();

  server.setExpectReturn("sayHello", expectHelloResponse);

  Request request = new Request();
  request.setMsg("hello, i'm guest");
  TProtocol protocol = TProtocolUtil.initTProtocol("127.0.0.1", 9999);
  HelloService.Iface helloService = new HelloService.Client(protocol);
  Response  actualResponse = helloService.sayHello(request);
  LOG.info("actualResponse: " + actualResponse);
  Assert.assertTrue(actualResponse.getCode() == 200);
  server.stop();
}
 
Example 4
Source Project: parquet-mr   Source File: Consumers.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * To consume a list of elements
 * @param c the class of the list content
 * @param consumer the consumer that will receive the list
 * @param <T> the type of the list content
 * @return a ListConsumer that can be passed to the DelegatingFieldConsumer
 */
public static <T extends TBase<T,? extends TFieldIdEnum>> ListConsumer listOf(Class<T> c, final Consumer<List<T>> consumer) {
  class ListConsumer implements Consumer<T> {
    List<T> list;
    @Override
    public void consume(T t) {
      list.add(t);
    }
  }
  final ListConsumer co = new ListConsumer();
  return new DelegatingListElementsConsumer(struct(c, co)) {
    @Override
    public void consumeList(TProtocol protocol,
        EventBasedThriftReader reader, TList tList) throws TException {
      co.list = new ArrayList<T>();
      super.consumeList(protocol, reader, tList);
      consumer.consume(co.list);
    }
  };
}
 
Example 5
Source Project: hbase   Source File: TestThriftHBaseServiceHandler.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Verify that thrift2 client calling thrift server can get the thrift server type correctly.
 */
@Test
public void testGetThriftServerOneType() throws Exception {

  // start a thrift server
  HBaseThriftTestingUtility THRIFT_TEST_UTIL = new HBaseThriftTestingUtility();

  LOG.info("Starting HBase Thrift server One");
  THRIFT_TEST_UTIL.startThriftServer(UTIL.getConfiguration(), ThriftServerType.ONE);
  try (TTransport transport = new TSocket(InetAddress.getLocalHost().getHostName(),
      THRIFT_TEST_UTIL.getServerPort())){
    TProtocol protocol = new TBinaryProtocol(transport);
    // This is our thrift2 client.
    THBaseService.Iface client = new THBaseService.Client(protocol);
    // open the transport
    transport.open();
    assertEquals(TThriftServerType.ONE.name(), client.getThriftServerType().name());
  } finally {
    THRIFT_TEST_UTIL.stopThriftServer();
  }
}
 
Example 6
Source Project: armeria   Source File: THttpClientDelegate.java    License: Apache License 2.0 6 votes vote down vote up
@Nullable
private static TApplicationException readApplicationException(int seqId, ThriftFunction func,
                                                              TProtocol inputProtocol,
                                                              TMessage msg) throws TException {
    if (msg.seqid != seqId) {
        throw new TApplicationException(TApplicationException.BAD_SEQUENCE_ID);
    }

    if (!func.name().equals(msg.name)) {
        return new TApplicationException(TApplicationException.WRONG_METHOD_NAME, msg.name);
    }

    if (msg.type == TMessageType.EXCEPTION) {
        final TApplicationException appEx = TApplicationExceptions.read(inputProtocol);
        inputProtocol.readMessageEnd();
        return appEx;
    }

    return null;
}
 
Example 7
Source Project: gemfirexd-oss   Source File: GfxdThriftServerSelector.java    License: Apache License 2.0 6 votes vote down vote up
protected ClientProcessData(GfxdTSocket socket, int connectionNumber,
    TProcessor proc, TTransport in, TTransport out, TProtocol inp,
    TProtocol outp, TServerEventHandler eventHandler) {
  this.clientSocket = socket;
  this.connectionNumber = connectionNumber;
  this.processor = proc;
  this.inputTransport = in;
  this.outputTransport = out;
  this.inputProtocol = inp;
  this.outputProtocol = outp;
  this.eventHandler = eventHandler;
  if (eventHandler != null) {
    this.connectionContext = eventHandler.createContext(inp, outp);
  }
  else {
    this.connectionContext = null;
  }
  this.idle = true;
}
 
Example 8
Source Project: ThriftBook   Source File: DiskSerZ.java    License: Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
    TTransport trans = null;
    try {
        System.out.println("Radio Observation Disk Serializer " + radio_observationConstants.Version);
        trans = new TSimpleFileTransport("data.z", true, true);
        trans = new TZlibTransport(trans);
        trans.open();
        TProtocol proto = new TBinaryProtocol(trans);
        if (args.length > 0 && 0 == args[0].compareTo("write")) {
            WriteRadioObservation(proto, args.length > 1);
        } else if (args.length>0 && 0==args[0].compareToIgnoreCase("read")) {
            ReadRadioObservation(proto);
        } else {
            System.out.println("Usage: DiskSer (read | write [bmp])");
        }
    } catch (TException | IOException ex) {
        System.out.println("Error: " + ex.getMessage());
    }
    if (null != trans) {
        trans.close();
    }
}
 
Example 9
Source Project: dubbox-hystrix   Source File: ThriftNativeCodec.java    License: Apache License 2.0 6 votes vote down vote up
protected void encodeRequest(Channel channel, ChannelBuffer buffer, Request request)
    throws IOException {
    Invocation invocation = (Invocation) request.getData();
    TProtocol protocol = newProtocol(channel.getUrl(), buffer);
    try {
        protocol.writeMessageBegin(new TMessage(
            invocation.getMethodName(), TMessageType.CALL, 
            thriftSeq.getAndIncrement()));
        protocol.writeStructBegin(new TStruct(invocation.getMethodName() + "_args"));
        for(int i = 0; i < invocation.getParameterTypes().length; i++) {
            Class<?> type = invocation.getParameterTypes()[i];

        }
    } catch (TException e) {
        throw new IOException(e.getMessage(), e);
    }

}
 
Example 10
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 11
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 12
Source Project: gemfirexd-oss   Source File: LocatorServiceImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public final boolean process(final TProtocol in, final TProtocol out)
    throws TException {
  final TMessage msg = in.readMessageBegin();
  final ProcessFunction<LocatorServiceImpl, ?> fn = this.fnMap
      .get(msg.name);
  if (fn != null) {
    fn.process(msg.seqid, in, out, this.inst);
    // terminate connection on receiving closeConnection
    // direct class comparison should be the fastest way
    return fn.getClass() != LocatorService.Processor.closeConnection.class;
  }
  else {
    TProtocolUtil.skip(in, TType.STRUCT);
    in.readMessageEnd();
    TApplicationException x = new TApplicationException(
        TApplicationException.UNKNOWN_METHOD, "Invalid method name: '"
            + msg.name + "'");
    out.writeMessageBegin(new TMessage(msg.name, TMessageType.EXCEPTION,
        msg.seqid));
    x.write(out);
    out.writeMessageEnd();
    out.getTransport().flush();
    return true;
  }
}
 
Example 13
Source Project: parquet-mr   Source File: ThriftRecordConverter.java    License: Apache License 2.0 6 votes vote down vote up
public ElementConverter(String listName, List<TProtocol> listEvents,
                        GroupType repeatedType, ThriftField thriftElement) {
  this.listEvents = listEvents;
  this.elementEvents = new ArrayList<TProtocol>();
  Type elementType = repeatedType.getType(0);
  if (elementType.isRepetition(Type.Repetition.OPTIONAL)) {
    if (ignoreNullElements) {
      LOG.warn("List " + listName +
          " has optional elements: null elements are ignored.");
    } else {
      throw new ParquetDecodingException("Cannot read list " + listName +
          " with optional elements: set " + IGNORE_NULL_LIST_ELEMENTS +
          " to ignore nulls.");
    }
  }
  elementConverter = newConverter(elementEvents, elementType, thriftElement);
}
 
Example 14
Source Project: nettythrift   Source File: ThriftMessageEncoder.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void messageReceived(ChannelHandlerContext ctx, ThriftMessage message) throws Exception {
	ByteBuf buffer = message.getContent();
	logger.debug("msg.content:: {}", buffer);
	try {
		TNettyTransport transport = new TNettyTransport(ctx.channel(), buffer);
		TProtocolFactory protocolFactory = message.getProtocolFactory();
		TProtocol protocol = protocolFactory.getProtocol(transport);
		serverDef.nettyProcessor.process(ctx, protocol, protocol,
				new DefaultWriterListener(message, transport, ctx, serverDef));
	} catch (Throwable ex) {
		int refCount = buffer.refCnt();
		if (refCount > 0) {
			buffer.release(refCount);
		}
		throw ex;
	}
}
 
Example 15
Source Project: nettythrift   Source File: DefaultNettyProcessor.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("rawtypes")
private void writeResult(final TProtocol out, final TMessage msg, final WriterHandler onComplete, TBase args,
		final TBase result) {
	try {
		onComplete.beforeWrite(msg, args, result);
		// if (!isOneway()) {
		out.writeMessageBegin(new TMessage(msg.name, TMessageType.REPLY, msg.seqid));
		if (result != null) {
			result.write(out);
		} else {
			out.writeStructBegin(null);
			out.writeFieldStop();
			out.writeStructEnd();
		}
		out.writeMessageEnd();
		out.getTransport().flush();
		// }
		onComplete.afterWrite(msg, null, TMessageType.REPLY, args, result);
	} catch (Throwable e) {
		onComplete.afterWrite(msg, e, TMessageType.EXCEPTION, args, result);
	}
}
 
Example 16
Source Project: parquet-mr   Source File: BufferedProtocolReadToWrite.java    License: Apache License 2.0 6 votes vote down vote up
private boolean readOneSet(TProtocol in, List<Action> buffer, SetType expectedType) throws TException {
  final TSet set = in.readSetBegin();
  buffer.add(new Action() {
    @Override
    public void write(TProtocol out) throws TException {
      out.writeSetBegin(set);
    }

    @Override
    public String toDebugString() {
      return "<e=" + set.elemType + ", s=" + set.size + ">{*";
    }
  });

  boolean hasFieldsIgnored = readCollectionElements(in, set.size, set.elemType, buffer, expectedType.getValues().getType());
  in.readSetEnd();
  buffer.add(SET_END);
  return hasFieldsIgnored;
}
 
Example 17
Source Project: onos   Source File: Bmv2PreControllerImpl.java    License: Apache License 2.0 6 votes vote down vote up
private boolean doCreateClient(DeviceId deviceId, String thriftServerIp, Integer thriftServerPort) {
    SafeThriftClient.Options options = new SafeThriftClient.Options(numConnectionRetries, timeBetweenRetries);

    try {
        // Make the expensive call
        TTransport transport = new TSocket(thriftServerIp, thriftServerPort);

        TProtocol protocol = new TBinaryProtocol(transport);
        // Create a client for simple_pre service.
        SimplePreLAG.Client simplePreClient = new SimplePreLAG.Client(
                new TMultiplexedProtocol(protocol, THRIFT_SERVICE_NAME));

        SimplePreLAG.Iface safeSimplePreClient = SafeThriftClient.wrap(simplePreClient,
                                                                       SimplePreLAG.Iface.class,
                                                                       options);

        Bmv2DeviceThriftClient client = new Bmv2DeviceThriftClient(deviceId, safeSimplePreClient);
        clients.put(deviceId, Pair.of(transport, client));
        return true;

    } catch (RuntimeException e) {
        log.warn("Failed to create Thrift client for BMv2 device. deviceId={}, cause={}", deviceId, e);
        return false;
    }
}
 
Example 18
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 19
Source Project: Firefly   Source File: FunctionCallTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void voidMethodWithoutOneway() 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.testfirefly.TestService testService = thrift.create(com.meituan.firefly.testfirefly.TestService.class, new Thrift.SimpleTProtocolFactory() {
        @Override
        public TProtocol get() {
            return new TBinaryProtocol(transport);
        }
    });
    testService.notifyWithoutOneway(100);
    Assert.assertTrue(notifyCheck.notified);
}
 
Example 20
Source Project: parquet-mr   Source File: TestThriftRecordConverter.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testUnknownEnumThrowsGoodException() throws Exception {
  EnumType et = new EnumType(Arrays.asList(new EnumValue(77, "hello")));
  ThriftField field = new ThriftField("name", (short) 1, Requirement.REQUIRED, et);

  ArrayList<TProtocol> events = new ArrayList<TProtocol>();

  FieldEnumConverter conv = new  FieldEnumConverter(events, field);

  conv.addBinary(Binary.fromString("hello"));

  assertEquals(1, events.size());
  assertEquals(77, events.get(0).readI32());

  try {
    conv.addBinary(Binary.fromString("FAKE_ENUM_VALUE"));
    fail("this should throw");
  } catch (ParquetDecodingException e) {
    assertEquals("Unrecognized enum value: FAKE_ENUM_VALUE known values: {Binary{\"hello\"}=77} in {\n" +
        "  \"name\" : \"name\",\n" +
        "  \"fieldId\" : 1,\n" +
        "  \"requirement\" : \"REQUIRED\",\n" +
        "  \"type\" : {\n" +
        "    \"id\" : \"ENUM\",\n" +
        "    \"values\" : [ {\n" +
        "      \"id\" : 77,\n" +
        "      \"name\" : \"hello\"\n" +
        "    } ]\n" +
        "  }\n" +
        "}", e.getMessage());
  }
}
 
Example 21
Source Project: parquet-mr   Source File: BufferedProtocolReadToWrite.java    License: Apache License 2.0 5 votes vote down vote up
private void writeShortAction(List<Action> buffer, final short s) {
  buffer.add(new Action() {
    @Override
    public void write(TProtocol out) throws TException {
      out.writeI16(s);
    }

    @Override
    public String toDebugString() {
      return String.valueOf(s);
    }
  });
}
 
Example 22
Source Project: thrift-mock   Source File: JoinServerTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * bind 2 different service into one mock server
 * @throws Exception
 */
@Test
public void testJoinServer() throws TException, InterruptedException {
  ThriftMockServer server = new ThriftMockServer(9988);
  Thread t = new Thread(server::start);
  t.start();
  Thread.sleep(10);

  String name = "guest";
  Response expectHelloResponse = new Response();
  expectHelloResponse.setCode(200);
  expectHelloResponse.setResponseMsg("hello:" + name);

  Response expectByeResponse = new Response();
  expectByeResponse.setCode(201);
  expectByeResponse.setResponseMsg("bye," + name);

  //Join two different service into one server
  //helloService
  server.setExpectReturn("sayHello", expectHelloResponse);
  //byeService
  server.setExpectReturn("sayBye", expectByeResponse);

  Request helloRequest = new Request();
  helloRequest.setMsg("hello, i'm " + name);

  TProtocol protocol = TProtocolUtil.initTProtocol("127.0.0.1", 9988);
  HelloService.Iface helloService = new HelloService.Client(protocol);
  Response actualHelloResponse = helloService.sayHello(helloRequest);
  LOG.info("actualHelloResponse: " + actualHelloResponse);
  Assert.assertTrue(actualHelloResponse.getCode() == 200);

  Request byeRequest = new Request();
  helloRequest.setMsg("bye, i'm " + name);

  ByeService.Iface byeService = new ByeService.Client(protocol);
  Response actualByeResponse = byeService.sayBye(byeRequest);
  LOG.info("actualByeResponse: " + actualByeResponse);
  Assert.assertEquals(actualByeResponse.getCode(), 201);
}
 
Example 23
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 24
Source Project: parquet-mr   Source File: TestParquetTBaseScheme.java    License: Apache License 2.0 5 votes vote down vote up
private void createFileForRead() throws Exception {
  final Path fileToCreate = new Path(parquetInputPath+"/names.parquet");

  final Configuration conf = new Configuration();
  final FileSystem fs = fileToCreate.getFileSystem(conf);
  if (fs.exists(fileToCreate)) fs.delete(fileToCreate, true);

  TProtocolFactory protocolFactory = new TCompactProtocol.Factory();
  TaskAttemptID taskId = new TaskAttemptID("local", 0, true, 0, 0);
  ThriftToParquetFileWriter w = new ThriftToParquetFileWriter(fileToCreate, ContextUtil.newTaskAttemptContext(conf, taskId), protocolFactory, Name.class);

  final ByteArrayOutputStream baos = new ByteArrayOutputStream();
  final TProtocol protocol = protocolFactory.getProtocol(new TIOStreamTransport(baos));

  Name n1 = new Name();
  n1.setFirst_name("Alice");
  n1.setLast_name("Practice");
  Name n2 = new Name();
  n2.setFirst_name("Bob");
  n2.setLast_name("Hope");
  Name n3 = new Name();
  n3.setFirst_name("Charlie");
  n3.setLast_name("Horse");

  n1.write(protocol);
  w.write(new BytesWritable(baos.toByteArray()));
  baos.reset();
  n2.write(protocol);
  w.write(new BytesWritable(baos.toByteArray()));
  baos.reset();
  n3.write(protocol);
  w.write(new BytesWritable(baos.toByteArray()));
  w.close();
}
 
Example 25
Source Project: octo-rpc   Source File: ThriftIDLSerializer.java    License: Apache License 2.0 5 votes vote down vote up
private Object deserializeResult(TProtocol protocol, String ifaceName, String methodName) {
    String resultClassName = ThriftUtil.generateResultClassName(ifaceName, methodName);
    TBase resultClassObj = getClazzInstance(resultClassName);
    try {
        resultClassObj.read(protocol);
    } catch (TException e) {
        throw new ProtocolException("Thrift deserialize result failed.", e);
    }
    Object realResult = null;
    String resultFieldsClassName = ThriftUtil.generateIDLFieldsClassName(resultClassObj.getClass().getName());
    Class<?> resultFieldsClazz = getClazz(resultFieldsClassName);
    Object[] resultFieldsEnums = resultFieldsClazz.getEnumConstants();
    if (resultFieldsEnums == null) {
        return realResult;
    }
    // 避免基本类型默认值导致异常返回被忽略, 从后面开始获取值
    for (int i = resultFieldsEnums.length - 1; i >= 0; i--) {
        TFieldIdEnum fieldIdEnum = (TFieldIdEnum) resultFieldsEnums[i];
        if (fieldIdEnum == null) {
            continue;
        }
        Object fieldValue = resultClassObj.getFieldValue(fieldIdEnum);
        if (fieldValue != null) {
            if (BYTE_ARRAY_CLASS_NAME.equals(fieldValue.getClass().getName())) {
                fieldValue = ByteBuffer.wrap((byte[]) fieldValue);
            }
            realResult = fieldValue;
            break;
        }
    }
    return realResult;
}
 
Example 26
Source Project: parquet-mr   Source File: BufferedProtocolReadToWrite.java    License: Apache License 2.0 5 votes vote down vote up
private void writeIntAction(List<Action> buffer, final int i) {
  buffer.add(new Action() {
    @Override
    public void write(TProtocol out) throws TException {
      out.writeI32(i);
    }

    @Override
    public String toDebugString() {
      return String.valueOf(i);
    }
  });
}
 
Example 27
Source Project: parquet-mr   Source File: BufferedProtocolReadToWrite.java    License: Apache License 2.0 5 votes vote down vote up
private void writeDoubleAction(List<Action> buffer, final double d) {
  buffer.add(new Action() {
    @Override
    public void write(TProtocol out) throws TException {
      out.writeDouble(d);
    }

    @Override
    public String toDebugString() {
      return String.valueOf(d);
    }
  });
}
 
Example 28
Source Project: incubator-sentry   Source File: InternalSentrySrv.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Thrift callback when a client is disconnecting
 */
@Override
public void deleteContext(ServerContext arg0, TProtocol arg1, TProtocol arg2) {
  clientList.remove(((SentryServerContext) arg0).getContextId());
  LOGGER.info("Client Disonnected: "
      + ((SentryServerContext) arg0).getContextId());
}
 
Example 29
Source Project: parquet-mr   Source File: ProtocolReadToWrite.java    License: Apache License 2.0 5 votes vote down vote up
private void readOneStruct(TProtocol in, TProtocol out) throws TException {
  final TStruct struct = in.readStructBegin();
  out.writeStructBegin(struct);
  TField field;
  while ((field = in.readFieldBegin()).type != TType.STOP) {
    out.writeFieldBegin(field);
    readOneValue(in, out, field.type);
    in.readFieldEnd();
    out.writeFieldEnd();
  }
  out.writeFieldStop();
  in.readStructEnd();
  out.writeStructEnd();
}
 
Example 30
Source Project: pinpoint   Source File: TBaseStream.java    License: Apache License 2.0 5 votes vote down vote up
public void write(final TBase<?, ?> base) throws TException {
    final TBaseStreamNode node = new TBaseStreamNode(transport);
    node.setClassName(base.getClass().getName());
    node.setBeginPosition(transport.getBufferPosition());

    final TProtocol protocol = protocolFactory.getProtocol(transport);
    base.write(protocol);

    node.setEndPosition(transport.getBufferPosition());
    nodes.add(node);
}