001/*
002 * Copyright 2002-2018 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.remoting.rmi;
018
019import java.lang.reflect.InvocationTargetException;
020import java.lang.reflect.Method;
021import java.rmi.Remote;
022import java.rmi.RemoteException;
023import java.util.Properties;
024
025import javax.naming.NamingException;
026
027import org.springframework.beans.factory.DisposableBean;
028import org.springframework.beans.factory.InitializingBean;
029import org.springframework.jndi.JndiTemplate;
030import org.springframework.lang.Nullable;
031import org.springframework.util.ReflectionUtils;
032
033/**
034 * Service exporter which binds RMI services to JNDI.
035 * Typically used for RMI-IIOP (CORBA).
036 *
037 * <p>Exports services via the {@link javax.rmi.PortableRemoteObject} class.
038 * You need to run "rmic" with the "-iiop" option to generate corresponding
039 * stubs and skeletons for each exported service.
040 *
041 * <p>Also supports exposing any non-RMI service via RMI invokers, to be accessed
042 * via {@link JndiRmiClientInterceptor} / {@link JndiRmiProxyFactoryBean}'s
043 * automatic detection of such invokers.
044 *
045 * <p>With an RMI invoker, RMI communication works on the {@link RmiInvocationHandler}
046 * level, needing only one stub for any service. Service interfaces do not have to
047 * extend {@code java.rmi.Remote} or throw {@code java.rmi.RemoteException}
048 * on all methods, but in and out parameters have to be serializable.
049 *
050 * <p>The JNDI environment can be specified as "jndiEnvironment" bean property,
051 * or be configured in a {@code jndi.properties} file or as system properties.
052 * For example:
053 *
054 * <pre class="code">&lt;property name="jndiEnvironment"&gt;
055 *       &lt;props>
056 *               &lt;prop key="java.naming.factory.initial"&gt;com.sun.jndi.cosnaming.CNCtxFactory&lt;/prop&gt;
057 *               &lt;prop key="java.naming.provider.url"&gt;iiop://localhost:1050&lt;/prop&gt;
058 *       &lt;/props&gt;
059 * &lt;/property&gt;</pre>
060 *
061 * @author Juergen Hoeller
062 * @since 1.1
063 * @see #setService
064 * @see #setJndiTemplate
065 * @see #setJndiEnvironment
066 * @see #setJndiName
067 * @see JndiRmiClientInterceptor
068 * @see JndiRmiProxyFactoryBean
069 * @see javax.rmi.PortableRemoteObject#exportObject
070 */
071public class JndiRmiServiceExporter extends RmiBasedExporter implements InitializingBean, DisposableBean {
072
073        @Nullable
074        private static Method exportObject;
075
076        @Nullable
077        private static Method unexportObject;
078
079        static {
080                try {
081                        Class<?> portableRemoteObject =
082                                        JndiRmiServiceExporter.class.getClassLoader().loadClass("javax.rmi.PortableRemoteObject");
083                        exportObject = portableRemoteObject.getMethod("exportObject", Remote.class);
084                        unexportObject = portableRemoteObject.getMethod("unexportObject", Remote.class);
085                }
086                catch (Throwable ex) {
087                        // java.corba module not available on JDK 9+
088                        exportObject = null;
089                        unexportObject = null;
090                }
091        }
092
093
094        private JndiTemplate jndiTemplate = new JndiTemplate();
095
096        private String jndiName;
097
098        private Remote exportedObject;
099
100
101        /**
102         * Set the JNDI template to use for JNDI lookups.
103         * You can also specify JNDI environment settings via "jndiEnvironment".
104         * @see #setJndiEnvironment
105         */
106        public void setJndiTemplate(JndiTemplate jndiTemplate) {
107                this.jndiTemplate = (jndiTemplate != null ? jndiTemplate : new JndiTemplate());
108        }
109
110        /**
111         * Set the JNDI environment to use for JNDI lookups.
112         * Creates a JndiTemplate with the given environment settings.
113         * @see #setJndiTemplate
114         */
115        public void setJndiEnvironment(Properties jndiEnvironment) {
116                this.jndiTemplate = new JndiTemplate(jndiEnvironment);
117        }
118
119        /**
120         * Set the JNDI name of the exported RMI service.
121         */
122        public void setJndiName(String jndiName) {
123                this.jndiName = jndiName;
124        }
125
126
127        @Override
128        public void afterPropertiesSet() throws NamingException, RemoteException {
129                prepare();
130        }
131
132        /**
133         * Initialize this service exporter, binding the specified service to JNDI.
134         * @throws NamingException if service binding failed
135         * @throws RemoteException if service export failed
136         */
137        public void prepare() throws NamingException, RemoteException {
138                if (this.jndiName == null) {
139                        throw new IllegalArgumentException("Property 'jndiName' is required");
140                }
141
142                // Initialize and cache exported object.
143                this.exportedObject = getObjectToExport();
144                invokePortableRemoteObject(exportObject);
145
146                rebind();
147        }
148
149        /**
150         * Rebind the specified service to JNDI, for recovering in case
151         * of the target registry having been restarted.
152         * @throws NamingException if service binding failed
153         */
154        public void rebind() throws NamingException {
155                if (logger.isDebugEnabled()) {
156                        logger.debug("Binding RMI service to JNDI location [" + this.jndiName + "]");
157                }
158                this.jndiTemplate.rebind(this.jndiName, this.exportedObject);
159        }
160
161        /**
162         * Unbind the RMI service from JNDI on bean factory shutdown.
163         */
164        @Override
165        public void destroy() throws NamingException, RemoteException {
166                if (logger.isDebugEnabled()) {
167                        logger.debug("Unbinding RMI service from JNDI location [" + this.jndiName + "]");
168                }
169                this.jndiTemplate.unbind(this.jndiName);
170                invokePortableRemoteObject(unexportObject);
171        }
172
173
174        private void invokePortableRemoteObject(@Nullable Method method) throws RemoteException {
175                if (method != null) {
176                        try {
177                                method.invoke(null, this.exportedObject);
178                        }
179                        catch (InvocationTargetException ex) {
180                                Throwable targetEx = ex.getTargetException();
181                                if (targetEx instanceof RemoteException) {
182                                        throw (RemoteException) targetEx;
183                                }
184                                ReflectionUtils.rethrowRuntimeException(targetEx);
185                        }
186                        catch (Throwable ex) {
187                                throw new IllegalStateException("PortableRemoteObject invocation failed", ex);
188                        }
189                }
190        }
191
192}