Java Code Examples for org.apache.thrift.protocol.TMessageType#EXCEPTION

The following examples show how to use org.apache.thrift.protocol.TMessageType#EXCEPTION . 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: ThriftJacksonTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void serializeThriftReplyWithException() throws IOException {
    final ThriftReply reply = new ThriftReply(
            new TMessage(THRIFT_METHOD_NAME, TMessageType.EXCEPTION, 0),
            new TApplicationException(1, "don't wanna say hello"));
    final String actualJson = defaultMapper.writeValueAsString(reply);
    final String actualJson2 = customMapper.writeValueAsString(reply);

    assertThatJson(actualJson).isEqualTo(
            '{' +
            "    \"header\": {" +
            "        \"name\": \"hello\"," +
            "        \"type\": 3," +
            "        \"seqid\": 0" +
            "    }," +
            "    \"result\": null," +
            "    \"exception\": {" +
            "        \"type\": 1," +
            "        \"message\": \"don't wanna say hello\"" +
            "    }" +
            '}');
    assertThatJson(actualJson2).isEqualTo(actualJson);
}
 
Example 2
Source File: ThriftIDLSerializer.java    From octo-rpc with Apache License 2.0 6 votes vote down vote up
protected RpcResult doDeserializeResponse(DefaultResponse response, TMessage message,
                                          TProtocol protocol) throws Exception {
    RpcResult rpcResult = new RpcResult();
    if (message.type == TMessageType.REPLY) {
        Object realResult = deserializeResult(protocol, response.getServiceInterface().getName(), message.name);
        if (realResult instanceof Exception) {
            // 服务端自定义异常
            response.setException((Exception) realResult);
        }
        rpcResult.setReturnVal(realResult);
    } else if (message.type == TMessageType.EXCEPTION) {
        TApplicationException exception = TApplicationException.read(protocol);
        MetaUtil.wrapException(exception, response);
    }
    if (!response.isOctoProtocol() && hasOldRequestHeader(protocol)) {
        // 解析老协议的Header
        RequestHeader requestHeader = new RequestHeader();
        protocol.readFieldBegin();
        requestHeader.read(protocol);
        protocol.readFieldEnd();
    }
    return rpcResult;
}
 
Example 3
Source File: TestDriftNettyServerTransport.java    From drift with Apache License 2.0 6 votes vote down vote up
private static ResultCode readLogResponse(int expectedSequenceId, TProtocol protocol)
        throws TException
{
    TMessage message = protocol.readMessageBegin();
    if (message.type == TMessageType.EXCEPTION) {
        throw TApplicationException.readFrom(protocol);
    }
    if (message.type != TMessageType.REPLY) {
        throw new TApplicationException(MISSING_RESULT, "request failed");
    }
    if (message.seqid != expectedSequenceId) {
        throw new TApplicationException(BAD_SEQUENCE_ID, format("expected sequenceId %s, but received %s", expectedSequenceId, message.seqid));
    }

    Log_result result = new Log_result();
    result.read(protocol);
    protocol.readMessageEnd();
    return result.success;
}
 
Example 4
Source File: TypedParser.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Override
void writeValue(JsonGenerator jw, Byte val) throws IOException {
    final String serialized;
    switch (val.byteValue()) {
    case TMessageType.CALL:
        serialized = "CALL";
        break;
    case TMessageType.REPLY:
        serialized = "REPLY";
        break;
    case TMessageType.EXCEPTION:
        serialized = "EXCEPTION";
        break;
    case TMessageType.ONEWAY:
        serialized = "ONEWAY";
        break;
    default:
        throw new IllegalArgumentException("Unsupported message type: " + val);
    }
    jw.writeString(serialized);
}
 
Example 5
Source File: TServiceClientNoPrint.java    From rpc-benchmark with Apache License 2.0 6 votes vote down vote up
@Override
protected void receiveBase(TBase<?, ?> result, String methodName) throws TException {
	TMessage msg = iprot_.readMessageBegin();
	if (msg.type == TMessageType.EXCEPTION) {
		TApplicationException x = new TApplicationException();
		x.read(iprot_);
		iprot_.readMessageEnd();
		throw x;
	}
	// System.out.format("Received %d%n", msg.seqid);
	if (msg.seqid != seqid_) {
		throw new TApplicationException(TApplicationException.BAD_SEQUENCE_ID, String.format(
				"%s failed: out of sequence response: expected %d but got %d", methodName, seqid_, msg.seqid));
	}
	result.read(iprot_);
	iprot_.readMessageEnd();
}
 
Example 6
Source File: THttpClientDelegate.java    From armeria with 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 File: ThriftIDLSerializer.java    From octo-rpc with Apache License 2.0 5 votes vote down vote up
@Override
protected Object deserialize4Thrift(byte[] buff, Class<?> iface, Map<String, Object> attachments) throws Exception {
    TraceTimeline timeline = TraceTimeline.newRecord(CommonUtil.objectToBool(attachments.get(Constants.TRACE_IS_RECORD_TIMELINE), false),
            TraceTimeline.DECODE_START_TS);

    Object obj = null;
    TMemoryInputTransport transport = new TMemoryInputTransport(buff);
    TBinaryProtocol protocol = new TBinaryProtocol(transport);
    TMessage message = protocol.readMessageBegin();
    if (message.type == TMessageType.CALL) {
        DefaultRequest request = new DefaultRequest(Long.valueOf(message.seqid));
        request.setServiceInterface(iface);
        RpcInvocation rpcInvocation = doDeserializeRequest(request, message, protocol);
        request.setData(rpcInvocation);
        obj = request;

        rpcInvocation.putAttachment(Constants.TRACE_TIMELINE, timeline);
    } else if (message.type == TMessageType.REPLY || message.type == TMessageType.EXCEPTION) {
        DefaultResponse response = new DefaultResponse(Long.valueOf(message.seqid));
        response.setServiceInterface(iface);
        try {
            RpcResult rpcResult = doDeserializeResponse(response, message, protocol);
            response.setResult(rpcResult);
        } catch (Exception e) {
            response.setException(e);
        }

        obj = response;
        if (response.getRequest() != null && response.getRequest().getData() != null) {
            TraceTimeline.copyRecord(timeline, response.getRequest().getData());
        }
    } else {
        throw new ProtocolException("Thrift deserialize message type is invalid");
    }
    protocol.readMessageEnd();

    MetaUtil.recordTraceInfoInDecode(buff, obj);
    return obj;
}
 
Example 8
Source File: ThriftReply.java    From armeria with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new instance that contains a Thrift {@link TMessageType#EXCEPTION} message.
 */
public ThriftReply(TMessage header, TApplicationException exception) {
    super(header);
    if (header.type != TMessageType.EXCEPTION) {
        throw new IllegalArgumentException(
                "header.type: " + typeStr(header.type) + " (expected: EXCEPTION)");
    }

    result = null;
    this.exception = requireNonNull(exception, "exception");
}
 
Example 9
Source File: TypedParser.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Override
Byte readFromString(String s) {
    switch (s) {
    case "CALL":
        return TMessageType.CALL;
    case "REPLY":
        return TMessageType.REPLY;
    case "EXCEPTION":
        return TMessageType.EXCEPTION;
    case "ONEWAY":
        return TMessageType.ONEWAY;
    default:
        throw new IllegalArgumentException("Unsupported message type: " + s);
    }
}
 
Example 10
Source File: ThriftMessage.java    From armeria with Apache License 2.0 5 votes vote down vote up
static String typeStr(byte type) {
    switch (type) {
        case TMessageType.CALL:
            return "CALL";
        case TMessageType.ONEWAY:
            return "ONEWAY";
        case TMessageType.REPLY:
            return "REPLY";
        case TMessageType.EXCEPTION:
            return "EXCEPTION";
        default:
            return "UNKNOWN(" + (type & 0xFF) + ')';
    }
}
 
Example 11
Source File: THttpService.java    From armeria with Apache License 2.0 5 votes vote down vote up
private static String typeString(byte typeValue) {
    switch (typeValue) {
        case TMessageType.CALL:
            return "CALL";
        case TMessageType.REPLY:
            return "REPLY";
        case TMessageType.EXCEPTION:
            return "EXCEPTION";
        case TMessageType.ONEWAY:
            return "ONEWAY";
        default:
            return "UNKNOWN(" + (typeValue & 0xFF) + ')';
    }
}
 
Example 12
Source File: InternalScribeCodec.java    From zipkin-reporter-java with Apache License 2.0 5 votes vote down vote up
/** Returns false if the scribe response was try later. */
public static boolean readLogResponse(int seqid, TBinaryProtocol iprot) throws TException {
  TMessage msg = iprot.readMessageBegin();
  if (msg.type == TMessageType.EXCEPTION) {
    throw TApplicationException.readFrom(iprot);
  } else if (msg.seqid != seqid) {
    throw new TApplicationException(BAD_SEQUENCE_ID, "Log failed: out of sequence response");
  }
  return parseResponse(iprot);
}
 
Example 13
Source File: TSimpleJSONProtocol.java    From nettythrift with Apache License 2.0 4 votes vote down vote up
/**
 * Reading methods.
 */
public TMessage readMessageBegin() throws TException {
	byte[] buf = new byte[256];
	ByteArrayOutputStream out = new ByteArrayOutputStream(1024);
	while (true) {
		int readLen = trans_.read(buf, 0, buf.length);
		if (readLen == 0) {
			break;
		}
		out.write(buf, 0, readLen);
		if (readLen < buf.length) {
			break;
		}
	}
	String sb = null;
	try {
		buf = out.toByteArray();
		sb = new String(buf, "UTF-8");
	} catch (UnsupportedEncodingException e1) {
		e1.printStackTrace();
	}
	// System.out.println("读取完毕: sb=" + sb);
	// TODO JSON 格式的检查
	if (sb.charAt(0) != '[' || sb.charAt(sb.length() - 1) != ']') {
		throw new TProtocolException(TProtocolException.INVALID_DATA, "bad format!");
	}
	JSONArray jsonArray = new JSONArray(sb);
	TMessage msg = new TMessage(jsonArray.getString(0), (byte) jsonArray.getInt(1), jsonArray.getInt(2));
	// System.out.println(msg + ", jsonArray.len = " + jsonArray.length());

	if (jsonArray.length() > 3) {
		if (argsTBaseClass == null) {
			try {
				argsTBaseClass = guessTBaseClassByMethodName(msg.name);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		if (argsTBaseClass == null) {
			// throw new
			// TProtocolException(TApplicationException.UNKNOWN_METHOD,
			// "Invalid method name: '" + msg.name + "'");
			return new TMessage(msg.name, TMessageType.EXCEPTION, msg.seqid);
		}
		@SuppressWarnings("unchecked")
		StructMetaData meta = new StructMetaData(TType.STRUCT, argsTBaseClass);
		msgStruct = new BaseArray(meta, (ArrayJson) jsonArray.get(3));
	}
	return msg;
}
 
Example 14
Source File: ThriftCodecTest.java    From dubbox with Apache License 2.0 2 votes vote down vote up
@Test
public void testDecodeExceptionResponse() throws Exception {

    URL url = URL.valueOf( ThriftProtocol.NAME + "://127.0.0.1:40880/" + Demo.class.getName() );

    Channel channel = new MockedChannel( url );

    RandomAccessByteArrayOutputStream bos = new RandomAccessByteArrayOutputStream( 128 );

    Request request = createRequest();

    DefaultFuture future = new DefaultFuture( channel, request, 10 );

    TMessage message = new TMessage( "echoString", TMessageType.EXCEPTION, ThriftCodec.getSeqId() );

    TTransport transport = new TIOStreamTransport( bos );

    TBinaryProtocol protocol = new TBinaryProtocol( transport );

    TApplicationException exception = new TApplicationException();

    int messageLength, headerLength;
    // prepare
    protocol.writeI16( ThriftCodec.MAGIC );
    protocol.writeI32( Integer.MAX_VALUE );
    protocol.writeI16( Short.MAX_VALUE );
    protocol.writeByte( ThriftCodec.VERSION );
    protocol.writeString( Demo.class.getName() );
    protocol.writeI64( request.getId() );
    protocol.getTransport().flush();
    headerLength = bos.size();

    protocol.writeMessageBegin( message );
    exception.write( protocol );
    protocol.writeMessageEnd();
    protocol.getTransport().flush();
    int oldIndex = messageLength = bos.size();

    try {
        bos.setWriteIndex( ThriftCodec.MESSAGE_LENGTH_INDEX );
        protocol.writeI32( messageLength );
        bos.setWriteIndex( ThriftCodec.MESSAGE_HEADER_LENGTH_INDEX );
        protocol.writeI16( ( short ) ( 0xffff & headerLength ) );
    } finally {
        bos.setWriteIndex( oldIndex );
    }
    // prepare

    ChannelBuffer bis = ChannelBuffers.wrappedBuffer(encodeFrame(bos.toByteArray()));

    Object obj = codec.decode( ( Channel ) null, bis );

    Assert.assertNotNull( obj );

    Assert.assertTrue( obj instanceof Response );

    Response response = ( Response ) obj;

    Assert.assertTrue( response.getResult() instanceof RpcResult );

    RpcResult result = ( RpcResult ) response.getResult();

    Assert.assertTrue( result.hasException() );

    Assert.assertTrue( result.getException() instanceof RpcException );

}
 
Example 15
Source File: ThriftCodecTest.java    From dubbox-hystrix with Apache License 2.0 2 votes vote down vote up
@Test
public void testDecodeExceptionResponse() throws Exception {

    URL url = URL.valueOf( ThriftProtocol.NAME + "://127.0.0.1:40880/" + Demo.class.getName() );

    Channel channel = new MockedChannel( url );

    RandomAccessByteArrayOutputStream bos = new RandomAccessByteArrayOutputStream( 128 );

    Request request = createRequest();

    DefaultFuture future = new DefaultFuture( channel, request, 10 );

    TMessage message = new TMessage( "echoString", TMessageType.EXCEPTION, ThriftCodec.getSeqId() );

    TTransport transport = new TIOStreamTransport( bos );

    TBinaryProtocol protocol = new TBinaryProtocol( transport );

    TApplicationException exception = new TApplicationException();

    int messageLength, headerLength;
    // prepare
    protocol.writeI16( ThriftCodec.MAGIC );
    protocol.writeI32( Integer.MAX_VALUE );
    protocol.writeI16( Short.MAX_VALUE );
    protocol.writeByte( ThriftCodec.VERSION );
    protocol.writeString( Demo.class.getName() );
    protocol.writeI64( request.getId() );
    protocol.getTransport().flush();
    headerLength = bos.size();

    protocol.writeMessageBegin( message );
    exception.write( protocol );
    protocol.writeMessageEnd();
    protocol.getTransport().flush();
    int oldIndex = messageLength = bos.size();

    try {
        bos.setWriteIndex( ThriftCodec.MESSAGE_LENGTH_INDEX );
        protocol.writeI32( messageLength );
        bos.setWriteIndex( ThriftCodec.MESSAGE_HEADER_LENGTH_INDEX );
        protocol.writeI16( ( short ) ( 0xffff & headerLength ) );
    } finally {
        bos.setWriteIndex( oldIndex );
    }
    // prepare

    ChannelBuffer bis = ChannelBuffers.wrappedBuffer(encodeFrame(bos.toByteArray()));

    Object obj = codec.decode( ( Channel ) null, bis );

    Assert.assertNotNull( obj );

    Assert.assertTrue( obj instanceof Response );

    Response response = ( Response ) obj;

    Assert.assertTrue( response.getResult() instanceof RpcResult );

    RpcResult result = ( RpcResult ) response.getResult();

    Assert.assertTrue( result.hasException() );

    Assert.assertTrue( result.getException() instanceof RpcException );

}
 
Example 16
Source File: ThriftCodecTest.java    From dubbox with Apache License 2.0 2 votes vote down vote up
@Test
public void testDecodeExceptionResponse() throws Exception {

    URL url = URL.valueOf( ThriftProtocol.NAME + "://127.0.0.1:40880/" + Demo.class.getName() );

    Channel channel = new MockedChannel( url );

    RandomAccessByteArrayOutputStream bos = new RandomAccessByteArrayOutputStream( 128 );

    Request request = createRequest();

    DefaultFuture future = new DefaultFuture( channel, request, 10 );

    TMessage message = new TMessage( "echoString", TMessageType.EXCEPTION, ThriftCodec.getSeqId() );

    TTransport transport = new TIOStreamTransport( bos );

    TBinaryProtocol protocol = new TBinaryProtocol( transport );

    TApplicationException exception = new TApplicationException();

    int messageLength, headerLength;
    // prepare
    protocol.writeI16( ThriftCodec.MAGIC );
    protocol.writeI32( Integer.MAX_VALUE );
    protocol.writeI16( Short.MAX_VALUE );
    protocol.writeByte( ThriftCodec.VERSION );
    protocol.writeString( Demo.class.getName() );
    protocol.writeI64( request.getId() );
    protocol.getTransport().flush();
    headerLength = bos.size();

    protocol.writeMessageBegin( message );
    exception.write( protocol );
    protocol.writeMessageEnd();
    protocol.getTransport().flush();
    int oldIndex = messageLength = bos.size();

    try {
        bos.setWriteIndex( ThriftCodec.MESSAGE_LENGTH_INDEX );
        protocol.writeI32( messageLength );
        bos.setWriteIndex( ThriftCodec.MESSAGE_HEADER_LENGTH_INDEX );
        protocol.writeI16( ( short ) ( 0xffff & headerLength ) );
    } finally {
        bos.setWriteIndex( oldIndex );
    }
    // prepare

    ChannelBuffer bis = ChannelBuffers.wrappedBuffer(encodeFrame(bos.toByteArray()));

    Object obj = codec.decode( ( Channel ) null, bis );

    Assert.assertNotNull( obj );

    Assert.assertTrue( obj instanceof Response );

    Response response = ( Response ) obj;

    Assert.assertTrue( response.getResult() instanceof RpcResult );

    RpcResult result = ( RpcResult ) response.getResult();

    Assert.assertTrue( result.hasException() );

    Assert.assertTrue( result.getException() instanceof RpcException );

}
 
Example 17
Source File: ThriftCodecTest.java    From dubbo-2.6.5 with Apache License 2.0 2 votes vote down vote up
@Test
public void testDecodeExceptionResponse() throws Exception {

    URL url = URL.valueOf(ThriftProtocol.NAME + "://127.0.0.1:40880/" + Demo.class.getName());

    Channel channel = new MockedChannel(url);

    RandomAccessByteArrayOutputStream bos = new RandomAccessByteArrayOutputStream(128);

    Request request = createRequest();

    DefaultFuture future = new DefaultFuture(channel, request, 10);

    TMessage message = new TMessage("echoString", TMessageType.EXCEPTION, ThriftCodec.getSeqId());

    TTransport transport = new TIOStreamTransport(bos);

    TBinaryProtocol protocol = new TBinaryProtocol(transport);

    TApplicationException exception = new TApplicationException();

    int messageLength, headerLength;
    // prepare
    protocol.writeI16(ThriftCodec.MAGIC);
    protocol.writeI32(Integer.MAX_VALUE);
    protocol.writeI16(Short.MAX_VALUE);
    protocol.writeByte(ThriftCodec.VERSION);
    protocol.writeString(Demo.class.getName());
    protocol.writeI64(request.getId());
    protocol.getTransport().flush();
    headerLength = bos.size();

    protocol.writeMessageBegin(message);
    exception.write(protocol);
    protocol.writeMessageEnd();
    protocol.getTransport().flush();
    int oldIndex = messageLength = bos.size();

    try {
        bos.setWriteIndex(ThriftCodec.MESSAGE_LENGTH_INDEX);
        protocol.writeI32(messageLength);
        bos.setWriteIndex(ThriftCodec.MESSAGE_HEADER_LENGTH_INDEX);
        protocol.writeI16((short) (0xffff & headerLength));
    } finally {
        bos.setWriteIndex(oldIndex);
    }
    // prepare

    ChannelBuffer bis = ChannelBuffers.wrappedBuffer(encodeFrame(bos.toByteArray()));

    Object obj = codec.decode((Channel) null, bis);

    Assert.assertNotNull(obj);

    Assert.assertTrue(obj instanceof Response);

    Response response = (Response) obj;

    Assert.assertTrue(response.getResult() instanceof RpcResult);

    RpcResult result = (RpcResult) response.getResult();

    Assert.assertTrue(result.hasException());

    Assert.assertTrue(result.getException() instanceof RpcException);

}
 
Example 18
Source File: ThriftCodecTest.java    From dubbox with Apache License 2.0 2 votes vote down vote up
@Test
public void testDecodeExceptionResponse() throws Exception {

    URL url = URL.valueOf( ThriftProtocol.NAME + "://127.0.0.1:40880/" + Demo.class.getName() );

    Channel channel = new MockedChannel( url );

    RandomAccessByteArrayOutputStream bos = new RandomAccessByteArrayOutputStream( 128 );

    Request request = createRequest();

    DefaultFuture future = new DefaultFuture( channel, request, 10 );

    TMessage message = new TMessage( "echoString", TMessageType.EXCEPTION, ThriftCodec.getSeqId() );

    TTransport transport = new TIOStreamTransport( bos );

    TBinaryProtocol protocol = new TBinaryProtocol( transport );

    TApplicationException exception = new TApplicationException();

    int messageLength, headerLength;
    // prepare
    protocol.writeI16( ThriftCodec.MAGIC );
    protocol.writeI32( Integer.MAX_VALUE );
    protocol.writeI16( Short.MAX_VALUE );
    protocol.writeByte( ThriftCodec.VERSION );
    protocol.writeString( Demo.class.getName() );
    protocol.writeI64( request.getId() );
    protocol.getTransport().flush();
    headerLength = bos.size();

    protocol.writeMessageBegin( message );
    exception.write( protocol );
    protocol.writeMessageEnd();
    protocol.getTransport().flush();
    int oldIndex = messageLength = bos.size();

    try {
        bos.setWriteIndex( ThriftCodec.MESSAGE_LENGTH_INDEX );
        protocol.writeI32( messageLength );
        bos.setWriteIndex( ThriftCodec.MESSAGE_HEADER_LENGTH_INDEX );
        protocol.writeI16( ( short ) ( 0xffff & headerLength ) );
    } finally {
        bos.setWriteIndex( oldIndex );
    }
    // prepare

    ChannelBuffer bis = ChannelBuffers.wrappedBuffer(encodeFrame(bos.toByteArray()));

    Object obj = codec.decode( ( Channel ) null, bis );

    Assert.assertNotNull( obj );

    Assert.assertTrue( obj instanceof Response );

    Response response = ( Response ) obj;

    Assert.assertTrue( response.getResult() instanceof RpcResult );

    RpcResult result = ( RpcResult ) response.getResult();

    Assert.assertTrue( result.hasException() );

    Assert.assertTrue( result.getException() instanceof RpcException );

}