Search in sources :

Example 1 with ObjectInput

use of com.alibaba.dubbo.common.serialize.ObjectInput in project dubbo by alibaba.

the class DecodeableRpcInvocation method decode.

public Object decode(Channel channel, InputStream input) throws IOException {
    ObjectInput in = CodecSupport.getSerialization(channel.getUrl(), serializationType).deserialize(channel.getUrl(), input);
    setAttachment(Constants.DUBBO_VERSION_KEY, in.readUTF());
    setAttachment(Constants.PATH_KEY, in.readUTF());
    setAttachment(Constants.VERSION_KEY, in.readUTF());
    setMethodName(in.readUTF());
    try {
        Object[] args;
        Class<?>[] pts;
        String desc = in.readUTF();
        if (desc.length() == 0) {
            pts = DubboCodec.EMPTY_CLASS_ARRAY;
            args = DubboCodec.EMPTY_OBJECT_ARRAY;
        } else {
            pts = ReflectUtils.desc2classArray(desc);
            args = new Object[pts.length];
            for (int i = 0; i < args.length; i++) {
                try {
                    args[i] = in.readObject(pts[i]);
                } catch (Exception e) {
                    if (log.isWarnEnabled()) {
                        log.warn("Decode argument failed: " + e.getMessage(), e);
                    }
                }
            }
        }
        setParameterTypes(pts);
        Map<String, String> map = (Map<String, String>) in.readObject(Map.class);
        if (map != null && map.size() > 0) {
            Map<String, String> attachment = getAttachments();
            if (attachment == null) {
                attachment = new HashMap<String, String>();
            }
            attachment.putAll(map);
            setAttachments(attachment);
        }
        // decode argument ,may be callback
        for (int i = 0; i < args.length; i++) {
            args[i] = decodeInvocationArgument(channel, this, pts, i, args[i]);
        }
        setArguments(args);
    } catch (ClassNotFoundException e) {
        throw new IOException(StringUtils.toString("Read invocation data failed.", e));
    } finally {
        if (in instanceof Cleanable) {
            ((Cleanable) in).cleanup();
        }
    }
    return this;
}
Also used : IOException(java.io.IOException) IOException(java.io.IOException) ObjectInput(com.alibaba.dubbo.common.serialize.ObjectInput) Cleanable(com.alibaba.dubbo.common.serialize.Cleanable) HashMap(java.util.HashMap) Map(java.util.Map)

Example 2 with ObjectInput

use of com.alibaba.dubbo.common.serialize.ObjectInput in project dubbo by alibaba.

the class RedisProtocol method refer.

public <T> Invoker<T> refer(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(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT));
        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) {

            protected Result doInvoke(Invocation invocation) throws Throwable {
                Jedis resource = null;
                try {
                    resource = 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 = resource.get(String.valueOf(invocation.getArguments()[0]).getBytes());
                        if (value == null) {
                            return new RpcResult();
                        }
                        ObjectInput oin = getSerialization(url).deserialize(url, new ByteArrayInputStream(value));
                        return new RpcResult(oin.readObject());
                    } 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]);
                        resource.set(key, output.toByteArray());
                        if (expiry > 1000) {
                            resource.expire(key, expiry / 1000);
                        }
                        return new RpcResult();
                    } 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);
                        }
                        resource.del(String.valueOf(invocation.getArguments()[0]).getBytes());
                        return new RpcResult();
                    } 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 TimeoutException || 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 (resource != null) {
                        try {
                            jedisPool.returnResource(resource);
                        } catch (Throwable t) {
                            logger.warn("returnResource error: " + t.getMessage(), t);
                        }
                    }
                }
            }

            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(com.alibaba.dubbo.rpc.Invocation) ObjectOutput(com.alibaba.dubbo.common.serialize.ObjectOutput) RpcResult(com.alibaba.dubbo.rpc.RpcResult) AbstractInvoker(com.alibaba.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(com.alibaba.dubbo.rpc.RpcException) JedisPool(redis.clients.jedis.JedisPool) ObjectInput(com.alibaba.dubbo.common.serialize.ObjectInput) JedisConnectionException(redis.clients.jedis.exceptions.JedisConnectionException) TimeoutException(java.util.concurrent.TimeoutException) SocketTimeoutException(java.net.SocketTimeoutException)

Example 3 with ObjectInput

use of com.alibaba.dubbo.common.serialize.ObjectInput in project dubbo by alibaba.

the class AbstractSerializationTest method test_doubleArray_withType.

@Test
public void test_doubleArray_withType() throws Exception {
    double[] data = new double[] { 37D, -3.14D, 123456.7D };
    ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream);
    objectOutput.writeObject(data);
    objectOutput.flushBuffer();
    ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
    ObjectInput deserialize = serialization.deserialize(url, byteArrayInputStream);
    assertArrayEquals(data, (double[]) deserialize.readObject(double[].class), 0.0001);
    try {
        deserialize.readObject(double[].class);
        fail();
    } catch (IOException expected) {
    }
}
Also used : ObjectOutput(com.alibaba.dubbo.common.serialize.ObjectOutput) ByteArrayInputStream(java.io.ByteArrayInputStream) ObjectInput(com.alibaba.dubbo.common.serialize.ObjectInput) IOException(java.io.IOException) Test(org.junit.Test)

Example 4 with ObjectInput

use of com.alibaba.dubbo.common.serialize.ObjectInput in project dubbo by alibaba.

the class AbstractSerializationTest method test_MediaContent_badStream.

// abnormal case
@Test
public void test_MediaContent_badStream() throws Exception {
    ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream);
    objectOutput.writeObject(mediaContent);
    objectOutput.flushBuffer();
    byte[] byteArray = byteArrayOutputStream.toByteArray();
    for (int i = 0; i < byteArray.length; i++) {
        if (i % 3 == 0) {
            byteArray[i] = (byte) ~byteArray[i];
        }
    }
    ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArray);
    try {
        ObjectInput deserialize = serialization.deserialize(url, byteArrayInputStream);
        // local variable, convenient for debug
        @SuppressWarnings("unused") Object read = deserialize.readObject();
        fail();
    } catch (IOException expected) {
        System.out.println(expected);
    }
}
Also used : ObjectOutput(com.alibaba.dubbo.common.serialize.ObjectOutput) ByteArrayInputStream(java.io.ByteArrayInputStream) ObjectInput(com.alibaba.dubbo.common.serialize.ObjectInput) IOException(java.io.IOException) Test(org.junit.Test)

Example 5 with ObjectInput

use of com.alibaba.dubbo.common.serialize.ObjectInput in project dubbo by alibaba.

the class AbstractSerializationTest method test_Bool_Multi.

@Test
public void test_Bool_Multi() throws Exception {
    boolean[] array = new boolean[100];
    for (int i = 0; i < array.length; i++) {
        array[i] = random.nextBoolean();
    }
    ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream);
    for (boolean b : array) {
        objectOutput.writeBool(b);
    }
    objectOutput.flushBuffer();
    ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
    ObjectInput deserialize = serialization.deserialize(url, byteArrayInputStream);
    for (boolean b : array) {
        assertEquals(b, deserialize.readBool());
    }
    try {
        deserialize.readBool();
        fail();
    } catch (IOException expected) {
    }
}
Also used : ObjectOutput(com.alibaba.dubbo.common.serialize.ObjectOutput) ByteArrayInputStream(java.io.ByteArrayInputStream) ObjectInput(com.alibaba.dubbo.common.serialize.ObjectInput) IOException(java.io.IOException) Test(org.junit.Test)

Aggregations

ObjectInput (com.alibaba.dubbo.common.serialize.ObjectInput)97 ObjectOutput (com.alibaba.dubbo.common.serialize.ObjectOutput)92 ByteArrayInputStream (java.io.ByteArrayInputStream)92 Test (org.junit.Test)83 IOException (java.io.IOException)59 BizException (com.alibaba.dubbo.common.model.BizException)4 BizExceptionNoDefaultConstructor (com.alibaba.dubbo.common.model.BizExceptionNoDefaultConstructor)4 LinkedHashMap (java.util.LinkedHashMap)4 Cleanable (com.alibaba.dubbo.common.serialize.Cleanable)3 HashMap (java.util.HashMap)3 Map (java.util.Map)3 URL (com.alibaba.dubbo.common.URL)2 MediaContent (com.alibaba.dubbo.common.model.media.MediaContent)2 BigPerson (com.alibaba.dubbo.common.model.person.BigPerson)2 Serialization (com.alibaba.dubbo.common.serialize.Serialization)2 Request (com.alibaba.dubbo.remoting.exchange.Request)2 Response (com.alibaba.dubbo.remoting.exchange.Response)2 JSONException (com.alibaba.fastjson.JSONException)2 ChannelBufferInputStream (com.alibaba.dubbo.remoting.buffer.ChannelBufferInputStream)1 Invocation (com.alibaba.dubbo.rpc.Invocation)1