1 /*
2 * #%L
3 * Nuiton Utils
4 * %%
5 * Copyright (C) 2004 - 2010 CodeLutin
6 * %%
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Lesser General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Lesser Public License for more details.
16 *
17 * You should have received a copy of the GNU General Lesser Public
18 * License along with this program. If not, see
19 * <http://www.gnu.org/licenses/lgpl-3.0.html>.
20 * #L%
21 */
22 package org.nuiton.util.rmi;
23
24 import java.lang.reflect.InvocationTargetException;
25 import java.lang.reflect.Method;
26 import java.rmi.RemoteException;
27
28 /**
29 * RMI implementation of an invocation handler. This object will be exported to
30 * a RMI registry and will delegate method calls to some business service. The
31 * service is provided in the constructor.
32 *
33 * @author Arnaud Thimel - thimel@codelutin.com
34 */
35 public class RemoteMethodExecutorImpl<T> implements RemoteMethodExecutor {
36
37 /** The target service on which calls will be made */
38 protected T service;
39
40 /**
41 * This is the only available constructor. It is mandatory to specify a
42 * target service on which call will be
43 * delegated.
44 *
45 * @param service the mandatory service which calls will be delegated on
46 */
47 public RemoteMethodExecutorImpl(T service) {
48 if (service == null) {
49 throw new NullPointerException("Service cannot be null");
50 }
51 this.service = service;
52 }
53
54 @Override
55 public Object execute(
56 String methodName, Class<?>[] parametersType, Object[] args)
57 throws RemoteException {
58
59 Object result;
60 try {
61
62 // Get the method on the target service then invoke it
63 Method method = service.getClass().getMethod(
64 methodName, parametersType);
65 result = method.invoke(service, args);
66
67 } catch (InvocationTargetException ite) {
68 // This is the normal behaviour if a business exception is thrown
69 Throwable targetException = ite.getTargetException();
70 throw new RemoteException(
71 "Business exception occurred", targetException);
72 } catch (NoSuchMethodException nsme) {
73 throw new RemoteException("Delegate method not found", nsme);
74 } catch (IllegalAccessException iae) {
75 throw new RemoteException("Delegate method not accessible", iae);
76 }
77
78 return result;
79 }
80
81 }