KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > lutris > airsent > presentation > BasePO


1 /*
2  * Copyright (c) 1999-2001 Lutris Technologies, Inc. All Rights
3  * Reserved.
4  *
5  * This source code file is distributed by Lutris Technologies, Inc. for
6  * use only by licensed users of product(s) that include this source
7  * file. Use of this source file or the software that uses it is covered
8  * by the terms and conditions of the Lutris Enhydra Development License
9  * Agreement included with this product.
10  *
11  * This Software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF
12  * ANY KIND, either express or implied. See the License for the specific terms
13  * governing rights and limitations under the License.
14  *
15  * Contributor(s):
16  *
17  * $Id: BasePO.java,v 1.1 2004/08/16 09:33:16 slobodan Exp $
18  */

19
20 package com.lutris.airsent.presentation;
21
22 import com.lutris.airsent.spec.address.*;
23 import com.lutris.airsent.spec.address.*;
24
25 import com.lutris.airsent.*;
26
27 import com.lutris.appserver.server.StandardAppUtil;
28 import org.enhydra.xml.xmlc.XMLObject;
29 import com.lutris.appserver.server.httpPresentation.*;
30 import com.lutris.appserver.server.session.*;
31 import com.lutris.appserver.server.Enhydra;
32 //import com.lutris.xml.xmlc.*;
33
//import com.lutris.xml.xmlc.html.*;
34
import com.lutris.logging.*;
35 import com.lutris.util.KeywordValueException;
36 import com.lutris.appserver.server.user.User;
37 import org.w3c.dom.*;
38 import org.w3c.dom.html.HTMLElement;
39 import java.lang.reflect.*;
40 import java.util.*;
41
42
43
44 /**
45  * This is the parent Presentaion object. All presentation objects
46  * should extend this class.
47  *
48  * The run method looks for an event parameter and then calls
49  * handle<EventName>. If the "event" Parameter is not defined then
50  * the handleDefault() method is called in your child class.
51  *
52  * @author
53  * @version
54  */

55 public abstract class BasePO implements HttpPresentation {
56     private static String JavaDoc EVENT = "event";
57     private static String JavaDoc STANDARD_METHOD_PREFIX = "handle";
58
59     /**
60      * This is the procedure that is called if there is no "event"
61      * HTTP parameter found. It must be overriden by the subclass to
62      * do default processing or error checking/handling.
63      *
64      * @return String The String representation of the HTML or (other format)
65      * of the document to be displayed. This method would need to be changed
66      * if you wanted to return binary data as well. It returns a String
67      * for simplicity right now.
68      */

69     public abstract XMLObject handleDefault()
70         throws HttpPresentationException;
71
72     /**
73      * This method should be implemented in the subclass so that it returns
74      * the authorization level necessary to access the po.
75      */

76     abstract protected int getRequiredAuthLevel();
77
78     /**
79      * Saved input and output context, and session data
80      */

81     protected HttpPresentationComms myComms = null;
82     protected AirSentSessionData mySessionData = null;
83
84     /**
85      * Gets HttpPresentation object
86      *
87      * @return The saved comms objects
88      * to whichever subclass needs it
89      */

90     public HttpPresentationComms getComms() {
91     return this.myComms;
92     }
93
94     /**
95      * Gets the session data
96      *
97      * @return session data
98      */

99     public AirSentSessionData getSessionData() {
100     return this.mySessionData;
101     }
102
103     /**
104      * This implements the run method in HttpPresentation.
105      *
106      * @param HttpPresentationComms
107      * @exception Exception
108      */

109     public void run(HttpPresentationComms comms) throws Exception JavaDoc {
110     
111     // Reroute based on content.
112
rerouteForContent(comms);
113
114     // Initialize new or get the existing session data
115
initSessionData(comms);
116
117     // Check if the user can access the given page.
118
checkAuthLevel();
119
120     try {
121         
122         // Handle the incoming event request
123
handleEvent(comms);
124     } catch (Exception JavaDoc e) {
125         System.err.println("EXCEPTION: " + e);
126         throw new Exception JavaDoc("Exception in run " + e);
127     }
128     }
129
130     /**
131      * Method that determines which content to output based on
132      * the accept type.
133      * Current types:
134      * text/html
135      * text/xml
136      * text/vnd.wap.wml
137      *
138      *
139      */

140     protected void rerouteForContent(HttpPresentationComms comms)
141         throws AirSentPresentationException {
142     DeviceUtils.rerouteForContent(comms);
143     }
144
145     /**
146      * Method to get or create the AirSentSessionData object from the user session
147      * This object is saved in the AirSentPresentation object
148      *
149      * @param HttpPresentationComms
150      * @exception Exception
151      */

152     protected void initSessionData(HttpPresentationComms comms)
153         throws AirSentPresentationException {
154
155     this.myComms = comms;
156     try {
157         Object JavaDoc obj = comms.sessionData.get(AirSentSessionData.SESSION_KEY);
158
159         // If we found the session data, save it in a private data member
160
if (obj != null) {
161         this.mySessionData = (AirSentSessionData) obj;
162         } else {
163         // If no session data was found, create a new session data instance
164
this.mySessionData = new AirSentSessionData();
165         comms.sessionData.set(AirSentSessionData.SESSION_KEY, this.mySessionData);
166         }
167     } catch (KeywordValueException ex) {
168         throw new AirSentPresentationException("Trouble initializing user", ex);
169     }
170     }
171
172     /**
173      * Checks the session data for a Student, if not there then redirects to the login page
174      * return the current authorization level (set during login)
175      *
176      * @return an int equal to the current authorization level.
177      */

178     protected int getCurrentAuthLevel()
179         throws ClientPageRedirectException, AirSentPresentationException {
180     int accessLevel = 0;
181
182     try {
183         accessLevel = getSessionData().getUserAuth();
184     } catch (Exception JavaDoc ex) {
185         throw new AirSentPresentationException("Trouble getting current authorization level",
186                            ex);
187     }
188
189     return accessLevel;
190     }
191
192     /**
193      * Checks the session data to see if the user has the authorization to
194      * access the given page. Authorization levels include:
195      * UNAUTH_USER (0) -- login not required.
196      * CUSTOMER_USER (1) -- login as customer required.
197      * MESSENGER_USER (2) -- login as messenger required.
198      * ADMIN_USER (3) -- login as administrator required.
199      *
200      * SIDE EFFECTS: redirects to login page if user not authorized to access page.
201      */

202     protected void checkAuthLevel()
203         throws ClientPageRedirectException, AirSentPresentationException {
204     int currentAuth = getCurrentAuthLevel();
205
206     try {
207 //We need to allow AirSent_pres to be functional , so if the requested url is /AirSent_pres/ we allow user to acsses to page
208

209     String JavaDoc uri = myComms.request.getRequestURI();
210         boolean is= uri.startsWith("/AirSent_pres");
211
212 if(!is){
213
214    if (currentAuth < getRequiredAuthLevel()) {
215         if (currentAuth > AirSentConstants.CUSTOMER_USER) {
216             throw new ClientPageRedirectException(AirSentConstants.ADMIN_LOGIN_PAGE);
217         }
218
219         throw new ClientPageRedirectException("/" + AirSentConstants.HTML_PAGE);
220         }
221     
222    }
223 } catch (Exception JavaDoc ex) {
224         throw new AirSentPresentationException("Trouble checking for user login status",
225                            ex);
226     }
227     }
228
229     /**
230      * Method to call the proper method for the incoming event
231      *
232      * @param HttpPresentationComms
233      * @exception Exception
234      */

235     public void handleEvent(HttpPresentationComms comms) throws Exception JavaDoc {
236     String JavaDoc event = comms.request.getParameter(EVENT);
237     XMLObject returnDoc = null;
238     try {
239         if (event == null || event.length() == 0) {
240         returnDoc = handleDefault();
241         } else {
242         returnDoc = getPage(event);
243         }
244         comms.response.writeDOM(returnDoc);
245     } catch (Exception JavaDoc e) {
246         throw new Exception JavaDoc("Exception writing dom:" + e);
247     }
248     }
249
250     /**
251      * this logs out a user from the session. it first grabs
252      * an instance of the sessionData associated with the request
253      * and then sets the user to null in the session data.
254      *
255      * @param HttpServletRequest request - this is the request that
256      * the session data is extracted from.
257      *
258      * @exception AirSentPresentationException when an error occurs or if
259      * the session data for the request is null.
260      */

261     public XMLObject handleLogout() throws AirSentPresentationException {
262     try {
263         mySessionData = null;
264             SessionManager sessionManager = myComms.session.getSessionManager();
265             sessionManager.deleteSession(myComms.session);
266         throw new ClientPageRedirectException(AirSentConstants.HTML_PAGE);
267     } catch (Exception JavaDoc e) {
268         throw new AirSentPresentationException("Trouble logging out user",
269                            e);
270     }
271     }
272
273     /**
274      * If an event parameter is defined then this invokes the method that
275      * handles that event.
276      *
277      * @param event, the incoming event name
278      * @exception Exception
279      */

280     public XMLObject getPage(String JavaDoc event) throws Exception JavaDoc {
281     try {
282         Method method = this.getClass().getMethod(toMethodName(event),
283                                                          null);
284         XMLObject thePage = (XMLObject) method.invoke(this, null);
285
286         return thePage;
287     } catch (InvocationTargetException ex) {
288
289         // Rethrow the originating exception if as it should be propagated as is
290
// It could be a page redirect exception, etc.
291
if (ex.getTargetException() instanceof Exception JavaDoc) {
292         throw (Exception JavaDoc) ex.getTargetException();
293         } else if (ex.getTargetException() instanceof Error JavaDoc) {
294         throw (Error JavaDoc) ex.getTargetException();
295         } else {
296         throw ex;
297         }
298     } catch (NoSuchMethodException JavaDoc ex) {
299
300         // The method to handle the event does not exist.
301
throw new AirSentPresentationException("NO EVENT HANDLER FOUND FOR EVENT: "
302                            + event, ex);
303     } catch (IllegalAccessException JavaDoc ex) {
304
305         // The method to handle the event does not exist.
306
throw new AirSentPresentationException("ILLEGAL ACCESS TO EVENT HANDLER (is it public?): "
307                            + event, ex);
308     }
309     }
310
311     /**
312      * Gets the URI prefix. Special because some devices incorrectly
313      * handle this.
314      *
315      */

316     protected String JavaDoc getURIPrefix() throws AirSentPresentationException {
317     try {
318         String JavaDoc scheme = myComms.request.getScheme();
319         String JavaDoc serverName = myComms.request.getServerName();
320         int serverPort = myComms.request.getServerPort();
321         String JavaDoc applicationPath = myComms.request.getApplicationPath();
322
323         // don't include default port in the full path
324
if (serverPort == 80) {
325         return scheme + "://" + serverName + applicationPath;
326         } else {
327         return scheme + "://" + serverName + ":" + serverPort
328                     + applicationPath;
329         }
330     } catch (Exception JavaDoc ex) {
331         throw new AirSentPresentationException("Can't get Server Root Name "
332                            + "Config file.", ex);
333     }
334     }
335
336     /**
337      * This sets the first letter of the event parameter value in order
338      * to adhere to Java method naming conventions.
339      *
340      * @param String event the incoming name of the event
341      * @return String the properly capitalized name
342      */

343     private String JavaDoc toMethodName(String JavaDoc event) {
344     StringBuffer JavaDoc methodName = new StringBuffer JavaDoc(STANDARD_METHOD_PREFIX);
345
346     methodName.append(Character.toUpperCase(event.charAt(0)));
347
348     if (event.length() > 1) {
349         methodName.append(event.substring(1));
350     }
351
352     return methodName.toString();
353     }
354
355     /**
356      * Returns the application object associated with the
357      * current request.
358      *
359      * @return the application object.
360      */

361     public AirSent getApplication() {
362     return (AirSent) Enhydra.getApplication();
363     }
364
365     /**
366      * Method to write a debugging message to the debug log
367      * channel when the DEBUG flag is turned on
368      *
369      * @param msg The message to write to the DEBUG log channel
370      */

371     public static void writeDebugMsg(String JavaDoc msg) {
372     Enhydra.getLogChannel().write(Logger.DEBUG, msg);
373     }
374
375
376     /**
377      * Returns true if the given string is null, empty, or contains
378      * only white space.
379      */

380     protected static boolean isNullField(String JavaDoc field) {
381     if (field == null) {
382         return true;
383     }
384
385     if (field.trim().equals("")) {
386         return true;
387     }
388
389     return false;
390     }
391
392
393     /**
394      * Returns true if the given string is null, empty, or contains
395      * only white space.
396      */

397     protected static boolean checkField(String JavaDoc field, int size) {
398     if (field == null || field.equals("")) {
399         return false;
400     }
401         if (field.length() <= size) {
402             return true;
403         }
404     return false;
405     }
406
407
408     /**
409      *
410      */

411     public static void dumpHeaders(HttpPresentationComms comms) {
412         System.out.println("DUMP HEADERS:" );
413         try {
414             HttpPresentationRequest req = comms.request;
415             Enumeration e = req.getHeaderNames();
416             while (e.hasMoreElements()) {
417                 String JavaDoc k = (String JavaDoc) e.nextElement();
418                 String JavaDoc p = req.getHeader(k);
419                 System.out.println(" NAME: " + k + "; VALUE: " + p);
420             }
421         } catch (Exception JavaDoc ex) {
422             System.err.println("ERROR: " + ex);
423         }
424     }
425
426     /**
427      *
428      */

429     public static void dump(HttpPresentationComms comms) {
430         System.out.println("DUMP PARAMETERS:" );
431         try {
432             HttpPresentationRequest req = comms.request;
433             Enumeration e = req.getParameterNames();
434             while (e.hasMoreElements()) {
435                 String JavaDoc k = (String JavaDoc) e.nextElement();
436                 String JavaDoc p = req.getParameter(k);
437                 System.out.println(" NAME: " + k + "; VALUE: " + p);
438             }
439         } catch (Exception JavaDoc ex) {
440             System.err.println("ERROR: " + ex);
441         }
442     }
443 }
444
445
446
447
448
Popular Tags