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