Example usage for org.apache.thrift.protocol TProtocol readMessageEnd

List of usage examples for org.apache.thrift.protocol TProtocol readMessageEnd

Introduction

In this page you can find the example usage for org.apache.thrift.protocol TProtocol readMessageEnd.

Prototype

public abstract void readMessageEnd() 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;// w w  w. jav  a  2s  .  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 w  w.  ja  va  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.facebook.nifty.codec.DefaultThriftFrameDecoder.java

License:Apache License

protected ChannelBuffer tryDecodeUnframedMessage(ChannelHandlerContext ctx, Channel channel,
        ChannelBuffer buffer, TProtocolFactory inputProtocolFactory) throws TException {
    // Perform a trial decode, skipping through
    // the fields, to see whether we have an entire message available.

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

    try {//from  ww w . j  a  va 2  s . co  m
        TNiftyTransport decodeAttemptTransport = new TNiftyTransport(channel, buffer,
                ThriftTransportType.UNFRAMED);
        int initialReadBytes = decodeAttemptTransport.getReadByteCount();
        TProtocol inputProtocol = inputProtocolFactory.getProtocol(decodeAttemptTransport);

        // Skip through the message
        inputProtocol.readMessageBegin();
        TProtocolUtil.skip(inputProtocol, TType.STRUCT);
        inputProtocol.readMessageEnd();

        messageLength = decodeAttemptTransport.getReadByteCount() - initialReadBytes;
    } catch (TTransportException | IndexOutOfBoundsException e) {
        // No complete message was decoded: ran out of bytes
        return null;
    } finally {
        if (buffer.readerIndex() - messageStartReaderIndex > maxFrameSize) {
            Channels.fireExceptionCaught(ctx,
                    new TooLongFrameException("Maximum frame size of " + maxFrameSize + " exceeded"));
        }

        buffer.readerIndex(messageStartReaderIndex);
    }

    if (messageLength <= 0) {
        return null;
    }

    // We have a full message in the read buffer, slice it off
    ChannelBuffer messageBuffer = extractFrame(buffer, messageStartReaderIndex, messageLength);
    buffer.readerIndex(messageStartReaderIndex + messageLength);
    return messageBuffer;
}

From source file:com.facebook.nifty.core.ThriftFrameDecoder.java

License:Apache License

private TTransport tryDecodeUnframedMessage(ChannelHandlerContext ctx, Channel channel, ChannelBuffer buffer)
        throws TException {
    // Perform a trial decode, skipping through
    // the fields, to see whether we have an entire message available.

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

    try {/*from   w ww  . j a v  a2 s. c o  m*/
        TNiftyTransport decodeAttemptTransport = new TNiftyTransport(channel, buffer,
                ThriftTransportType.UNFRAMED);
        TProtocol inputProtocol = this.inputProtocolFactory.getProtocol(decodeAttemptTransport);

        // Skip through the message
        inputProtocol.readMessageBegin();
        TProtocolUtil.skip(inputProtocol, TType.STRUCT);
        inputProtocol.readMessageEnd();

        messageLength = buffer.readerIndex() - messageStartReaderIndex;
    } catch (IndexOutOfBoundsException e) {
        // No complete message was decoded: ran out of bytes
        return null;
    } finally {
        if (buffer.readerIndex() - messageStartReaderIndex > maxFrameSize) {
            Channels.fireExceptionCaught(ctx,
                    new TooLongFrameException("Maximum frame size of " + maxFrameSize + " exceeded"));
        }

        buffer.readerIndex(messageStartReaderIndex);
    }

    if (messageLength <= 0) {
        return null;
    }

    // We have a full message in the read buffer, slice it off
    ChannelBuffer messageBuffer = extractFrame(buffer, messageStartReaderIndex, messageLength);
    buffer.readerIndex(messageStartReaderIndex + messageLength);
    return new TNiftyTransport(channel, messageBuffer, ThriftTransportType.UNFRAMED);
}

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

License:Apache License

private Object readResponse(TProtocol in) throws Exception {
    TProtocolReader reader = new TProtocolReader(in);
    reader.readStructBegin();/*from   w ww .j  av a  2s. com*/
    Object results = null;
    Exception exception = null;
    while (reader.nextField()) {
        if (reader.getFieldId() == 0) {
            results = reader.readField(successCodec);
        } else {
            ThriftCodec<Object> exceptionCodec = exceptionCodecs.get(reader.getFieldId());
            if (exceptionCodec != null) {
                exception = (Exception) reader.readField(exceptionCodec);
            } else {
                reader.skipFieldData();
            }
        }
    }
    reader.readStructEnd();
    in.readMessageEnd();

    if (exception != null) {
        throw exception;
    }

    if (successCodec.getType() == ThriftType.VOID) {
        // TODO: check for non-null return from a void function?
        return null;
    }

    if (results == null) {
        throw new TApplicationException(TApplicationException.MISSING_RESULT, name + " failed: unknown result");
    }
    return results;
}

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();
        throw exception;
    }/* w w w  . j av  a  2 s  .  c o  m*/
    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.facebook.swift.service.ThriftMethodProcessor.java

License:Apache License

public ListenableFuture<Boolean> process(TProtocol in, final TProtocol out, final int sequenceId,
        final ContextChain contextChain) throws Exception {
    // read args//from w ww . j a  v a2s . c o  m
    contextChain.preRead();
    Object[] args = readArguments(in);
    contextChain.postRead(args);
    final RequestContext requestContext = RequestContexts.getCurrentContext();

    in.readMessageEnd();

    // invoke method
    final ListenableFuture<?> invokeFuture = invokeMethod(args);
    final SettableFuture<Boolean> resultFuture = SettableFuture.create();

    Futures.addCallback(invokeFuture, new FutureCallback<Object>() {
        @Override
        public void onSuccess(Object result) {
            if (oneway) {
                resultFuture.set(true);
            } else {
                RequestContext oldRequestContext = RequestContexts.getCurrentContext();
                RequestContexts.setCurrentContext(requestContext);

                // write success reply
                try {
                    contextChain.preWrite(result);

                    writeResponse(out, sequenceId, TMessageType.REPLY, "success", (short) 0, successCodec,
                            result);

                    contextChain.postWrite(result);

                    resultFuture.set(true);
                } catch (Exception e) {
                    // An exception occurred trying to serialize a return value onto the output protocol
                    resultFuture.setException(e);
                } finally {
                    RequestContexts.setCurrentContext(oldRequestContext);
                }
            }
        }

        @Override
        public void onFailure(Throwable t) {
            RequestContext oldRequestContext = RequestContexts.getCurrentContext();
            RequestContexts.setCurrentContext(requestContext);

            try {
                contextChain.preWriteException(t);
                if (!oneway) {
                    ExceptionProcessor exceptionCodec = exceptionCodecs.get(t.getClass());

                    if (exceptionCodec == null) {
                        // In case the method throws a subtype of one of its declared
                        // exceptions, exact lookup will fail. We need to simulate it.
                        // (This isn't a problem for normal returns because there the
                        // output codec is decided in advance.)
                        for (Map.Entry<Class<?>, ExceptionProcessor> entry : exceptionCodecs.entrySet()) {
                            if (entry.getKey().isAssignableFrom(t.getClass())) {
                                exceptionCodec = entry.getValue();
                                break;
                            }
                        }
                    }

                    if (exceptionCodec != null) {
                        contextChain.declaredUserException(t, exceptionCodec.getCodec());
                        // write expected exception response
                        writeResponse(out, sequenceId, TMessageType.REPLY, "exception", exceptionCodec.getId(),
                                exceptionCodec.getCodec(), t);
                        contextChain.postWriteException(t);
                    } else {
                        contextChain.undeclaredUserException(t);
                        // unexpected exception
                        TApplicationException applicationException = ThriftServiceProcessor
                                .createAndWriteApplicationException(out, requestContext, method.getName(),
                                        sequenceId, INTERNAL_ERROR,
                                        "Internal error processing " + method.getName() + ": " + t.getMessage(),
                                        t);

                        contextChain.postWriteException(applicationException);
                    }
                }

                resultFuture.set(true);
            } catch (Exception e) {
                // An exception occurred trying to serialize an exception onto the output protocol
                resultFuture.setException(e);
            } finally {
                RequestContexts.setCurrentContext(oldRequestContext);
            }
        }
    });

    return resultFuture;
}

From source file:com.flipkart.phantom.runtime.impl.server.netty.decoder.thrift.ThriftBufferDecoder.java

License:Apache License

/**
 * Interface method implementation. Tries to read the Thrift protocol message. Returns null if unsuccessful, else returns the read byte array. Also
 * resets the {@link ChannelBuffer} reader index to nullify the effect of the read operation.
 * @see org.jboss.netty.handler.codec.replay.ReplayingDecoder#decode(org.jboss.netty.channel.ChannelHandlerContext, org.jboss.netty.channel.Channel, org.jboss.netty.buffer.ChannelBuffer, java.lang.Enum)
 *///from   ww  w .  j  a v a  2s  .c  o  m
protected Object decode(ChannelHandlerContext ctx, Channel channel, ChannelBuffer buffer, VoidEnum voidEnum)
        throws Exception {
    ThriftNettyChannelBuffer ttransport = new ThriftNettyChannelBuffer(buffer, null); // we dont use the output buffer, so null is fine
    TProtocol iprot = this.protocolFactory.getProtocol(ttransport);
    int beginIndex = buffer.readerIndex();
    buffer.markReaderIndex();

    iprot.readMessageBegin();
    TProtocolUtil.skip(iprot, TType.STRUCT);
    iprot.readMessageEnd();

    int endIndex = buffer.readerIndex();
    buffer.resetReaderIndex();

    return buffer.readSlice(endIndex - beginIndex);
}

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

License:Apache License

/**
 *
 * Is called by the {@link com.flipkart.phantom.thrift.impl.ThriftProxyExecutor#run()} for processing the request.
 * Currently not utilizing the generic pooled objects.
 *
 * @param clientTransport//from   ww w  .  j  a  v a 2  s .c  om
 * @return transport {@link TTransport} containing clientOutput
 * @throws Exception
 */
@SuppressWarnings("rawtypes")
public TTransport doRequest(TTransport clientTransport) {
    TSocket serviceSocket = null;
    try {
        //Get Protocol from transport
        TProtocol clientProtocol = this.protocolFactory.getProtocol(clientTransport);

        TMessage message = clientProtocol.readMessageBegin();
        //Arguments
        ProcessFunction invokedProcessFunction = this.getProcessMap().get(message.name);
        if (invokedProcessFunction == null) {
            throw new RuntimeException(
                    "Unable to find a matching ProcessFunction for invoked method : " + message.name);
        }
        TBase args = invokedProcessFunction.getEmptyArgsInstance(); // get the empty args. The values will then be read from the client's TProtocol
        //Read the argument values from the client's TProtocol
        args.read(clientProtocol);
        clientProtocol.readMessageEnd();

        // Instantiate the call result object using the Thrift naming convention used for classes
        TBase result = (TBase) Class
                .forName(this.getThriftServiceClass() + "$" + message.name + DEFAULT_RESULT_CLASS_NAME)
                .newInstance();

        serviceSocket = new TSocket(this.getThriftServer(), this.getThriftPort(),
                this.getThriftTimeoutMillis());
        TProtocol serviceProtocol = new TBinaryProtocol(serviceSocket);
        serviceSocket.open();

        //Send the arguments to the server and relay the response back
        //Create the custom TServiceClient client which sends request to actual Thrift servers and relays the response back to the client
        ProxyServiceClient proxyClient = new ProxyServiceClient(clientProtocol, serviceProtocol,
                serviceProtocol);

        //Send the request
        proxyClient.sendBase(message.name, args, message.seqid);
        //Get the response back (it is written to client's TProtocol)
        proxyClient.receiveBase(result, message.name);

        LOGGER.debug("Processed message : " + this.getThriftServiceClass() + "." + message.name);
    } catch (Exception e) {
        if (e.getClass().isAssignableFrom(TTransportException.class)) {
            //isConnectionValid = false;
            throw new RuntimeException("Thrift transport exception executing the proxy service call : "
                    + THRIFT_ERRORS.get(((TTransportException) e).getType()), e);
        } else {
            throw new RuntimeException("Exception executing the proxy service call : " + e.getMessage(), e);
        }
    } finally {
        if (serviceSocket != null) {
            serviceSocket.close();
        }
    }
    return clientTransport;
}

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

License:Apache License

@SuppressWarnings({ "unchecked", "rawtypes" })
@Override//  www.  j a  v a 2 s.c  om
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());
}