001/*
002 * Copyright 2002-2017 the original author or authors.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *      https://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package org.springframework.ejb.access;
018
019import java.lang.reflect.InvocationTargetException;
020import java.lang.reflect.Method;
021
022import javax.ejb.CreateException;
023import javax.ejb.EJBLocalHome;
024import javax.ejb.EJBLocalObject;
025import javax.naming.NamingException;
026
027import org.aopalliance.intercept.MethodInvocation;
028
029import org.springframework.lang.Nullable;
030
031/**
032 * Invoker for a local Stateless Session Bean.
033 * Designed for EJB 2.x, but works for EJB 3 Session Beans as well.
034 *
035 * <p>Caches the home object, since a local EJB home can never go stale.
036 * See {@link org.springframework.jndi.JndiObjectLocator} for info on
037 * how to specify the JNDI location of the target EJB.
038 *
039 * <p>In a bean container, this class is normally best used as a singleton. However,
040 * if that bean container pre-instantiates singletons (as do the XML ApplicationContext
041 * variants) you may have a problem if the bean container is loaded before the EJB
042 * container loads the target EJB. That is because by default the JNDI lookup will be
043 * performed in the init method of this class and cached, but the EJB will not have been
044 * bound at the target location yet. The best solution is to set the lookupHomeOnStartup
045 * property to false, in which case the home will be fetched on first access to the EJB.
046 * (This flag is only true by default for backwards compatibility reasons).
047 *
048 * @author Rod Johnson
049 * @author Juergen Hoeller
050 * @see AbstractSlsbInvokerInterceptor#setLookupHomeOnStartup
051 * @see AbstractSlsbInvokerInterceptor#setCacheHome
052 */
053public class LocalSlsbInvokerInterceptor extends AbstractSlsbInvokerInterceptor {
054
055        private volatile boolean homeAsComponent = false;
056
057
058        /**
059         * This implementation "creates" a new EJB instance for each invocation.
060         * Can be overridden for custom invocation strategies.
061         * <p>Alternatively, override {@link #getSessionBeanInstance} and
062         * {@link #releaseSessionBeanInstance} to change EJB instance creation,
063         * for example to hold a single shared EJB instance.
064         */
065        @Override
066        @Nullable
067        public Object invokeInContext(MethodInvocation invocation) throws Throwable {
068                Object ejb = null;
069                try {
070                        ejb = getSessionBeanInstance();
071                        Method method = invocation.getMethod();
072                        if (method.getDeclaringClass().isInstance(ejb)) {
073                                // directly implemented
074                                return method.invoke(ejb, invocation.getArguments());
075                        }
076                        else {
077                                // not directly implemented
078                                Method ejbMethod = ejb.getClass().getMethod(method.getName(), method.getParameterTypes());
079                                return ejbMethod.invoke(ejb, invocation.getArguments());
080                        }
081                }
082                catch (InvocationTargetException ex) {
083                        Throwable targetEx = ex.getTargetException();
084                        if (logger.isDebugEnabled()) {
085                                logger.debug("Method of local EJB [" + getJndiName() + "] threw exception", targetEx);
086                        }
087                        if (targetEx instanceof CreateException) {
088                                throw new EjbAccessException("Could not create local EJB [" + getJndiName() + "]", targetEx);
089                        }
090                        else {
091                                throw targetEx;
092                        }
093                }
094                catch (NamingException ex) {
095                        throw new EjbAccessException("Failed to locate local EJB [" + getJndiName() + "]", ex);
096                }
097                catch (IllegalAccessException ex) {
098                        throw new EjbAccessException("Could not access method [" + invocation.getMethod().getName() +
099                                "] of local EJB [" + getJndiName() + "]", ex);
100                }
101                finally {
102                        if (ejb instanceof EJBLocalObject) {
103                                releaseSessionBeanInstance((EJBLocalObject) ejb);
104                        }
105                }
106        }
107
108        /**
109         * Check for EJB3-style home object that serves as EJB component directly.
110         */
111        @Override
112        protected Method getCreateMethod(Object home) throws EjbAccessException {
113                if (this.homeAsComponent) {
114                        return null;
115                }
116                if (!(home instanceof EJBLocalHome)) {
117                        // An EJB3 Session Bean...
118                        this.homeAsComponent = true;
119                        return null;
120                }
121                return super.getCreateMethod(home);
122        }
123
124        /**
125         * Return an EJB instance to delegate the call to.
126         * Default implementation delegates to newSessionBeanInstance.
127         * @throws NamingException if thrown by JNDI
128         * @throws InvocationTargetException if thrown by the create method
129         * @see #newSessionBeanInstance
130         */
131        protected Object getSessionBeanInstance() throws NamingException, InvocationTargetException {
132                return newSessionBeanInstance();
133        }
134
135        /**
136         * Release the given EJB instance.
137         * Default implementation delegates to removeSessionBeanInstance.
138         * @param ejb the EJB instance to release
139         * @see #removeSessionBeanInstance
140         */
141        protected void releaseSessionBeanInstance(EJBLocalObject ejb) {
142                removeSessionBeanInstance(ejb);
143        }
144
145        /**
146         * Return a new instance of the stateless session bean.
147         * Can be overridden to change the algorithm.
148         * @throws NamingException if thrown by JNDI
149         * @throws InvocationTargetException if thrown by the create method
150         * @see #create
151         */
152        protected Object newSessionBeanInstance() throws NamingException, InvocationTargetException {
153                if (logger.isDebugEnabled()) {
154                        logger.debug("Trying to create reference to local EJB");
155                }
156                Object ejbInstance = create();
157                if (logger.isDebugEnabled()) {
158                        logger.debug("Obtained reference to local EJB: " + ejbInstance);
159                }
160                return ejbInstance;
161        }
162
163        /**
164         * Remove the given EJB instance.
165         * @param ejb the EJB instance to remove
166         * @see javax.ejb.EJBLocalObject#remove()
167         */
168        protected void removeSessionBeanInstance(@Nullable EJBLocalObject ejb) {
169                if (ejb != null && !this.homeAsComponent) {
170                        try {
171                                ejb.remove();
172                        }
173                        catch (Throwable ex) {
174                                logger.warn("Could not invoke 'remove' on local EJB proxy", ex);
175                        }
176                }
177        }
178
179}