KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > opensubsystems > core > www > WebUIServlet


1 /*
2  * Copyright (c) 2003 - 2007 OpenSubsystems s.r.o. Slovak Republic. All rights reserved.
3  *
4  * Project: OpenSubsystems
5  *
6  * $Id: WebUIServlet.java,v 1.16 2007/02/20 04:12:15 bastafidli Exp $
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; version 2 of the License.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20  */

21
22 package org.opensubsystems.core.www;
23
24 import java.io.IOException JavaDoc;
25 import java.util.HashMap JavaDoc;
26 import java.util.Map JavaDoc;
27 import java.util.logging.Logger JavaDoc;
28
29 import javax.servlet.RequestDispatcher JavaDoc;
30 import javax.servlet.ServletConfig JavaDoc;
31 import javax.servlet.ServletException JavaDoc;
32 import javax.servlet.http.HttpServletRequest JavaDoc;
33 import javax.servlet.http.HttpServletResponse JavaDoc;
34 import javax.servlet.http.HttpSession JavaDoc;
35
36 import org.opensubsystems.core.util.CallContext;
37 import org.opensubsystems.core.util.GlobalConstants;
38 import org.opensubsystems.core.util.Log;
39 import org.opensubsystems.core.util.MyTimer;
40
41 /**
42  * Base class for all servlets developed as part of this project, which perform
43  * web form processing or execute an action based on request from the user
44  * interface. It's main responsibility is to provide default implementation if
45  * functionality for form processing is required.
46  *
47  * @version $Id: WebUIServlet.java,v 1.16 2007/02/20 04:12:15 bastafidli Exp $
48  * @author Miro Halas
49  * @code.reviewer Miro Halas
50  * @code.reviewed 1.9 2006/02/24 00:19:55 jlegeny
51  */

52 public class WebUIServlet extends WebSessionServlet
53 {
54    // Configuration settings ///////////////////////////////////////////////////
55

56    /**
57     * Property used to specify page to display messages to user for example
58     * in case of error.
59     */

60    public static final String JavaDoc WEBUI_MESSAGEBOX_PAGE = "oss.webui.messagebox.page";
61
62    /**
63     * Property used to specify stylesheet used to display messages to user for
64     * example in case of error.
65     */

66    public static final String JavaDoc WEBUI_MESSAGEBOX_STYLE_SHEET = "oss.webui.messagebox.css";
67    
68 // /**
69
// * TODO: For Miro: What is this for?
70
// */
71
// public static final String CLOSE_PREVIEW_PAGE = "oss.webui.closepreview.page";
72

73    // Constants ////////////////////////////////////////////////////////////////
74

75    /**
76     * Name of the generic attribute used to pass some string representation of
77     * the current request to the message box page in case it wants to display
78     * some troubleshooting information.
79     */

80    public static final String JavaDoc ORIGINAL_REQUEST_INFO_REQUEST_PARAM = "originalrequest";
81
82    /**
83     * Name of the generic attribute used to pass some data to the rendering page.
84     * Any aditional data can be passed in attributed named "databean2", "databean3",
85     * etc.
86     */

87    public static final String JavaDoc DATA_ATTRIBUTE_REQUEST_PARAM = "databean";
88
89    /**
90     * Name of the attribute used to pass page title to the rendering pages.
91     */

92    public static final String JavaDoc PAGE_TITLE_REQUEST_PARAM = "pagetitle";
93
94    /**
95     * Name of the attribute used to pass flag if the user is logged in.
96     */

97    public static final String JavaDoc LOGGEDIN_REQUEST_PARAM = "loggedin";
98    
99    /**
100     * Name of the attribute used to pass flag if the dialog has to be maximized.
101     */

102    public static final String JavaDoc FORCE_MAXIMIZE_PARAM = "forcemaximize";
103
104    /**
105     * Parameter used to identify form to be processed.
106     * @see #FORM_UNKNOWN_ID
107     * @see #getFormToProcess
108     */

109    public static final String JavaDoc FORM_NAME_REQUEST_PARAM = "FORM_NAME";
110
111    /**
112     * Constants for forms recognized by this servlet
113     * @see #FORM_NAME_REQUEST_PARAM
114     * @see #getFormToProcess
115     */

116    public static final int FORM_UNKNOWN_ID = -1;
117
118    /**
119     * Constants for number of forms recognized by this servlet
120     */

121    public static final int FORM_COUNT_WEBUI = 0;
122
123    // Cached values ////////////////////////////////////////////////////////////
124

125    /**
126     * Logger for this class
127     */

128    private static Logger JavaDoc s_logger = Log.getInstance(WebUIServlet.class);
129
130    /**
131     * Style sheet used for message boxes if any.
132     */

133    protected String JavaDoc m_strMessageStyleSheet;
134    
135    /**
136     * Cache where paths to individual UI pages will be stored once initialized
137     * from configuration file.
138     * We can use notsychronized HashMap instead of synchronized Hashtable
139     * becaue once the map in inialized, it will be read only.
140     * This cache cannot be static since every instance of this servlet
141     * can be configured to use different UI.
142     */

143    private final Map JavaDoc m_mpUIPathCache = new HashMap JavaDoc();
144    
145    /**
146     * Cache where initialized dispatchers to individual UI pages will be stored
147     * once initialized. This is only if they can be cached.
148     * We can use notsychronized HashMap instead of synchronized Hashtable
149     * becaue once the map in inialized, it will be read only.
150     * This cache cannot be static since every instance of this servlet
151     * can be configured to use different UI.
152     */

153    private final Map JavaDoc m_mpUIRendererCache = new HashMap JavaDoc();
154
155    // Attributes ///////////////////////////////////////////////////////////////
156

157    /**
158     * Generated serial version id for this class.
159     */

160    private static final long serialVersionUID = 322547463691937622L;
161
162    // Servlet operations ///////////////////////////////////////////////////////
163

164    /**
165     * {@inheritDoc}
166     */

167    public void init(
168       ServletConfig JavaDoc scConfig
169    ) throws ServletException JavaDoc
170    {
171       super.init(scConfig);
172
173       // Cache this value
174
cacheUIPath(scConfig, WEBUI_MESSAGEBOX_PAGE,
175                   "Path to message box page is not set in property "
176                   + WEBUI_MESSAGEBOX_PAGE);
177 // TODO: For Miro: Remove this if you remove the lines above
178
// cacheUIPath(scConfig, CLOSE_PREVIEW_PAGE,
179
// "Path to close preview page is not set in property "
180
// + CLOSE_PREVIEW_PAGE);
181

182       m_strMessageStyleSheet = WebUtils.readProperty(scConfig,
183                                                      WEBUI_MESSAGEBOX_STYLE_SHEET,
184                                                      null,
185                                                      true);
186       if ((m_strMessageStyleSheet == null) || (m_strMessageStyleSheet.length() == 0))
187       {
188          s_logger.config(WEBUI_MESSAGEBOX_STYLE_SHEET + " = not defined");
189          // Make it null to make checking easy
190
m_strMessageStyleSheet = null;
191       }
192       else
193       {
194          s_logger.config(WEBUI_MESSAGEBOX_STYLE_SHEET + " = "
195                          + m_strMessageStyleSheet);
196       }
197    }
198
199    /**
200     * {@inheritDoc}
201     */

202    public String JavaDoc getServletInfo(
203    )
204    {
205       return this.getClass().getName();
206    }
207
208    // Helper methods for accessing user interface //////////////////////////////
209

210    /**
211     * {@inheritDoc}
212     */

213    protected void preservice(
214       HttpSession JavaDoc hsSession,
215       HttpServletRequest JavaDoc hsrqRequest,
216       HttpServletResponse JavaDoc hsrpResponse,
217       boolean bLoginVerified
218    ) throws ServletException JavaDoc,
219             IOException JavaDoc
220    {
221       super.preservice(hsSession, hsrqRequest, hsrpResponse, bLoginVerified);
222       
223       // All gui application may need to know if the user is logged in or not
224
setLoggedInFlag(hsrqRequest, hsrpResponse);
225    }
226
227    /**
228     * Cache path to portion of user interface by first search servlet configuration
229     * information and if not found then other predefined locations.
230     *
231     * @param scConfig - servlet config to read parameters from
232     * @param strUIID - unique ID of the configuration parameter used to specify
233     * user interface which is URL or path to some kind of
234     * rendering page (e.g. JSP page)
235     * @param strErrorMessage - error message to display if the path doesn't exist
236     * @throws ServletException - problem finding the specified UI
237     */

238    protected final void cacheUIPath(
239       ServletConfig JavaDoc scConfig,
240       String JavaDoc strUIID,
241       String JavaDoc strErrorMessage
242    ) throws ServletException JavaDoc
243    {
244       String JavaDoc strUIPath;
245       
246       strUIPath = WebUtils.readProperty(scConfig, strUIID, null, false);
247       if ((strUIPath != null) && (strUIPath.length() > 0))
248       {
249          // Found something, try to cache it
250
// Cache this value
251
m_mpUIPathCache.put(strUIID, strUIPath);
252          cacheDispatcher(strUIID, strUIPath);
253       }
254       else
255       {
256          throw new ServletException JavaDoc(strErrorMessage);
257       }
258    }
259    
260    /**
261     * Cache dispatcher to given resource if caching is possible.
262     *
263     * @param strUIID - unique ID of the configuration parameter used to specify this UI
264     * @param strUIPath - path to given resource
265     * @throws ServletException - problem finding the specified UI
266     */

267    protected final void cacheDispatcher(
268       String JavaDoc strUIID,
269       String JavaDoc strUIPath
270    ) throws ServletException JavaDoc
271    {
272       if (isDispatcherCachingEnabled())
273       {
274          // Create dispatcher since they can be cached
275
RequestDispatcher JavaDoc rdCachedDispatcher;
276          
277          rdCachedDispatcher = m_scServletContext.getRequestDispatcher(strUIPath);
278          if (rdCachedDispatcher == null)
279          {
280             throw new ServletException JavaDoc("Cannot initialize user interface handler"
281                                         + " specified by property "
282                                         + strUIID + " = " + strUIPath);
283          }
284          else
285          {
286             // Cache the dispatched
287
m_mpUIRendererCache.put(strUIID, rdCachedDispatcher);
288          }
289       }
290    }
291    
292    /**
293     * Get handle to resource responsible for rendering of specified part of UI
294     *
295     * @param strUIID - unique ID of the configuration parameter used to specify
296     * UI to display. This is the same ID previously passed into
297     * cacheUIPath method.
298     * @param hsrqRequest - the servlet request.
299     * @param hsrpResponse - the servlet response.
300     * @throws ServletException - problems displaying UI
301     * @throws IOException - problems displaying UI
302     */

303    protected final void displayUI(
304       String JavaDoc strUIID,
305       HttpServletRequest JavaDoc hsrqRequest,
306       HttpServletResponse JavaDoc hsrpResponse
307    ) throws ServletException JavaDoc,
308              IOException JavaDoc
309    {
310       // In Jetty RequestDispatcher is reusable, e.g. in WebLogic it is not
311
// so this code needs to reflect it
312
RequestDispatcher JavaDoc rdReturn;
313       String JavaDoc strUIPath;
314       MyTimer timer = new MyTimer();
315      
316       if (isDispatcherCachingEnabled())
317       {
318          // Get the cahed copy, it was supposed to be initialized and cached
319
rdReturn = (RequestDispatcher JavaDoc)m_mpUIRendererCache.get(strUIID);
320          
321          if (GlobalConstants.ERROR_CHECKING)
322          {
323             assert rdReturn != null
324                    : "Request dispatcher for " + strUIID + " wasn't cached properly.";
325          }
326       }
327       else
328       {
329          strUIPath = (String JavaDoc)m_mpUIPathCache.get(strUIID);
330
331          if (GlobalConstants.ERROR_CHECKING)
332          {
333             assert strUIPath != null
334                    : "Unknown UI rendered to retrieve " + strUIID;
335          }
336
337          rdReturn = m_scServletContext.getRequestDispatcher(strUIPath);
338          if (rdReturn == null)
339          {
340             throw new ServletException JavaDoc("Cannot initialize user interface handler"
341                                         + " specified by property "
342                                         + strUIID + " = " + strUIPath);
343          }
344       }
345       
346       // When somebody is getting UI rendered, thats a good sign that processing
347
// is done so add error messages to the request
348
hsrqRequest.setAttribute(MessageTag.MESSAGES_REQUEST_PARAM,
349                                CallContext.getInstance().getMessages());
350       
351       if (hsrqRequest.getParameter(FORCE_MAXIMIZE_PARAM) != null)
352       {
353          // set up force maximize flag into the request attribute
354
hsrqRequest.setAttribute(FORCE_MAXIMIZE_PARAM, "true");
355       }
356         
357       rdReturn.forward(hsrqRequest, hsrpResponse);
358       timer.stop();
359       s_logger.fine("Displaying of " + strUIID + " took " + timer.toString());
360    }
361    
362    // Helper methods for generating pages //////////////////////////////////////
363

364    /**
365     * If the user has logged in, this method will set necessary flag to mark
366     * the page that way. User is logged in if the session exists and user name
367     * is set as session attribute. If user is not logged in, the flag will be
368     * set to the flag to false.
369     *
370     * @param hsrqRequest - the servlet request.
371     * @param hsrpResponse - the servlet response.
372     */

373    protected void setLoggedInFlag(
374       HttpServletRequest JavaDoc hsrqRequest,
375       HttpServletResponse JavaDoc hsrpResponse
376    )
377    {
378       HttpSession JavaDoc hsSession;
379       
380       // Don't create new session becaue if the session doesn't exists, user
381
// is not logged in
382
hsSession = hsrqRequest.getSession(false);
383       
384       if (WebSessionUtils.isLoggedIn(hsSession))
385       {
386          hsrqRequest.setAttribute(LOGGEDIN_REQUEST_PARAM, Boolean.TRUE);
387       }
388       else
389       {
390          hsrqRequest.setAttribute(LOGGEDIN_REQUEST_PARAM, Boolean.FALSE);
391       }
392    }
393
394    /**
395     * Display page with a message to the user.
396     *
397     * @param hsrqRequest - the servlet request.
398     * @param hsrpResponse - the servlet response.
399     * @param strPageTitle - title of the message box
400     * @param strMessage - message to display in the message box
401     * @param strProceedURL - what URL to proceed to
402     * @param cause - what was the cause of the problem if any
403     * @throws ServletException - an error has occured while displaying message box
404     * @throws IOException - error writing response
405     */

406    protected void messageBoxPage(
407       HttpServletRequest JavaDoc hsrqRequest,
408       HttpServletResponse JavaDoc hsrpResponse,
409       String JavaDoc strPageTitle,
410       String JavaDoc strMessage,
411       String JavaDoc strProceedURL,
412       Throwable JavaDoc cause
413    ) throws IOException JavaDoc,
414             ServletException JavaDoc
415    {
416       messageBoxPage(hsrqRequest,
417                      hsrpResponse,
418                      strPageTitle,
419                      strMessage,
420                      strProceedURL,
421                      cause,
422                      WEBUI_MESSAGEBOX_PAGE);
423    }
424
425    /**
426     * Display page with a message to the user, when there was a file error.
427     *
428     * @param hsrqRequest - the servlet request.
429     * @param hsrpResponse - the servlet response.
430     * @param strPageTitle - title of the message box
431     * @param strMessage - message to display in the file message box
432     * @param strProceedURL - what URL to proceed to
433     * @param cause - what was the cause of the problem if any
434     * @param strUIPage -
435     * @throws ServletException - an error has occured while displaying file message box
436     * @throws IOException - error writing response
437     */

438    protected void messageBoxPage(
439       HttpServletRequest JavaDoc hsrqRequest,
440       HttpServletResponse JavaDoc hsrpResponse,
441       String JavaDoc strPageTitle,
442       String JavaDoc strMessage,
443       String JavaDoc strProceedURL,
444       Throwable JavaDoc cause,
445       String JavaDoc strUIPage
446    ) throws IOException JavaDoc,
447             ServletException JavaDoc
448    {
449       if (m_strMessageStyleSheet != null)
450       {
451          hsrqRequest.setAttribute(WEBUI_MESSAGEBOX_STYLE_SHEET,
452                                   m_strMessageStyleSheet);
453       }
454       
455       // Include the information about the original request in case we want
456
// to display it on the error page to allow troubleshooting
457
hsrqRequest.setAttribute(ORIGINAL_REQUEST_INFO_REQUEST_PARAM,
458                                WebUtils.debug(hsrqRequest));
459       
460       // Maybe we should reconsider displaying the same page where user
461
// came from but with message in popup window
462
hsrqRequest.setAttribute(DATA_ATTRIBUTE_REQUEST_PARAM,
463                                (strMessage == null) ? "Unknown error has occured."
464                                                     : strMessage);
465       hsrqRequest.setAttribute(PAGE_TITLE_REQUEST_PARAM,
466                                (strPageTitle == null) ? "Unknown error has occured."
467                                                       : strPageTitle);
468       if (strProceedURL != null)
469       {
470          hsrqRequest.setAttribute(DATA_ATTRIBUTE_REQUEST_PARAM + "2",
471                                   strProceedURL);
472       }
473       else
474       {
475          hsrqRequest.setAttribute(DATA_ATTRIBUTE_REQUEST_PARAM + "2",
476                                   WebCommonConstants.DEFAULT_DIRECTORY_WEB_PAGE);
477       }
478       if (cause != null)
479       {
480          hsrqRequest.setAttribute(DATA_ATTRIBUTE_REQUEST_PARAM + "3",
481                                   cause);
482       }
483       displayUI(strUIPage, hsrqRequest, hsrpResponse);
484    }
485
486    // Helper methods for processing forms //////////////////////////////////////
487

488    /**
489     * Examine request and find out what form needs to be processed. Unique number
490     * assigned to the form will be returned
491     *
492     * @param hsrqRequest - the servlet request, which is used to find out
493     * what form needs to be processed
494     * @return int - one of the FORM_XXX constants
495     */

496    protected int getFormToProcess(
497       HttpServletRequest JavaDoc hsrqRequest
498    )
499    {
500       return FORM_UNKNOWN_ID;
501    }
502 }
503
Popular Tags