org.apache.thrift.protocol.TMessageType Java Examples

The following examples show how to use org.apache.thrift.protocol.TMessageType. 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: ThriftNativeCodec.java    From dubbox with 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 #2
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 #3
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 #4
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 #5
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 #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: ThriftNativeCodec.java    From dubbox with 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 #8
Source File: ThriftNativeCodec.java    From dubbox-hystrix with 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 #9
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 #10
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 #11
Source File: ThriftNativeCodec.java    From dubbo-2.6.5 with 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 #12
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 #13
Source File: ThriftJacksonTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void serializeThriftCall() throws IOException {
    final ThriftCall call = new ThriftCall(
            new TMessage(THRIFT_METHOD_NAME, TMessageType.CALL, 0),
            new hello_args().setName("kawamuray"));
    final String actualJson = defaultMapper.writeValueAsString(call);
    final String actualJson2 = customMapper.writeValueAsString(call);

    assertThatJson(actualJson).isEqualTo(
            '{' +
            "    \"header\": {" +
            "        \"name\": \"hello\"," +
            "        \"type\": 1," +
            "        \"seqid\": 0" +
            "    }," +
            "    \"args\": {" +
            "        \"name\": \"kawamuray\"" +
            "    }" +
            '}');
    assertThatJson(actualJson2).isEqualTo(actualJson);
}
 
Example #14
Source File: DefaultNettyProcessor.java    From nettythrift with 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 #15
Source File: ThriftJacksonTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void serializeThriftReply() throws IOException {
    final ThriftReply reply = new ThriftReply(
            new TMessage(THRIFT_METHOD_NAME, TMessageType.REPLY, 0),
            new hello_result().setSuccess("Hello kawamuray"));
    final String actualJson = defaultMapper.writeValueAsString(reply);
    final String actualJson2 = customMapper.writeValueAsString(reply);

    assertThatJson(actualJson).isEqualTo(
            '{' +
            "    \"header\": {" +
            "        \"name\": \"hello\"," +
            "        \"type\": 2," +
            "        \"seqid\": 0" +
            "    }," +
            "    \"result\": {" +
            "        \"success\": \"Hello kawamuray\"" +
            "    }," +
            "    \"exception\": null" +
            '}');
    assertThatJson(actualJson2).isEqualTo(actualJson);
}
 
Example #16
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 #17
Source File: ThriftNativeCodec.java    From dubbox with 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 #18
Source File: NettyDispatcher.java    From ikasoa with MIT License 6 votes vote down vote up
private void sendTApplicationException(TApplicationException e, ChannelHandlerContext ctx, TNettyMessage request,
		int responseSequenceId, TNettyTransport requestTransport, TProtocol inProtocol, TProtocol outProtocol) {
	if (ctx.getChannel().isConnected()) {
		try {
			TMessage message = inProtocol.readMessageBegin();
			outProtocol.writeMessageBegin(new TMessage(message.name, TMessageType.EXCEPTION, message.seqid));
			e.write(outProtocol);
			outProtocol.writeMessageEnd();
			requestTransport.setTApplicationException(e);
			outProtocol.getTransport().flush();
			writeResponse(ctx, request.getMessageFactory().create(requestTransport.getOutputBuffer()),
					responseSequenceId, DispatcherContext.isResponseOrderingRequired(ctx));
		} catch (TException ex) {
			onDispatchException(ctx, ex);
		}
	}
}
 
Example #19
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 #20
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 #21
Source File: THttpService.java    From armeria with Apache License 2.0 5 votes vote down vote up
private static HttpData encodeSuccess(ServiceRequestContext ctx,
                                      RpcResponse reply,
                                      SerializationFormat serializationFormat,
                                      String methodName, int seqId,
                                      TBase<?, ?> result) {

    final ByteBuf buf = ctx.alloc().buffer(128);
    boolean success = false;
    try {
        final TTransport transport = new TByteBufTransport(buf);
        final TProtocol outProto = ThriftProtocolFactories.get(serializationFormat).getProtocol(transport);
        final TMessage header = new TMessage(methodName, TMessageType.REPLY, seqId);
        outProto.writeMessageBegin(header);
        result.write(outProto);
        outProto.writeMessageEnd();

        ctx.logBuilder().responseContent(reply, new ThriftReply(header, result));

        final HttpData encoded = PooledHttpData.wrap(buf);
        success = true;
        return encoded;
    } catch (TException e) {
        throw new Error(e); // Should never reach here.
    } finally {
        if (!success) {
            buf.release();
        }
    }
}
 
Example #22
Source File: TTextProtocolTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
public void rpcTApplicationException() throws Exception {
    final String request =
            "{\n" +
            "  \"method\" : \"doDebug\",\n" +
            "  \"type\" : \"EXCEPTION\",\n" +
            "  \"seqid\" : 101,\n" +
            "  \"args\" : {\n" +
            "    \"type\" : 4,\n" +
            "    \"message\" : \"bad_seq_id\"\n" +
            "    }\n" +
            "  }\n" +
            '}';

    TTextProtocol prot = new TTextProtocol(
            new TIOStreamTransport(new ByteArrayInputStream(request.getBytes())));
    final TMessage header = prot.readMessageBegin();
    final TApplicationException result = TApplicationExceptions.read(prot);
    prot.readMessageEnd();

    assertThat(header.name).isEqualTo("doDebug");
    assertThat(header.type).isEqualTo(TMessageType.EXCEPTION);
    assertThat(header.seqid).isEqualTo(101);

    assertThat(result.getType()).isEqualTo(TApplicationException.BAD_SEQUENCE_ID);

    final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    prot = new TTextProtocol(new TIOStreamTransport(outputStream));
    prot.writeMessageBegin(header);
    new TApplicationException(TApplicationException.BAD_SEQUENCE_ID, "bad_seq_id").write(prot);
    prot.writeMessageEnd();

    assertThatJson(new String(outputStream.toByteArray(), StandardCharsets.UTF_8)).isEqualTo(request);
}
 
Example #23
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#REPLY} message.
 */
public ThriftReply(TMessage header, TBase<?, ?> result) {
    super(header);
    if (header.type != TMessageType.REPLY) {
        throw new IllegalArgumentException(
                "header.type: " + typeStr(header.type) + " (expected: REPLY)");
    }

    this.result = requireNonNull(result, "result");
    exception = null;
}
 
Example #24
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 #25
Source File: ThriftOverHttpClientTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@ParameterizedTest
@ArgumentsSource(ParametersProvider.class)
void testMessageLogsForOneWay(
        ClientOptions clientOptions, SerializationFormat format, SessionProtocol protocol)
        throws Exception {
    final OnewayHelloService.Iface client = Clients.builder(uri(Handlers.HELLO, format, protocol))
                                                   .options(clientOptions)
                                                   .build(Handlers.ONEWAYHELLO.iface());
    recordMessageLogs = true;
    client.hello("trustin");

    final RequestLog log = requestLogs.take();

    assertThat(log.requestHeaders()).isInstanceOf(HttpHeaders.class);
    assertThat(log.requestContent()).isInstanceOf(RpcRequest.class);
    assertThat(log.rawRequestContent()).isInstanceOf(ThriftCall.class);

    final RpcRequest request = (RpcRequest) log.requestContent();
    assertThat(request.serviceType()).isEqualTo(OnewayHelloService.Iface.class);
    assertThat(request.method()).isEqualTo("hello");
    assertThat(request.params()).containsExactly("trustin");

    final ThriftCall rawRequest = (ThriftCall) log.rawRequestContent();
    assertThat(rawRequest.header().type).isEqualTo(TMessageType.ONEWAY);
    assertThat(rawRequest.header().name).isEqualTo("hello");
    assertThat(rawRequest.args()).isInstanceOf(OnewayHelloService.hello_args.class);
    assertThat(((OnewayHelloService.hello_args) rawRequest.args()).getName()).isEqualTo("trustin");

    assertThat(log.responseHeaders()).isInstanceOf(HttpHeaders.class);
    assertThat(log.responseContent()).isInstanceOf(RpcResponse.class);
    assertThat(log.rawResponseContent()).isNull();

    final RpcResponse response = (RpcResponse) log.responseContent();
    assertThat(response.get()).isNull();
}
 
Example #26
Source File: AbstractThriftOverHttpTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 10000)
public void testMessageLogsForException() throws Exception {
    try (TTransport transport = newTransport("http", "/exception")) {
        final HelloService.Client client =
                new HelloService.Client.Factory().getClient(
                        ThriftProtocolFactories.BINARY.getProtocol(transport));
        recordMessageLogs = true;
        assertThatThrownBy(() -> client.hello("Trustin")).isInstanceOf(TApplicationException.class);
    }

    final RequestLog log = takeLog();

    assertThat(log.requestHeaders()).isInstanceOf(HttpHeaders.class);
    assertThat(log.requestContent()).isInstanceOf(RpcRequest.class);
    assertThat(log.rawRequestContent()).isInstanceOf(ThriftCall.class);

    final RpcRequest request = (RpcRequest) log.requestContent();
    assertThat(request.serviceType()).isEqualTo(HelloService.AsyncIface.class);
    assertThat(request.method()).isEqualTo("hello");
    assertThat(request.params()).containsExactly("Trustin");

    final ThriftCall rawRequest = (ThriftCall) log.rawRequestContent();
    assertThat(rawRequest.header().type).isEqualTo(TMessageType.CALL);
    assertThat(rawRequest.header().name).isEqualTo("hello");
    assertThat(rawRequest.args()).isInstanceOf(HelloService.hello_args.class);
    assertThat(((HelloService.hello_args) rawRequest.args()).getName()).isEqualTo("Trustin");

    assertThat(log.responseHeaders()).isInstanceOf(HttpHeaders.class);
    assertThat(log.responseContent()).isInstanceOf(RpcResponse.class);
    assertThat(log.rawResponseContent()).isInstanceOf(ThriftReply.class);

    final RpcResponse response = (RpcResponse) log.responseContent();
    assertThat(response.cause()).isNotNull();

    final ThriftReply rawResponse = (ThriftReply) log.rawResponseContent();
    assertThat(rawResponse.header().type).isEqualTo(TMessageType.EXCEPTION);
    assertThat(rawResponse.header().name).isEqualTo("hello");
    assertThat(rawResponse.exception()).isNotNull();
}
 
Example #27
Source File: TTextProtocolTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
public void rpcCall_noSeqId() throws Exception {
    final String request =
            "{\n" +
            "  \"method\" : \"doDebug\",\n" +
            "  \"type\" : \"CALL\",\n" +
            "  \"args\" : {\n" +
            "    \"methodArg1\" : \"foo1\",\n" +
            "    \"methodArg2\" : 200,\n" +
            "    \"details\" : {\n" +
            "      \"detailsArg1\" : \"foo2\",\n" +
            "      \"detailsArg2\" : 100\n" +
            "    }\n" +
            "  }\n" +
            '}';

    final TTextProtocol prot = new TTextProtocol(
            new TIOStreamTransport(new ByteArrayInputStream(request.getBytes())));
    final TMessage header = prot.readMessageBegin();
    final doDebug_args args = new RpcDebugService.Processor.doDebug().getEmptyArgsInstance();
    args.read(prot);
    prot.readMessageEnd();

    assertThat(header.name).isEqualTo("doDebug");
    assertThat(header.type).isEqualTo(TMessageType.CALL);
    assertThat(header.seqid).isZero();
}
 
Example #28
Source File: TTextProtocolTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
public void rpcReply() throws Exception {
    final String request =
            "{\n" +
            "  \"method\" : \"doDebug\",\n" +
            "  \"type\" : \"REPLY\",\n" +
            "  \"seqid\" : 100,\n" +
            "  \"args\" : {\n" +
            "    \"success\" : {\n" +
            "      \"response\" : \"Nice response\"\n" +
            "    }\n" +
            "  }\n" +
            '}';

    TTextProtocol prot = new TTextProtocol(
            new TIOStreamTransport(new ByteArrayInputStream(request.getBytes())));
    final TMessage header = prot.readMessageBegin();
    final doDebug_result result = new doDebug_result();
    result.read(prot);
    prot.readMessageEnd();

    assertThat(header.name).isEqualTo("doDebug");
    assertThat(header.type).isEqualTo(TMessageType.REPLY);
    assertThat(header.seqid).isEqualTo(100);

    assertThat(result.getSuccess().getResponse()).isEqualTo("Nice response");

    final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    prot = new TTextProtocol(new TIOStreamTransport(outputStream));
    prot.writeMessageBegin(header);
    result.write(prot);
    prot.writeMessageEnd();

    assertThatJson(new String(outputStream.toByteArray(), StandardCharsets.UTF_8)).isEqualTo(request);
}
 
Example #29
Source File: TTextProtocolTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
public void rpcException() throws Exception {
    final String request =
            "{\n" +
            "  \"method\" : \"doDebug\",\n" +
            "  \"type\" : \"EXCEPTION\",\n" +
            "  \"seqid\" : 101,\n" +
            "  \"args\" : {\n" +
            "    \"e\" : {\n" +
            "      \"reason\" : \"Bad rpc\"\n" +
            "    }\n" +
            "  }\n" +
            '}';

    TTextProtocol prot = new TTextProtocol(
            new TIOStreamTransport(new ByteArrayInputStream(request.getBytes())));
    final TMessage header = prot.readMessageBegin();
    final doDebug_result result = new doDebug_result();
    result.read(prot);
    prot.readMessageEnd();

    assertThat(header.name).isEqualTo("doDebug");
    assertThat(header.type).isEqualTo(TMessageType.EXCEPTION);
    assertThat(header.seqid).isEqualTo(101);

    assertThat(result.getE().getReason()).isEqualTo("Bad rpc");

    final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    prot = new TTextProtocol(new TIOStreamTransport(outputStream));
    prot.writeMessageBegin(header);
    result.write(prot);
    prot.writeMessageEnd();

    assertThatJson(new String(outputStream.toByteArray(), StandardCharsets.UTF_8)).isEqualTo(request);
}
 
Example #30
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);
    }
}