com.alibaba.dubbo.common.serialize.Serialization Java Examples

The following examples show how to use com.alibaba.dubbo.common.serialize.Serialization. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: HessianProtocolTest.java    From dubbo-2.6.5 with Apache License 2.0 6 votes vote down vote up
@Test
public void testGenericInvokeWithNativeJava() throws IOException, ClassNotFoundException {
    HessianServiceImpl server = new HessianServiceImpl();
    Assert.assertFalse(server.isCalled());
    ProxyFactory proxyFactory = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension();
    Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension();
    URL url = URL.valueOf("hessian://127.0.0.1:5342/" + HessianService.class.getName() + "?version=1.0.0&generic=nativejava");
    Exporter<HessianService> exporter = protocol.export(proxyFactory.getInvoker(server, HessianService.class, url));
    Invoker<GenericService> invoker = protocol.refer(GenericService.class, url);
    GenericService client = proxyFactory.getProxy(invoker);

    Serialization serialization = new NativeJavaSerialization();
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

    ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream);
    objectOutput.writeObject("haha");
    objectOutput.flushBuffer();

    Object result = client.$invoke("sayHello", new String[]{"java.lang.String"}, new Object[]{byteArrayOutputStream.toByteArray()});
    ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream((byte[]) result);
    ObjectInput objectInput = serialization.deserialize(url, byteArrayInputStream);
    Assert.assertTrue(server.isCalled());
    Assert.assertEquals("Hello, haha", objectInput.readObject());
    invoker.destroy();
    exporter.unexport();
}
 
Example #2
Source File: HttpProtocolTest.java    From dubbo-2.6.5 with Apache License 2.0 6 votes vote down vote up
@Test
public void testGenericInvokeWithNativeJava() throws IOException, ClassNotFoundException {
    HttpServiceImpl server = new HttpServiceImpl();
    Assert.assertFalse(server.isCalled());
    ProxyFactory proxyFactory = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension();
    Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension();
    URL url = URL.valueOf("http://127.0.0.1:5342/" + HttpService.class.getName() + "?version=1.0.0&generic=nativejava");
    Exporter<HttpService> exporter = protocol.export(proxyFactory.getInvoker(server, HttpService.class, url));
    Invoker<GenericService> invoker = protocol.refer(GenericService.class, url);
    GenericService client = proxyFactory.getProxy(invoker);

    Serialization serialization = new NativeJavaSerialization();
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

    ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream);
    objectOutput.writeObject("haha");
    objectOutput.flushBuffer();

    Object result = client.$invoke("sayHello", new String[]{"java.lang.String"}, new Object[]{byteArrayOutputStream.toByteArray()});
    ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream((byte[]) result);
    ObjectInput objectInput = serialization.deserialize(url, byteArrayInputStream);
    Assert.assertTrue(server.isCalled());
    Assert.assertEquals("Hello, haha", objectInput.readObject());
    invoker.destroy();
    exporter.unexport();
}
 
Example #3
Source File: ConfigUtilsTest.java    From dubbox-hystrix with Apache License 2.0 5 votes vote down vote up
/**
 * 测试点1:用户配置参数在最后 测试点2:用户配置参数如果带-,会删除同名的默认参数 测试点3:default开头的默认参数会被删除
 */
@Test
public void testMergeValues() {
    List<String> merged = ConfigUtils.mergeValues(Serialization.class, "aaa,bbb,default.cunstom",
            toArray("dubbo","default.hessian2","json"));
    Assert.assertEquals(toArray("dubbo", "json", "aaa", "bbb", "default.cunstom"), merged);
}
 
Example #4
Source File: CodecSupport.java    From dubbox with Apache License 2.0 5 votes vote down vote up
public static Serialization getSerialization(URL url, Byte id) {
    Serialization result = getSerializationById(id);
    if (result == null) {
        result = getSerialization(url);
    }
    return result;
}
 
Example #5
Source File: CodecSupport.java    From dubbo-2.6.5 with Apache License 2.0 5 votes vote down vote up
public static Serialization getSerialization(URL url, Byte id) throws IOException {
//        查询序列化器,默认hessian2,还支持java、kryo、fastjson等序列化器
        Serialization serialization = getSerializationById(id);
//        默认hessian2序列化
        String serializationName = url.getParameter(Constants.SERIALIZATION_KEY, Constants.DEFAULT_REMOTING_SERIALIZATION);
        // Check if "serialization id" passed from network matches the id on this side(only take effect for JDK serialization), for security purpose.为了安全起见,检查从网络传递的“序列化id”是否与这一侧的id匹配(仅对JDK序列化有效)。
        if (serialization == null
                || ((id == 3 || id == 7 || id == 4) && !(serializationName.equals(ID_SERIALIZATIONNAME_MAP.get(id))))) {
            throw new IOException("Unexpected serialization id:" + id + " received from network, please check if the peer send the right id.");
        }
        return serialization;
    }
 
Example #6
Source File: ConfigUtilsTest.java    From dubbox with Apache License 2.0 5 votes vote down vote up
/**
 * 测试点1:用户配置参数在最后 测试点2:用户配置参数如果带-,会删除同名的默认参数 测试点3:default开头的默认参数会被删除
 */
@Test
public void testMergeValues() {
    List<String> merged = ConfigUtils.mergeValues(Serialization.class, "aaa,bbb,default.cunstom",
            toArray("dubbo","default.hessian2","json"));
    Assert.assertEquals(toArray("dubbo", "json", "aaa", "bbb", "default.cunstom"), merged);
}
 
Example #7
Source File: DeprecatedExchangeCodec.java    From dubbo-2.6.5 with Apache License 2.0 5 votes vote down vote up
protected void encodeRequest(Channel channel, OutputStream os, Request req) throws IOException {
    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] = (byte) (FLAG_REQUEST | serialization.getContentTypeId());

    if (req.isTwoWay()) header[2] |= FLAG_TWOWAY;
    if (req.isEvent()) header[2] |= FLAG_EVENT;

    // set request id.
    Bytes.long2bytes(req.getId(), header, 4);

    // encode request data.
    UnsafeByteArrayOutputStream bos = new UnsafeByteArrayOutputStream(1024);
    ObjectOutput out = serialization.serialize(channel.getUrl(), bos);
    if (req.isEvent()) {
        encodeEventData(channel, out, req.getData());
    } else {
        encodeRequestData(channel, out, req.getData());
    }
    out.flushBuffer();
    bos.flush();
    bos.close();
    byte[] data = bos.toByteArray();
    checkPayload(channel, data.length);
    Bytes.int2bytes(data.length, header, 12);

    // write
    os.write(header); // write header.
    os.write(data); // write data.
}
 
Example #8
Source File: CodecSupport.java    From dubbox with Apache License 2.0 5 votes vote down vote up
public static Serialization getSerialization(URL url, Byte id) {
    Serialization result = getSerializationById(id);
    if (result == null) {
        result = getSerialization(url);
    }
    return result;
}
 
Example #9
Source File: DeprecatedExchangeCodec.java    From dubbox with Apache License 2.0 5 votes vote down vote up
protected void encodeRequest(Channel channel, OutputStream os, Request req) throws IOException {
    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] = (byte) (FLAG_REQUEST | serialization.getContentTypeId());

    if (req.isTwoWay()) header[2] |= FLAG_TWOWAY;
    if (req.isEvent()) header[2] |= FLAG_EVENT;

    // set request id.
    Bytes.long2bytes(req.getId(), header, 4);

    // encode request data.
    UnsafeByteArrayOutputStream bos = new UnsafeByteArrayOutputStream(1024);
    ObjectOutput out = serialization.serialize(channel.getUrl(), bos);
    if (req.isEvent()) {
        encodeEventData(channel, out, req.getData());
    } else {
        encodeRequestData(channel, out, req.getData());
    }
    out.flushBuffer();
    bos.flush();
    bos.close();
    byte[] data = bos.toByteArray();
    checkPayload(channel, data.length);
    Bytes.int2bytes(data.length, header, 12);

    // write
    os.write(header); // write header.
    os.write(data); // write data.
}
 
Example #10
Source File: ConfigUtilsTest.java    From dubbox with Apache License 2.0 5 votes vote down vote up
/**
 * 测试点1:用户配置参数在最后 测试点2:用户配置参数如果带-,会删除同名的默认参数 测试点3:default开头的默认参数会被删除
 */
@Test
public void testMergeValues_addDefault() {
    List<String> merged = ConfigUtils.mergeValues(Serialization.class, "aaa,bbb,default,zzz",
            toArray("dubbo","default.hessian2","json"));
    Assert.assertEquals(toArray("aaa", "bbb","dubbo", "json",  "zzz"), merged);
}
 
Example #11
Source File: ConfigUtilsTest.java    From dubbox with Apache License 2.0 5 votes vote down vote up
/**
 * 测试点1:用户配置参数在最后 测试点2:用户配置参数如果带-,会删除同名的默认参数 测试点3:default开头的默认参数会被删除
 */
@Test
public void testMergeValues() {
    List<String> merged = ConfigUtils.mergeValues(Serialization.class, "aaa,bbb,default.cunstom",
            toArray("dubbo","default.hessian2","json"));
    Assert.assertEquals(toArray("dubbo", "json", "aaa", "bbb", "default.cunstom"), merged);
}
 
Example #12
Source File: ConfigUtilsTest.java    From dubbox with Apache License 2.0 5 votes vote down vote up
/**
 * 测试点1:用户配置参数在最后 测试点2:用户配置参数如果带-,会删除同名的默认参数 测试点3:default开头的默认参数会被删除
 */
@Test
public void testMergeValues_addDefault() {
    List<String> merged = ConfigUtils.mergeValues(Serialization.class, "aaa,bbb,default,zzz",
            toArray("dubbo","default.hessian2","json"));
    Assert.assertEquals(toArray("aaa", "bbb","dubbo", "json",  "zzz"), merged);
}
 
Example #13
Source File: ConfigUtilsTest.java    From dubbo3 with Apache License 2.0 5 votes vote down vote up
/**
 * 测试点1:用户配置参数在最后 测试点2:用户配置参数如果带-,会删除同名的默认参数 测试点3:default开头的默认参数会被删除
 */
@Test
public void testMergeValues() {
    List<String> merged = ConfigUtils.mergeValues(Serialization.class, "aaa,bbb,default.cunstom",
            toArray("dubbo","default.hessian2","json"));
    Assert.assertEquals(toArray("dubbo", "json", "aaa", "bbb", "default.cunstom"), merged);
}
 
Example #14
Source File: DeprecatedExchangeCodec.java    From dubbo3 with Apache License 2.0 5 votes vote down vote up
protected void encodeRequest(Channel channel, OutputStream os, Request req) throws IOException {
    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] = (byte) (FLAG_REQUEST | serialization.getContentTypeId());

    if (req.isTwoWay()) header[2] |= FLAG_TWOWAY;
    if (req.isEvent()) header[2] |= FLAG_EVENT;

    // set request id.
    Bytes.long2bytes(req.getId(), header, 4);

    // encode request data.
    UnsafeByteArrayOutputStream bos = new UnsafeByteArrayOutputStream(1024);
    ObjectOutput out = serialization.serialize(channel.getUrl(), bos);
    if (req.isEvent()) {
        encodeEventData(channel, out, req.getData());
    } else {
        encodeRequestData(channel, out, req.getData());
    }
    out.flushBuffer();
    bos.flush();
    bos.close();
    byte[] data = bos.toByteArray();
    checkPayload(channel, data.length);
    Bytes.int2bytes(data.length, header, 12);

    // write
    os.write(header); // write header.
    os.write(data); // write data.
}
 
Example #15
Source File: CodecSupport.java    From dubbo3 with Apache License 2.0 5 votes vote down vote up
public static Serialization getSerialization(URL url, Byte id) {
    Serialization result = getSerializationById(id);
    if (result == null) {
        result = getSerialization(url);
    }
    return result;
}
 
Example #16
Source File: CodecSupport.java    From dubbox-hystrix with Apache License 2.0 5 votes vote down vote up
public static Serialization getSerialization(URL url, Byte id) {
    Serialization result = getSerializationById(id);
    if (result == null) {
        result = getSerialization(url);
    }
    return result;
}
 
Example #17
Source File: ConfigUtilsTest.java    From dubbo3 with Apache License 2.0 5 votes vote down vote up
/**
 * 测试点1:用户配置参数在最后 测试点2:用户配置参数如果带-,会删除同名的默认参数 测试点3:default开头的默认参数会被删除
 */
@Test
public void testMergeValues_addDefault() {
    List<String> merged = ConfigUtils.mergeValues(Serialization.class, "aaa,bbb,default,zzz",
            toArray("dubbo","default.hessian2","json"));
    Assert.assertEquals(toArray("aaa", "bbb","dubbo", "json",  "zzz"), merged);
}
 
Example #18
Source File: DeprecatedExchangeCodec.java    From dubbox-hystrix with Apache License 2.0 5 votes vote down vote up
protected void encodeRequest(Channel channel, OutputStream os, Request req) throws IOException {
    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] = (byte) (FLAG_REQUEST | serialization.getContentTypeId());

    if (req.isTwoWay()) header[2] |= FLAG_TWOWAY;
    if (req.isEvent()) header[2] |= FLAG_EVENT;

    // set request id.
    Bytes.long2bytes(req.getId(), header, 4);

    // encode request data.
    UnsafeByteArrayOutputStream bos = new UnsafeByteArrayOutputStream(1024);
    ObjectOutput out = serialization.serialize(channel.getUrl(), bos);
    if (req.isEvent()) {
        encodeEventData(channel, out, req.getData());
    } else {
        encodeRequestData(channel, out, req.getData());
    }
    out.flushBuffer();
    bos.flush();
    bos.close();
    byte[] data = bos.toByteArray();
    checkPayload(channel, data.length);
    Bytes.int2bytes(data.length, header, 12);

    // write
    os.write(header); // write header.
    os.write(data); // write data.
}
 
Example #19
Source File: ExchangeCodec.java    From dubbo3 with Apache License 2.0 5 votes vote down vote up
protected void encodeRequest(Channel channel, ChannelBuffer buffer, Request req) throws IOException {
    Serialization serialization = getSerialization(channel);
    // header.
    byte[] header = new byte[HEADER_LENGTH];
    // set magic number.
    Bytes.short2bytes(MAGIC, header);

    // set request and serialization flag.
    header[2] = (byte) (FLAG_REQUEST | serialization.getContentTypeId());

    if (req.isTwoWay()) header[2] |= FLAG_TWOWAY;
    if (req.isEvent()) header[2] |= FLAG_EVENT;

    // set request id.
    Bytes.long2bytes(req.getId(), header, 4);

    // encode request data.
    int savedWriteIndex = buffer.writerIndex();
    buffer.writerIndex(savedWriteIndex + HEADER_LENGTH);
    ChannelBufferOutputStream bos = new ChannelBufferOutputStream(buffer);
    ObjectOutput out = serialization.serialize(channel.getUrl(), bos);
    if (req.isEvent()) {
        encodeEventData(channel, out, req.getData());
    } else {
        encodeRequestData(channel, out, req.getData());
    }
    out.flushBuffer();
    bos.flush();
    bos.close();
    int len = bos.writtenBytes();
    checkPayload(channel, len);
    Bytes.int2bytes(len, header, 12);

    // write
    buffer.writerIndex(savedWriteIndex);
    buffer.writeBytes(header); // write header.
    buffer.writerIndex(savedWriteIndex + HEADER_LENGTH + len);
}
 
Example #20
Source File: DeprecatedExchangeCodec.java    From dubbox with Apache License 2.0 5 votes vote down vote up
protected void encodeRequest(Channel channel, OutputStream os, Request req) throws IOException {
    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] = (byte) (FLAG_REQUEST | serialization.getContentTypeId());

    if (req.isTwoWay()) header[2] |= FLAG_TWOWAY;
    if (req.isEvent()) header[2] |= FLAG_EVENT;

    // set request id.
    Bytes.long2bytes(req.getId(), header, 4);

    // encode request data.
    UnsafeByteArrayOutputStream bos = new UnsafeByteArrayOutputStream(1024);
    ObjectOutput out = serialization.serialize(channel.getUrl(), bos);
    if (req.isEvent()) {
        encodeEventData(channel, out, req.getData());
    } else {
        encodeRequestData(channel, out, req.getData());
    }
    out.flushBuffer();
    bos.flush();
    bos.close();
    byte[] data = bos.toByteArray();
    checkPayload(channel, data.length);
    Bytes.int2bytes(data.length, header, 12);

    // write
    os.write(header); // write header.
    os.write(data); // write data.
}
 
Example #21
Source File: ConfigUtilsTest.java    From dubbox with Apache License 2.0 5 votes vote down vote up
/**
 * 测试点1:用户配置参数在最后 测试点2:用户配置参数如果带-,会删除同名的默认参数 测试点3:default开头的默认参数会被删除
 */
@Test
public void testMergeValues_addDefault() {
    List<String> merged = ConfigUtils.mergeValues(Serialization.class, "aaa,bbb,default,zzz",
            toArray("dubbo","default.hessian2","json"));
    Assert.assertEquals(toArray("aaa", "bbb","dubbo", "json",  "zzz"), merged);
}
 
Example #22
Source File: ProtocolConfig.java    From dubbox-hystrix with Apache License 2.0 4 votes vote down vote up
public void setSerialization(String serialization) {
    if ("dubbo".equals(name)) {
        checkMultiExtension(Serialization.class, "serialization", serialization);
    }
    this.serialization = serialization;
}
 
Example #23
Source File: ConfigUtilsTest.java    From dubbox-hystrix with Apache License 2.0 4 votes vote down vote up
/**
 * 测试点1:用户配置-default,会删除所有默认参数
 */
@Test
public void testMergeValuesDelete() {
    List<String> merged = ConfigUtils.mergeValues(Serialization.class, "-dubbo,aaa", toArray("dubbo","default.hessian2","json"));
    Assert.assertEquals(toArray("json", "aaa"), merged);
}
 
Example #24
Source File: GenericServiceTest.java    From dubbox-hystrix with Apache License 2.0 4 votes vote down vote up
@Test
public void testGenericSerializationJava() throws Exception {
    ServiceConfig<DemoService> service = new ServiceConfig<DemoService>();
    service.setApplication(new ApplicationConfig("generic-provider"));
    service.setRegistry(new RegistryConfig("N/A"));
    service.setProtocol(new ProtocolConfig("dubbo", 29581));
    service.setInterface(DemoService.class.getName());
    DemoServiceImpl ref = new DemoServiceImpl();
    service.setRef(ref);
    service.export();
    try {
        ReferenceConfig<GenericService> reference = new ReferenceConfig<GenericService>();
        reference.setApplication(new ApplicationConfig("generic-consumer"));
        reference.setInterface(DemoService.class);
        reference.setUrl("dubbo://127.0.0.1:29581?scope=remote");
        reference.setGeneric(Constants.GENERIC_SERIALIZATION_NATIVE_JAVA);
        GenericService genericService = reference.get();
        try {
            String name = "kimi";
            ByteArrayOutputStream bos = new ByteArrayOutputStream(512);
            ExtensionLoader.getExtensionLoader(Serialization.class)
                .getExtension("nativejava").serialize(null, bos).writeObject(name);
            byte[] arg = bos.toByteArray();
            Object obj = genericService.$invoke("sayName", new String[]{String.class.getName()}, new Object[]{arg});
            Assert.assertTrue(obj instanceof byte[]);
            byte[] result = (byte[]) obj;
            Assert.assertEquals(ref.sayName(name), ExtensionLoader.getExtensionLoader(Serialization.class)
                .getExtension("nativejava").deserialize(null, new ByteArrayInputStream(result)).readObject().toString());

            // getUsers
            List<User> users = new ArrayList<User>();
            User user = new User();
            user.setName(name);
            users.add(user);
            bos = new ByteArrayOutputStream(512);
            ExtensionLoader.getExtensionLoader(Serialization.class)
                .getExtension("nativejava").serialize(null, bos).writeObject(users);
            obj = genericService.$invoke("getUsers",
                                         new String[]{List.class.getName()},
                                         new Object[]{bos.toByteArray()});
            Assert.assertTrue(obj instanceof byte[]);
            result = (byte[]) obj;
            Assert.assertEquals(users,
                                ExtensionLoader.getExtensionLoader(Serialization.class)
                                    .getExtension("nativejava")
                                    .deserialize(null, new ByteArrayInputStream(result))
                                    .readObject());

            // echo(int)
            bos = new ByteArrayOutputStream(512);
            ExtensionLoader.getExtensionLoader(Serialization.class).getExtension("nativejava")
                .serialize(null, bos).writeObject(Integer.MAX_VALUE);
            obj = genericService.$invoke("echo", new String[]{int.class.getName()}, new Object[]{bos.toByteArray()});
            Assert.assertTrue(obj instanceof byte[]);
            Assert.assertEquals(Integer.MAX_VALUE,
                                ExtensionLoader.getExtensionLoader(Serialization.class)
                                    .getExtension("nativejava")
                                    .deserialize(null, new ByteArrayInputStream((byte[]) obj))
                                    .readObject());

        } finally {
            reference.destroy();
        }
    } finally {
        service.unexport();
    }
}
 
Example #25
Source File: RedisProtocol.java    From dubbox with Apache License 2.0 4 votes vote down vote up
private Serialization getSerialization(URL url) {
    return ExtensionLoader.getExtensionLoader(Serialization.class).getExtension(url.getParameter(Constants.SERIALIZATION_KEY, "java"));
}
 
Example #26
Source File: CodecSupport.java    From dubbo3 with Apache License 2.0 4 votes vote down vote up
public static Serialization getSerialization(URL url) {
    return ExtensionLoader.getExtensionLoader(Serialization.class).getExtension(
        url.getParameter(Constants.SERIALIZATION_KEY, Constants.DEFAULT_REMOTING_SERIALIZATION));
}
 
Example #27
Source File: DubboCodec.java    From dubbox with Apache License 2.0 4 votes vote down vote up
private ObjectInput deserialize(Serialization serialization, URL url, InputStream is)
        throws IOException {
    return serialization.deserialize(url, is);
}
 
Example #28
Source File: RedisProtocol.java    From dubbox with Apache License 2.0 4 votes vote down vote up
private Serialization getSerialization(URL url) {
    return ExtensionLoader.getExtensionLoader(Serialization.class).getExtension(url.getParameter(Constants.SERIALIZATION_KEY, "java"));
}
 
Example #29
Source File: DeprecatedExchangeCodec.java    From dubbo3 with Apache License 2.0 4 votes vote down vote up
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
        os.write(header); // write header.
        os.write(data); // 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);
        }
    }
}
 
Example #30
Source File: ExchangeCodecTest.java    From dubbox with Apache License 2.0 4 votes vote down vote up
private static Serialization getSerialization(String name) {
    Serialization serialization = ExtensionLoader.getExtensionLoader(Serialization.class).getExtension(name);
    return serialization;
}