summaryrefslogtreecommitdiffstats
path: root/sca-java-2.x/tags/2.0.1-RC1/modules/binding-ejb-runtime/src/main/java/org/apache/tuscany/sca/binding/ejb/util/EJBHandler.java
blob: c7c0f907100ccf6207e6acbfb36f201dc5d29b68 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
/*
 * 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.tuscany.sca.binding.ejb.util;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.rmi.RemoteException;
import java.util.HashMap;
import java.util.Map;

import javax.ejb.EJBObject;
import javax.rmi.CORBA.Util;

import org.apache.tuscany.sca.binding.ejb.corba.ClassLoadingUtil;
import org.omg.CORBA.ORB;
import org.omg.CORBA.SystemException;
import org.omg.CORBA.portable.ApplicationException;
import org.omg.CORBA.portable.ObjectImpl;
import org.omg.CORBA.portable.RemarshalException;
import org.omg.CORBA.portable.ServantObject;
import org.omg.CORBA_2_3.portable.InputStream;
import org.omg.CORBA_2_3.portable.OutputStream;
import org.oasisopen.sca.ServiceRuntimeException;

/**
 * EJBMessageHandler
 *
 * @version $Rev$ $Date$
 */
public class EJBHandler {
    private static final Map<String, Class> PRIMITIVE_TYPES = new HashMap<String, Class>();
    static {
        PRIMITIVE_TYPES.put("boolean", boolean.class);
        PRIMITIVE_TYPES.put("byte", byte.class);
        PRIMITIVE_TYPES.put("char", char.class);
        PRIMITIVE_TYPES.put("short", short.class);
        PRIMITIVE_TYPES.put("int", int.class);
        PRIMITIVE_TYPES.put("long", long.class);
        PRIMITIVE_TYPES.put("float", float.class);
        PRIMITIVE_TYPES.put("double", double.class);
        PRIMITIVE_TYPES.put("void", void.class);
    }

    private Object ejbStub;

    private InterfaceInfo interfaceInfo;
    private Class ejbInterface;

    public EJBHandler(NamingEndpoint namingEndpoint, Class ejbInterface) {
        this(namingEndpoint, InterfaceInfo.getInstance(ejbInterface));
        this.ejbInterface = ejbInterface;
    }

    // locates the stub
    private EJBHandler(NamingEndpoint namingEndpoint, InterfaceInfo ejbInterface) {
        try {
            this.ejbStub = EJBStubHelper.lookup(namingEndpoint, ejbInterface);
            this.interfaceInfo = ejbInterface;
        } catch (Exception e) {
            throw new ServiceRuntimeException(e);
        }
    }

    private static Class loadClass(final String name) {
        try {
            return ClassLoadingUtil.loadClass(name, Thread.currentThread().getContextClassLoader());
        } catch (ClassNotFoundException e) {
            throw new ServiceRuntimeException(e);
        }
    }

    // invokes EJB method
    public Object invoke(String methodName, Object[] args) {
        Object response = null;
        try {
            if (ejbStub instanceof ObjectImpl) {
                ObjectImpl objectImpl = (ObjectImpl)ejbStub;
                // TODO: If the Java 2 security is turned on, then
                // the ORB will try to create proxy
                // from the interfaces defined on the stub
                if (System.getSecurityManager() == null && objectImpl._is_local()) {
                    /*
                     * CORBA.Stub is what the object from JNDI will be for a
                     * remote EJB in the same JVM as the client, but with no
                     * stub classes available on the client
                     */
                    response = invokeLocalCORBACall(objectImpl, methodName, args);
                } else {
                    /*
                     * _EJBObject_Stub is what the object from JNDI will be for
                     * a remote EJB with no stub classes available on the client
                     */
                    response = invokeRemoteCORBACall(objectImpl, methodName, args);
                }
            } else {
                /*
                 * A generated ejb stub or it must be an EJB in the same ear as
                 * the client or an AppServer with a single ClassLoader, so
                 * reflection can be used directly on the JNDI
                 */
                JavaReflectionAdapter reflectionAdapter =
                    JavaReflectionAdapter.createJavaReflectionAdapter(ejbStub.getClass());
                try {
                    Method method = reflectionAdapter.getMethod(methodName);
                    response = method.invoke(ejbStub, args);
                } catch (InvocationTargetException e) {
                    Throwable t = e.getTargetException();
                    // FIXME need to throw really a business exception.
                    // ServiceBusinessException?
                    // Tuscany core doesn't have ServiceBusinessException
                    throw new ServiceRuntimeException(t);
                }
            }

            return response;
        } catch (Exception e) {
            // FIXME this be business exception? Tuscany core doesn't have
            // ServiceBusinessException
            throw new ServiceRuntimeException(e);

        } catch (Throwable e) {
            throw new ServiceRuntimeException(e);
        }
    }

    /**
     * Get the IDL operation name for a java method
     * 
     * @param methodName java method name
     * @return The IDL operation name
     */
    private String getOperation(String methodName) {
        if (interfaceInfo == null) {
            return methodName;
        }
        MethodInfo methodInfo = interfaceInfo.getMethod(methodName);
        if (methodInfo != null) {
            return methodInfo.getIDLName();
        } else {
            return null;
        }
    }

    /*
     * Derive the EJB interface name from the Stub When loading a stub class
     * corresponding to an interface or class <packagename>.<typename>, the
     * class <packagename>._<typename>_Stub shall be used if it exists;
     * otherwise, the class org.omg.stub.<packagename>._<typename>_Stub shall
     * be used.
     */
    private static String getInterface(String stubName) {
        int index = stubName.lastIndexOf('.');
        String packageName = null;
        String typeName = stubName;
        if (index != -1) {
            packageName = stubName.substring(0, index);
            if (packageName.startsWith("org.omg.stub.")) {
                packageName = packageName.substring("org.omg.stub.".length());
            }
            typeName = stubName.substring(index + 1);
        }
        if (typeName.startsWith("_") && typeName.endsWith("_Stub")) {
            typeName = typeName.substring(1, typeName.length() - "_Stub".length());
        }
        if (packageName != null)
            return packageName + "." + typeName;
        else
            return typeName;
    }

    /**
     * Invoke a method on the local CORBA object
     * 
     * @param stub
     * @param methodName
     * @param args
     * @return
     * @throws RemoteException
     * @throws ServiceBusinessException
     */
    private Object invokeLocalCORBACall(final ObjectImpl stub, String methodName, Object[] args)
        throws RemoteException {

        final String operation = getOperation(methodName);

        Class type = loadClass(getInterface(stub.getClass().getName()));
        if (type == null)
            type = (ejbInterface != null) ? ejbInterface : EJBObject.class;

        ServantObject so = stub._servant_preinvoke(operation, type);
        if (so == null) {
            // The Servant is not local any more
            return invokeRemoteCORBACall(stub, methodName, args);
        }
        Object[] newArgs = null;
        ORB orb = stub._orb();
        try {
            if (args != null)
                newArgs = Util.copyObjects(args, orb);
            JavaReflectionAdapter reflectionAdapter =
                JavaReflectionAdapter.createJavaReflectionAdapter(so.servant.getClass());
            Method method = reflectionAdapter.getMethod(methodName);
            Object obj = reflectionAdapter.invoke(method, so.servant, newArgs);
            Object result = Util.copyObject(obj, orb);
            return result;

        } catch (InvocationTargetException e) {
            Throwable exCopy = (Throwable)Util.copyObject(e.getTargetException(), orb);
            MethodInfo methodInfo = interfaceInfo.getMethod(methodName);
            String[] exceptionTypes = methodInfo.getExceptionTypes();
            for (int i = 0; i < exceptionTypes.length; i++) {
                Class exceptionType =
                    methodInfo.getMethod() != null ? methodInfo.getMethod().getExceptionTypes()[i]
                        : loadClass(exceptionTypes[i]);
                if (exceptionType.isAssignableFrom(exCopy.getClass()))
                    throw new ServiceRuntimeException(exCopy); // FIXME should
                // be business
                // exception?
            }
            throw Util.wrapException(exCopy);
        } catch (Throwable e) {
            // Other exceptions thrown from "invoke"
            throw new ServiceRuntimeException(e);
        } finally {
            stub._servant_postinvoke(so);
        }
    }

    /**
     * Invoke a method on a remote CORBA object
     * 
     * @param stub The remote stub
     * @param methodName The name of the method
     * @param args Argument list
     * @return
     * @throws RemoteException
     * @throws ServiceBusinessException
     */
    private Object invokeRemoteCORBACall(ObjectImpl stub, String methodName, Object[] args) throws RemoteException {

        try {
            String operation = getOperation(methodName);

            MethodInfo methodInfo = interfaceInfo.getMethod(methodName);
            if (methodInfo == null) {
                throw new ServiceRuntimeException("Invalid Method " + methodName);
            }
            Class[] parameterTypes = null;
            Class returnType = null;
            if (methodInfo.getMethod() != null) {
                parameterTypes = methodInfo.getMethod().getParameterTypes();
                returnType = methodInfo.getMethod().getReturnType();
            } else {
                String[] types = methodInfo.getParameterTypes();
                if (args != null) {
                    if (types.length != args.length)
                        throw new ServiceRuntimeException(
                                                          "The argument list doesn't match the method signature of " + methodName);
                }

                parameterTypes = new Class[types.length];
                for (int i = 0; i < types.length; i++) {
                    parameterTypes[i] = loadClass(types[i]);
                }
                returnType = loadClass(methodInfo.getReturnType());
            }

            InputStream in = null;
            try {
                OutputStream out = (OutputStream)stub._request(operation, true);

                for (int i = 0; i < parameterTypes.length; i++) {
                    // Object arg = (args.length < i) ? null : args[i];
                    writeValue(out, args[i], parameterTypes[i]);
                }
                if (returnType == void.class) {
                    // void return
                    stub._invoke(out);
                    return null;
                } else {
                    // read the return value
                    in = (InputStream)stub._invoke(out);
                    Object response = readValue(in, returnType);
                    return response;
                }

            } catch (ApplicationException ex) {
                in = (InputStream)ex.getInputStream();
                try {
                    org.apache.tuscany.sca.binding.ejb.corba.Java2IDLUtil.throwException(methodInfo.getMethod(), in);
                    return null;
                } catch (Throwable e) {
                    throw new RemoteException(e.getMessage(), e);
                }
            } catch (RemarshalException ex) {
                return invokeRemoteCORBACall(stub, methodName, args);
            } finally {
                stub._releaseReply(in);
            }
        } catch (SystemException ex) {
            throw Util.mapSystemException(ex);
        }
    }

    /**
     * @param out
     * @param value
     * @param type
     */
    private void writeValue(OutputStream out, Object value, Class type) {
        org.apache.tuscany.sca.binding.ejb.corba.Java2IDLUtil.writeObject(type, value, out);
    }

    /**
     * @param in
     * @param type
     * @return
     */
    private Object readValue(InputStream in, Class type) {
        return org.apache.tuscany.sca.binding.ejb.corba.Java2IDLUtil.readObject(type, in);
    }
}