org.apache.thrift.protocol.TType Java Examples

The following examples show how to use org.apache.thrift.protocol.TType. 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: MockResult.java    From thrift-mock with Apache License 2.0 6 votes vote down vote up
public void read(org.apache.thrift.protocol.TProtocol iprot, MockResult struct) throws org.apache.thrift.TException {
  org.apache.thrift.protocol.TField schemeField;
  iprot.readStructBegin();
  while (true) {
    schemeField = iprot.readFieldBegin();
    if (schemeField.type == TType.STOP) {
      break;
    }
    processSchemeField(schemeField, iprot, struct);
    iprot.readFieldEnd();
  }
  iprot.readStructEnd();

  // check for required fields of primitive type, which can't be checked in the validate method
  struct.validate();
}
 
Example #2
Source File: ThriftRequestProperty.java    From pinpoint with Apache License 2.0 6 votes vote down vote up
public void writeTraceHeader(ThriftHeader headerKey, TProtocol oprot) throws TException {
    Object headerValue = this.thriftHeaders.get(headerKey);
    if (headerValue == null) {
        return;
    }
    byte headerType = headerKey.getType();
    TField traceField = new TField(headerKey.name(), headerKey.getType(), headerKey.getId());
    oprot.writeFieldBegin(traceField);
    try {
        if (headerType == TType.STRING) {
            // these will be read as byte buffer although it's probably safe to just use writeString here.
            // see org.apache.thrift.protocol.TProtocolUtil.skip(TProtocol, byte, int)
            oprot.writeBinary(stringToByteBuffer((String)headerValue));
        } else if (headerType == TType.I64) {
            oprot.writeI64((Long)headerValue);
        } else if (headerType == TType.I16) {
            oprot.writeI16((Short)headerValue);
        } else if (headerType == TType.BOOL) {
            oprot.writeBool((Boolean)headerValue);
        } else {
            throw new TProtocolException("Invalid pinpoint header type - " + headerType);
        }
    } finally {
        oprot.writeFieldEnd();
    }
}
 
Example #3
Source File: ThriftRequestProperty.java    From pinpoint with Apache License 2.0 6 votes vote down vote up
public void setTraceHeader(ThriftHeader headerKey, Object value) throws TException {
    byte headerType = headerKey.getType();
    if (headerType == TType.STRING) {
        // skipped Strings are read as byte buffer.
        // see org.apache.thrift.protocol.TProtocolUtil.skip(TProtocol, byte, int)
        this.thriftHeaders.put(headerKey, byteBufferToString((ByteBuffer)value));
    } else if (headerType == TType.I64) {
        this.thriftHeaders.put(headerKey, (Long)value);
    } else if (headerType == TType.I16) {
        this.thriftHeaders.put(headerKey, (Short)value);
    } else if (headerType == TType.BOOL) {
        this.thriftHeaders.put(headerKey, (Boolean)value);
    } else {
        throw new TProtocolException("Invalid pinpoint header type - " + headerType);
    }
}
 
Example #4
Source File: ParquetWriteProtocol.java    From parquet-mr with Apache License 2.0 6 votes vote down vote up
@Override
public void writeFieldBegin(TField field) throws TException {
  if (field.type == TType.STOP) {
    return;
  }
  try {
    currentType = thriftFieldIdToParquetField[field.id];
    if (currentType == null) {
      throw new ParquetEncodingException("field " + field.id + " was not found in " + thriftType + " and " + schema.getType());
    }
    final int index = currentType.getIndex();
    recordConsumer.startField(currentType.getName(), index);
    currentProtocol = children[index];
  } catch (ArrayIndexOutOfBoundsException e) {
    throw new ParquetEncodingException("field " + field.id + " was not found in " + thriftType + " and " + schema.getType());
  }
}
 
Example #5
Source File: LocatorServiceImpl.java    From gemfirexd-oss with 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 #6
Source File: AbstractThriftBase.java    From ikasoa with MIT License 6 votes vote down vote up
/**
 * 读取操作
 */
@Override
public void read(TProtocol iprot) throws TException {
	if (!StringUtil.equals("org.apache.thrift.scheme.StandardScheme", iprot.getScheme().getName()))
		throw new TApplicationException("Service scheme must be 'org.apache.thrift.scheme.StandardScheme' !");
	TField schemeField;
	iprot.readStructBegin();
	while (true) {
		schemeField = iprot.readFieldBegin();
		if (ObjectUtil.same(schemeField.type, TType.STOP))
			break;
		if (ObjectUtil.same(schemeField.type, TType.STRING))
			str = iprot.readString();
		else
			throw new TApplicationException("field type must be 'String' !");
		iprot.readFieldEnd();
	}
	iprot.readStructEnd();
}
 
Example #7
Source File: LocatorServiceImpl.java    From gemfirexd-oss with 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 #8
Source File: MockResult.java    From thrift-mock with Apache License 2.0 6 votes vote down vote up
public MockResult(String methodName, TBase value) {
  this.methodName = methodName;
  this.success = value;
  this.structDesc = new TStruct(methodName+"_result");

  //init metaDatMap
  Map<_Fields, FieldMetaData> tmpMap = new EnumMap<>(_Fields.class);
  tmpMap.put(_Fields.SUCCESS,
             new FieldMetaData(SUCCESS_NAME, TFieldRequirementType.DEFAULT,
                               new FieldValueMetaData(TType.STRUCT          , value.getClass().getCanonicalName())));
  metaDataMap = Collections.unmodifiableMap(tmpMap);
  FieldMetaData.addStructMetaDataMap(MockResult.class, metaDataMap);

  schemes.put(StandardScheme.class, new MockResultStandardSchemeFactory(structDesc));
  schemes.put(TupleScheme.class, new MockResultTupleSchemeFactory());

}
 
Example #9
Source File: TProtobufProcessor.java    From jigsaw-payment with Apache License 2.0 6 votes vote down vote up
@Override
public boolean process(TProtocol in, TProtocol out) throws TException {
	TMessage msg = in.readMessageBegin();
	Controller<?, ?> fn = (Controller<?, ?>) this.beanFactory
			.getBean(msg.name);
	if (fn == null) {
		if (LOGGER.isWarnEnabled()) {
			LOGGER.warn("Invalid request: failed to find interface="
					+ msg.name + ", from: " + getInetAddress(in));
		}

		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;
	}
	process(msg.seqid, msg.name, in, out, fn);
	return true;
}
 
Example #10
Source File: ThriftProtocolAgentIntercept.java    From java-specialagent with Apache License 2.0 6 votes vote down vote up
public static void writeFieldStop(final Object protocol) throws TException {
  if (injected.get())
    return;

  final TProtocol tProtocol = (TProtocol)protocol;
  final Span span = spanHolder.get();
  if (span == null)
    return;

  final Map<String,String> map = new HashMap<>();
  GlobalTracer.get().inject(span.context(), Builtin.TEXT_MAP, new TextMapAdapter(map));

  tProtocol.writeFieldBegin(new TField("span", TType.MAP, SPAN_FIELD_ID));
  tProtocol.writeMapBegin(new TMap(TType.STRING, TType.STRING, map.size()));
  for (final Entry<String,String> entry : map.entrySet()) {
    tProtocol.writeString(entry.getKey());
    tProtocol.writeString(entry.getValue());
  }

  tProtocol.writeMapEnd();
  tProtocol.writeFieldEnd();
  injected.set(true);
}
 
Example #11
Source File: TApplicationExceptions.java    From armeria with Apache License 2.0 5 votes vote down vote up
/**
 * Reads a {@link TApplicationException} from the specified {@link TProtocol}.
 *
 * <p>Note: This has been copied from {@link TApplicationException#read(TProtocol)} due to API differences
 * between libthrift 0.9.x and 0.10.x.
 */
public static TApplicationException read(TProtocol iprot) throws TException {
    TField field;
    iprot.readStructBegin();

    String message = null;
    int type = TApplicationException.UNKNOWN;

    while (true) {
        field = iprot.readFieldBegin();
        if (field.type == TType.STOP) {
            break;
        }
        switch (field.id) {
            case 1:
                if (field.type == TType.STRING) {
                    message = iprot.readString();
                } else {
                    TProtocolUtil.skip(iprot, field.type);
                }
                break;
            case 2:
                if (field.type == TType.I32) {
                    type = iprot.readI32();
                } else {
                    TProtocolUtil.skip(iprot, field.type);
                }
                break;
            default:
                TProtocolUtil.skip(iprot, field.type);
                break;
        }
        iprot.readFieldEnd();
    }
    iprot.readStructEnd();

    return new TApplicationException(type, message);
}
 
Example #12
Source File: ThriftDocServicePluginTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void testNewExceptionInfo() {
    final ExceptionInfo exception = newExceptionInfo(FooServiceException.class);

    assertThat(exception).isEqualTo(new ExceptionInfo(
            FooServiceException.class.getName(),
            ImmutableList.of(newFieldInfo(
                    FooServiceException.class,
                    new FieldMetaData("stringVal", TFieldRequirementType.DEFAULT,
                                      new FieldValueMetaData(TType.STRING, false))))));
}
 
Example #13
Source File: CompFileWrite.java    From ThriftBook with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws TException {
    TTransport trans = new TSimpleFileTransport("data.comp", false, true);
    TProtocol proto = new TCompactProtocol(trans);			

    Trade trade = new Trade();
    trade.symbol = "F";
    trade.price = 13.10;
    trade.size = 2500;

    proto.writeStructBegin(new TStruct());

    proto.writeFieldBegin(new TField("symbol", 
                                     TType.STRING, 
                                     (short) 1));
    proto.writeString(trade.symbol);
    proto.writeFieldEnd();

    proto.writeFieldBegin(new TField("price", 
                                     TType.DOUBLE, 
                                     (short) 2));
    proto.writeDouble(trade.price);
    proto.writeFieldEnd();

    proto.writeFieldBegin(new TField("size", 
                                     TType.I32, 
                                     (short) 3));
    proto.writeI32(trade.size);
    proto.writeFieldEnd();

    proto.writeFieldStop();
    proto.writeStructEnd();
    
    System.out.println("Wrote trade to file");
}
 
Example #14
Source File: BinFileRead.java    From ThriftBook with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws TException {
    TTransport trans = new TSimpleFileTransport("data", true, false);
    TProtocol proto = new TBinaryProtocol(trans);		

    Trade trade_read = new Trade();
    TField field = new TField();

    TStruct struct_obj = proto.readStructBegin();		
    while(true) {						
        field = proto.readFieldBegin();			
        if (field.id == TType.STOP) {				
            break;
        }
        switch(field.id) {					
        case 1:
            trade_read.symbol = proto.readString();	
            break;
        case 2:
            trade_read.price = proto.readDouble();
            break;
        case 3:
            trade_read.size = proto.readI32();
            break;
        default:
            TProtocolUtil.skip(proto,field.type);	
            break;
        }
        proto.readFieldEnd();				
    }
    proto.readStructEnd();				

    System.out.println("Trade: " + trade_read.symbol + " " +
                       trade_read.size + " @ " + trade_read.price);
}
 
Example #15
Source File: EventBasedThriftReader.java    From parquet-format with Apache License 2.0 5 votes vote down vote up
/**
 * reads the content of a struct (fields) from the underlying protocol and passes the events to c
 * @param c the field consumer
 * @throws TException
 */
public void readStructContent(FieldConsumer c) throws TException {
  TField field;
  while (true) {
    field = protocol.readFieldBegin();
    if (field.type == TType.STOP) {
      break;
    }
    c.consumeField(protocol, this, field.id, field.type);
  }
}
 
Example #16
Source File: EventBasedThriftReader.java    From parquet-mr with Apache License 2.0 5 votes vote down vote up
/**
 * reads the content of a struct (fields) from the underlying protocol and passes the events to c
 * @param c the field consumer
 * @throws TException if any thrift related error occurs during the reading
 */
public void readStructContent(FieldConsumer c) throws TException {
  TField field;
  while (true) {
    field = protocol.readFieldBegin();
    if (field.type == TType.STOP) {
      break;
    }
    c.consumeField(protocol, this, field.id, field.type);
  }
}
 
Example #17
Source File: ProtocolReadToWrite.java    From parquet-mr with 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 #18
Source File: MockResult.java    From thrift-mock with Apache License 2.0 5 votes vote down vote up
private void readSuccessStruct(org.apache.thrift.protocol.TField schemeField,
                               org.apache.thrift.protocol.TProtocol iprot,
                               MockResult struct) throws org.apache.thrift.TException {
  if (schemeField.type == TType.STRUCT) {
    try {
      struct.success = struct.success.getClass().newInstance();
    } catch (Exception e) {
      throw new IllegalArgumentException("init object failed:" + struct.success.getClass() + e);
    }
    struct.success.read(iprot);
    struct.setSuccessIsSet(true);
  } else {
    org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
  }
}
 
Example #19
Source File: GFXDServiceImpl.java    From gemfirexd-oss with Apache License 2.0 5 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<GFXDServiceImpl, ?> 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
    // TODO: SW: also need to clean up connection artifacts in the case of
    // client connection failure (ConnectionListener does get a notification
    // but how to tie the socket/connectionNumber to the connectionID?)
    return fn.getClass() != GFXDService.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 #20
Source File: InternalScribeCodec.java    From zipkin-reporter-java with Apache License 2.0 5 votes vote down vote up
static boolean parseResponse(TBinaryProtocol iprot) throws TException {
  Boolean result = null;
  iprot.readStructBegin();
  TField schemeField;
  while ((schemeField = iprot.readFieldBegin()).type != TType.STOP) {
    if (schemeField.id == 0 /* SUCCESS */ && schemeField.type == TType.I32) {
      result = iprot.readI32() == 0;
    } else {
      TProtocolUtil.skip(iprot, schemeField.type);
    }
  }
  iprot.readStructEnd();
  if (result != null) return result;
  throw new TApplicationException(MISSING_RESULT, "Log failed: unknown result");
}
 
Example #21
Source File: InternalScribeCodec.java    From zipkin-reporter-java with Apache License 2.0 5 votes vote down vote up
public static void writeLogRequest(
    byte[] category, List<byte[]> encodedSpans, int seqid, TBinaryProtocol oprot)
    throws TException {
  oprot.writeMessageBegin(new TMessage("Log", TMessageType.CALL, seqid));
  oprot.writeFieldBegin(MESSAGES_FIELD_DESC);
  oprot.writeListBegin(new TList(TType.STRUCT, encodedSpans.size()));
  for (byte[] encodedSpan : encodedSpans) write(category, encodedSpan, oprot);
  oprot.writeFieldStop();
}
 
Example #22
Source File: AbstractThriftBase.java    From ikasoa with MIT License 5 votes vote down vote up
/**
 * 写入操作
 */
@Override
public void write(TProtocol oprot) throws TException {
	if (!StringUtil.equals("org.apache.thrift.scheme.StandardScheme", oprot.getScheme().getName()))
		throw new TApplicationException("Service scheme must be 'org.apache.thrift.scheme.StandardScheme' !");
	oprot.writeStructBegin(getTStruct());
	if (ObjectUtil.isNotNull(str)) {
		oprot.writeFieldBegin(new TField("value", TType.STRING, (short) 0));
		oprot.writeString(str);
		oprot.writeFieldEnd();
	}
	oprot.writeFieldStop();
	oprot.writeStructEnd();
}
 
Example #23
Source File: ThriftFrameDecoder.java    From ikasoa with MIT License 5 votes vote down vote up
protected ChannelBuffer tryDecodeUnframedMessage(ChannelHandlerContext ctx, Channel channel, ChannelBuffer buffer,
		TProtocolFactory inputProtocolFactory) throws TException {

	int messageLength = 0;
	int messageStartReaderIndex = buffer.readerIndex();

	try {
		TNettyTransport decodeAttemptTransport = new TNettyTransport(channel, buffer, TNettyTransportType.UNFRAMED);
		int initialReadBytes = decodeAttemptTransport.getReadByteCount();
		TProtocol inputProtocol = inputProtocolFactory.getProtocol(decodeAttemptTransport);
		inputProtocol.readMessageBegin();
		TProtocolUtil.skip(inputProtocol, TType.STRUCT);
		inputProtocol.readMessageEnd();
		messageLength = decodeAttemptTransport.getReadByteCount() - initialReadBytes;
	} catch (TTransportException | IndexOutOfBoundsException e) {
		return null;
	} finally {
		if (buffer.readerIndex() - messageStartReaderIndex > maxFrameSize)
			Channels.fireExceptionCaught(ctx,
					new TooLongFrameException(String.format("Maximum frame size of %d exceeded .", maxFrameSize)));
		buffer.readerIndex(messageStartReaderIndex);
	}

	if (messageLength <= 0)
		return null;

	ChannelBuffer messageBuffer = extractFrame(buffer, messageStartReaderIndex, messageLength);
	buffer.readerIndex(messageStartReaderIndex + messageLength);
	return messageBuffer;
}
 
Example #24
Source File: GFXDServiceImpl.java    From gemfirexd-oss with Apache License 2.0 5 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<GFXDServiceImpl, ?> 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
    // TODO: SW: also need to clean up connection artifacts in the case of
    // client connection failure (ConnectionListener does get a notification
    // but how to tie the socket/connectionNumber to the connectionID?)
    return fn.getClass() != GFXDService.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 #25
Source File: BufferedProtocolReadToWrite.java    From parquet-mr with Apache License 2.0 4 votes vote down vote up
/**
 * @return true when all value is consumed, false when some values is ignored due to the field is not defined in expectedType
 * @throws TException
 */
private boolean readOneValue(TProtocol in, byte type, List<Action> buffer, ThriftType expectedType) throws TException {
  if (expectedType != null && expectedType.getType().getSerializedThriftType() != type) {
    throw new DecodingSchemaMismatchException("the data type does not match the expected thrift structure: expected " + expectedType + " got " + typeName(type));
  }
  boolean hasFieldsIgnored = false;
  switch (type) {
  case TType.LIST:
    hasFieldsIgnored = readOneList(in, buffer, (ListType)expectedType);
    break;
  case TType.MAP:
    hasFieldsIgnored = readOneMap(in, buffer, (MapType)expectedType);
    break;
  case TType.SET:
    hasFieldsIgnored = readOneSet(in, buffer, (SetType)expectedType);
    break;
  case TType.STRUCT:
    hasFieldsIgnored = readOneStruct(in, buffer, (StructType)expectedType);
    break;
  case TType.STOP:
    break;
  case TType.BOOL:
    final boolean bool = in.readBool();
    writeBoolAction(buffer, bool);
    break;
  case TType.BYTE:
    final byte b = in.readByte();
    writeByteAction(buffer, b);
    break;
  case TType.DOUBLE:
    final double d = in.readDouble();
    writeDoubleAction(buffer, d);
    break;
  case TType.I16:
    final short s = in.readI16();
    writeShortAction(buffer, s);
    break;
  case TType.ENUM: // same as i32 => actually never seen in the protocol layer as enums are written as a i32 field
  case TType.I32:
    final int i = in.readI32();
    checkEnum(expectedType,i);
    writeIntAction(buffer, i);
    break;
  case TType.I64:
    final long l = in.readI64();
    writeLongAction(buffer, l);
    break;
  case TType.STRING:
    final ByteBuffer bin = in.readBinary();
    writeStringAction(buffer, bin);
    break;
  case TType.VOID:
    break;
  default:
    throw new TException("Unknown type: " + type);
  }
  return hasFieldsIgnored;
}
 
Example #26
Source File: ProtocolReadToWrite.java    From parquet-mr with Apache License 2.0 4 votes vote down vote up
void readOneValue(TProtocol in, TProtocol out, byte type)
    throws TException {
  switch (type) {
  case TType.LIST:
    readOneList(in, out);
    break;
  case TType.MAP:
    readOneMap(in, out);
    break;
  case TType.SET:
    readOneSet(in, out);
    break;
  case TType.STRUCT:
    readOneStruct(in, out);
    break;
  case TType.STOP:
    break;
  case TType.BOOL:
    out.writeBool(in.readBool());
    break;
  case TType.BYTE:
    out.writeByte(in.readByte());
    break;
  case TType.DOUBLE:
    out.writeDouble(in.readDouble());
    break;
  case TType.I16:
    out.writeI16(in.readI16());
    break;
  case TType.ENUM: // same as i32 => actually never seen in the protocol layer as enums are written as a i32 field
  case TType.I32:
    out.writeI32(in.readI32());
    break;
  case TType.I64:
    out.writeI64(in.readI64());
    break;
  case TType.STRING:
    out.writeBinary(in.readBinary());
    break;
  case TType.VOID:
    break;
  default:
    throw new TException("Unknown type: " + type);
  }
}
 
Example #27
Source File: MappedFileTBinaryProtocol.java    From singer with Apache License 2.0 4 votes vote down vote up
public TField readFieldBegin() throws TException {
  byte type = readByte();
  short id = type == TType.STOP ? 0 : readI16();
  return new TField("", type, id);
}
 
Example #28
Source File: ThriftDocServicePluginTest.java    From armeria with Apache License 2.0 4 votes vote down vote up
@Test
void incompleteStructMetadata() throws Exception {
    assertThat(toTypeSignature(new FieldValueMetaData(TType.STRUCT)))
            .isEqualTo(TypeSignature.ofUnresolved("unknown"));
}
 
Example #29
Source File: StructContext.java    From armeria with Apache License 2.0 4 votes vote down vote up
/**
 * Compute a new field name map for the current thrift message
 * we are parsing.
 */
private Map<String, TField> computeFieldNameMap(Class<?> clazz) {
    final Map<String, TField> map = new HashMap<>();

    if (isTBase(clazz)) {
        // Get the metaDataMap for this Thrift class
        @SuppressWarnings("unchecked")
        final Map<? extends TFieldIdEnum, FieldMetaData> metaDataMap =
                FieldMetaData.getStructMetaDataMap((Class<? extends TBase<?, ?>>) clazz);

        for (Entry<? extends TFieldIdEnum, FieldMetaData> e : metaDataMap.entrySet()) {
            final String fieldName = e.getKey().getFieldName();
            final FieldMetaData metaData = e.getValue();

            final FieldValueMetaData elementMetaData;
            if (metaData.valueMetaData.isContainer()) {
                if (metaData.valueMetaData instanceof SetMetaData) {
                    elementMetaData = ((SetMetaData) metaData.valueMetaData).elemMetaData;
                } else if (metaData.valueMetaData instanceof ListMetaData) {
                    elementMetaData = ((ListMetaData) metaData.valueMetaData).elemMetaData;
                } else if (metaData.valueMetaData instanceof MapMetaData) {
                    elementMetaData = ((MapMetaData) metaData.valueMetaData).valueMetaData;
                } else {
                    // Unrecognized container type, but let's still continue processing without
                    // special enum support.
                    elementMetaData = metaData.valueMetaData;
                }
            } else {
                elementMetaData = metaData.valueMetaData;
            }

            if (elementMetaData instanceof EnumMetaData) {
                classMap.put(fieldName, ((EnumMetaData) elementMetaData).enumClass);
            } else if (elementMetaData instanceof StructMetaData) {
                classMap.put(fieldName, ((StructMetaData) elementMetaData).structClass);
            } else {
                // Workaround a bug where the generated 'FieldMetaData' does not provide
                // a fully qualified class name.
                final String typedefName = elementMetaData.getTypedefName();
                if (typedefName != null) {
                    final String fqcn = clazz.getPackage().getName() + '.' + typedefName;
                    Class<?> fieldClass = fieldMetaDataClassCache.get(fqcn);
                    if (fieldClass == null) {
                        fieldClass = fieldMetaDataClassCache.computeIfAbsent(fqcn, key -> {
                            try {
                                return Class.forName(key);
                            } catch (ClassNotFoundException ignored) {
                                return StructContext.class;
                            }
                        });
                    }
                    if (fieldClass != StructContext.class) {
                        classMap.put(fieldName, fieldClass);
                    }
                }
            }

            // Workaround a bug in the generated thrift message read()
            // method by mapping the ENUM type to the INT32 type
            // The thrift generated parsing code requires that, when expecting
            // a value of enum, we actually parse a value of type int32. The
            // generated read() method then looks up the enum value in a map.
            final byte type = TType.ENUM == metaData.valueMetaData.type ? TType.I32
                                                                        : metaData.valueMetaData.type;

            map.put(fieldName,
                    new TField(fieldName,
                               type,
                               e.getKey().getThriftFieldId()));
        }
    } else { // TApplicationException
        map.put("message", new TField("message", (byte)11, (short)1));
        map.put("type", new TField("type", (byte)8, (short)2));
    }

    return map;
}
 
Example #30
Source File: TypeAdapter.java    From Firefly with Apache License 2.0 4 votes vote down vote up
@Override
public byte getTType() {
    return TType.DOUBLE;
}