Search in sources :

Example 1 with JavaBeanDescriptor

use of com.alibaba.dubbo.common.beanutil.JavaBeanDescriptor 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 2 with JavaBeanDescriptor

use of com.alibaba.dubbo.common.beanutil.JavaBeanDescriptor in project brave by openzipkin.

the class ITTracingFilter_Provider method customParser.

@Test
public void customParser() {
    Tag<DubboResponse> javaValue = new Tag<DubboResponse>("dubbo.result_value") {

        @Override
        protected String parseValue(DubboResponse input, TraceContext context) {
            Result result = input.result();
            if (result == null)
                return null;
            Object value = result.getValue();
            if (value instanceof JavaBeanDescriptor) {
                return String.valueOf(((JavaBeanDescriptor) value).getProperty("value"));
            }
            return null;
        }
    };
    RpcTracing rpcTracing = RpcTracing.newBuilder(tracing).serverResponseParser((res, context, span) -> {
        RpcResponseParser.DEFAULT.parse(res, context, span);
        if (res instanceof DubboResponse) {
            javaValue.tag((DubboResponse) res, span);
        }
    }).build();
    init().setRpcTracing(rpcTracing);
    String javaResult = client.get().sayHello("jorge");
    assertThat(testSpanHandler.takeRemoteSpan(SERVER).tags()).containsEntry("dubbo.result_value", javaResult);
}
Also used : ReferenceConfig(com.alibaba.dubbo.config.ReferenceConfig) Result(com.alibaba.dubbo.rpc.Result) RpcResponseParser(brave.rpc.RpcResponseParser) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) ALWAYS_SAMPLE(brave.sampler.Sampler.ALWAYS_SAMPLE) JavaBeanDescriptor(com.alibaba.dubbo.common.beanutil.JavaBeanDescriptor) ApplicationConfig(com.alibaba.dubbo.config.ApplicationConfig) Test(org.junit.Test) TraceContext(brave.propagation.TraceContext) RpcTracing(brave.rpc.RpcTracing) B3SingleFormat(brave.propagation.B3SingleFormat) Assertions.assertThatThrownBy(org.assertj.core.api.Assertions.assertThatThrownBy) RpcRuleSampler(brave.rpc.RpcRuleSampler) NEVER_SAMPLE(brave.sampler.Sampler.NEVER_SAMPLE) Tag(brave.Tag) RpcContext(com.alibaba.dubbo.rpc.RpcContext) SamplingFlags(brave.propagation.SamplingFlags) SERVER(brave.Span.Kind.SERVER) RpcRequestMatchers.methodEquals(brave.rpc.RpcRequestMatchers.methodEquals) RpcRequestMatchers.serviceEquals(brave.rpc.RpcRequestMatchers.serviceEquals) Before(org.junit.Before) JavaBeanDescriptor(com.alibaba.dubbo.common.beanutil.JavaBeanDescriptor) TraceContext(brave.propagation.TraceContext) RpcTracing(brave.rpc.RpcTracing) Tag(brave.Tag) Result(com.alibaba.dubbo.rpc.Result) Test(org.junit.Test)

Example 3 with JavaBeanDescriptor

use of com.alibaba.dubbo.common.beanutil.JavaBeanDescriptor in project brave by openzipkin.

the class ITTracingFilter_Consumer method customParser.

@Test
public void customParser() {
    Tag<DubboResponse> javaValue = new Tag<DubboResponse>("dubbo.result_value") {

        @Override
        protected String parseValue(DubboResponse input, TraceContext context) {
            Result result = input.result();
            if (result == null)
                return null;
            Object value = result.getValue();
            if (value instanceof JavaBeanDescriptor) {
                return String.valueOf(((JavaBeanDescriptor) value).getProperty("value"));
            }
            return null;
        }
    };
    RpcTracing rpcTracing = RpcTracing.newBuilder(tracing).clientResponseParser((res, context, span) -> {
        RpcResponseParser.DEFAULT.parse(res, context, span);
        if (res instanceof DubboResponse) {
            javaValue.tag((DubboResponse) res, span);
        }
    }).build();
    init().setRpcTracing(rpcTracing);
    String javaResult = client.get().sayHello("jorge");
    assertThat(testSpanHandler.takeRemoteSpan(CLIENT).tags()).containsEntry("dubbo.result_value", javaResult);
}
Also used : ReferenceConfig(com.alibaba.dubbo.config.ReferenceConfig) Result(com.alibaba.dubbo.rpc.Result) RpcResponseParser(brave.rpc.RpcResponseParser) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) ALWAYS_SAMPLE(brave.sampler.Sampler.ALWAYS_SAMPLE) ApplicationConfig(com.alibaba.dubbo.config.ApplicationConfig) Assertions.assertThatThrownBy(org.assertj.core.api.Assertions.assertThatThrownBy) RpcRuleSampler(brave.rpc.RpcRuleSampler) RpcContext(com.alibaba.dubbo.rpc.RpcContext) RpcRequestMatchers.methodEquals(brave.rpc.RpcRequestMatchers.methodEquals) RpcRequestMatchers.serviceEquals(brave.rpc.RpcRequestMatchers.serviceEquals) Before(org.junit.Before) CLIENT(brave.Span.Kind.CLIENT) JavaBeanDescriptor(com.alibaba.dubbo.common.beanutil.JavaBeanDescriptor) Test(org.junit.Test) RpcException(com.alibaba.dubbo.rpc.RpcException) TraceContext(brave.propagation.TraceContext) Clock(brave.Clock) RpcTracing(brave.rpc.RpcTracing) MutableSpan(brave.handler.MutableSpan) ExtensionLoader(com.alibaba.dubbo.common.extension.ExtensionLoader) NEVER_SAMPLE(brave.sampler.Sampler.NEVER_SAMPLE) Scope(brave.propagation.CurrentTraceContext.Scope) Tag(brave.Tag) SamplingFlags(brave.propagation.SamplingFlags) Filter(com.alibaba.dubbo.rpc.Filter) JavaBeanDescriptor(com.alibaba.dubbo.common.beanutil.JavaBeanDescriptor) TraceContext(brave.propagation.TraceContext) RpcTracing(brave.rpc.RpcTracing) Tag(brave.Tag) Result(com.alibaba.dubbo.rpc.Result) Test(org.junit.Test)

Example 4 with JavaBeanDescriptor

use of com.alibaba.dubbo.common.beanutil.JavaBeanDescriptor in project dubbo by alibaba.

the class GenericServiceTest method testGenericInvokeWithBeanSerialization.

@Test
public void testGenericInvokeWithBeanSerialization() throws Exception {
    ServiceConfig<DemoService> service = new ServiceConfig<DemoService>();
    service.setApplication(new ApplicationConfig("bean-provider"));
    service.setInterface(DemoService.class);
    service.setRegistry(new RegistryConfig("N/A"));
    DemoServiceImpl impl = new DemoServiceImpl();
    service.setRef(impl);
    service.setProtocol(new ProtocolConfig("dubbo", 29581));
    service.export();
    ReferenceConfig<GenericService> reference = null;
    try {
        reference = new ReferenceConfig<GenericService>();
        reference.setApplication(new ApplicationConfig("bean-consumer"));
        reference.setInterface(DemoService.class);
        reference.setUrl("dubbo://127.0.0.1:29581?scope=remote");
        reference.setGeneric(Constants.GENERIC_SERIALIZATION_BEAN);
        GenericService genericService = reference.get();
        User user = new User();
        user.setName("zhangsan");
        List<User> users = new ArrayList<User>();
        users.add(user);
        Object result = genericService.$invoke("getUsers", new String[] { ReflectUtils.getName(List.class) }, new Object[] { JavaBeanSerializeUtil.serialize(users, JavaBeanAccessor.METHOD) });
        Assert.assertTrue(result instanceof JavaBeanDescriptor);
        JavaBeanDescriptor descriptor = (JavaBeanDescriptor) result;
        Assert.assertTrue(descriptor.isCollectionType());
        Assert.assertEquals(1, descriptor.propertySize());
        descriptor = (JavaBeanDescriptor) descriptor.getProperty(0);
        Assert.assertTrue(descriptor.isBeanType());
        Assert.assertEquals(user.getName(), ((JavaBeanDescriptor) descriptor.getProperty("name")).getPrimitiveProperty());
    } finally {
        if (reference != null) {
            reference.destroy();
        }
        service.unexport();
    }
}
Also used : User(com.alibaba.dubbo.config.api.User) GenericService(com.alibaba.dubbo.rpc.service.GenericService) ArrayList(java.util.ArrayList) DemoService(com.alibaba.dubbo.config.api.DemoService) JavaBeanDescriptor(com.alibaba.dubbo.common.beanutil.JavaBeanDescriptor) ArrayList(java.util.ArrayList) List(java.util.List) DemoServiceImpl(com.alibaba.dubbo.config.provider.impl.DemoServiceImpl) Test(org.junit.Test)

Example 5 with JavaBeanDescriptor

use of com.alibaba.dubbo.common.beanutil.JavaBeanDescriptor in project dubbo by alibaba.

the class GenericServiceTest method testGenericImplementationWithBeanSerialization.

@Test
public void testGenericImplementationWithBeanSerialization() throws Exception {
    final AtomicReference reference = new AtomicReference();
    ServiceConfig<GenericService> service = new ServiceConfig<GenericService>();
    service.setApplication(new ApplicationConfig("bean-provider"));
    service.setRegistry(new RegistryConfig("N/A"));
    service.setProtocol(new ProtocolConfig("dubbo", 29581));
    service.setInterface(DemoService.class.getName());
    service.setRef(new GenericService() {

        public Object $invoke(String method, String[] parameterTypes, Object[] args) throws GenericException {
            if ("getUsers".equals(method)) {
                GenericParameter arg = new GenericParameter();
                arg.method = method;
                arg.parameterTypes = parameterTypes;
                arg.arguments = args;
                reference.set(arg);
                return args[0];
            }
            if ("sayName".equals(method)) {
                return null;
            }
            return args;
        }
    });
    service.export();
    ReferenceConfig<DemoService> ref = null;
    try {
        ref = new ReferenceConfig<DemoService>();
        ref.setApplication(new ApplicationConfig("bean-consumer"));
        ref.setInterface(DemoService.class);
        ref.setUrl("dubbo://127.0.0.1:29581?scope=remote&generic=bean");
        DemoService demoService = ref.get();
        User user = new User();
        user.setName("zhangsan");
        List<User> users = new ArrayList<User>();
        users.add(user);
        List<User> result = demoService.getUsers(users);
        Assert.assertEquals(users.size(), result.size());
        Assert.assertEquals(user.getName(), result.get(0).getName());
        GenericParameter gp = (GenericParameter) reference.get();
        Assert.assertEquals("getUsers", gp.method);
        Assert.assertEquals(1, gp.parameterTypes.length);
        Assert.assertEquals(ReflectUtils.getName(List.class), gp.parameterTypes[0]);
        Assert.assertEquals(1, gp.arguments.length);
        Assert.assertTrue(gp.arguments[0] instanceof JavaBeanDescriptor);
        JavaBeanDescriptor descriptor = (JavaBeanDescriptor) gp.arguments[0];
        Assert.assertTrue(descriptor.isCollectionType());
        Assert.assertEquals(ArrayList.class.getName(), descriptor.getClassName());
        Assert.assertEquals(1, descriptor.propertySize());
        descriptor = (JavaBeanDescriptor) descriptor.getProperty(0);
        Assert.assertTrue(descriptor.isBeanType());
        Assert.assertEquals(User.class.getName(), descriptor.getClassName());
        Assert.assertEquals(user.getName(), ((JavaBeanDescriptor) descriptor.getProperty("name")).getPrimitiveProperty());
        Assert.assertNull(demoService.sayName("zhangsan"));
    } finally {
        if (ref != null) {
            ref.destroy();
        }
        service.unexport();
    }
}
Also used : User(com.alibaba.dubbo.config.api.User) GenericService(com.alibaba.dubbo.rpc.service.GenericService) ArrayList(java.util.ArrayList) DemoService(com.alibaba.dubbo.config.api.DemoService) AtomicReference(java.util.concurrent.atomic.AtomicReference) GenericException(com.alibaba.dubbo.rpc.service.GenericException) JavaBeanDescriptor(com.alibaba.dubbo.common.beanutil.JavaBeanDescriptor) ArrayList(java.util.ArrayList) List(java.util.List) Test(org.junit.Test)

Aggregations

JavaBeanDescriptor (com.alibaba.dubbo.common.beanutil.JavaBeanDescriptor)7 Result (com.alibaba.dubbo.rpc.Result)4 Test (org.junit.Test)4 ApplicationConfig (com.alibaba.dubbo.config.ApplicationConfig)3 ReferenceConfig (com.alibaba.dubbo.config.ReferenceConfig)3 RpcException (com.alibaba.dubbo.rpc.RpcException)3 GenericException (com.alibaba.dubbo.rpc.service.GenericException)3 Before (org.junit.Before)3 Tag (brave.Tag)2 SamplingFlags (brave.propagation.SamplingFlags)2 TraceContext (brave.propagation.TraceContext)2 RpcRequestMatchers.methodEquals (brave.rpc.RpcRequestMatchers.methodEquals)2 RpcRequestMatchers.serviceEquals (brave.rpc.RpcRequestMatchers.serviceEquals)2 RpcResponseParser (brave.rpc.RpcResponseParser)2 RpcRuleSampler (brave.rpc.RpcRuleSampler)2 RpcTracing (brave.rpc.RpcTracing)2 ALWAYS_SAMPLE (brave.sampler.Sampler.ALWAYS_SAMPLE)2 NEVER_SAMPLE (brave.sampler.Sampler.NEVER_SAMPLE)2 DemoService (com.alibaba.dubbo.config.api.DemoService)2 User (com.alibaba.dubbo.config.api.User)2