1 4 package org.jfox.ioc.connector; 5 6 import java.io.BufferedInputStream ; 7 import java.io.BufferedOutputStream ; 8 import java.io.ObjectInputStream ; 9 import java.io.PrintStream ; 10 import java.net.Socket ; 11 import java.net.URI ; 12 import java.net.URISyntaxException ; 13 import java.rmi.MarshalledObject ; 14 import java.util.HashMap ; 15 import java.util.Map ; 16 import javax.rmi.PortableRemoteObject ; 17 18 21 22 public class ConnectorHelper { 23 24 27 private static Map connectors = new HashMap (); 28 29 public static ConnectorRemote lookupConnector(String providerURL) { 30 URI uri; 31 try { 32 uri = new URI (providerURL); 33 } 34 catch(URISyntaxException e){ 35 throw new RuntimeException (e); 36 } 37 String host = uri.getHost(); 38 int port = uri.getPort(); 39 String protocol = uri.getScheme(); 40 String key = providerURL; 41 if(connectors.containsKey(key)) { ConnectorRemote remote = (ConnectorRemote) connectors.get(key); 43 try { 44 remote.ping(); 45 return remote; 46 } 47 catch(Throwable e) { 48 connectors.remove(key); 49 e.printStackTrace(); 50 } 51 } 52 53 try { 54 ConnectorRemote stub = lookupConnector(host,port,protocol); 55 connectors.put(key, stub); 56 return stub; 57 } 58 catch(Throwable e) { 59 e.printStackTrace(); 60 connectors.remove(key); 61 return null; 62 } 63 } 64 65 public static ConnectorRemote lookupConnector(String host, int port, String protocol) throws Exception { 66 Socket csocket = new Socket (host, port); 67 PrintStream out = new PrintStream (new BufferedOutputStream (csocket.getOutputStream())); 69 out.println(protocol); 70 out.flush(); 71 72 ObjectInputStream in = new ObjectInputStream (new BufferedInputStream (csocket.getInputStream())); 73 Object obj = in.readObject(); 74 csocket.close(); 75 ConnectorRemote stub; 76 if(obj instanceof MarshalledObject ) { 77 MarshalledObject mobj = (MarshalledObject ) PortableRemoteObject.narrow(obj, MarshalledObject .class); 78 stub = (ConnectorRemote) mobj.get(); 79 } 80 else { 81 stub = (ConnectorRemote) PortableRemoteObject.narrow(obj, ConnectorRemote.class); 82 } 83 stub.ping(); 84 return stub; 85 } 86 87 public static void main(String [] args) { 88 89 } 90 } 91 92 | Popular Tags |