You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@camel.apache.org by da...@apache.org on 2011/09/19 09:54:04 UTC

svn commit: r1172503 - in /camel/trunk/camel-core/src: main/java/org/apache/camel/component/bean/ main/java/org/apache/camel/model/ main/java/org/apache/camel/util/ test/java/org/apache/camel/component/bean/ test/java/org/apache/camel/util/

Author: davsclaus
Date: Mon Sep 19 07:54:04 2011
New Revision: 1172503

URL: http://svn.apache.org/viewvc?rev=1172503&view=rev
Log:
CAMEL-4386: Bean component can now invoke static methods without the need for creating a new bean instance.

Added:
    camel/trunk/camel-core/src/test/java/org/apache/camel/component/bean/BeanInvokeStaticTest.java
      - copied, changed from r1172205, camel/trunk/camel-core/src/test/java/org/apache/camel/component/bean/BeanInvokeTest.java
    camel/trunk/camel-core/src/test/java/org/apache/camel/component/bean/MyStaticClass.java
Modified:
    camel/trunk/camel-core/src/main/java/org/apache/camel/component/bean/BeanInfo.java
    camel/trunk/camel-core/src/main/java/org/apache/camel/component/bean/MethodInfo.java
    camel/trunk/camel-core/src/main/java/org/apache/camel/component/bean/MethodNotFoundException.java
    camel/trunk/camel-core/src/main/java/org/apache/camel/model/BeanDefinition.java
    camel/trunk/camel-core/src/main/java/org/apache/camel/util/ObjectHelper.java
    camel/trunk/camel-core/src/test/java/org/apache/camel/util/ObjectHelperTest.java

Modified: camel/trunk/camel-core/src/main/java/org/apache/camel/component/bean/BeanInfo.java
URL: http://svn.apache.org/viewvc/camel/trunk/camel-core/src/main/java/org/apache/camel/component/bean/BeanInfo.java?rev=1172503&r1=1172502&r2=1172503&view=diff
==============================================================================
--- camel/trunk/camel-core/src/main/java/org/apache/camel/component/bean/BeanInfo.java (original)
+++ camel/trunk/camel-core/src/main/java/org/apache/camel/component/bean/BeanInfo.java Mon Sep 19 07:54:04 2011
@@ -196,6 +196,7 @@ public class BeanInfo {
     protected void introspect(Class<?> clazz) {
         // get the target clazz as it could potentially have been enhanced by CGLIB etc.
         clazz = getTargetClass(clazz);
+        ObjectHelper.notNull(clazz, "clazz", this);
 
         LOG.trace("Introspecting class: {}", clazz);
 
@@ -785,6 +786,28 @@ public class BeanInfo {
     }
 
     /**
+     * Do we have a static method with the given name.
+     * <p/>
+     * Shorthand method names for getters is supported, so you can pass in eg 'name' and Camel
+     * will can find the real 'getName' method instead.
+     *
+     * @param methodName the method name
+     * @return <tt>true</tt> if we have such a static method.
+     */
+    public boolean hasStaticMethod(String methodName) {
+        List<MethodInfo> methods = getOperations(methodName);
+        if (methods == null || methods.isEmpty()) {
+            return false;
+        }
+        for (MethodInfo method : methods) {
+            if (method.isStaticMethod()) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+    /**
      * Gets the list of methods sorted by A..Z method name.
      *
      * @return the methods.

Modified: camel/trunk/camel-core/src/main/java/org/apache/camel/component/bean/MethodInfo.java
URL: http://svn.apache.org/viewvc/camel/trunk/camel-core/src/main/java/org/apache/camel/component/bean/MethodInfo.java?rev=1172503&r1=1172502&r2=1172503&view=diff
==============================================================================
--- camel/trunk/camel-core/src/main/java/org/apache/camel/component/bean/MethodInfo.java (original)
+++ camel/trunk/camel-core/src/main/java/org/apache/camel/component/bean/MethodInfo.java Mon Sep 19 07:54:04 2011
@@ -22,6 +22,7 @@ import java.lang.reflect.AccessibleObjec
 import java.lang.reflect.AnnotatedElement;
 import java.lang.reflect.InvocationTargetException;
 import java.lang.reflect.Method;
+import java.lang.reflect.Modifier;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Iterator;
@@ -330,6 +331,10 @@ public class MethodInfo {
         return method.getReturnType().getName().equals("void");
     }
 
+    public boolean isStaticMethod() {
+        return Modifier.isStatic(method.getModifiers());
+    }
+
     protected Object invoke(Method mth, Object pojo, Object[] arguments, Exchange exchange) throws IllegalAccessException, InvocationTargetException {
         try {
             return mth.invoke(pojo, arguments);

Modified: camel/trunk/camel-core/src/main/java/org/apache/camel/component/bean/MethodNotFoundException.java
URL: http://svn.apache.org/viewvc/camel/trunk/camel-core/src/main/java/org/apache/camel/component/bean/MethodNotFoundException.java?rev=1172503&r1=1172502&r2=1172503&view=diff
==============================================================================
--- camel/trunk/camel-core/src/main/java/org/apache/camel/component/bean/MethodNotFoundException.java (original)
+++ camel/trunk/camel-core/src/main/java/org/apache/camel/component/bean/MethodNotFoundException.java Mon Sep 19 07:54:04 2011
@@ -36,6 +36,12 @@ public class MethodNotFoundException ext
         this.bean = pojo;
     }
 
+    public MethodNotFoundException(Exchange exchange, Class type, String methodName, boolean isStaticMethod) {
+        super((isStaticMethod ? "Static method" : "Method") + " with name: " + methodName + " not found on class: " + ObjectHelper.name(type), exchange);
+        this.methodName = methodName;
+        this.bean = null;
+    }
+
     public MethodNotFoundException(Object pojo, String methodName, Throwable cause) {
         super("Method with name: " + methodName + " not found on bean: " + pojo + " of type:" + ObjectHelper.className(pojo), null, cause);
         this.methodName = methodName;

Modified: camel/trunk/camel-core/src/main/java/org/apache/camel/model/BeanDefinition.java
URL: http://svn.apache.org/viewvc/camel/trunk/camel-core/src/main/java/org/apache/camel/model/BeanDefinition.java?rev=1172503&r1=1172502&r2=1172503&view=diff
==============================================================================
--- camel/trunk/camel-core/src/main/java/org/apache/camel/model/BeanDefinition.java (original)
+++ camel/trunk/camel-core/src/main/java/org/apache/camel/model/BeanDefinition.java Mon Sep 19 07:54:04 2011
@@ -23,8 +23,11 @@ import javax.xml.bind.annotation.XmlRoot
 import javax.xml.bind.annotation.XmlTransient;
 
 import org.apache.camel.Processor;
+import org.apache.camel.RuntimeCamelException;
+import org.apache.camel.component.bean.BeanHolder;
 import org.apache.camel.component.bean.BeanInfo;
 import org.apache.camel.component.bean.BeanProcessor;
+import org.apache.camel.component.bean.ConstantBeanHolder;
 import org.apache.camel.component.bean.MethodNotFoundException;
 import org.apache.camel.component.bean.RegistryBean;
 import org.apache.camel.spi.Required;
@@ -170,6 +173,9 @@ public class BeanDefinition extends NoOu
     @Override
     public Processor createProcessor(RouteContext routeContext) {
         BeanProcessor answer;
+        Class<?> clazz = bean != null ? bean.getClass() : null;
+        BeanInfo beanInfo = null;
+
         if (ObjectHelper.isNotEmpty(ref)) {
             RegistryBean beanHolder = new RegistryBean(routeContext.getCamelContext(), ref);
             // bean holder will check if the bean exists
@@ -178,15 +184,17 @@ public class BeanDefinition extends NoOu
         } else {
             if (bean == null) {
                 ObjectHelper.notNull(beanType, "bean, ref or beanType", this);
-                Class<?> clazz;
                 try {
                     clazz = routeContext.getCamelContext().getClassResolver().resolveMandatoryClass(beanType);
                 } catch (ClassNotFoundException e) {
                     throw ObjectHelper.wrapRuntimeCamelException(e);
                 }
-                bean = CamelContextHelper.newInstance(routeContext.getCamelContext(), clazz);
+                // create a bean if there is a default public no-arg constructor
+                if (ObjectHelper.hasDefaultPublicNoArgConstructor(clazz)) {
+                    bean = CamelContextHelper.newInstance(routeContext.getCamelContext(), clazz);
+                    ObjectHelper.notNull(bean, "bean", this);
+                }
             }
-            ObjectHelper.notNull(bean, "bean", this);
 
             // validate the bean type is not from java so you by mistake think its a reference
             // to a bean name but the String is being invoke instead
@@ -194,15 +202,32 @@ public class BeanDefinition extends NoOu
                 throw new IllegalArgumentException("The bean instance is a java.lang.String type: " + bean
                     + ". We suppose you want to refer to a bean instance by its id instead. Please use beanRef.");
             }
-            answer = new BeanProcessor(bean, routeContext.getCamelContext());
+
+            // notice bean may be null if its a static class
+            beanInfo = new BeanInfo(routeContext.getCamelContext(), clazz);
+            answer = new BeanProcessor(new ConstantBeanHolder(bean, beanInfo));
         }
         if (method != null) {
             answer.setMethod(method);
 
             // check there is a method with the given name, and leverage BeanInfo for that
-            BeanInfo info = new BeanInfo(routeContext.getCamelContext(), bean.getClass());
-            if (!info.hasMethod(method)) {
-                throw ObjectHelper.wrapRuntimeCamelException(new MethodNotFoundException(null, bean, method));
+            if (bean != null) {
+                clazz = bean.getClass();
+            }
+            if (beanInfo == null) {
+                beanInfo = new BeanInfo(routeContext.getCamelContext(), clazz);
+            }
+
+            if (bean != null) {
+                // there is a bean instance, so check for any methods
+                if (!beanInfo.hasMethod(method)) {
+                    throw ObjectHelper.wrapRuntimeCamelException(new MethodNotFoundException(null, bean, method));
+                }
+            } else {
+                // there is no bean instance, so check for static methods only
+                if (!beanInfo.hasStaticMethod(method)) {
+                    throw ObjectHelper.wrapRuntimeCamelException(new MethodNotFoundException(null, clazz, method, true));
+                }
             }
         }
         return answer;

Modified: camel/trunk/camel-core/src/main/java/org/apache/camel/util/ObjectHelper.java
URL: http://svn.apache.org/viewvc/camel/trunk/camel-core/src/main/java/org/apache/camel/util/ObjectHelper.java?rev=1172503&r1=1172502&r2=1172503&view=diff
==============================================================================
--- camel/trunk/camel-core/src/main/java/org/apache/camel/util/ObjectHelper.java (original)
+++ camel/trunk/camel-core/src/main/java/org/apache/camel/util/ObjectHelper.java Mon Sep 19 07:54:04 2011
@@ -22,9 +22,11 @@ import java.io.FileNotFoundException;
 import java.io.InputStream;
 import java.lang.annotation.Annotation;
 import java.lang.reflect.AnnotatedElement;
+import java.lang.reflect.Constructor;
 import java.lang.reflect.Field;
 import java.lang.reflect.InvocationTargetException;
 import java.lang.reflect.Method;
+import java.lang.reflect.Modifier;
 import java.net.URL;
 import java.nio.channels.ReadableByteChannel;
 import java.nio.charset.Charset;
@@ -1096,6 +1098,19 @@ public final class ObjectHelper {
     }
 
     /**
+     * Does the given class have a default public no-arg constructor.
+     */
+    public static boolean hasDefaultPublicNoArgConstructor(Class type) {
+        // getConstructors() returns only public constructors
+        for (Constructor ctr : type.getConstructors()) {
+            if (ctr.getParameterTypes().length == 0) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+    /**
      * Returns true if the given name is a valid java identifier
      */
     public static boolean isJavaIdentifier(String name) {

Copied: camel/trunk/camel-core/src/test/java/org/apache/camel/component/bean/BeanInvokeStaticTest.java (from r1172205, camel/trunk/camel-core/src/test/java/org/apache/camel/component/bean/BeanInvokeTest.java)
URL: http://svn.apache.org/viewvc/camel/trunk/camel-core/src/test/java/org/apache/camel/component/bean/BeanInvokeStaticTest.java?p2=camel/trunk/camel-core/src/test/java/org/apache/camel/component/bean/BeanInvokeStaticTest.java&p1=camel/trunk/camel-core/src/test/java/org/apache/camel/component/bean/BeanInvokeTest.java&r1=1172205&r2=1172503&rev=1172503&view=diff
==============================================================================
--- camel/trunk/camel-core/src/test/java/org/apache/camel/component/bean/BeanInvokeTest.java (original)
+++ camel/trunk/camel-core/src/test/java/org/apache/camel/component/bean/BeanInvokeStaticTest.java Mon Sep 19 07:54:04 2011
@@ -17,96 +17,52 @@
 package org.apache.camel.component.bean;
 
 import org.apache.camel.ContextTestSupport;
+import org.apache.camel.FailedToCreateRouteException;
+import org.apache.camel.RuntimeCamelException;
 import org.apache.camel.builder.RouteBuilder;
 import org.apache.camel.component.mock.MockEndpoint;
 
 /**
  * @version 
  */
-public class BeanInvokeTest extends ContextTestSupport {
+public class BeanInvokeStaticTest extends ContextTestSupport {
 
     public void testA() throws Exception {
+        context.addRoutes(new RouteBuilder() {
+            @Override
+            public void configure() throws Exception {
+                from("direct:a").bean(MyStaticClass.class, "changeSomething").to("mock:a");
+            }
+        });
+        context.start();
+
         MockEndpoint mock = getMockEndpoint("mock:a");
+        mock.expectedBodiesReceived("Bye World");
 
-        mock.expectedBodiesReceived("Hello World");
         template.sendBody("direct:a", "Hello World");
-        assertMockEndpointsSatisfied();
-
-        mock.reset();
-        mock.expectedBodiesReceived("");
-        template.sendBody("direct:a", "");
-        assertMockEndpointsSatisfied();
 
-        mock.reset();
-        mock.expectedMessageCount(1);
-        mock.message(0).body().isNull();
-        template.sendBody("direct:a", null);
         assertMockEndpointsSatisfied();
     }
 
     public void testB() throws Exception {
-        MockEndpoint mock = getMockEndpoint("mock:b");
-
-        mock.expectedBodiesReceived("Bye World");
-        template.sendBody("direct:b", "Hello World");
-        assertMockEndpointsSatisfied();
-
-        mock.reset();
-        mock.expectedMessageCount(1);
-        mock.message(0).body().isNull();
-        template.sendBody("direct:b", "");
-        assertMockEndpointsSatisfied();
-
-        mock.reset();
-        mock.expectedMessageCount(1);
-        mock.message(0).body().isNull();
-        template.sendBody("direct:b", null);
-        assertMockEndpointsSatisfied();
-    }
-
-    public void testC() throws Exception {
-        MockEndpoint mock = getMockEndpoint("mock:c");
-
-        mock.expectedBodiesReceived("Hello World");
-        template.sendBody("direct:c", "Hello World");
-        assertMockEndpointsSatisfied();
-
-        mock.reset();
-        mock.expectedBodiesReceived("");
-        template.sendBody("direct:c", "");
-        assertMockEndpointsSatisfied();
-
-        mock.reset();
-        mock.expectedMessageCount(1);
-        mock.message(0).body().isNull();
-        template.sendBody("direct:c", null);
-        assertMockEndpointsSatisfied();
-    }
-
-    @Override
-    protected RouteBuilder createRouteBuilder() throws Exception {
-        return new RouteBuilder() {
+        context.addRoutes(new RouteBuilder() {
             @Override
             public void configure() throws Exception {
-                from("direct:a").bean(BeanInvokeTest.class, "doSomething").to("mock:a");
-                from("direct:b").bean(BeanInvokeTest.class, "changeSomething").to("mock:b");
-                from("direct:c").bean(BeanInvokeTest.class, "doNothing").to("mock:c");
+                from("direct:a").bean(MyStaticClass.class, "doSomething").to("mock:a");
             }
-        };
-    }
-
-    public String doSomething(String s) {
-        return s;
-    }
-
-    public String changeSomething(String s) {
-        if ("Hello World".equals(s)) {
-            return "Bye World";
+        });
+        try {
+            context.start();
+        } catch (FailedToCreateRouteException e) {
+            assertIsInstanceOf(RuntimeCamelException.class, e.getCause());
+            assertIsInstanceOf(MethodNotFoundException.class, e.getCause().getCause());
+            assertEquals("Static method with name: doSomething not found on class: org.apache.camel.component.bean.MyStaticClass", e.getCause().getCause().getMessage());
         }
-        return null;
     }
 
-    public void doNothing(String s) {
+    @Override
+    public boolean isUseRouteBuilder() {
+        return false;
     }
 
 }
\ No newline at end of file

Added: camel/trunk/camel-core/src/test/java/org/apache/camel/component/bean/MyStaticClass.java
URL: http://svn.apache.org/viewvc/camel/trunk/camel-core/src/test/java/org/apache/camel/component/bean/MyStaticClass.java?rev=1172503&view=auto
==============================================================================
--- camel/trunk/camel-core/src/test/java/org/apache/camel/component/bean/MyStaticClass.java (added)
+++ camel/trunk/camel-core/src/test/java/org/apache/camel/component/bean/MyStaticClass.java Mon Sep 19 07:54:04 2011
@@ -0,0 +1,38 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.component.bean;
+
+/**
+*
+*/
+public final class MyStaticClass {
+
+    private MyStaticClass() {
+    }
+
+    public static String changeSomething(String s) {
+        if ("Hello World".equals(s)) {
+            return "Bye World";
+        }
+        return null;
+    }
+
+    public void doSomething() {
+        // noop
+    }
+
+}

Modified: camel/trunk/camel-core/src/test/java/org/apache/camel/util/ObjectHelperTest.java
URL: http://svn.apache.org/viewvc/camel/trunk/camel-core/src/test/java/org/apache/camel/util/ObjectHelperTest.java?rev=1172503&r1=1172502&r2=1172503&view=diff
==============================================================================
--- camel/trunk/camel-core/src/test/java/org/apache/camel/util/ObjectHelperTest.java (original)
+++ camel/trunk/camel-core/src/test/java/org/apache/camel/util/ObjectHelperTest.java Mon Sep 19 07:54:04 2011
@@ -27,6 +27,7 @@ import java.util.List;
 import junit.framework.TestCase;
 import org.apache.camel.Exchange;
 import org.apache.camel.Message;
+import org.apache.camel.component.bean.MyStaticClass;
 import org.apache.camel.impl.DefaultMessage;
 
 /**
@@ -299,4 +300,9 @@ public class ObjectHelperTest extends Te
         assertEquals(null, ObjectHelper.lookupConstantFieldValue(null, "FILE_NAME"));
     }
 
+    public void testHasDefaultPublicNoArgConstructor() {
+        assertTrue(ObjectHelper.hasDefaultPublicNoArgConstructor(ObjectHelperTest.class));
+        assertFalse(ObjectHelper.hasDefaultPublicNoArgConstructor(MyStaticClass.class));
+    }
+
 }