View Javadoc

1   /**
2    *  BlueCove - Java library for Bluetooth
3    *  Copyright (C) 2008 Michael Lifshits
4    *  Copyright (C) 2008 Vlad Skarzhevskyy
5    *
6    *  Licensed to the Apache Software Foundation (ASF) under one
7    *  or more contributor license agreements.  See the NOTICE file
8    *  distributed with this work for additional information
9    *  regarding copyright ownership.  The ASF licenses this file
10   *  to you under the Apache License, Version 2.0 (the
11   *  "License"); you may not use this file except in compliance
12   *  with the License.  You may obtain a copy of the License at
13   *
14   *    http://www.apache.org/licenses/LICENSE-2.0
15   *
16   *  Unless required by applicable law or agreed to in writing,
17   *  software distributed under the License is distributed on an
18   *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
19   *  KIND, either express or implied.  See the License for the
20   *  specific language governing permissions and limitations
21   *  under the License.
22   *
23   *  @author vlads
24   *  @version $Id: RemoteServiceImpl.java 2471 2008-12-01 03:44:20Z skarzhevskyy $
25   */
26  package com.intel.bluetooth.rmi;
27  
28  import java.lang.reflect.InvocationTargetException;
29  import java.lang.reflect.Method;
30  import java.rmi.RemoteException;
31  import java.util.HashMap;
32  import java.util.Map;
33  
34  class RemoteServiceImpl implements RemoteService {
35  
36  	private static final long serialVersionUID = 1L;
37  
38  	private Map<String, Class<?>> cash = new HashMap<String, Class<?>>();
39  
40  	public RemoteServiceImpl() throws RemoteException {
41  	}
42  
43  	private Class<?> getClassByInterfaceName(String interfaceName) throws ClassNotFoundException {
44  		Class<?> c;
45  		synchronized (cash) {
46  			c = cash.get(interfaceName);
47  			if (c == null) {
48  				c = Class.forName(interfaceName + "Impl");
49  				cash.put(interfaceName, c);
50  			}
51  		}
52  		return c;
53  	}
54  
55  	public boolean verify(String interfaceName) throws RemoteException {
56  		try {
57  			getClassByInterfaceName(interfaceName);
58  		} catch (Throwable e) {
59  			throw new RemoteException("Service for " + interfaceName + " not ready", e);
60  		}
61  		return true;
62  	}
63  
64  	public ServiceResponse execute(ServiceRequest request) {
65  		try {
66  			Class<?> c = getClassByInterfaceName(request.getClassName());
67  			Method m = c.getDeclaredMethod(request.getMethodName(), request.getParameterTypes());
68  			ServiceResponse response = new ServiceResponse();
69  			try {
70  				response.setReturnValue(m.invoke(c.newInstance(), request.getParameters()));
71  			} catch (InvocationTargetException e) {
72  				response.setException(e.getTargetException());
73  			}
74  			return response;
75  		} catch (Throwable e) {
76  			return new ServiceResponse(e);
77  		}
78  	}
79  
80  }