01: /* JFox, the OpenSource J2EE Application Server
02: *
03: * Copyright (C) 2002 huihoo.com
04: * Distributable under GNU LGPL license
05: * See the GNU Lesser General Public License for more details.
06: */
07:
08: package org.huihoo.jfox.jndi;
09:
10: import java.net.Socket;
11: import java.io.ObjectInputStream;
12: import java.io.BufferedInputStream;
13: import java.util.Map;
14: import java.util.HashMap;
15: import java.rmi.MarshalledObject;
16: import javax.naming.CommunicationException;
17:
18: //import javax.rmi.PortableRemoteObject;
19: //import javax.rmi.CORBA.Stub;
20:
21: //import org.omg.CORBA.ORB;
22:
23: /**
24: * cache and get NamingService
25: *
26: * @author <a href="mailto:young_yy@hotmail.com">Young Yang</a>
27: */
28:
29: class ServiceLocator {
30: private static Map services = new HashMap();
31:
32: // private static ORB orb = ORB.init(new String[0],null);
33:
34: /**
35: * get NamingService Remote Reference from the host:port
36: */
37: public static NamingService getNamingService(String host, int port)
38: throws CommunicationException {
39: if (services.containsKey(genKey(host, port))) { // return from cache
40: try {
41: // return (NamingService)PortableRemoteObject.narrow(((MarshalledObject)services.get(genKey(host,port))).get(),NamingService.class);
42: return (NamingService) (((MarshalledObject) services
43: .get(genKey(host, port))).get());
44: } catch (Exception e) {
45: services.remove(genKey(host, port));
46: e.printStackTrace();
47: throw new CommunicationException(e.getMessage());
48: }
49: } else {
50: try {
51: Socket csocket = new Socket(host, port);
52: ObjectInputStream in = new ObjectInputStream(
53: new BufferedInputStream(csocket
54: .getInputStream()));
55: Object obj = in.readObject();
56: csocket.close();
57: MarshalledObject mobj = (MarshalledObject) obj;
58: NamingService stub = (NamingService) mobj.get();
59: // NamingService stub = (NamingService)PortableRemoteObject.narrow(mobj.get(),NamingService.class);
60: // ((Stub)stub).connect(orb);
61: services.put(genKey(host, port), mobj);
62: return stub;
63: } catch (Exception e) {
64: e.printStackTrace();
65: services.remove(genKey(host, port));
66: throw new CommunicationException(e.getMessage());
67: }
68: }
69: }
70:
71: private static String genKey(String host, int port) {
72: return host + ":" + port;
73: }
74:
75: }
|