Example usage for org.apache.thrift.transport TIOStreamTransport TIOStreamTransport

List of usage examples for org.apache.thrift.transport TIOStreamTransport TIOStreamTransport

Introduction

In this page you can find the example usage for org.apache.thrift.transport TIOStreamTransport TIOStreamTransport.

Prototype

public TIOStreamTransport(OutputStream os) 

Source Link

Document

Output stream constructor, constructs an output only transport.

Usage

From source file:andromache.hadoop.WritableMutation.java

License:Apache License

@Override
public void write(DataOutput out) throws IOException {
    out.writeUTF(keySpace);//from w  ww. j a v  a 2s  .c  o  m
    out.writeUTF(columnFamily);

    ByteArrayOutputStream os = new ByteArrayOutputStream();
    TBinaryProtocol binaryProtocol = new TBinaryProtocol(new TIOStreamTransport(os));
    try {
        mutation.write(binaryProtocol);
        byte[] serialized = os.toByteArray();
        out.writeInt(serialized.length);
        out.write(serialized);
    } catch (TException e) {
        throw new IOException("Unable to serialize mutation", e);
    }

}

From source file:andromache.hadoop.WritableMutation.java

License:Apache License

@Override
public void readFields(DataInput in) throws IOException {
    this.keySpace = in.readUTF();
    this.columnFamily = in.readUTF();
    int length = in.readInt();
    byte[] serialized = new byte[length];

    in.readFully(serialized);/*from  ww w  . ja v  a2 s . co  m*/

    ByteArrayInputStream is = new ByteArrayInputStream(serialized);
    TBinaryProtocol binaryProtocol = new TBinaryProtocol(new TIOStreamTransport(is));

    try {
        this.mutation = new Mutation();
        mutation.read(binaryProtocol);
    } catch (TException e) {
        throw new IOException("Unable to deserialize mutation", e);
    }

}

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

License:Open Source License

@Override
public Object decode(Channel channel, ChannelBuffer buffer) throws IOException {

    int available = buffer.readableBytes();

    if (available < MESSAGE_SHORTEST_LENGTH) {

        return DecodeResult.NEED_MORE_INPUT;

    } else {/*from   w ww . j a  v a  2  s .c  o m*/

        TIOStreamTransport transport = new TIOStreamTransport(new ChannelBufferInputStream(buffer));

        TBinaryProtocol protocol = new TBinaryProtocol(transport);

        String serviceName = channel.getUrl().getParameter(Constants.INTERFACE_KEY);
        return decode(serviceName, protocol);

    }

}

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

License:Open Source License

private void encodeRequest(Channel channel, ChannelBuffer buffer, Request request) throws IOException {

    RpcInvocation inv = (RpcInvocation) request.getData();

    int seqId = new Long(request.getId()).intValue();

    String serviceName = inv.getAttachment(Constants.INTERFACE_KEY);

    if (StringUtils.isEmpty(serviceName)) {
        throw new IllegalArgumentException(
                new StringBuilder(32).append("Could not find service name in attachment with key ")
                        .append(Constants.INTERFACE_KEY).toString());
    }//  w  ww .ja  v a 2 s  .  com

    TMessage message = new TMessage(inv.getMethodName(), TMessageType.CALL, seqId);

    ExtensionLoader<ClassNameGenerator> loader = ExtensionLoader.getExtensionLoader(ClassNameGenerator.class);
    String name = channel.getUrl().getParameter(ThriftConstants.CLASS_NAME_GENERATOR_KEY,
            ThriftClassNameGenerator.NAME);
    ClassNameGenerator generator = loader.getExtension(name);
    String methodName = inv.getMethodName();
    String methodArgs = generator.generateArgsClassName(serviceName, methodName);

    if (StringUtils.isEmpty(methodArgs)) {
        throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, new StringBuilder(32)
                .append("Could not encode request, the specified interface may be incorrect.").toString());
    }

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

    if (clazz == null) {

        try {

            clazz = ClassHelper.forNameWithThreadContextClassLoader(methodArgs);

            cachedClass.putIfAbsent(methodArgs, 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);
    }

    for (int i = 0; i < inv.getArguments().length; i++) {

        Object obj = inv.getArguments()[i];

        if (obj == null) {
            continue;
        }

        TFieldIdEnum field = args.fieldForId(i + 1);

        String setMethodName = ThriftUtils.generateSetMethodName(field.getFieldName());

        Method method;

        try {
            method = clazz.getMethod(setMethodName, inv.getParameterTypes()[i]);
        } catch (NoSuchMethodException e) {
            throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e);
        }

        try {
            method.invoke(args, obj);
        } catch (IllegalAccessException e) {
            throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e);
        } catch (InvocationTargetException e) {
            throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e);
        }

    }

    RandomAccessByteArrayOutputStream bos = new RandomAccessByteArrayOutputStream(1024);

    TIOStreamTransport transport = new TIOStreamTransport(bos);

    TBinaryProtocol protocol = new TBinaryProtocol(transport);

    try {
        protocol.writeMessageBegin(message);
        args.write(protocol);
        protocol.writeMessageEnd();
        protocol.getTransport().flush();
    } catch (TException e) {
        throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e);
    }

    buffer.writeBytes(bos.toByteArray());

}

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

License:Open Source License

private void encodeResponse(Channel channel, ChannelBuffer buffer, Response response) throws IOException {

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

    RequestData rd = cachedRequest.get((int) response.getId());
    String service = channel.getUrl().getParameter(ThriftConstants.CLASS_NAME_GENERATOR_KEY,
            ThriftClassNameGenerator.NAME);
    ClassNameGenerator generator = ExtensionLoader.getExtensionLoader(ClassNameGenerator.class)
            .getExtension(service);/*from   w ww.ja va  2s. c  o  m*/
    String resultClassName = generator.generateResultClassName(rd.serviceName, rd.methodName);

    if (StringUtils.isEmpty(resultClassName)) {
        throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, new StringBuilder(32)
                .append("Could not encode response, the specified interface may be incorrect.").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 resultObj;

    try {
        resultObj = (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);
    }

    TApplicationException applicationException = null;
    TMessage message;

    if (result.hasException()) {
        Throwable throwable = result.getException();
        int index = 1;
        boolean found = false;
        while (true) {
            TFieldIdEnum fieldIdEnum = resultObj.fieldForId(index++);
            if (fieldIdEnum == null) {
                break;
            }
            String fieldName = fieldIdEnum.getFieldName();
            String getMethodName = ThriftUtils.generateGetMethodName(fieldName);
            String setMethodName = ThriftUtils.generateSetMethodName(fieldName);
            Method getMethod;
            Method setMethod;
            try {
                getMethod = clazz.getMethod(getMethodName);
                if (getMethod.getReturnType().equals(throwable.getClass())) {
                    found = true;
                    setMethod = clazz.getMethod(setMethodName, throwable.getClass());
                    setMethod.invoke(resultObj, throwable);
                }
            } catch (NoSuchMethodException e) {
                throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e);
            } catch (InvocationTargetException e) {
                throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e);
            } catch (IllegalAccessException e) {
                throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e);
            }
        }

        if (!found) {
            applicationException = new TApplicationException(throwable.getMessage());
        }

    } else {
        Object realResult = result.getResult();
        // result field id is 0
        String fieldName = resultObj.fieldForId(0).getFieldName();
        String setMethodName = ThriftUtils.generateSetMethodName(fieldName);
        String getMethodName = ThriftUtils.generateGetMethodName(fieldName);
        Method getMethod;
        Method setMethod;
        try {
            getMethod = clazz.getMethod(getMethodName);
            setMethod = clazz.getMethod(setMethodName, getMethod.getReturnType());
            setMethod.invoke(resultObj, realResult);
        } catch (NoSuchMethodException e) {
            throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e);
        } catch (InvocationTargetException e) {
            throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e);
        } catch (IllegalAccessException e) {
            throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e);
        }

    }

    if (applicationException != null) {
        message = new TMessage(rd.methodName, TMessageType.EXCEPTION, rd.id);
    } else {
        message = new TMessage(rd.methodName, TMessageType.REPLY, rd.id);
    }

    RandomAccessByteArrayOutputStream bos = new RandomAccessByteArrayOutputStream(1024);

    TIOStreamTransport transport = new TIOStreamTransport(bos);

    TBinaryProtocol protocol = new TBinaryProtocol(transport);

    try {
        protocol.writeMessageBegin(message);
        switch (message.type) {
        case TMessageType.EXCEPTION:
            applicationException.write(protocol);
            break;
        case TMessageType.REPLY:
            resultObj.write(protocol);
            break;
        }
        protocol.writeMessageEnd();
        protocol.getTransport().flush();
    } catch (TException e) {
        throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e);
    }

    buffer.writeBytes(bos.toByteArray());

}

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

License:Open Source License

public boolean process(TProtocol in, TProtocol out) throws TException {

    short magic = in.readI16();

    if (magic != ThriftCodec.MAGIC) {
        logger.error(new StringBuilder(24).append("Unsupported magic ").append(magic).toString());
        return false;
    }/*  www . j  a  v  a 2  s . co  m*/

    in.readI32();
    in.readI16();
    byte version = in.readByte();
    String serviceName = in.readString();
    long id = in.readI64();

    ByteArrayOutputStream bos = new ByteArrayOutputStream(1024);

    TIOStreamTransport transport = new TIOStreamTransport(bos);

    TProtocol protocol = protocolFactory.getProtocol(transport);

    TProcessor processor = processorMap.get(serviceName);

    if (processor == null) {
        logger.error(new StringBuilder(32).append("Could not find processor for service ").append(serviceName)
                .toString());
        return false;
    }

    // todo if exception
    boolean result = processor.process(in, protocol);

    ByteArrayOutputStream header = new ByteArrayOutputStream(512);

    TIOStreamTransport headerTransport = new TIOStreamTransport(header);

    TProtocol headerProtocol = protocolFactory.getProtocol(headerTransport);

    headerProtocol.writeI16(magic);
    headerProtocol.writeI32(Integer.MAX_VALUE);
    headerProtocol.writeI16(Short.MAX_VALUE);
    headerProtocol.writeByte(version);
    headerProtocol.writeString(serviceName);
    headerProtocol.writeI64(id);
    headerProtocol.getTransport().flush();

    out.writeI16(magic);
    out.writeI32(bos.size() + header.size());
    out.writeI16((short) (0xffff & header.size()));
    out.writeByte(version);
    out.writeString(serviceName);
    out.writeI64(id);

    out.getTransport().write(bos.toByteArray());
    out.getTransport().flush();

    return result;

}

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

License:Open Source License

public Object decode(Channel channel, InputStream input) throws IOException {

    int available = input.available();

    if (available < MESSAGE_SHORTEST_LENGTH) {

        return Codec.NEED_MORE_INPUT;

    } else {/*from   w w w.j  a v a  2  s. c  o  m*/

        TIOStreamTransport transport = new TIOStreamTransport(input);

        TBinaryProtocol protocol = new TBinaryProtocol(transport);

        short magic;
        int messageLength;

        try {
            //                protocol.readI32(); // skip the first message length
            byte[] bytes = new byte[4];
            transport.read(bytes, 0, 4);
            magic = protocol.readI16();
            messageLength = protocol.readI32();

        } catch (TException e) {
            throw new IOException(e.getMessage(), e);
        }

        if (MAGIC != magic) {
            throw new IOException(new StringBuilder(32).append("Unknown magic code ").append(magic).toString());
        }

        if (available < messageLength) {
            return NEED_MORE_INPUT;
        }

        return decode(protocol);

    }

}

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

License:Open Source License

private void encodeRequest(Channel channel, OutputStream output, Request request) throws IOException {

    RpcInvocation inv = (RpcInvocation) request.getData();

    int seqId = nextSeqId();

    String serviceName = inv.getAttachment(Constants.INTERFACE_KEY);

    if (StringUtils.isEmpty(serviceName)) {
        throw new IllegalArgumentException(
                new StringBuilder(32).append("Could not find service name in attachment with key ")
                        .append(Constants.INTERFACE_KEY).toString());
    }/*from w ww.  ja  va  2 s .  c o  m*/

    TMessage message = new TMessage(inv.getMethodName(), TMessageType.CALL, seqId);

    String methodArgs = ExtensionLoader
            .getExtensionLoader(ClassNameGenerator.class).getExtension(channel.getUrl()
                    .getParameter(ThriftConstants.CLASS_NAME_GENERATOR_KEY, ThriftClassNameGenerator.NAME))
            .generateArgsClassName(serviceName, inv.getMethodName());

    if (StringUtils.isEmpty(methodArgs)) {
        throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, new StringBuilder(32)
                .append("Could not encode request, the specified interface may be incorrect.").toString());
    }

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

    if (clazz == null) {

        try {

            clazz = ClassHelper.forNameWithThreadContextClassLoader(methodArgs);

            cachedClass.putIfAbsent(methodArgs, 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);
    }

    for (int i = 0; i < inv.getArguments().length; i++) {

        Object obj = inv.getArguments()[i];

        if (obj == null) {
            continue;
        }

        TFieldIdEnum field = args.fieldForId(i + 1);

        String setMethodName = ThriftUtils.generateSetMethodName(field.getFieldName());

        Method method;

        try {
            method = clazz.getMethod(setMethodName, inv.getParameterTypes()[i]);
        } catch (NoSuchMethodException e) {
            throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e);
        }

        try {
            method.invoke(args, obj);
        } catch (IllegalAccessException e) {
            throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e);
        } catch (InvocationTargetException e) {
            throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e);
        }

    }

    RandomAccessByteArrayOutputStream bos = new RandomAccessByteArrayOutputStream(1024);

    TIOStreamTransport transport = new TIOStreamTransport(bos);

    TBinaryProtocol protocol = new TBinaryProtocol(transport);

    int headerLength, messageLength;

    byte[] bytes = new byte[4];
    try {
        // magic
        protocol.writeI16(MAGIC);
        // message length placeholder
        protocol.writeI32(Integer.MAX_VALUE);
        // message header length placeholder
        protocol.writeI16(Short.MAX_VALUE);
        // version
        protocol.writeByte(VERSION);
        // service name
        protocol.writeString(serviceName);
        // dubbo request id
        protocol.writeI64(request.getId());
        protocol.getTransport().flush();
        // header size
        headerLength = bos.size();

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

        // fill in message length and header length
        try {
            TFramedTransport.encodeFrameSize(messageLength, bytes);
            bos.setWriteIndex(MESSAGE_LENGTH_INDEX);
            protocol.writeI32(messageLength);
            bos.setWriteIndex(MESSAGE_HEADER_LENGTH_INDEX);
            protocol.writeI16((short) (0xffff & headerLength));
        } finally {
            bos.setWriteIndex(oldIndex);
        }

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

    output.write(bytes);
    bos.writeTo(output);
    output.flush();

}

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

License:Open Source License

private void encodeResponse(Channel channel, OutputStream output, Response response) throws IOException {

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

    RequestData rd = cachedRequest.get(response.getId());

    String resultClassName = ExtensionLoader
            .getExtensionLoader(ClassNameGenerator.class).getExtension(channel.getUrl()
                    .getParameter(ThriftConstants.CLASS_NAME_GENERATOR_KEY, ThriftClassNameGenerator.NAME))
            .generateResultClassName(rd.serviceName, rd.methodName);

    if (StringUtils.isEmpty(resultClassName)) {
        throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, new StringBuilder(32)
                .append("Could not encode response, the specified interface may be incorrect.").toString());
    }/*from   w w w  . j a  va 2s  .  c  o m*/

    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 resultObj;

    try {
        resultObj = (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);
    }

    TApplicationException applicationException = null;
    TMessage message;

    if (result.hasException()) {
        Throwable throwable = result.getException();
        int index = 1;
        boolean found = false;
        while (true) {
            TFieldIdEnum fieldIdEnum = resultObj.fieldForId(index++);
            if (fieldIdEnum == null) {
                break;
            }
            String fieldName = fieldIdEnum.getFieldName();
            String getMethodName = ThriftUtils.generateGetMethodName(fieldName);
            String setMethodName = ThriftUtils.generateSetMethodName(fieldName);
            Method getMethod;
            Method setMethod;
            try {
                getMethod = clazz.getMethod(getMethodName);
                if (getMethod.getReturnType().equals(throwable.getClass())) {
                    found = true;
                    setMethod = clazz.getMethod(setMethodName, throwable.getClass());
                    setMethod.invoke(resultObj, throwable);
                }
            } catch (NoSuchMethodException e) {
                throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e);
            } catch (InvocationTargetException e) {
                throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e);
            } catch (IllegalAccessException e) {
                throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e);
            }
        }

        if (!found) {
            applicationException = new TApplicationException(throwable.getMessage());
        }

    } else {
        Object realResult = result.getResult();
        // result field id is 0
        String fieldName = resultObj.fieldForId(0).getFieldName();
        String setMethodName = ThriftUtils.generateSetMethodName(fieldName);
        String getMethodName = ThriftUtils.generateGetMethodName(fieldName);
        Method getMethod;
        Method setMethod;
        try {
            getMethod = clazz.getMethod(getMethodName);
            setMethod = clazz.getMethod(setMethodName, getMethod.getReturnType());
            setMethod.invoke(resultObj, realResult);
        } catch (NoSuchMethodException e) {
            throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e);
        } catch (InvocationTargetException e) {
            throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e);
        } catch (IllegalAccessException e) {
            throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e);
        }

    }

    if (applicationException != null) {
        message = new TMessage(rd.methodName, TMessageType.EXCEPTION, rd.id);
    } else {
        message = new TMessage(rd.methodName, TMessageType.REPLY, rd.id);
    }

    RandomAccessByteArrayOutputStream bos = new RandomAccessByteArrayOutputStream(1024);

    TIOStreamTransport transport = new TIOStreamTransport(bos);

    TBinaryProtocol protocol = new TBinaryProtocol(transport);

    int messageLength;
    int headerLength;

    byte[] bytes = new byte[4];
    try {
        // magic
        protocol.writeI16(MAGIC);
        // message length
        protocol.writeI32(Integer.MAX_VALUE);
        // message header length
        protocol.writeI16(Short.MAX_VALUE);
        // version
        protocol.writeByte(VERSION);
        // service name
        protocol.writeString(rd.serviceName);
        // id
        protocol.writeI64(response.getId());
        protocol.getTransport().flush();
        headerLength = bos.size();

        // message
        protocol.writeMessageBegin(message);
        switch (message.type) {
        case TMessageType.EXCEPTION:
            applicationException.write(protocol);
            break;
        case TMessageType.REPLY:
            resultObj.write(protocol);
            break;
        }
        protocol.writeMessageEnd();
        protocol.getTransport().flush();
        int oldIndex = messageLength = bos.size();

        try {
            TFramedTransport.encodeFrameSize(messageLength, bytes);
            bos.setWriteIndex(MESSAGE_LENGTH_INDEX);
            protocol.writeI32(messageLength);
            bos.setWriteIndex(MESSAGE_HEADER_LENGTH_INDEX);
            protocol.writeI16((short) (0xffff & headerLength));
        } finally {
            bos.setWriteIndex(oldIndex);
        }

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

    output.write(bytes);
    bos.writeTo(output);
    output.flush();

}

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

License:Open Source License

@Test
public void testEncodeRequest() throws Exception {

    Request request = createRequest();

    ByteArrayOutputStream output = new ByteArrayOutputStream(1024);

    codec.encode(channel, output, request);

    byte[] bytes = output.toByteArray();

    ByteArrayInputStream bis = new ByteArrayInputStream(bytes);

    TTransport transport = new TIOStreamTransport(bis);

    TBinaryProtocol protocol = new TBinaryProtocol(transport);

    // frame//from w  w w  . j a v a  2  s  . c  o  m
    byte[] length = new byte[4];
    transport.read(length, 0, 4);

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

    // magic
    Assert.assertEquals(ThriftCodec.MAGIC, protocol.readI16());

    // message length
    int messageLength = protocol.readI32();
    Assert.assertEquals(messageLength + 4, bytes.length);

    // header length
    short headerLength = protocol.readI16();
    // version
    Assert.assertEquals(ThriftCodec.VERSION, protocol.readByte());
    // service name
    Assert.assertEquals(Demo.Iface.class.getName(), protocol.readString());
    // dubbo request id
    Assert.assertEquals(request.getId(), protocol.readI64());

    // test message header length
    if (bis.markSupported()) {
        bis.reset();
        bis.skip(headerLength);
    }

    TMessage message = protocol.readMessageBegin();

    Demo.echoString_args args = new Demo.echoString_args();

    args.read(protocol);

    protocol.readMessageEnd();

    Assert.assertEquals("echoString", message.name);

    Assert.assertEquals(TMessageType.CALL, message.type);

    Assert.assertEquals("Hello, World!", args.getArg());

}