StartBrowser.java
001 package com.bea.medrec.startup;
002 
003 import java.io.IOException;
004 import java.net.Socket;
005 import javax.servlet.ServletContext;
006 import javax.servlet.ServletContextEvent;
007 import javax.servlet.ServletContextListener;
008 import javax.naming.InitialContext;
009 import javax.management.MBeanServer;
010 import javax.management.ObjectName;
011 import weblogic.servlet.internal.WebAppServletContext;
012 
013 /**
014  <p>Example demonstrates the use of ServletContext listeners.</p>
015  *
016  @author Copyright (c) 2003-2006 by BEA Systems, Inc. All Rights Reserved.
017  */
018 public class StartBrowser
019   implements ServletContextListener, Runnable {
020 
021   private Socket socket;
022   private String host = "localhost";
023   private String port = "7101";
024   private String page = "index.jsp";
025   private static int SLEEPTIME = 500;
026 
027   // Used to identify the windows platform.
028   private static final String WIN_ID = "Windows";
029   // The default system browser under windows.
030   private static final String WIN_PATH = "rundll32";
031   // The flag to display a url.
032   private static final String WIN_FLAG = "url.dll,FileProtocolHandler";
033   // The default browser under unix.
034   private static final String UNIX_PATH = "netscape";
035   // The flag to display a url.
036   private static final String UNIX_FLAG = "-remote openURL";
037 
038   // constructors
039   public StartBrowser() {
040   }
041 
042   public StartBrowser(String host, String port, String page) {
043     this.host = host;
044     this.port = port;
045     this.page = page;
046   }
047 
048   public void contextInitialized(ServletContextEvent sce) {
049     ServletContext context = sce.getServletContext();
050     // get page to popup
051     String tempPage = context.getInitParameter("StartBrowser.page");
052     page = (tempPage != null && tempPage.equals(""? tempPage : page);
053 
054     // determine host and port
055     getListenAddressAndPort();
056 
057     // log info msg
058     log(getInfoString(page));
059 
060     // kick it off
061     Thread t = new Thread(new StartBrowser(host, port, page));
062     t.start();
063     return;
064   }
065 
066   public void contextDestroyed(ServletContextEvent sce) { }
067 
068   /**
069   * Loops indefinitely trying to create a socket to host/port
070   * waits sleepTime in between each try.
071   * On a successful socket create, start browser.
072   */
073   public void run() {
074     boolean loop = true;
075     while (loop) {
076       try {
077         // loop thru until webapp is listening
078         socket = new Socket(this.host, new Integer(this.port).intValue());
079         socket.close();
080 
081         //launch browser
082         openBrowser("http://"+this.host+":"+this.port+"/"+this.page);
083 
084         // connection made, stop looping
085         loop = false;
086       catch (Exception e) {
087         try {
088           Thread.sleep(SLEEPTIME)// try every 500 ms
089         catch (InterruptedException ie) {}
090         finally {
091           try {
092             socket.close();
093           catch (Exception se) {}
094         }
095       }
096     }
097   }
098 
099   // The method executing the task
100   public void openBrowser(String url) {
101     boolean windows = isWindowsPlatform();
102     String cmd = null;
103     try {
104       if (windows) {
105         // cmd = 'rundll32 url.dll,FileProtocolHandler http://...'
106         cmd = WIN_PATH+" "+WIN_FLAG+" "+url;
107         Process p = Runtime.getRuntime().exec(cmd);
108       }
109       else {
110         // Under Unix, Netscape has to be running for the "-remote"
111         // command to work.  So, we try sending the command and
112         // check for an exit value.  If the exit command is 0,
113         // it worked, otherwise we need to start the browser.
114         // cmd = 'netscape -remote openURL(url)'
115         cmd = UNIX_PATH+" "+UNIX_FLAG+"("+url+")";
116         Process p = Runtime.getRuntime().exec(cmd);
117 
118         try {
119           // wait for exit code -- if it's 0, command worked,
120           // otherwise we need to start the browser up.
121           int exitCode = p.waitFor();
122           if (exitCode != 0) {
123             // Command failed, start up the browser
124             // cmd = 'netscape url'
125             cmd = UNIX_PATH+" "+url;
126             p = Runtime.getRuntime().exec(cmd);
127           }
128         }
129         catch(InterruptedException x) {
130           System.err.println("Error bringing up browser, cmd='"+cmd+"'.  "+
131               "Please make sure that 'netscape' can open from the cmd-line.\n"+x);
132         }
133       }
134     }
135     catch (IOException x) {
136       // couldn't exec browser
137       System.err.println("Could not invoke browser, command="+cmd+"'.  "+
138           "Windows: Please make sure that default browser can open.  "+
139           "Unix: Please make sure that 'netscape' can open from the cmd-line.\n"+x);
140     }
141   }
142 
143   /**
144    * Try to determine whether this application is running under Windows
145    * or some other platform by examing the "os.name" property.
146    *
147    @return true if this application is running under a Windows OS
148    */
149   public static boolean isWindowsPlatform() {
150     String os = System.getProperty("os.name");
151     if (os != null && os.startsWith(WIN_ID)) return true;
152     else return false;
153   }
154 
155   public String getInfoString(String url) {
156     StringBuffer str = new StringBuffer();
157     str.append("\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
158     str.append("\nAfter the server has booted, your browser should");
159     str.append("\nautomatically launch and point to the ");
160     str.append("\nAvitek Medical Records Sample Application Introduction Page ");
161     str.append("\nrunning on this server. If your browser fails to launch, ");
162     str.append("\npoint your browser to the following URL:");
163     str.append("\n\"http://"+this.host+":"+this.port+"/"+url+"\"");
164     str.append("\nNote: On Unix-based systems, browser defaults to Netscape.");
165     str.append("\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
166     return str.toString();
167   }
168 
169   public void getListenAddressAndPort() {
170     InitialContext ctx = null;
171     String listenAddress = "";
172     Integer listenPort = null;
173     try {
174       ctx = new InitialContext();
175       MBeanServer mbeanServer = (MBeanServer)ctx.lookup(
176           "java:comp/env/jmx/runtime");
177       String runtimeServiceName =  "com.bea:Name=RuntimeService,Type="+
178         "weblogic.management.mbeanservers.runtime.RuntimeServiceMBean";
179 
180       // Create Objectname for the runtime service
181       ObjectName runtimeService = new ObjectName(runtimeServiceName);
182 
183       // Get the ObjectName for the ServerRuntimeMBean
184       ObjectName serverRuntime = (ObjectNamembeanServer.getAttribute(
185           runtimeService,"ServerRuntime");
186 
187       // Get the listen address of the server
188       listenAddress = (StringmbeanServer.getAttribute(serverRuntime,
189           "ListenAddress");
190       listenPort = (IntegermbeanServer.getAttribute(serverRuntime,
191           "ListenPort");
192       if ((listenAddress == null || listenAddress.equals("")
193           || listenPort == null)) {
194         throw new Exception("listenAddress and/or listenPort are null or == \"\"");
195       }
196     catch (Exception e) {
197       System.out.println("Unable to obtain listen address; using default "+
198           "localhost:7101. : "+e.getMessage());
199     }
200     this.host = (listenAddress != null &&
201         !listenAddress.equals(""?
202         listenAddress.substring(listenAddress.indexOf('/')+1this.host);
203     this.port = (listenPort != null ? listenPort.toString() this.port);
204   }
205 
206   private void log(String str) { System.out.println(str)}
207 }