KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sun > enterprise > tools > admingui > AdminGUIServlet


1 /*
2  * The contents of this file are subject to the terms
3  * of the Common Development and Distribution License
4  * (the License). You may not use this file except in
5  * compliance with the License.
6  *
7  * You can obtain a copy of the license at
8  * https://glassfish.dev.java.net/public/CDDLv1.0.html or
9  * glassfish/bootstrap/legal/CDDLv1.0.txt.
10  * See the License for the specific language governing
11  * permissions and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL
14  * Header Notice in each file and include the License file
15  * at glassfish/bootstrap/legal/CDDLv1.0.txt.
16  * If applicable, add the following below the CDDL Header,
17  * with the fields enclosed by brackets [] replaced by
18  * you own identifying information:
19  * "Portions Copyrighted [year] [name of copyright owner]"
20  *
21  * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
22  */

23
24 package com.sun.enterprise.tools.admingui;
25
26 import java.io.IOException JavaDoc;
27 import javax.servlet.ServletConfig JavaDoc;
28 import javax.servlet.ServletException JavaDoc;
29 import javax.servlet.ServletRequest JavaDoc;
30 import javax.servlet.http.HttpServletResponse JavaDoc;
31 import javax.servlet.http.HttpServletRequest JavaDoc;
32 import javax.servlet.http.HttpSession JavaDoc;
33
34 import org.xml.sax.EntityResolver JavaDoc;
35
36 import com.iplanet.jato.ModelTypeMap;
37 import com.iplanet.jato.CompleteRequestException;
38 import com.iplanet.jato.RequestContext;
39 import com.iplanet.jato.RequestContextImpl;
40 import com.iplanet.jato.RequestManager;
41 import com.iplanet.jato.view.View;
42
43 import com.sun.enterprise.tools.admingui.util.Util;
44 import com.sun.enterprise.tools.admingui.util.MBeanUtil;
45 import com.sun.enterprise.tools.admingui.util.PreloadXML;
46 import com.sun.enterprise.tools.admingui.handlers.CommonHandlers;
47 import com.sun.enterprise.tools.jsfext.util.ClasspathEntityResolver;
48 import com.sun.enterprise.tools.guiframework.view.BaseServlet;
49 import com.sun.enterprise.tools.guiframework.view.descriptors.ViewDescriptor;
50 import com.sun.enterprise.tools.guiframework.view.event.ErrorEvent;
51 import com.sun.enterprise.tools.guiframework.exception.FrameworkException;
52 import com.sun.enterprise.tools.guiframework.view.ViewXMLEntityResolver;
53 import com.sun.enterprise.tools.guiframework.util.LogUtil;
54
55 import com.sun.web.ui.renderer.template.xml.XMLLayoutDefinitionManager;
56
57 import java.io.File JavaDoc;
58 import java.io.UnsupportedEncodingException JavaDoc;
59 import java.net.URL JavaDoc;
60 import java.util.Enumeration JavaDoc;
61 import java.util.logging.Handler JavaDoc;
62
63 import com.sun.web.ui.common.CCPrivateConfiguration;
64
65 /**
66  *
67  */

68 public class AdminGUIServlet extends BaseServlet {
69     
70     private static final boolean debug = false;
71
72     public AdminGUIServlet() {
73     super();
74     setDefaultHandlerName("TopFrameset");
75         setEnforceStrictSessionTimeout(true);
76         setupConfig();
77
78         // initialize Lockhart
79
CCPrivateConfiguration.setEntityResolver(new LockhartEntityResolver());
80     ((XMLLayoutDefinitionManager) XMLLayoutDefinitionManager.getInstance()).
81         setEntityResolver(new ClasspathEntityResolver());
82     }
83     
84     /**
85      * This method provides a last resort spot to handle any uncaught
86      * exceptions or errors. The preferred way to handle exceptions or errors
87      * is to register and "error" event to dispatch the handling to the
88      * designated handler, however, if that fails or you do not do this, this
89      * method will be invoked. The ErrorEvent that is passed in will contain
90      * information about what went wrong. The View and ViewDescriptor
91      * contained in the Error event may be null as there was no handler
92      * defined to take care of this exception.
93      *
94      * @param errorEvent The ErrorEvent object describing the exception
95      */

96     protected void handleUncaughtException(ErrorEvent errorEvent) {
97     if (Util.isLoggableWARNING()) {
98         Util.logWARNING("Exception NOT handled!", errorEvent.getException());
99     }
100     ViewDescriptor viewDesc = errorEvent.getCauseViewDescriptor();
101     if (Util.isLoggableINFO()) {
102         if (viewDesc != null) {
103         Util.logINFO("Problem near ViewDescriptor: '"+viewDesc.getName()+"'");
104         }
105     }
106     String JavaDoc cause = errorEvent.getCauseMessage();
107     if (Util.isLoggableINFO()) {
108         if (cause != null) {
109         Util.logINFO(cause);
110         }
111     }
112     if (Util.isLoggableINFO()) {
113         Util.logINFO(errorEvent.getRegularTrace());
114     }
115     if (viewDesc != null) {
116         // Find the top ViewDescriptor
117
while (viewDesc.getParent() != null) {
118         viewDesc = viewDesc.getParent();
119         }
120         // Get the View / view name
121
RequestContext ctx = RequestManager.getRequestContext();
122         String JavaDoc redirName = null;
123         View view = null;
124         try {
125         view = viewDesc.getView(ctx);
126         while (view.getParent() != null) {
127             view = view.getParent();
128         }
129         redirName = view.getName();
130         } catch (Exception JavaDoc ex) {
131         if (Util.isLoggableWARNING()) {
132             Util.logWARNING(ex);
133         }
134         redirName = viewDesc.getName();
135         }
136
137         // Send redirect
138
try {
139         ServletRequest JavaDoc req = ctx.getRequest();
140         if (req.getAttribute(UNCAUGHT_REDIR) != null) {
141             // This isn't good, but we don't want an endless loop
142
return;
143         }
144         ctx.getRequest().setAttribute(UNCAUGHT_REDIR, "true");
145         ctx.getResponse().sendRedirect(redirName);
146         } catch (Throwable JavaDoc ex) {
147         if (Util.isLoggableWARNING()) {
148             Util.logWARNING(ex);
149         }
150         }
151     }
152     }
153
154     // Install a new formatter of log message; easier for debugging; not so good
155
// for log reader tools, such as AdminGUI's logViewer.
156
private void changeLogFileFormatter() {
157         Handler JavaDoc[] h = LogUtil._logger.getHandlers();
158         for (int i = 0; i < h.length; i++) {
159             h[i].setFormatter(new PlainFormatter());
160         }
161     }
162
163     /**
164      * This method should return a String URL pointing to the location of the
165      * XML file containing the ViewDescriptor definitions.
166      */

167     protected URL JavaDoc getViewXMLURL() {
168         if (debug)
169             changeLogFileFormatter();
170
171     // Get the viewXML filename
172
String JavaDoc viewXMLFile = ConfigProperties.getInstance().getViewXMLFileName();
173     URL JavaDoc viewXML = null;
174
175     // Attempt to load from the CLASSPATH
176
viewXML = getClass().getClassLoader().getResource(viewXMLFile);
177
178     // The following is mostly for development, XML file outside of the CP
179
if (viewXML == null) {
180         if (Util.isLoggableFINEST()) {
181         Util.logFINEST("Unable to find XML FILE in the CLASSPATH: " +
182             viewXMLFile);
183         }
184             String JavaDoc sURL = "file:///" +
185                 getServletConfig().getServletContext().getRealPath(viewXMLFile);
186             try {
187                 viewXML = new URL JavaDoc(sURL);
188             } catch (Exception JavaDoc exc) {
189                 throw new FrameworkException("Unable to create URL: '"+sURL+
190             "' while attempting to locate '"+viewXMLFile+"'", exc);
191             }
192     }
193     return viewXML;
194     }
195
196     protected EntityResolver JavaDoc getViewXMLEntityResolver() {
197         if (entityResolver == null) {
198             entityResolver = new ViewXMLEntityResolver();
199         }
200         return entityResolver;
201     }
202     
203     /**
204      * This method should return a String to prefix before all JSP paths.
205      * This method may soon be deprecated, I recommend returning "" from this
206      * method to avoid problems later.
207      */

208     protected String JavaDoc getJSPRoot() {
209         return AdminGUIConstants.DEFAULT_DISPLAY_URL_DIR;
210     }
211
212
213     /**
214      * @return The package name of the Servlet.
215      */

216     protected String JavaDoc getPackageName() {
217     return PACKAGE_NAME;
218     }
219
220
221     public void init(ServletConfig JavaDoc config) throws ServletException JavaDoc {
222     // Fix for CR# 6376475, the Admin GUI may not enter through the
223
// login.jsp and therefor may not be initialized. This fix ensures
224
// the ViewDescriptors are loaded. This MUST be done before
225
// super.init() (or it will think its loaded already b/c init()
226
// sets this stuff up.
227
if (!PreloadXML.isAlreadyLoaded()) {
228         // Intentionally NOT running as a seperate Thread
229
new PreloadXML(config).run();
230     }
231
232     super.init(config);
233     MODEL_TYPE_MAP = new ModelTypeMapImpl();
234     }
235     
236     /* DEBUGGING METHODS.....
237     private void printParams(HttpServletRequest request) {
238         System.out.print("pathInfo: "+request.getPathInfo());
239         System.out.print("contextPath: "+request.getContextPath());
240         System.out.print("servletPath: "+request.getServletPath());
241         System.out.print("user agent: "+request.getHeader("USER-AGENT"));
242         System.out.println("");
243         
244         Enumeration enum = request.getParameterNames();
245         while (enum.hasMoreElements()) {
246             String name = (String) enum.nextElement();
247             String value = request.getParameter(name);
248             System.out.print("ReqParam: "+name+"="+value);
249         }
250         System.out.println("");
251         
252         enum = request.getAttributeNames();
253         while (enum.hasMoreElements()) {
254             String name = (String) enum.nextElement();
255             Object value = request.getAttribute(name);
256             System.out.print("ReqAttr: "+name+"="+value);
257         }
258         System.out.println("");
259         
260         enum = getServletConfig().getServletContext().getInitParameterNames();
261         while (enum.hasMoreElements()) {
262             String name = (String) enum.nextElement();
263             String value = request.getParameter(name);
264             System.out.print("initParam: "+name+"="+value);
265         }
266         System.out.println("");
267     }
268     */

269
270     /* setup some config parameters - this would typically be used to control
271      * configuration across different versions of the product */

272     protected void setupConfig() {
273         ConfigProperties config = ConfigProperties.getInstance();
274         config.setViewXMLFileName("xml/viewDescriptor.xml");
275         config.setTreeXMLFileName("xml/treeDescriptor.xml", "index");
276         config.setDefaultDisplayURLDir("/jsp/");
277         config.setTargetSupported(new Boolean JavaDoc(false));
278         config.setInitialRightPage("homePageFrameset");
279         config.setLoggerName("javax.enterprise.system.tools.admin");
280         config.setDefaultTarget("server");
281         config.setConsoleTitleKey("common.consoleTitlePE");
282     }
283     
284     protected void onBeforeRequest(RequestContext requestContext)
285     throws javax.servlet.ServletException JavaDoc {
286         HttpSession JavaDoc session = requestContext.getRequest().getSession();
287         if (session != null) {
288             try {
289                 String JavaDoc timeOutSet = (String JavaDoc)session.getAttribute("AdminGUItimeOut");
290                 if (timeOutSet == null) {
291                     session.setAttribute("AdminGUItimeOut", "true");
292                     CommonHandlers.setTimeOut(requestContext);
293                     // We have a new session. Maybe from a session timeout, then
294
// need to redirect to index.html so that all frames will be drawn.
295
//onSessionTimeout(requestContext);
296
}
297             } catch (CompleteRequestException cre) {
298                 throw new CompleteRequestException();
299             } catch (Exception JavaDoc ex) {
300                 // log any error and keep going ....
301
if (Util.isLoggableINFO()) {
302                     Util.logINFO(ex);
303                 }
304             }
305         }
306     }
307
308     protected void onNewSession(RequestContext requestContext) throws ServletException JavaDoc {
309         super.onNewSession(requestContext);
310         CommonHandlers.setTimeOut(requestContext);
311     }
312         
313     protected void onSessionTimeout(RequestContext requestContext) throws javax.servlet.ServletException JavaDoc {
314     try {
315         String JavaDoc fileName = Util.getLocalizedHTML(requestContext, "/index.html");
316         requestContext.getResponse().sendRedirect(".."+fileName);
317     } catch (IOException JavaDoc ex) {
318         if (Util.isLoggableWARNING()) {
319         Util.logWARNING(ex);
320         }
321     } catch (IllegalStateException JavaDoc ex) {
322         if (Util.isLoggableWARNING()) {
323         Util.logWARNING(ex);
324         }
325     }
326     throw new CompleteRequestException();
327     }
328
329
330     ////////////////////////////////////////////////////////////////////////////////
331
// Servlet methods
332
////////////////////////////////////////////////////////////////////////////////
333

334     /**
335      *
336      *
337      */

338     protected void initializeRequestContext(RequestContext requestContext) {
339     super.initializeRequestContext(requestContext);
340     
341     try {
342         //fix for bugid: 6196436. We can move this fix to sun-web.xml after this release.
343
HttpServletRequest JavaDoc request = requestContext.getRequest();
344         if(request != null) {
345             request.setCharacterEncoding("UTF-8");
346
347             if(request.isSecure()) {
348                 CCPrivateConfiguration.setSecurePort(request.getServerPort());
349                 CCPrivateConfiguration.setSecureHelp(true);
350             }
351         }
352     }
353     catch(UnsupportedEncodingException JavaDoc ex) {
354         if(Util.isLoggableWARNING()) {
355             Util.logWARNING(ex);
356         }
357     }
358
359     // Set a model manager in the request context. This must be
360
// done at the application level because the MODEL_TYPE_MAP
361
// is application specific.
362
com.sun.enterprise.tools.guiframework.model.ModelManager modelManager =
363         new com.sun.enterprise.tools.guiframework.model.ModelManager(
364         requestContext, MODEL_TYPE_MAP);
365     ((RequestContextImpl)requestContext).setModelManager(modelManager);
366     }
367
368
369     /**
370      *
371      *
372      */

373     public String JavaDoc getModuleURL() {
374     // The superclass can be configured from init params specified at
375
// deployment time. If the superclass has been configured with
376
// a different module URL, it will return a non-null value here.
377
// If it has not been configured with a different URL, we use our
378
// (hopefully) sensible default.
379
String JavaDoc result=super.getModuleURL();
380     if (result != null) {
381         return result;
382     }
383     return DEFAULT_MODULE_URL;
384     }
385         
386     public static final String JavaDoc DEFAULT_MODULE_URL = "../admingui";
387     public static String JavaDoc PACKAGE_NAME=getPackageName(AdminGUIServlet.class.getName());
388     protected static final String JavaDoc UNCAUGHT_REDIR = "__uncaughtRedirFlag";
389
390     protected EntityResolver JavaDoc entityResolver;
391     protected static ModelTypeMap MODEL_TYPE_MAP;
392
393     // FIXME: Currently the logging backend is broken such that there is no
394
// FIXME: way to set the this log level via the GUI, so for now I am
395
// FIXME: hard-coding the Level here.
396
static {
397         if (debug)
398             com.sun.enterprise.tools.guiframework.util.LogUtil.setLevel(
399                 com.sun.enterprise.tools.guiframework.util.LogUtil.FINER);
400         else
401             com.sun.enterprise.tools.guiframework.util.LogUtil.setLevel(
402                 com.sun.enterprise.tools.guiframework.util.LogUtil.WARNING);
403     }
404 }
405
Popular Tags