Example usage for org.apache.thrift TApplicationException read

List of usage examples for org.apache.thrift TApplicationException read

Introduction

In this page you can find the example usage for org.apache.thrift TApplicationException read.

Prototype

public void read(TProtocol iprot) throws TException 

Source Link

Usage

From source file:com.alibaba.dubbo.rpc.protocol.swift.ThriftCodec.java

License:Open Source License

private Object decode(String serviceName, TProtocol protocol) throws IOException {

    TMessage message;//from w ww. ja v a2 s  .co  m

    try {
        message = protocol.readMessageBegin();
    } catch (TException e) {
        throw new IOException(e.getMessage(), e);
    }

    if (message.type == TMessageType.CALL) {

        RpcInvocation result = new RpcInvocation();
        result.setAttachment(Constants.INTERFACE_KEY, serviceName);
        result.setMethodName(message.name);

        String argsClassName = ExtensionLoader.getExtensionLoader(ClassNameGenerator.class)
                .getExtension(ThriftClassNameGenerator.NAME).generateArgsClassName(serviceName, message.name);

        if (StringUtils.isEmpty(argsClassName)) {
            throw new RpcException(RpcException.SERIALIZATION_EXCEPTION,
                    "The specified interface name incorrect.");
        }

        Class clazz = cachedClass.get(argsClassName);

        if (clazz == null) {
            try {

                clazz = ClassHelper.forNameWithThreadContextClassLoader(argsClassName);

                cachedClass.putIfAbsent(argsClassName, clazz);

            } catch (ClassNotFoundException e) {
                throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e);
            }
        }

        TBase args;

        try {
            args = (TBase) clazz.newInstance();
        } catch (InstantiationException e) {
            throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e);
        } catch (IllegalAccessException e) {
            throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e);
        }

        try {
            args.read(protocol);
            protocol.readMessageEnd();
        } catch (TException e) {
            throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e);
        }

        List<Object> parameters = new ArrayList<Object>();
        List<Class<?>> parameterTypes = new ArrayList<Class<?>>();
        int index = 1;

        while (true) {

            TFieldIdEnum fieldIdEnum = args.fieldForId(index++);

            if (fieldIdEnum == null) {
                break;
            }

            String fieldName = fieldIdEnum.getFieldName();

            String getMethodName = ThriftUtils.generateGetMethodName(fieldName);

            Method getMethod;

            try {
                getMethod = clazz.getMethod(getMethodName);
            } catch (NoSuchMethodException e) {
                throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e);
            }

            parameterTypes.add(getMethod.getReturnType());
            try {
                parameters.add(getMethod.invoke(args));
            } catch (IllegalAccessException e) {
                throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e);
            } catch (InvocationTargetException e) {
                throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e);
            }

        }

        result.setArguments(parameters.toArray());
        result.setParameterTypes(parameterTypes.toArray(new Class[parameterTypes.size()]));

        Request request = new Request(message.seqid);
        request.setData(result);

        cachedRequest.putIfAbsent(message.seqid, RequestData.create(message.seqid, serviceName, message.name));

        return request;

    } else if (message.type == TMessageType.EXCEPTION) {

        TApplicationException exception;

        try {
            exception = TApplicationException.read(protocol);
            protocol.readMessageEnd();
        } catch (TException e) {
            throw new IOException(e.getMessage(), e);
        }

        RpcResult result = new RpcResult();

        result.setException(new RpcException(exception.getMessage()));

        Response response = new Response();

        response.setResult(result);

        response.setId(message.seqid);

        return response;

    } else if (message.type == TMessageType.REPLY) {

        String resultClassName = ExtensionLoader.getExtensionLoader(ClassNameGenerator.class)
                .getExtension(ThriftClassNameGenerator.NAME).generateResultClassName(serviceName, message.name);

        if (StringUtils.isEmpty(resultClassName)) {
            throw new IllegalArgumentException(new StringBuilder(32)
                    .append("Could not infer service result class name from service name ").append(serviceName)
                    .append(", the service name you specified may not generated by thrift idl compiler")
                    .toString());
        }

        Class<?> clazz = cachedClass.get(resultClassName);

        if (clazz == null) {

            try {

                clazz = ClassHelper.forNameWithThreadContextClassLoader(resultClassName);

                cachedClass.putIfAbsent(resultClassName, clazz);

            } catch (ClassNotFoundException e) {
                throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e);
            }

        }

        TBase<?, ? extends TFieldIdEnum> result;
        try {
            result = (TBase<?, ?>) clazz.newInstance();
        } catch (InstantiationException e) {
            throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e);
        } catch (IllegalAccessException e) {
            throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e);
        }

        try {
            result.read(protocol);
            protocol.readMessageEnd();
        } catch (TException e) {
            throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e);
        }

        Object realResult = null;

        int index = 0;

        while (true) {

            TFieldIdEnum fieldIdEnum = result.fieldForId(index++);

            if (fieldIdEnum == null) {
                break;
            }

            Field field;

            try {
                field = clazz.getDeclaredField(fieldIdEnum.getFieldName());
                field.setAccessible(true);
            } catch (NoSuchFieldException e) {
                throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e);
            }

            try {
                realResult = field.get(result);
            } catch (IllegalAccessException e) {
                throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e);
            }

            if (realResult != null) {
                break;
            }

        }

        Response response = new Response();

        response.setId(message.seqid);

        RpcResult rpcResult = new RpcResult();

        if (realResult instanceof Throwable) {
            rpcResult.setException((Throwable) realResult);
        } else {
            rpcResult.setValue(realResult);
        }

        response.setResult(rpcResult);

        return response;

    } else {
        // Impossible
        throw new IOException();
    }

}

From source file:com.alibaba.dubbo.rpc.protocol.thrift.ThriftCodec.java

License:Open Source License

private Object decode(TProtocol protocol) throws IOException {

    // version/*from w  ww.  j a  v  a 2 s .  c  o m*/
    String serviceName;
    long id;

    TMessage message;

    try {
        protocol.readI16();
        protocol.readByte();
        serviceName = protocol.readString();
        id = protocol.readI64();
        message = protocol.readMessageBegin();
    } catch (TException e) {
        throw new IOException(e.getMessage(), e);
    }

    if (message.type == TMessageType.CALL) {

        RpcInvocation result = new RpcInvocation();
        result.setAttachment(Constants.INTERFACE_KEY, serviceName);
        result.setMethodName(message.name);

        String argsClassName = ExtensionLoader.getExtensionLoader(ClassNameGenerator.class)
                .getExtension(ThriftClassNameGenerator.NAME).generateArgsClassName(serviceName, message.name);

        if (StringUtils.isEmpty(argsClassName)) {
            throw new RpcException(RpcException.SERIALIZATION_EXCEPTION,
                    "The specified interface name incorrect.");
        }

        Class clazz = cachedClass.get(argsClassName);

        if (clazz == null) {
            try {

                clazz = ClassHelper.forNameWithThreadContextClassLoader(argsClassName);

                cachedClass.putIfAbsent(argsClassName, clazz);

            } catch (ClassNotFoundException e) {
                throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e);
            }
        }

        TBase args;

        try {
            args = (TBase) clazz.newInstance();
        } catch (InstantiationException e) {
            throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e);
        } catch (IllegalAccessException e) {
            throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e);
        }

        try {
            args.read(protocol);
            protocol.readMessageEnd();
        } catch (TException e) {
            throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e);
        }

        List<Object> parameters = new ArrayList<Object>();
        List<Class<?>> parameterTypes = new ArrayList<Class<?>>();
        int index = 1;

        while (true) {

            TFieldIdEnum fieldIdEnum = args.fieldForId(index++);

            if (fieldIdEnum == null) {
                break;
            }

            String fieldName = fieldIdEnum.getFieldName();

            String getMethodName = ThriftUtils.generateGetMethodName(fieldName);

            Method getMethod;

            try {
                getMethod = clazz.getMethod(getMethodName);
            } catch (NoSuchMethodException e) {
                throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e);
            }

            parameterTypes.add(getMethod.getReturnType());
            try {
                parameters.add(getMethod.invoke(args));
            } catch (IllegalAccessException e) {
                throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e);
            } catch (InvocationTargetException e) {
                throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e);
            }

        }

        result.setArguments(parameters.toArray());
        result.setParameterTypes(parameterTypes.toArray(new Class[parameterTypes.size()]));

        Request request = new Request(id);
        request.setData(result);

        cachedRequest.putIfAbsent(id, RequestData.create(message.seqid, serviceName, message.name));

        return request;

    } else if (message.type == TMessageType.EXCEPTION) {

        TApplicationException exception;

        try {
            exception = TApplicationException.read(protocol);
            protocol.readMessageEnd();
        } catch (TException e) {
            throw new IOException(e.getMessage(), e);
        }

        RpcResult result = new RpcResult();

        result.setException(new RpcException(exception.getMessage()));

        Response response = new Response();

        response.setResult(result);

        response.setId(id);

        return response;

    } else if (message.type == TMessageType.REPLY) {

        String resultClassName = ExtensionLoader.getExtensionLoader(ClassNameGenerator.class)
                .getExtension(ThriftClassNameGenerator.NAME).generateResultClassName(serviceName, message.name);

        if (StringUtils.isEmpty(resultClassName)) {
            throw new IllegalArgumentException(new StringBuilder(32)
                    .append("Could not infer service result class name from service name ").append(serviceName)
                    .append(", the service name you specified may not generated by thrift idl compiler")
                    .toString());
        }

        Class<?> clazz = cachedClass.get(resultClassName);

        if (clazz == null) {

            try {

                clazz = ClassHelper.forNameWithThreadContextClassLoader(resultClassName);

                cachedClass.putIfAbsent(resultClassName, clazz);

            } catch (ClassNotFoundException e) {
                throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e);
            }

        }

        TBase<?, ? extends TFieldIdEnum> result;
        try {
            result = (TBase<?, ?>) clazz.newInstance();
        } catch (InstantiationException e) {
            throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e);
        } catch (IllegalAccessException e) {
            throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e);
        }

        try {
            result.read(protocol);
            protocol.readMessageEnd();
        } catch (TException e) {
            throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e);
        }

        Object realResult = null;

        int index = 0;

        while (true) {

            TFieldIdEnum fieldIdEnum = result.fieldForId(index++);

            if (fieldIdEnum == null) {
                break;
            }

            Field field;

            try {
                field = clazz.getDeclaredField(fieldIdEnum.getFieldName());
                field.setAccessible(true);
            } catch (NoSuchFieldException e) {
                throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e);
            }

            try {
                realResult = field.get(result);
            } catch (IllegalAccessException e) {
                throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e);
            }

            if (realResult != null) {
                break;
            }

        }

        Response response = new Response();

        response.setId(id);

        RpcResult rpcResult = new RpcResult();

        if (realResult instanceof Throwable) {
            rpcResult.setException((Throwable) realResult);
        } else {
            rpcResult.setValue(realResult);
        }

        response.setResult(rpcResult);

        return response;

    } else {
        // Impossible
        throw new IOException();
    }

}

From source file:com.alibaba.dubbo.rpc.protocol.thrift.ThriftCodecTest.java

License:Open Source License

@Test
public void testEncodeExceptionResponse() throws Exception {

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

    Channel channel = new MockedChannel(url);

    Request request = createRequest();

    RpcResult rpcResult = new RpcResult();
    String exceptionMessage = "failed";
    rpcResult.setException(new RuntimeException(exceptionMessage));

    Response response = new Response();
    response.setResult(rpcResult);//  ww  w.  j ava2s.  c o  m
    response.setId(request.getId());
    RandomAccessByteArrayOutputStream bos = new RandomAccessByteArrayOutputStream(1024);

    ThriftCodec.RequestData rd = ThriftCodec.RequestData.create(ThriftCodec.getSeqId(),
            Demo.Iface.class.getName(), "echoString");
    ThriftCodec.cachedRequest.put(request.getId(), rd);
    codec.encode(channel, bos, response);

    byte[] buf = new byte[bos.size() - 4];
    System.arraycopy(bos.toByteArray(), 4, buf, 0, bos.size() - 4);
    ByteArrayInputStream bis = new ByteArrayInputStream(buf);

    if (bis.markSupported()) {
        bis.mark(0);
    }

    TIOStreamTransport transport = new TIOStreamTransport(bis);
    TBinaryProtocol protocol = new TBinaryProtocol(transport);

    Assert.assertEquals(ThriftCodec.MAGIC, protocol.readI16());
    Assert.assertEquals(protocol.readI32() + 4, bos.toByteArray().length);
    int headerLength = protocol.readI16();

    Assert.assertEquals(ThriftCodec.VERSION, protocol.readByte());
    Assert.assertEquals(Demo.Iface.class.getName(), protocol.readString());
    Assert.assertEquals(request.getId(), protocol.readI64());

    if (bis.markSupported()) {
        bis.reset();
        bis.skip(headerLength);
    }

    TMessage message = protocol.readMessageBegin();
    Assert.assertEquals("echoString", message.name);
    Assert.assertEquals(TMessageType.EXCEPTION, message.type);
    Assert.assertEquals(ThriftCodec.getSeqId(), message.seqid);
    TApplicationException exception = TApplicationException.read(protocol);
    protocol.readMessageEnd();

    Assert.assertEquals(exceptionMessage, exception.getMessage());

}

From source file:com.facebook.swift.service.ThriftMethodHandler.java

License:Apache License

private void waitForResponse(TProtocol in, int sequenceId) throws TException {
    TMessage message = in.readMessageBegin();
    if (message.type == EXCEPTION) {
        TApplicationException exception = TApplicationException.read(in);
        in.readMessageEnd();//from  w ww .j a  va2  s . c o  m
        throw exception;
    }
    if (message.type != REPLY) {
        throw new TApplicationException(INVALID_MESSAGE_TYPE,
                "Received invalid message type " + message.type + " from server");
    }
    if (!message.name.equals(this.name)) {
        throw new TApplicationException(WRONG_METHOD_NAME,
                "Wrong method name in reply: expected " + this.name + " but received " + message.name);
    }
    if (message.seqid != sequenceId) {
        throw new TApplicationException(BAD_SEQUENCE_ID, name + " failed: out of sequence response");
    }
}

From source file:com.flipkart.phantom.thrift.impl.ProxyServiceClient.java

License:Apache License

/**
 * Overriden super class method. Receives the service response and relays it back to the client
 * @see org.apache.thrift.TServiceClient#receiveBase(org.apache.thrift.TBase, String)
 *///  www  .j  a  va  2  s.c o  m
public void receiveBase(TBase result, String methodName) throws TException {
    // Read the service response - same as in TServiceClient#receiveBase
    TMessage msg = iprot_.readMessageBegin();
    if (msg.type == TMessageType.EXCEPTION) {
        TApplicationException x = TApplicationException.read(iprot_);
        iprot_.readMessageEnd();
        throw x;
    }
    if (msg.seqid != this.seqid_) {
        throw new TApplicationException(TApplicationException.BAD_SEQUENCE_ID,
                methodName + " failed: out of sequence response");
    }
    result.read(iprot_);
    iprot_.readMessageEnd();

    // now relay the response to the client
    clientProtocol.writeMessageBegin(msg);
    result.write(clientProtocol);
    clientProtocol.writeMessageEnd();
    clientProtocol.getTransport().flush();
    LOGGER.debug("Relayed thrift response to client. Seq Id : " + msg.seqid + ", Method : " + msg.name
            + ", value : " + result);
}

From source file:com.linecorp.armeria.client.thrift.ThriftClientCodec.java

License:Apache License

@SuppressWarnings({ "unchecked", "rawtypes" })
@Override/*from  w  ww.jav a  2s  . c  o m*/
public <T> T decodeResponse(ServiceInvocationContext ctx, ByteBuf content, Object originalResponse)
        throws Exception {
    if (content == null) {
        return null;
    }

    if (!content.isReadable()) {
        ThriftMethod thriftMethod = getThriftMethod(ctx);
        if (thriftMethod != null && thriftMethod.isOneWay()) {
            return null;
        }
        throw new TApplicationException(TApplicationException.MISSING_RESULT, ctx.toString());
    }

    TByteBufInputTransport inputTransport = new TByteBufInputTransport(content);
    TProtocol inputProtocol = protocolFactory.getProtocol(inputTransport);
    TMessage msg = inputProtocol.readMessageBegin();
    if (msg.type == TMessageType.EXCEPTION) {
        TApplicationException ex = TApplicationException.read(inputProtocol);
        inputProtocol.readMessageEnd();
        throw ex;
    }
    ThriftMethod method = methodMap.get(msg.name);
    if (method == null) {
        throw new TApplicationException(TApplicationException.WRONG_METHOD_NAME, msg.name);
    }
    TBase<? extends TBase, TFieldIdEnum> result = method.createResult();
    result.read(inputProtocol);
    inputProtocol.readMessageEnd();

    for (TFieldIdEnum fieldIdEnum : method.getExceptionFields()) {
        if (result.isSet(fieldIdEnum)) {
            throw (TException) result.getFieldValue(fieldIdEnum);
        }
    }

    TFieldIdEnum successField = method.successField();
    if (successField == null) { //void method
        return null;
    }
    if (result.isSet(successField)) {
        return (T) result.getFieldValue(successField);
    }

    throw new TApplicationException(TApplicationException.MISSING_RESULT,
            result.getClass().getName() + '.' + successField.getFieldName());
}

From source file:com.linecorp.armeria.client.thrift.ThriftClientDelegate.java

License:Apache License

private Object decodeResponse(ThriftFunction method, HttpData content) throws TException {
    if (content.isEmpty()) {
        if (method.isOneway()) {
            return null;
        }/*from  w ww  . j a  va 2 s .com*/
        throw new TApplicationException(TApplicationException.MISSING_RESULT);
    }

    final TMemoryInputTransport inputTransport = new TMemoryInputTransport(content.array(), content.offset(),
            content.length());
    final TProtocol inputProtocol = protocolFactory.getProtocol(inputTransport);

    final TMessage msg = inputProtocol.readMessageBegin();
    if (msg.type == TMessageType.EXCEPTION) {
        TApplicationException ex = TApplicationException.read(inputProtocol);
        inputProtocol.readMessageEnd();
        throw ex;
    }

    if (!method.name().equals(msg.name)) {
        throw new TApplicationException(TApplicationException.WRONG_METHOD_NAME, msg.name);
    }
    TBase<? extends TBase<?, ?>, TFieldIdEnum> result = method.newResult();
    result.read(inputProtocol);
    inputProtocol.readMessageEnd();

    for (TFieldIdEnum fieldIdEnum : method.exceptionFields()) {
        if (result.isSet(fieldIdEnum)) {
            throw (TException) result.getFieldValue(fieldIdEnum);
        }
    }

    TFieldIdEnum successField = method.successField();
    if (successField == null) { // void method
        return null;
    }
    if (result.isSet(successField)) {
        return result.getFieldValue(successField);
    }

    throw new TApplicationException(TApplicationException.MISSING_RESULT,
            result.getClass().getName() + '.' + successField.getFieldName());
}

From source file:com.linecorp.armeria.client.thrift.THttpClientDelegate.java

License:Apache License

private static TApplicationException readApplicationException(ThriftFunction func, TProtocol inputProtocol,
        TMessage msg) throws TException {
    final TApplicationException appEx;
    if (msg.type == TMessageType.EXCEPTION) {
        appEx = TApplicationException.read(inputProtocol);
        inputProtocol.readMessageEnd();//from  ww  w  . j  a v a2 s .  c  o m
    } else if (!func.name().equals(msg.name)) {
        appEx = new TApplicationException(TApplicationException.WRONG_METHOD_NAME, msg.name);
    } else {
        appEx = null;
    }
    return appEx;
}

From source file:com.linecorp.armeria.common.thrift.text.TTextProtocolTest.java

License:Apache License

@Test
public void rpcTApplicationException() throws Exception {
    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())));
    TMessage header = prot.readMessageBegin();
    TApplicationException result = TApplicationException.read(prot);
    prot.readMessageEnd();/* w w  w. jav  a 2  s. c o m*/

    assertEquals("doDebug", header.name);
    assertEquals(TMessageType.EXCEPTION, header.type);
    assertEquals(101, header.seqid);

    assertEquals(TApplicationException.BAD_SEQUENCE_ID, result.getType());

    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();

    assertJsonEquals(request, new String(outputStream.toByteArray(), StandardCharsets.UTF_8));
}

From source file:org.apache.accumulo.core.rpc.TServiceClientWrapper.java

License:Apache License

@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();/*ww w .j  a va 2 s . c  om*/
        throw x;
    }
    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();
}