KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > enhydra > pim > presentation > BasePO


1 /*
2  * Enhydra Java Application Server Project
3  *
4  * The contents of this file are subject to the Enhydra Public License
5  * Version 1.1 (the "License"); you may not use this file except in
6  * compliance with the License. You may obtain a copy of the License on
7  * the Enhydra web site ( http://www.enhydra.org/ ).
8  *
9  * Software distributed under the License is distributed on an "AS IS"
10  * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
11  * the License for the specific terms governing rights and limitations
12  * under the License.
13  *
14  * The Initial Developer of the Enhydra Application Server is Lutris
15  * Technologies, Inc. The Enhydra Application Server and portions created
16  * by Lutris Technologies, Inc. are Copyright Lutris Technologies, Inc.
17  * All Rights Reserved.
18  *
19  * Contributor(s):
20  *
21  * $Id: BasePO.java,v 1.2 2004/09/20 13:27:59 zoran Exp $
22  */

23
24 package org.enhydra.pim.presentation;
25
26 import java.lang.reflect.InvocationTargetException JavaDoc;
27 import java.lang.reflect.Method JavaDoc;
28 import java.sql.SQLException JavaDoc;
29
30 import org.enhydra.pim.Enhydrapim;
31 import org.enhydra.pim.business.TransactionContextI;
32 import org.enhydra.pim.business.api.CommonConstants;
33 import org.enhydra.pim.business.api.OwnerI;
34 import org.enhydra.pim.exception.EnhydraPimException;
35 import org.enhydra.pim.presentation.enhydrapim.ErrorHTML;
36 import org.enhydra.pim.presentation.enhydrapim.IndexHTML;
37 import org.enhydra.pim.spec.TransactionContextFactory;
38 import org.enhydra.xml.xmlc.XMLObject;
39 import org.w3c.dom.Element JavaDoc;
40
41 import com.lutris.appserver.server.Enhydra;
42 import com.lutris.appserver.server.httpPresentation.ClientPageRedirectException;
43 import com.lutris.appserver.server.httpPresentation.HttpPresentation;
44 import com.lutris.appserver.server.httpPresentation.HttpPresentationComms;
45 import com.lutris.appserver.server.httpPresentation.HttpPresentationException;
46 import com.lutris.logging.Logger;
47 import com.lutris.util.KeywordValueException;
48
49 /**
50  * This is the parent Presentaion object. All presentation objects should extend
51  * this class.
52  *
53  * The run method looks for an event parameter and then calls handle
54  * <EventName>. If the "event" Parameter is not defined then the handleDefault()
55  * method is called in your child class.
56  */

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

77     public abstract XMLObject handleDefault() throws HttpPresentationException;
78
79     /**
80      * This method should be implemented in the subclass so that it returns true
81      * if this particular request requires the user to be logged in, otherwise
82      * false.
83      */

84     protected abstract boolean loggedInUserRequired();
85
86     /**
87      * Saved input and output context, and session data
88      */

89     protected HttpPresentationComms myComms = null;
90
91     /**
92      *
93      * @uml.property name="mySessionData"
94      * @uml.associationEnd multiplicity="(0 1)"
95      */

96     protected EnhydraPimSessionData mySessionData = null;
97
98     /**
99      * Reference to the person logged in to the session
100      *
101      * @uml.property name="myPerson"
102      * @uml.associationEnd multiplicity="(0 1)"
103      */

104     protected OwnerI myPerson = null;
105
106     /**
107      * Gets HttpPresentation object
108      *
109      * @return The saved comms objects to whichever subclass needs it
110      */

111     public HttpPresentationComms getComms() {
112         return this.myComms;
113     }
114
115     /**
116      * Gets the session data
117      *
118      * @return session data
119      */

120     public EnhydraPimSessionData getSessionData() {
121         return this.mySessionData;
122     }
123
124     /**
125      * Sets the user into the session
126      *
127      * @param thePerson
128      * the person to be set in the session
129      * @exception EnhydraPimPresentationException
130      */

131     public void setUser(OwnerI thePerson)
132             throws EnhydraPimPresentationException {
133         this.getSessionData().setUser(thePerson);
134     }
135
136     /**
137      * Gets the user from the session
138      *
139      * @return the person object in the session
140      */

141     public OwnerI getUser() {
142         return this.getSessionData().getUser();
143     }
144
145     /**
146      * Method to remove the current user from the session
147      */

148     public void removeUserFromSession() {
149         this.getSessionData().removeUser();
150     }
151
152     /**
153      * This implements the run method in HttpPresentation.
154      *
155      * @param comms
156      * HttpPresentationComms
157      * @exception Exception
158      */

159     public void run(HttpPresentationComms comms) throws Exception JavaDoc {
160         // Initialize new or get the existing session data
161
initSessionData(comms);
162         
163         // Check if the user needs to be logged in for this request.
164
if (this.loggedInUserRequired()) {
165             checkForUserLogin();
166         }
167         
168         TransactionContextI transCtx= TransactionContextFactory.getTransactionContext();
169
170         try {
171             transCtx.beginContext(CommonConstants.productionDatabaseName);
172             handleEvent(comms);
173         }catch(Exception JavaDoc e){
174             transCtx.rollbackContext();
175             throw new EnhydraPimException("Unhandled Application Error");
176         }finally {
177             try {
178                 transCtx.commitContext();
179             } catch (SQLException JavaDoc e){
180                 throw new EnhydraPimException("Unhandled Application Error");
181             }
182         }
183         
184     }
185
186     /**
187      * Method to get or create the AgSessionData object from the user session
188      * This object is saved in the EbrokerPresentation object
189      *
190      * @param comms
191      * HttpPresentationComms
192      * @exception Exception
193      */

194     protected void initSessionData(HttpPresentationComms comms)
195             throws EnhydraPimPresentationException {
196         this.myComms = comms;
197
198         try {
199             Object JavaDoc obj = comms.sessionData.get(EnhydraPimSessionData.SESSION_KEY);
200             // If we found the session data, save it in a private data member
201
if (null != obj) {
202                 this.mySessionData = (EnhydraPimSessionData) obj;
203             } else {
204                 // If no session data was found, create a new session data
205
// instance
206
this.mySessionData = new EnhydraPimSessionData();
207                 comms.sessionData.set(EnhydraPimSessionData.SESSION_KEY,
208                         this.mySessionData);
209             }
210         } catch (KeywordValueException ex) {
211             writeDebugMsg("Problem getting session data from session: "
212                     + ex.getMessage());
213         }
214     }
215
216     
217     /**
218      * Checks the session data for a User, if not there then redirects to the
219      * login page
220      */

221     protected void checkForUserLogin() throws ClientPageRedirectException,
222             EnhydraPimPresentationException {
223
224         try {
225             OwnerI user = getUser();
226
227             if (null == user) {
228 // String uri = myComms.request.getRequestURI();
229
// boolean is = uri.startsWith("/discRack_pres");
230
// if (!is) {
231

232                     writeDebugMsg("USER NOT FOUND IN SESSION");
233                     //send to LoginPage if a logged in user is required.
234
String JavaDoc requestedPO = myComms.request.getRequestURI();
235                     this.writeDebugMsg("PO: " + requestedPO);
236                     // Call the subclass's implemented method
237
writeDebugMsg("REDIRECTING TO LOGIN PAGE");
238                     throw new ClientPageRedirectException(LOGIN_PAGE);
239 // }
240
} else {
241                 writeDebugMsg("USER ALREADY LOGGED IN WITH A SESSION");
242             }
243
244         } catch (Exception JavaDoc ex) {
245             throw new EnhydraPimPresentationException(
246                     "Trouble checking for user login status", ex);
247         }
248     }
249
250     
251     /**
252      * Method to call the proper method for the incoming event
253      *
254      * @param comms
255      * HttpPresentationComms
256      * @exception Exception
257      */

258     public void handleEvent(HttpPresentationComms comms) throws Exception JavaDoc {
259         String JavaDoc event = comms.request.getParameter(EVENT);
260
261         XMLObject returnHTML = null;
262         
263         try {
264             // Handle the incoming event request
265
if (event == null || event.length() == 0 || event.equalsIgnoreCase("none") || event.equalsIgnoreCase("Default")) {
266                 returnHTML = handleDefault();
267             } else {
268                 returnHTML = getPageContentForEvent(event);
269             }
270             //comms.response.setEncoding("UTF8");
271
if(getUser()!=null && getUser().getUsername()!=null) {
272                 Element JavaDoc htm =returnHTML.getElementById("LogUserName");
273                 htm.getFirstChild().setNodeValue("<"+getUser().getUsername()+">");
274             }
275         } catch (Exception JavaDoc e) {
276             e.printStackTrace();
277             returnHTML = showErrorPage("Presentation Error:"+e.getMessage());
278         }
279         comms.response.writeDOM(returnHTML);
280     }
281
282     /**
283      * If an event parameter is defined then this invokes the method that
284      * handles that event.
285      *
286      * @param event
287      * the incoming event name
288      * @exception Exception
289      */

290     public XMLObject getPageContentForEvent(String JavaDoc event) throws Exception JavaDoc {
291
292         try {
293             Method JavaDoc method = this.getClass().getMethod(toMethodName(event), null);
294             XMLObject thePage = (XMLObject) method.invoke(this, null);
295             
296             return thePage;
297         } catch (InvocationTargetException JavaDoc ex) {
298             // Rethrow the originating exception if as it should be propagated
299
// as is
300
// It could be a page redirect exception, etc.
301
if (ex.getTargetException() instanceof Exception JavaDoc) {
302                 throw (Exception JavaDoc) ex.getTargetException();
303             } else if (ex.getTargetException() instanceof Error JavaDoc) {
304                 throw (Error JavaDoc) ex.getTargetException();
305             } else {
306                 throw ex;
307             }
308         } catch (NoSuchMethodException JavaDoc ex) {
309             //The method to handle the event does not exist.
310
throw new EnhydraPimPresentationException(
311                     "NO EVENT HANDLER FOUND FOR EVENT: " + event, ex);
312         } catch (IllegalAccessException JavaDoc ex) {
313             //The method to handle the event does not exist.
314
throw new EnhydraPimPresentationException(
315                     "ILLEGAL ACCESS TO EVENT HANDLER (is it public?): " + event,
316                     ex);
317         }
318     }
319
320     /**
321      * This sets the first letter of the event parameter value in order to
322      * adhere to Java method naming conventions.
323      *
324      * @param event
325      * the incoming name of the event
326      * @return String the properly capitalized name
327      */

328     private String JavaDoc toMethodName(String JavaDoc event) {
329         StringBuffer JavaDoc methodName = new StringBuffer JavaDoc(STANDARD_METHOD_PREFIX);
330         methodName.append(Character.toUpperCase(event.charAt(0)));
331
332         if (event.length() > 1) {
333             methodName.append(event.substring(1));
334         }
335
336         return methodName.toString();
337     }
338
339     /**
340      * Returns the application object associated with the current request.
341      *
342      * @return the application object.
343      */

344     public Enhydrapim getApplication() {
345         return (Enhydrapim) Enhydra.getApplication();
346     }
347
348     /**
349      * Method to write a debugging message to the debug log channel when the
350      * DEBUG flag is turned on
351      *
352      * @param msg
353      * The message to write to the DEBUG log channel
354      */

355     public static void writeDebugMsg(String JavaDoc msg) {
356         Enhydra.getLogChannel().write(Logger.DEBUG, msg);
357     }
358     
359     
360     
361     /**
362      * Display Error.html page
363      *
364      * @return html document
365      * @throws ClientPageRedirectException
366      * @throws HttpPresentationException
367      */

368     public void goToErrorPage(String JavaDoc errorText) throws ClientPageRedirectException, HttpPresentationException{
369         if(errorText!=null) {
370             this.getSessionData().setUserMessage(errorText);
371         }
372         throw new ClientPageRedirectException(ERROR_PAGE);
373     }
374     
375     
376     /**
377      * Display Error.html page
378      *
379      * @return html document
380      * @throws ClientPageRedirectException
381      * @throws HttpPresentationException
382      */

383     public XMLObject showErrorPage(String JavaDoc errorText) throws ClientPageRedirectException, HttpPresentationException{
384         ErrorHTML errorPage = (ErrorHTML) myComms.xmlcFactory.create(ErrorHTML.class);
385         if(errorText!=null) {
386             errorPage.setTextErrorText(errorText);
387         }else {
388             errorPage.setTextErrorText("Unhandled presentation Error");
389         }
390         return errorPage;
391     }
392     
393
394     
395     /**
396      * Display Index.html page
397      *
398      * @return html document
399      */

400     public XMLObject showIndexPage() {
401         return (IndexHTML) myComms.xmlcFactory.create(IndexHTML.class);
402     }
403     
404 }
Popular Tags