Search in sources :

Example 6 with UnsafeByteArrayOutputStream

use of com.alibaba.dubbo.common.io.UnsafeByteArrayOutputStream in project dubbo by alibaba.

the class DeprecatedExchangeCodec method encodeResponse.

protected void encodeResponse(Channel channel, OutputStream os, Response res) throws IOException {
    try {
        Serialization serialization = CodecSupport.getSerialization(channel.getUrl());
        // header.
        byte[] header = new byte[HEADER_LENGTH];
        // set magic number.
        Bytes.short2bytes(MAGIC, header);
        // set request and serialization flag.
        header[2] = serialization.getContentTypeId();
        if (res.isHeartbeat())
            header[2] |= FLAG_EVENT;
        // set response status.
        byte status = res.getStatus();
        header[3] = status;
        // set request id.
        Bytes.long2bytes(res.getId(), header, 4);
        UnsafeByteArrayOutputStream bos = new UnsafeByteArrayOutputStream(1024);
        ObjectOutput out = serialization.serialize(channel.getUrl(), bos);
        // encode response data or error message.
        if (status == Response.OK) {
            if (res.isHeartbeat()) {
                encodeHeartbeatData(channel, out, res.getResult());
            } else {
                encodeResponseData(channel, out, res.getResult());
            }
        } else
            out.writeUTF(res.getErrorMessage());
        out.flushBuffer();
        bos.flush();
        bos.close();
        byte[] data = bos.toByteArray();
        checkPayload(channel, data.length);
        Bytes.int2bytes(data.length, header, 12);
        // write
        // write header.
        os.write(header);
        // write data.
        os.write(data);
    } catch (Throwable t) {
        // 发送失败信息给Consumer,否则Consumer只能等超时了
        if (!res.isEvent() && res.getStatus() != Response.BAD_RESPONSE) {
            try {
                // FIXME 在Codec中打印出错日志?在IoHanndler的caught中统一处理?
                logger.warn("Fail to encode response: " + res + ", send bad_response info instead, cause: " + t.getMessage(), t);
                Response r = new Response(res.getId(), res.getVersion());
                r.setStatus(Response.BAD_RESPONSE);
                r.setErrorMessage("Failed to send response: " + res + ", cause: " + StringUtils.toString(t));
                channel.send(r);
                return;
            } catch (RemotingException e) {
                logger.warn("Failed to send bad_response info back: " + res + ", cause: " + e.getMessage(), e);
            }
        }
        // 重新抛出收到的异常
        if (t instanceof IOException) {
            throw (IOException) t;
        } else if (t instanceof RuntimeException) {
            throw (RuntimeException) t;
        } else if (t instanceof Error) {
            throw (Error) t;
        } else {
            throw new RuntimeException(t.getMessage(), t);
        }
    }
}
Also used : Serialization(com.alibaba.dubbo.common.serialize.Serialization) Response(com.alibaba.dubbo.remoting.exchange.Response) ObjectOutput(com.alibaba.dubbo.common.serialize.ObjectOutput) RemotingException(com.alibaba.dubbo.remoting.RemotingException) UnsafeByteArrayOutputStream(com.alibaba.dubbo.common.io.UnsafeByteArrayOutputStream) IOException(java.io.IOException)

Example 7 with UnsafeByteArrayOutputStream

use of com.alibaba.dubbo.common.io.UnsafeByteArrayOutputStream in project dubbo by alibaba.

the class CodecAdapter method encode.

public void encode(Channel channel, ChannelBuffer buffer, Object message) throws IOException {
    UnsafeByteArrayOutputStream os = new UnsafeByteArrayOutputStream(1024);
    codec.encode(channel, os, message);
    buffer.writeBytes(os.toByteArray());
}
Also used : UnsafeByteArrayOutputStream(com.alibaba.dubbo.common.io.UnsafeByteArrayOutputStream)

Example 8 with UnsafeByteArrayOutputStream

use of com.alibaba.dubbo.common.io.UnsafeByteArrayOutputStream in project dubbo by alibaba.

the class ExchangeCodecTest method getRequestBytes.

private byte[] getRequestBytes(Object obj, byte[] header) throws IOException {
    // encode request data.
    UnsafeByteArrayOutputStream bos = new UnsafeByteArrayOutputStream(1024);
    ObjectOutput out = serialization.serialize(url, bos);
    out.writeObject(obj);
    out.flushBuffer();
    bos.flush();
    bos.close();
    byte[] data = bos.toByteArray();
    byte[] len = Bytes.int2bytes(data.length);
    System.arraycopy(len, 0, header, 12, 4);
    byte[] request = join(header, data);
    return request;
}
Also used : ObjectOutput(com.alibaba.dubbo.common.serialize.ObjectOutput) UnsafeByteArrayOutputStream(com.alibaba.dubbo.common.io.UnsafeByteArrayOutputStream)

Example 9 with UnsafeByteArrayOutputStream

use of com.alibaba.dubbo.common.io.UnsafeByteArrayOutputStream in project dubbo by alibaba.

the class GenericFilter method invoke.

public Result invoke(Invoker<?> invoker, Invocation inv) throws RpcException {
    if (inv.getMethodName().equals(Constants.$INVOKE) && inv.getArguments() != null && inv.getArguments().length == 3 && !ProtocolUtils.isGeneric(invoker.getUrl().getParameter(Constants.GENERIC_KEY))) {
        String name = ((String) inv.getArguments()[0]).trim();
        String[] types = (String[]) inv.getArguments()[1];
        Object[] args = (Object[]) inv.getArguments()[2];
        try {
            Method method = ReflectUtils.findMethodByMethodSignature(invoker.getInterface(), name, types);
            Class<?>[] params = method.getParameterTypes();
            if (args == null) {
                args = new Object[params.length];
            }
            String generic = inv.getAttachment(Constants.GENERIC_KEY);
            if (StringUtils.isEmpty(generic) || ProtocolUtils.isDefaultGenericSerialization(generic)) {
                args = PojoUtils.realize(args, params, method.getGenericParameterTypes());
            } else if (ProtocolUtils.isJavaGenericSerialization(generic)) {
                for (int i = 0; i < args.length; i++) {
                    if (byte[].class == args[i].getClass()) {
                        try {
                            UnsafeByteArrayInputStream is = new UnsafeByteArrayInputStream((byte[]) args[i]);
                            args[i] = ExtensionLoader.getExtensionLoader(Serialization.class).getExtension(Constants.GENERIC_SERIALIZATION_NATIVE_JAVA).deserialize(null, is).readObject();
                        } catch (Exception e) {
                            throw new RpcException("Deserialize argument [" + (i + 1) + "] failed.", e);
                        }
                    } else {
                        throw new RpcException(new StringBuilder(32).append("Generic serialization [").append(Constants.GENERIC_SERIALIZATION_NATIVE_JAVA).append("] only support message type ").append(byte[].class).append(" and your message type is ").append(args[i].getClass()).toString());
                    }
                }
            } else if (ProtocolUtils.isBeanGenericSerialization(generic)) {
                for (int i = 0; i < args.length; i++) {
                    if (args[i] instanceof JavaBeanDescriptor) {
                        args[i] = JavaBeanSerializeUtil.deserialize((JavaBeanDescriptor) args[i]);
                    } else {
                        throw new RpcException(new StringBuilder(32).append("Generic serialization [").append(Constants.GENERIC_SERIALIZATION_BEAN).append("] only support message type ").append(JavaBeanDescriptor.class.getName()).append(" and your message type is ").append(args[i].getClass().getName()).toString());
                    }
                }
            }
            Result result = invoker.invoke(new RpcInvocation(method, args, inv.getAttachments()));
            if (result.hasException() && !(result.getException() instanceof GenericException)) {
                return new RpcResult(new GenericException(result.getException()));
            }
            if (ProtocolUtils.isJavaGenericSerialization(generic)) {
                try {
                    UnsafeByteArrayOutputStream os = new UnsafeByteArrayOutputStream(512);
                    ExtensionLoader.getExtensionLoader(Serialization.class).getExtension(Constants.GENERIC_SERIALIZATION_NATIVE_JAVA).serialize(null, os).writeObject(result.getValue());
                    return new RpcResult(os.toByteArray());
                } catch (IOException e) {
                    throw new RpcException("Serialize result failed.", e);
                }
            } else if (ProtocolUtils.isBeanGenericSerialization(generic)) {
                return new RpcResult(JavaBeanSerializeUtil.serialize(result.getValue(), JavaBeanAccessor.METHOD));
            } else {
                return new RpcResult(PojoUtils.generalize(result.getValue()));
            }
        } catch (NoSuchMethodException e) {
            throw new RpcException(e.getMessage(), e);
        } catch (ClassNotFoundException e) {
            throw new RpcException(e.getMessage(), e);
        }
    }
    return invoker.invoke(inv);
}
Also used : RpcInvocation(com.alibaba.dubbo.rpc.RpcInvocation) RpcResult(com.alibaba.dubbo.rpc.RpcResult) UnsafeByteArrayInputStream(com.alibaba.dubbo.common.io.UnsafeByteArrayInputStream) Method(java.lang.reflect.Method) IOException(java.io.IOException) GenericException(com.alibaba.dubbo.rpc.service.GenericException) IOException(java.io.IOException) RpcException(com.alibaba.dubbo.rpc.RpcException) GenericException(com.alibaba.dubbo.rpc.service.GenericException) Result(com.alibaba.dubbo.rpc.Result) RpcResult(com.alibaba.dubbo.rpc.RpcResult) Serialization(com.alibaba.dubbo.common.serialize.Serialization) JavaBeanDescriptor(com.alibaba.dubbo.common.beanutil.JavaBeanDescriptor) RpcException(com.alibaba.dubbo.rpc.RpcException) UnsafeByteArrayOutputStream(com.alibaba.dubbo.common.io.UnsafeByteArrayOutputStream)

Example 10 with UnsafeByteArrayOutputStream

use of com.alibaba.dubbo.common.io.UnsafeByteArrayOutputStream in project dubbo by alibaba.

the class BuilderTest method testObjectBuilder.

@Test
public void testObjectBuilder() throws Exception {
    UnsafeByteArrayOutputStream os = new UnsafeByteArrayOutputStream();
    Builder<Bean> BeanBuilder = Builder.register(Bean.class);
    Bean bean = new Bean();
    bean.name = "ql";
    bean.type = Type.High;
    bean.types = new Type[] { Type.High, Type.High };
    BeanBuilder.writeTo(bean, os);
    byte[] b = os.toByteArray();
    System.out.println(b.length + ":" + Bytes.bytes2hex(b));
    bean = BeanBuilder.parseFrom(b);
    assertNull(bean.time);
    assertEquals(bean.i, 123123);
    assertEquals(bean.ni, -12344);
    assertEquals(bean.d, 12.345);
    assertEquals(bean.nd, -12.345);
    assertEquals(bean.l, 1281447759383l);
    assertEquals(bean.nl, -13445l);
    assertEquals(bean.vl, 100l);
    assertEquals(bean.type, Type.High);
    assertEquals(bean.types.length, 2);
    assertEquals(bean.types[0], Type.High);
    assertEquals(bean.types[1], Type.High);
    assertEquals(bean.list.size(), 3);
    assertEquals(bean.list.get(0), 1);
    assertEquals(bean.list.get(1), 2);
    assertEquals(bean.list.get(2), 1308147);
}
Also used : UnsafeByteArrayOutputStream(com.alibaba.dubbo.common.io.UnsafeByteArrayOutputStream) Test(org.junit.Test)

Aggregations

UnsafeByteArrayOutputStream (com.alibaba.dubbo.common.io.UnsafeByteArrayOutputStream)19 Test (org.junit.Test)13 ObjectOutput (com.alibaba.dubbo.common.serialize.ObjectOutput)3 Serialization (com.alibaba.dubbo.common.serialize.Serialization)3 UnsafeByteArrayInputStream (com.alibaba.dubbo.common.io.UnsafeByteArrayInputStream)2 IOException (java.io.IOException)2 JavaBeanDescriptor (com.alibaba.dubbo.common.beanutil.JavaBeanDescriptor)1 DataInput (com.alibaba.dubbo.common.serialize.DataInput)1 DataOutput (com.alibaba.dubbo.common.serialize.DataOutput)1 GenericDataInput (com.alibaba.dubbo.common.serialize.support.dubbo.GenericDataInput)1 GenericDataOutput (com.alibaba.dubbo.common.serialize.support.dubbo.GenericDataOutput)1 RemotingException (com.alibaba.dubbo.remoting.RemotingException)1 Response (com.alibaba.dubbo.remoting.exchange.Response)1 Result (com.alibaba.dubbo.rpc.Result)1 RpcException (com.alibaba.dubbo.rpc.RpcException)1 RpcInvocation (com.alibaba.dubbo.rpc.RpcInvocation)1 RpcResult (com.alibaba.dubbo.rpc.RpcResult)1 GenericException (com.alibaba.dubbo.rpc.service.GenericException)1 Method (java.lang.reflect.Method)1 HashMap (java.util.HashMap)1