Search in sources :

Example 1 with Serialization

use of org.apache.dubbo.common.serialize.Serialization in project dubbo by alibaba.

the class DeprecatedExchangeCodec method encodeRequest.

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
    // write header.
    os.write(header);
    // write data.
    os.write(data);
}
Also used : Serialization(org.apache.dubbo.common.serialize.Serialization) ObjectOutput(org.apache.dubbo.common.serialize.ObjectOutput) UnsafeByteArrayOutputStream(org.apache.dubbo.common.io.UnsafeByteArrayOutputStream)

Example 2 with Serialization

use of org.apache.dubbo.common.serialize.Serialization in project dubbo by alibaba.

the class DubboCodecSupport method getResponseSerialization.

public static Serialization getResponseSerialization(URL url, AppResponse appResponse) {
    Object invocationObj = appResponse.getAttribute(INVOCATION_KEY);
    if (invocationObj != null) {
        Invocation invocation = (Invocation) invocationObj;
        Object serializationTypeObj = invocation.get(SERIALIZATION_ID_KEY);
        if (serializationTypeObj != null) {
            return CodecSupport.getSerializationById((byte) serializationTypeObj);
        }
    }
    return ExtensionLoader.getExtensionLoader(Serialization.class).getExtension(url.getParameter(Constants.SERIALIZATION_KEY, Constants.DEFAULT_REMOTING_SERIALIZATION));
}
Also used : Serialization(org.apache.dubbo.common.serialize.Serialization) Invocation(org.apache.dubbo.rpc.Invocation)

Example 3 with Serialization

use of org.apache.dubbo.common.serialize.Serialization in project dubbo by alibaba.

the class HessianProtocolTest method testGenericInvokeWithNativeJava.

@Test
public void testGenericInvokeWithNativeJava() throws IOException, ClassNotFoundException {
    // temporary enable native java generic serialize
    System.setProperty(CommonConstants.ENABLE_NATIVE_JAVA_GENERIC_SERIALIZE, "true");
    HessianServiceImpl server = new HessianServiceImpl();
    Assertions.assertFalse(server.isCalled());
    ProxyFactory proxyFactory = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension();
    Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension();
    int port = NetUtils.getAvailablePort();
    URL url = URL.valueOf("hessian://127.0.0.1:" + port + "/" + 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);
    Assertions.assertTrue(server.isCalled());
    Assertions.assertEquals("Hello, haha", objectInput.readObject());
    invoker.destroy();
    exporter.unexport();
    System.clearProperty(CommonConstants.ENABLE_NATIVE_JAVA_GENERIC_SERIALIZE);
}
Also used : GenericService(org.apache.dubbo.rpc.service.GenericService) ObjectOutput(org.apache.dubbo.common.serialize.ObjectOutput) ProxyFactory(org.apache.dubbo.rpc.ProxyFactory) ByteArrayOutputStream(java.io.ByteArrayOutputStream) NativeJavaSerialization(org.apache.dubbo.common.serialize.nativejava.NativeJavaSerialization) URL(org.apache.dubbo.common.URL) Serialization(org.apache.dubbo.common.serialize.Serialization) NativeJavaSerialization(org.apache.dubbo.common.serialize.nativejava.NativeJavaSerialization) ByteArrayInputStream(java.io.ByteArrayInputStream) ObjectInput(org.apache.dubbo.common.serialize.ObjectInput) Protocol(org.apache.dubbo.rpc.Protocol) Test(org.junit.jupiter.api.Test)

Example 4 with Serialization

use of org.apache.dubbo.common.serialize.Serialization in project dubbo by alibaba.

the class RedisProtocolTest method testAuthRedis.

@Test
public void testAuthRedis() {
    // default db.index=0
    Invoker<IDemoService> refer = PROTOCOL.refer(IDemoService.class, registryUrl.addParameter("max.idle", 10).addParameter("max.active", 20));
    IDemoService demoService = this.PROXY.getProxy(refer);
    String value = demoService.get("key");
    assertThat(value, is(nullValue()));
    demoService.set("key", "newValue");
    value = demoService.get("key");
    assertThat(value, is("newValue"));
    demoService.delete("key");
    value = demoService.get("key");
    assertThat(value, is(nullValue()));
    refer.destroy();
    // change db.index=1
    String password = "123456";
    int database = 1;
    this.registryUrl = this.registryUrl.setPassword(password).addParameter("db.index", database);
    refer = PROTOCOL.refer(IDemoService.class, registryUrl.addParameter("max.idle", 10).addParameter("max.active", 20));
    demoService = this.PROXY.getProxy(refer);
    demoService.set("key", "newValue");
    value = demoService.get("key");
    assertThat(value, is("newValue"));
    // jedis gets the result comparison
    JedisPool pool = new JedisPool(new GenericObjectPoolConfig(), "localhost", registryUrl.getPort(), 2000, password, database, (String) null);
    try (Jedis jedis = pool.getResource()) {
        byte[] valueByte = jedis.get("key".getBytes());
        Serialization serialization = ExtensionLoader.getExtensionLoader(Serialization.class).getExtension(this.registryUrl.getParameter(Constants.SERIALIZATION_KEY, "java"));
        ObjectInput oin = serialization.deserialize(this.registryUrl, new ByteArrayInputStream(valueByte));
        String actual = (String) oin.readObject();
        assertThat(value, is(actual));
    } catch (Exception e) {
        Assertions.fail("jedis gets the result comparison is error!");
    } finally {
        pool.destroy();
    }
    demoService.delete("key");
    value = demoService.get("key");
    assertThat(value, is(nullValue()));
    refer.destroy();
}
Also used : Serialization(org.apache.dubbo.common.serialize.Serialization) Jedis(redis.clients.jedis.Jedis) GenericObjectPoolConfig(org.apache.commons.pool2.impl.GenericObjectPoolConfig) ByteArrayInputStream(java.io.ByteArrayInputStream) JedisPool(redis.clients.jedis.JedisPool) ObjectInput(org.apache.dubbo.common.serialize.ObjectInput) JedisConnectionException(redis.clients.jedis.exceptions.JedisConnectionException) JedisDataException(redis.clients.jedis.exceptions.JedisDataException) IOException(java.io.IOException) RpcException(org.apache.dubbo.rpc.RpcException) Test(org.junit.jupiter.api.Test)

Example 5 with Serialization

use of org.apache.dubbo.common.serialize.Serialization in project dubbo by alibaba.

the class ExchangeCodec method encodeResponse.

protected void encodeResponse(Channel channel, ChannelBuffer buffer, Response res) throws IOException {
    int savedWriteIndex = buffer.writerIndex();
    try {
        Serialization serialization = getSerialization(channel, res);
        // 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);
        buffer.writerIndex(savedWriteIndex + HEADER_LENGTH);
        ChannelBufferOutputStream bos = new ChannelBufferOutputStream(buffer);
        // encode response data or error message.
        if (status == Response.OK) {
            if (res.isHeartbeat()) {
                // heartbeat response data is always null
                bos.write(CodecSupport.getNullBytesOf(serialization));
            } else {
                ObjectOutput out = serialization.serialize(channel.getUrl(), bos);
                if (res.isEvent()) {
                    encodeEventData(channel, out, res.getResult());
                } else {
                    encodeResponseData(channel, out, res.getResult(), res.getVersion());
                }
                out.flushBuffer();
                if (out instanceof Cleanable) {
                    ((Cleanable) out).cleanup();
                }
            }
        } else {
            ObjectOutput out = serialization.serialize(channel.getUrl(), bos);
            out.writeUTF(res.getErrorMessage());
            out.flushBuffer();
            if (out instanceof Cleanable) {
                ((Cleanable) out).cleanup();
            }
        }
        bos.flush();
        bos.close();
        int len = bos.writtenBytes();
        checkPayload(channel, len);
        Bytes.int2bytes(len, header, 12);
        // write
        buffer.writerIndex(savedWriteIndex);
        // write header.
        buffer.writeBytes(header);
        buffer.writerIndex(savedWriteIndex + HEADER_LENGTH + len);
    } catch (Throwable t) {
        // clear buffer
        buffer.writerIndex(savedWriteIndex);
        // send error message to Consumer, otherwise, Consumer will wait till timeout.
        if (!res.isEvent() && res.getStatus() != Response.BAD_RESPONSE) {
            Response r = new Response(res.getId(), res.getVersion());
            r.setStatus(Response.BAD_RESPONSE);
            if (t instanceof ExceedPayloadLimitException) {
                logger.warn(t.getMessage(), t);
                try {
                    r.setErrorMessage(t.getMessage());
                    channel.send(r);
                    return;
                } catch (RemotingException e) {
                    logger.warn("Failed to send bad_response info back: " + t.getMessage() + ", cause: " + e.getMessage(), e);
                }
            } else {
                // FIXME log error message in Codec and handle in caught() of IoHanndler?
                logger.warn("Fail to encode response: " + res + ", send bad_response info instead, cause: " + t.getMessage(), t);
                try {
                    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);
                }
            }
        }
        // Rethrow exception
        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 : ChannelBufferOutputStream(org.apache.dubbo.remoting.buffer.ChannelBufferOutputStream) ObjectOutput(org.apache.dubbo.common.serialize.ObjectOutput) IOException(java.io.IOException) Serialization(org.apache.dubbo.common.serialize.Serialization) Response(org.apache.dubbo.remoting.exchange.Response) RemotingException(org.apache.dubbo.remoting.RemotingException) ExceedPayloadLimitException(org.apache.dubbo.remoting.transport.ExceedPayloadLimitException) Cleanable(org.apache.dubbo.common.serialize.Cleanable)

Aggregations

Serialization (org.apache.dubbo.common.serialize.Serialization)8 ObjectOutput (org.apache.dubbo.common.serialize.ObjectOutput)5 IOException (java.io.IOException)4 UnsafeByteArrayOutputStream (org.apache.dubbo.common.io.UnsafeByteArrayOutputStream)3 ByteArrayInputStream (java.io.ByteArrayInputStream)2 Cleanable (org.apache.dubbo.common.serialize.Cleanable)2 ObjectInput (org.apache.dubbo.common.serialize.ObjectInput)2 RemotingException (org.apache.dubbo.remoting.RemotingException)2 ChannelBufferOutputStream (org.apache.dubbo.remoting.buffer.ChannelBufferOutputStream)2 Response (org.apache.dubbo.remoting.exchange.Response)2 RpcException (org.apache.dubbo.rpc.RpcException)2 Test (org.junit.jupiter.api.Test)2 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1 GenericObjectPoolConfig (org.apache.commons.pool2.impl.GenericObjectPoolConfig)1 URL (org.apache.dubbo.common.URL)1 NativeJavaSerialization (org.apache.dubbo.common.serialize.nativejava.NativeJavaSerialization)1 ExceedPayloadLimitException (org.apache.dubbo.remoting.transport.ExceedPayloadLimitException)1 Invocation (org.apache.dubbo.rpc.Invocation)1 Protocol (org.apache.dubbo.rpc.Protocol)1 ProxyFactory (org.apache.dubbo.rpc.ProxyFactory)1