You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@aries.apache.org by oz...@apache.org on 2009/11/17 14:52:29 UTC

svn commit: r881290 - in /incubator/aries/trunk/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/proxy: ./ CgLibInterceptorWrapper.java Collaborator.java WrapperedObject.java

Author: ozzy
Date: Tue Nov 17 13:52:29 2009
New Revision: 881290

URL: http://svn.apache.org/viewvc?rev=881290&view=rev
Log:
ARIES-47 Add interceptor concept to blueprint

Added:
    incubator/aries/trunk/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/proxy/
    incubator/aries/trunk/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/proxy/CgLibInterceptorWrapper.java
    incubator/aries/trunk/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/proxy/Collaborator.java
    incubator/aries/trunk/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/proxy/WrapperedObject.java

Added: incubator/aries/trunk/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/proxy/CgLibInterceptorWrapper.java
URL: http://svn.apache.org/viewvc/incubator/aries/trunk/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/proxy/CgLibInterceptorWrapper.java?rev=881290&view=auto
==============================================================================
--- incubator/aries/trunk/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/proxy/CgLibInterceptorWrapper.java (added)
+++ incubator/aries/trunk/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/proxy/CgLibInterceptorWrapper.java Tue Nov 17 13:52:29 2009
@@ -0,0 +1,140 @@
+/*
+ * 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.aries.blueprint.proxy;
+
+import java.lang.reflect.Method;
+import java.util.List;
+
+import net.sf.cglib.proxy.Enhancer;
+import net.sf.cglib.proxy.MethodInterceptor;
+import net.sf.cglib.proxy.MethodProxy;
+
+import org.apache.aries.blueprint.Interceptor;
+import org.osgi.service.blueprint.container.ComponentDefinitionException;
+import org.osgi.service.blueprint.reflect.ComponentMetadata;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Simple class that coordinates creation of object wrappers that invoke
+ * interceptors.
+ */
+public class CgLibInterceptorWrapper {
+    private static final Logger LOGGER = LoggerFactory
+            .getLogger(CgLibInterceptorWrapper.class);
+
+    /**
+     * Classloader for CGLib usage, that spans the delegate classloader (for the
+     * bean being intercepted), the blueprint classloader (for the wrapped bean
+     * interface), and the cglib classloader (for cglib packages).
+     */
+    private static class BridgingClassLoader extends ClassLoader {
+        private ClassLoader cgLibClassLoader;
+        private ClassLoader blueprintClassLoader;
+        private ClassLoader delegateClassLoader;
+
+        public BridgingClassLoader(ClassLoader delegate) {
+            this.delegateClassLoader = delegate;
+            this.cgLibClassLoader = Enhancer.class.getClassLoader();
+            this.blueprintClassLoader = this.getClass().getClassLoader();
+        }
+
+        public Class<?> loadClass(String className)
+                throws ClassNotFoundException {
+            if (className.equals("org.apache.aries.blueprint.proxy.WrapperedObject")) {
+                //CgLib will need to use 'WrapperedObject' which is from us.
+                return blueprintClassLoader.loadClass(className);
+            } else if (className.startsWith("net.sf.cglib")) {
+                //CgLib will need to load classes from within its bundle, that we 
+                //cannot load with the blueprintClassLoader.
+                return cgLibClassLoader.loadClass(className);
+            } else {
+                //CgLib will need to load classes from the application bundle.
+                return delegateClassLoader.loadClass(className);
+            }
+        }
+    }
+
+    /**
+     * Create a proxy object, given a delegate instance, associated metadata,
+     * and a list of interceptors.
+     * <p>
+     * 
+     * @param cl
+     *            Classloader to use to create proxy instance
+     * @param cm
+     *            ComponentMetadata for delegate instance
+     * @param interceptors
+     *            List of Interceptor for invocation pre/post.
+     * @param delegate
+     *            Instance to delegate method calls to.
+     * @param classesToProxy
+     *            List of interfaces/classes this proxy should present itself
+     *            as.
+     * @return Interceptor wrappered proxy. Can be used functionally the same as
+     *         'delegate' but will invoke interceptors. Will implement WrapperedObject
+     *         which can be used to unwrap the original object.
+     * @throws ComponentDefinitionException
+     *             if the delegate cannot be proxied.
+     */
+    public static Object createProxyObject(ClassLoader cl,
+            ComponentMetadata cm, List<Interceptor> interceptors,
+            Object delegate, Class<?>... classesToProxy) {
+
+        LOGGER.debug("createProxyObject " + cm.getId() + " " + delegate);
+        final Collaborator c = new Collaborator(cm, interceptors, delegate);
+        Enhancer e = new Enhancer();
+
+        e.setClassLoader(new BridgingClassLoader(cl));
+        e.setInterceptDuringConstruction(false);
+
+        // add the WrapperedObject interface to the list of interfaces for the
+        // subclass.
+        int origIfLen = 0;
+        if (classesToProxy != null)
+            origIfLen = classesToProxy.length;
+        Class<?> ifs[] = new Class<?>[origIfLen + 1];
+        ifs[0] = WrapperedObject.class;
+        if (classesToProxy != null && classesToProxy.length > 0) {
+            for (int i = 1; i < (classesToProxy.length + 1); i++) {
+                ifs[i] = classesToProxy[i - 1];
+            }
+        }
+        e.setInterfaces(ifs);
+        
+        e.setSuperclass(delegate.getClass());
+        e.setCallback(new MethodInterceptor() {
+            public Object intercept(Object arg0, Method arg1, Object[] arg2,
+                    MethodProxy arg3) throws Throwable {
+                return c.invoke(arg0, arg1, arg2);
+            }
+        });
+
+        Object wrappered = null;
+        try {
+            wrappered = e.create();
+        } catch (IllegalArgumentException iae) {
+            // thrown if the bean has no zero-arg constructor,
+            // or is final, or otherwise unable to be proxied.
+            throw new ComponentDefinitionException(
+                    "Unable to proxy bean for interceptors: " + iae);
+        }
+        return wrappered;
+    }
+}

Added: incubator/aries/trunk/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/proxy/Collaborator.java
URL: http://svn.apache.org/viewvc/incubator/aries/trunk/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/proxy/Collaborator.java?rev=881290&view=auto
==============================================================================
--- incubator/aries/trunk/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/proxy/Collaborator.java (added)
+++ incubator/aries/trunk/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/proxy/Collaborator.java Tue Nov 17 13:52:29 2009
@@ -0,0 +1,278 @@
+/*
+ * 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.aries.blueprint.proxy;
+
+import java.io.Serializable;
+import java.lang.reflect.InvocationHandler;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.util.List;
+import java.util.Stack;
+
+import org.apache.aries.blueprint.Interceptor;
+import org.osgi.service.blueprint.reflect.ComponentMetadata;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * A collaborator which ensures preInvoke and postInvoke occur before and after
+ * method invocation
+ */
+class Collaborator implements InvocationHandler, Serializable {
+
+    /** Serial version UID for this class */
+    private static final long serialVersionUID = -58189302118314469L;
+
+    private static final Logger LOGGER = LoggerFactory
+            .getLogger(Collaborator.class);
+
+    /** The invocation handler to call */
+    final InvocationHandler delegate;
+    final Object object;
+
+    private transient List<Interceptor> interceptors = null;
+    private transient ComponentMetadata cm = null;
+    private transient boolean sorted = false;
+
+    Collaborator(ComponentMetadata cm, List<Interceptor> interceptors,
+            final Object delegateObj) {
+        this.cm = cm;
+        this.object = delegateObj;
+        this.delegate = new InvocationHandler() {
+            private void onUnexpectedException(Throwable cause) {
+                throw new Error("Unreachable catch statement reached", cause);
+            }
+
+            public Object invoke(Object proxy, Method method, Object[] args)
+                    throws Throwable {
+                Object result;
+                try {
+                    result = method.invoke(object, args);
+                } catch (InvocationTargetException ite) {
+                    // We are invisible, so unwrap and throw the cause as
+                    // though we called the method directly.
+                    throw ite.getCause();
+                } catch (IllegalAccessException e) {
+                    onUnexpectedException(e);
+                    return null;
+                } catch (IllegalArgumentException e) {
+                    onUnexpectedException(e);
+                    return null;
+                } catch (SecurityException e) {
+                    onUnexpectedException(e);
+                    return null;
+                }
+
+                return result;
+            }
+        };
+        this.interceptors = interceptors;
+    }
+
+    /**
+     * Invoke the preCall method on the interceptor
+     * 
+     * @param cm
+     *            : component Metadata
+     * @param m
+     *            : method
+     * @param parameters
+     *            : method paramters
+     * @throws Throwable
+     */
+    private void preCallInterceptor(List<Interceptor> interceptorList,
+            ComponentMetadata cm, Method m, Object[] parameters,
+            Stack<Collaborator.StackElement> calledInterceptors)
+            throws Throwable {
+        if ((interceptors != null) && !(interceptors.isEmpty())) {
+            for (Interceptor im : interceptorList) {
+                Collaborator.StackElement se = new StackElement(im);
+
+                // should we do this before or after the preCall ?
+                calledInterceptors.push(se);
+
+                // allow exceptions to propagate
+                se.setPreCallToken(im.preCall(cm, m, parameters));
+            }
+        }
+    }
+
+    public Object invoke(Object proxy, Method method, Object[] args)
+            throws Throwable {
+        Object toReturn = null;
+
+        // Added method to unwrap from the collaborator.
+        if (method.getName().equals("getWrappedObject")
+                && method.getDeclaringClass() == WrapperedObject.class) {
+            toReturn = object;
+        } else
+        // Unwrap calls for equals 
+        if (method.getName().equals("equals")
+                && method.getDeclaringClass() == Object.class) {
+            if (args[0] instanceof WrapperedObject) {
+                //replace the wrapper with the unwrapped object, to 
+                //enable object identity etc to function.
+                args[0] = ((WrapperedObject) args[0]).unwrapObject();
+            }
+            toReturn = delegate.invoke(proxy, method, args);
+        } else 
+        // Proxy the call through to the delegate, wrapping call in 
+        // interceptor invocations.
+        {
+            Stack<Collaborator.StackElement> calledInterceptors = new Stack<Collaborator.StackElement>();
+            boolean inInvoke = false;
+            try {
+                preCallInterceptor(interceptors, cm, method, args,
+                        calledInterceptors);
+                inInvoke = true;
+                toReturn = delegate.invoke(proxy, method, args);
+                inInvoke = false;
+                postCallInterceptorWithReturn(cm, method, toReturn,
+                        calledInterceptors);
+
+            } catch (Exception e) {
+                // log the exception e
+                LOGGER.error("invoke", e);
+
+                // if we catch an exception we decide carefully which one to
+                // throw onwards
+                Exception exceptionToRethrow = null;
+                // if the exception came from a precall or postcall interceptor
+                // we will rethrow it
+                // after we cycle through the rest of the interceptors using
+                // postCallInterceptorWithException
+                if (!inInvoke) {
+                    exceptionToRethrow = e;
+                }
+                // if the exception didn't come from precall or postcall then it
+                // came from invoke
+                // we will rethrow this exception if it is not a runtime
+                // exception
+                else {
+                    if (!(e instanceof RuntimeException)) {
+                        exceptionToRethrow = e;
+                    }
+                }
+                try {
+                    postCallInterceptorWithException(cm, method, e,
+                            calledInterceptors);
+                } catch (Exception f) {
+                    // we caught an exception from
+                    // postCallInterceptorWithException
+                    // logger.catching("invoke", f);
+                    // if we haven't already chosen an exception to rethrow then
+                    // we will throw this exception
+                    if (exceptionToRethrow == null) {
+                        exceptionToRethrow = f;
+                    }
+                }
+                // if we made it this far without choosing an exception we
+                // should throw e
+                if (exceptionToRethrow == null) {
+                    exceptionToRethrow = e;
+                }
+                throw exceptionToRethrow;
+            }
+        }
+        return toReturn;
+    }
+
+    /**
+     * Called when the method is called and returned normally
+     * 
+     * @param cm
+     *            : component metadata
+     * @param method
+     *            : method
+     * @param returnType
+     *            : return type
+     * @throws Throwable
+     */
+    private void postCallInterceptorWithReturn(ComponentMetadata cm,
+            Method method, Object returnType,
+            Stack<Collaborator.StackElement> calledInterceptors)
+            throws Throwable {
+
+        while (!calledInterceptors.isEmpty()) {
+            Collaborator.StackElement se = calledInterceptors.pop();
+            try {
+                se.interceptor.postCallWithReturn(cm, method, returnType, se
+                        .getPreCallToken());
+            } catch (Throwable t) {
+                LOGGER.error("postCallInterceptorWithReturn", t);
+                // propagate this to invoke ... further interceptors will be
+                // called via the postCallInterceptorWithException method
+                throw t;
+            }
+        } // end while
+    }
+
+    /**
+     * Called when the method is called and returned with an exception
+     * 
+     * @param cm
+     *            : component metadata
+     * @param method
+     *            : method
+     * @param exception
+     *            : exception throwed
+     */
+    private void postCallInterceptorWithException(ComponentMetadata cm,
+            Method method, Exception exception,
+            Stack<Collaborator.StackElement> calledInterceptors)
+            throws Throwable {
+        Throwable tobeRethrown = null;
+        while (!calledInterceptors.isEmpty()) {
+            Collaborator.StackElement se = calledInterceptors.pop();
+
+            try {
+                se.interceptor.postCallWithException(cm, method, exception, se
+                        .getPreCallToken());
+            } catch (Throwable t) {
+                // log the exception
+                LOGGER.error("postCallInterceptorWithException", t);
+                if (tobeRethrown == null)
+                    tobeRethrown = t;
+            }
+
+        } // end while
+
+        if (tobeRethrown != null)
+            throw tobeRethrown;
+    }
+
+    // info to store on interceptor stack during invoke
+    private static class StackElement {
+        private Interceptor interceptor;
+        private Object preCallToken;
+
+        private StackElement(Interceptor i) {
+            interceptor = i;
+        }
+
+        private void setPreCallToken(Object preCallToken) {
+            this.preCallToken = preCallToken;
+        }
+
+        private Object getPreCallToken() {
+            return preCallToken;
+        }
+
+    }
+}
\ No newline at end of file

Added: incubator/aries/trunk/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/proxy/WrapperedObject.java
URL: http://svn.apache.org/viewvc/incubator/aries/trunk/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/proxy/WrapperedObject.java?rev=881290&view=auto
==============================================================================
--- incubator/aries/trunk/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/proxy/WrapperedObject.java (added)
+++ incubator/aries/trunk/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/proxy/WrapperedObject.java Tue Nov 17 13:52:29 2009
@@ -0,0 +1,30 @@
+/*
+ * 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.aries.blueprint.proxy;
+
+/**
+ * Interface added to wrapped objects, to enable retrieval of the original object.
+ */
+public interface WrapperedObject {
+    /**
+     * Obtain the object wrapped by this wrapper.
+     * @return unwrapped object.
+     */
+    public Object unwrapObject();
+}