001 package railo.cli; 002 003 import java.io.File; 004 import java.net.InetAddress; 005 import java.net.UnknownHostException; 006 import java.rmi.ConnectException; 007 import java.rmi.NotBoundException; 008 import java.rmi.RemoteException; 009 import java.rmi.registry.LocateRegistry; 010 import java.rmi.registry.Registry; 011 import java.rmi.server.RemoteServer; 012 import java.rmi.server.UnicastRemoteObject; 013 import java.util.Map; 014 015 import javax.servlet.ServletException; 016 017 018 //import railo.cli.servlet.ServletConfigImpl; 019 //import railo.cli.servlet.ServletContextImpl; 020 021 public class CLIFactory extends Thread { 022 023 private static final int PORT=8893; 024 private File root; 025 private String servletName; 026 private Map<String, String> config; 027 private long idleTime; 028 029 public CLIFactory(File root, String servletName, Map<String, String> config) { 030 this.root=root; 031 this.servletName=servletName; 032 this.config=config; 033 034 this.idleTime=60000; 035 String strIdle = config.get("idle"); 036 if(strIdle!=null) { 037 try{ 038 idleTime=Long.parseLong(strIdle); 039 } 040 catch(Throwable t){} 041 } 042 } 043 044 @Override 045 public void run() { 046 047 String name=root.getAbsolutePath(); 048 InetAddress current=null; 049 try { 050 current = InetAddress.getLocalHost(); 051 } catch (UnknownHostException e1) { 052 e1.printStackTrace(); 053 return; 054 } 055 try { 056 try { 057 // first try to call existing service 058 invoke(current,name); 059 060 } 061 catch (ConnectException e) { 062 startInvoker(name); 063 invoke(current,name); 064 } 065 } 066 catch (Throwable t) { 067 t.printStackTrace(); 068 } 069 } 070 071 private void invoke(InetAddress current, String name) throws RemoteException, NotBoundException { 072 Registry registry = LocateRegistry.getRegistry(current.getHostAddress(),PORT); 073 CLIInvoker invoker = (CLIInvoker) registry.lookup( name ); 074 invoker.invoke(config); 075 } 076 077 private void startInvoker(String name) throws ServletException, RemoteException { 078 Registry myReg = getRegistry(PORT); 079 CLIInvokerImpl invoker=new CLIInvokerImpl(root, servletName); 080 CLIInvoker stub = (CLIInvoker) UnicastRemoteObject.exportObject( invoker, 0 ); 081 myReg.rebind( name, stub ); 082 if(idleTime>0){ 083 Closer closer = new Closer(myReg,invoker,name,idleTime); 084 closer.setDaemon(false); 085 closer.start(); 086 } 087 } 088 089 public static Registry getRegistry(int port) { 090 Registry registry=null; 091 try { 092 093 registry= LocateRegistry.createRegistry( port ); 094 } 095 catch (RemoteException e) {} 096 097 try { 098 099 if(registry==null)registry= LocateRegistry.getRegistry(port); 100 } 101 catch (RemoteException e) { 102 } 103 104 105 RemoteServer.setLog(System.out ); 106 107 return registry; 108 } 109 }