Search in sources :

Example 6 with ObjectInput

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

the class AbstractProtobufSerializationTest method test_Float.

@Test
public void test_Float() throws Exception {
    ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream);
    objectOutput.writeFloat(1.28F);
    objectOutput.flushBuffer();
    ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
    ObjectInput deserialize = serialization.deserialize(url, byteArrayInputStream);
    assertEquals(1.28F, deserialize.readFloat());
    try {
        deserialize.readFloat();
        fail();
    } catch (Exception expected) {
        expected.printStackTrace();
    }
}
Also used : ObjectOutput(org.apache.dubbo.common.serialize.ObjectOutput) ByteArrayInputStream(java.io.ByteArrayInputStream) ObjectInput(org.apache.dubbo.common.serialize.ObjectInput) Test(org.junit.jupiter.api.Test)

Example 7 with ObjectInput

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

the class AbstractProtobufSerializationTest method test_Bool.

@Test
public void test_Bool() throws Exception {
    ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream);
    objectOutput.writeBool(false);
    objectOutput.flushBuffer();
    ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
    ObjectInput deserialize = serialization.deserialize(url, byteArrayInputStream);
    assertFalse(deserialize.readBool());
    try {
        deserialize.readBool();
        fail();
    } catch (Exception expected) {
        expected.printStackTrace();
    }
}
Also used : ObjectOutput(org.apache.dubbo.common.serialize.ObjectOutput) ByteArrayInputStream(java.io.ByteArrayInputStream) ObjectInput(org.apache.dubbo.common.serialize.ObjectInput) Test(org.junit.jupiter.api.Test)

Example 8 with ObjectInput

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

the class AbstractProtobufSerializationTest method test_Bytes.

@Test
public void test_Bytes() throws Exception {
    ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream);
    objectOutput.writeBytes("123中华人民共和国".getBytes());
    objectOutput.flushBuffer();
    ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
    ObjectInput deserialize = serialization.deserialize(url, byteArrayInputStream);
    assertArrayEquals("123中华人民共和国".getBytes(), deserialize.readBytes());
    try {
        deserialize.readBytes();
        fail();
    } catch (Exception expected) {
        expected.printStackTrace();
    }
}
Also used : ObjectOutput(org.apache.dubbo.common.serialize.ObjectOutput) ByteArrayInputStream(java.io.ByteArrayInputStream) ObjectInput(org.apache.dubbo.common.serialize.ObjectInput) Test(org.junit.jupiter.api.Test)

Example 9 with ObjectInput

use of org.apache.dubbo.common.serialize.ObjectInput 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 10 with ObjectInput

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

the class RedisProtocol method protocolBindingRefer.

@Override
protected <T> Invoker<T> protocolBindingRefer(final Class<T> type, final URL url) throws RpcException {
    try {
        GenericObjectPoolConfig config = new GenericObjectPoolConfig();
        config.setTestOnBorrow(url.getParameter("test.on.borrow", true));
        config.setTestOnReturn(url.getParameter("test.on.return", false));
        config.setTestWhileIdle(url.getParameter("test.while.idle", false));
        if (url.getParameter("max.idle", 0) > 0) {
            config.setMaxIdle(url.getParameter("max.idle", 0));
        }
        if (url.getParameter("min.idle", 0) > 0) {
            config.setMinIdle(url.getParameter("min.idle", 0));
        }
        if (url.getParameter("max.active", 0) > 0) {
            config.setMaxTotal(url.getParameter("max.active", 0));
        }
        if (url.getParameter("max.total", 0) > 0) {
            config.setMaxTotal(url.getParameter("max.total", 0));
        }
        if (url.getParameter("max.wait", 0) > 0) {
            config.setMaxWaitMillis(url.getParameter("max.wait", 0));
        }
        if (url.getParameter("num.tests.per.eviction.run", 0) > 0) {
            config.setNumTestsPerEvictionRun(url.getParameter("num.tests.per.eviction.run", 0));
        }
        if (url.getParameter("time.between.eviction.runs.millis", 0) > 0) {
            config.setTimeBetweenEvictionRunsMillis(url.getParameter("time.between.eviction.runs.millis", 0));
        }
        if (url.getParameter("min.evictable.idle.time.millis", 0) > 0) {
            config.setMinEvictableIdleTimeMillis(url.getParameter("min.evictable.idle.time.millis", 0));
        }
        final JedisPool jedisPool = new JedisPool(config, url.getHost(), url.getPort(DEFAULT_PORT), url.getParameter(TIMEOUT_KEY, DEFAULT_TIMEOUT), StringUtils.isBlank(url.getPassword()) ? null : url.getPassword(), url.getParameter("db.index", 0));
        final int expiry = url.getParameter("expiry", 0);
        final String get = url.getParameter("get", "get");
        final String set = url.getParameter("set", Map.class.equals(type) ? "put" : "set");
        final String delete = url.getParameter("delete", Map.class.equals(type) ? "remove" : "delete");
        return new AbstractInvoker<T>(type, url) {

            @Override
            protected Result doInvoke(Invocation invocation) throws Throwable {
                Jedis jedis = null;
                try {
                    jedis = jedisPool.getResource();
                    if (get.equals(invocation.getMethodName())) {
                        if (invocation.getArguments().length != 1) {
                            throw new IllegalArgumentException("The redis get method arguments mismatch, must only one arguments. interface: " + type.getName() + ", method: " + invocation.getMethodName() + ", url: " + url);
                        }
                        byte[] value = jedis.get(String.valueOf(invocation.getArguments()[0]).getBytes());
                        if (value == null) {
                            return AsyncRpcResult.newDefaultAsyncResult(invocation);
                        }
                        ObjectInput oin = getSerialization(url).deserialize(url, new ByteArrayInputStream(value));
                        return AsyncRpcResult.newDefaultAsyncResult(oin.readObject(), invocation);
                    } else if (set.equals(invocation.getMethodName())) {
                        if (invocation.getArguments().length != 2) {
                            throw new IllegalArgumentException("The redis set method arguments mismatch, must be two arguments. interface: " + type.getName() + ", method: " + invocation.getMethodName() + ", url: " + url);
                        }
                        byte[] key = String.valueOf(invocation.getArguments()[0]).getBytes();
                        ByteArrayOutputStream output = new ByteArrayOutputStream();
                        ObjectOutput value = getSerialization(url).serialize(url, output);
                        value.writeObject(invocation.getArguments()[1]);
                        jedis.set(key, output.toByteArray());
                        if (expiry > 1000) {
                            jedis.expire(key, expiry / 1000);
                        }
                        return AsyncRpcResult.newDefaultAsyncResult(invocation);
                    } else if (delete.equals(invocation.getMethodName())) {
                        if (invocation.getArguments().length != 1) {
                            throw new IllegalArgumentException("The redis delete method arguments mismatch, must only one arguments. interface: " + type.getName() + ", method: " + invocation.getMethodName() + ", url: " + url);
                        }
                        jedis.del(String.valueOf(invocation.getArguments()[0]).getBytes());
                        return AsyncRpcResult.newDefaultAsyncResult(invocation);
                    } else {
                        throw new UnsupportedOperationException("Unsupported method " + invocation.getMethodName() + " in redis service.");
                    }
                } catch (Throwable t) {
                    RpcException re = new RpcException("Failed to invoke redis service method. interface: " + type.getName() + ", method: " + invocation.getMethodName() + ", url: " + url + ", cause: " + t.getMessage(), t);
                    if (t instanceof SocketTimeoutException) {
                        re.setCode(RpcException.TIMEOUT_EXCEPTION);
                    } else if (t instanceof JedisConnectionException || t instanceof IOException) {
                        re.setCode(RpcException.NETWORK_EXCEPTION);
                    } else if (t instanceof JedisDataException) {
                        re.setCode(RpcException.SERIALIZATION_EXCEPTION);
                    }
                    throw re;
                } finally {
                    if (jedis != null) {
                        try {
                            jedis.close();
                        } catch (Throwable t) {
                            logger.warn("returnResource error: " + t.getMessage(), t);
                        }
                    }
                }
            }

            @Override
            public void destroy() {
                super.destroy();
                try {
                    jedisPool.destroy();
                } catch (Throwable e) {
                    logger.warn(e.getMessage(), e);
                }
            }
        };
    } catch (Throwable t) {
        throw new RpcException("Failed to refer redis service. interface: " + type.getName() + ", url: " + url + ", cause: " + t.getMessage(), t);
    }
}
Also used : Invocation(org.apache.dubbo.rpc.Invocation) ObjectOutput(org.apache.dubbo.common.serialize.ObjectOutput) AbstractInvoker(org.apache.dubbo.rpc.protocol.AbstractInvoker) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) JedisDataException(redis.clients.jedis.exceptions.JedisDataException) Jedis(redis.clients.jedis.Jedis) SocketTimeoutException(java.net.SocketTimeoutException) GenericObjectPoolConfig(org.apache.commons.pool2.impl.GenericObjectPoolConfig) ByteArrayInputStream(java.io.ByteArrayInputStream) RpcException(org.apache.dubbo.rpc.RpcException) JedisPool(redis.clients.jedis.JedisPool) ObjectInput(org.apache.dubbo.common.serialize.ObjectInput) JedisConnectionException(redis.clients.jedis.exceptions.JedisConnectionException)

Aggregations

ObjectInput (org.apache.dubbo.common.serialize.ObjectInput)84 ByteArrayInputStream (java.io.ByteArrayInputStream)76 Test (org.junit.jupiter.api.Test)74 ObjectOutput (org.apache.dubbo.common.serialize.ObjectOutput)73 IOException (java.io.IOException)42 AbstractSerializationPersonFailTest (org.apache.dubbo.common.serialize.base.AbstractSerializationPersonFailTest)7 AbstractSerializationPersonOkTest (org.apache.dubbo.common.serialize.base.AbstractSerializationPersonOkTest)7 InputStream (java.io.InputStream)6 HashMap (java.util.HashMap)3 Cleanable (org.apache.dubbo.common.serialize.Cleanable)3 BigPerson (org.apache.dubbo.common.serialize.model.person.BigPerson)3 ByteArrayOutputStream (java.io.ByteArrayOutputStream)2 LinkedHashMap (java.util.LinkedHashMap)2 GenericObjectPoolConfig (org.apache.commons.pool2.impl.GenericObjectPoolConfig)2 URL (org.apache.dubbo.common.URL)2 Serialization (org.apache.dubbo.common.serialize.Serialization)2 BizException (org.apache.dubbo.common.serialize.model.BizException)2 BizExceptionNoDefaultConstructor (org.apache.dubbo.common.serialize.model.BizExceptionNoDefaultConstructor)2 Request (org.apache.dubbo.remoting.exchange.Request)2 Response (org.apache.dubbo.remoting.exchange.Response)2