KickJava   Java API By Example, From Geeks To Geeks.

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


1 package org.enhydra.snapper.presentation;
2 /**
3  * <p>Title: Document Management Project</p>
4  * <p>Description: </p>
5  * <p>Copyright: Copyright (c) 2004</p>
6  * <p>Company: Prozone</p>
7  * @author Vladimir Radisic
8  * @version 1.0
9  */

10
11 import java.sql.SQLException JavaDoc;
12 import java.util.ArrayList JavaDoc;
13 import java.util.Enumeration JavaDoc;
14 import java.util.Hashtable JavaDoc;
15 import java.util.StringTokenizer JavaDoc;
16
17
18 import org.enhydra.xml.xmlc.XMLObject;
19 import org.enhydra.snapper.Log;
20
21 import org.w3c.dom.Attr JavaDoc;
22 import org.w3c.dom.Document JavaDoc;
23 import org.w3c.dom.Element JavaDoc;
24 import org.w3c.dom.NamedNodeMap JavaDoc;
25 import org.w3c.dom.Node JavaDoc;
26 import org.w3c.dom.NodeList JavaDoc;
27 import org.w3c.dom.html.HTMLElement;
28 import org.w3c.dom.html.HTMLInputElement;
29
30 import com.lutris.appserver.server.httpPresentation.HttpPresentation;
31 import com.lutris.appserver.server.httpPresentation.HttpPresentationComms;
32 import com.lutris.appserver.server.httpPresentation.HttpPresentationException;
33 //import com.lutris.appserver.server.httpPresentation.ServerPageRedirectException;
34
import com.lutris.appserver.server.sql.DBTransaction;
35 import com.lutris.util.Config;
36 import org.enhydra.dods.DODS;
37
38 /**
39  * Base abstract presentation class used for dynamic representation of particular java DOM generated
40  * objects. This class is super class for all presentation objects used in Versicherungsmathemathik
41  * application.
42  */

43 public abstract class BasePO implements HttpPresentation {
44
45
46   /**
47    * Saves reference to current transaction within presentation object.
48    */

49   protected DBTransaction dbTransaction = null;
50
51
52   /**
53    * Storage for HttpPresentationComms object passed to presentation object.
54    */

55   protected HttpPresentationComms comms = null;
56
57
58   /**
59    * Exception which was thrown during the generationg of presentation object and which error
60    * message should be displayed in current form or passed to other form.
61    */

62   Exception JavaDoc errorObj;
63
64   /**
65    * Info passed from other page which should be shown on this page.
66    */

67   protected String JavaDoc infoText;
68
69   /**
70    * Error passed from other page which should be shown on this page.
71    */

72   protected String JavaDoc errorText;
73
74   /**
75    * Page identification (unique on session level)
76    */

77   protected int pageId = -1;
78
79   // Parameters for common usage
80
// ---------------------------------------------------------------------
81

82   /**
83    * Argument is used as parameter delimiter in bundled parameters.
84    */

85   public static String JavaDoc paramDelimiter = ";";
86
87   /**
88    * Page Encoding definition.
89    */

90   public static String JavaDoc ENCODING = "UTF-8";
91
92   /**
93    * Returns transaction defined for current presentation object.
94    *
95    * @return
96    */

97   public DBTransaction getTransaction() {
98     return this.dbTransaction;
99   }
100
101   /**
102    * Sets error withouth possibility of overriding already existed error.
103    * @param err BaseException error object
104    */

105   public void setError(Exception JavaDoc err) {
106     if (this.errorObj == null) {
107       Log.logException(err);
108       this.errorObj = err;
109     }
110   }
111
112   /**
113    * Sets error with possibility of overriding already existed error.
114    * @param err BaseException error object
115    * @param override flag to indicate overriding (true) or rejecting of new error (false)
116    */

117   public void setError(Exception JavaDoc err, boolean override) {
118     if (override)
119       this.errorObj = err;
120     else if (this.errorObj == null)
121       this.errorObj = err;
122   }
123
124   /**
125    * Returns the current error
126    * @return
127    */

128   public Exception JavaDoc getError() {
129     return this.errorObj;
130   }
131
132   /**
133    * Clears the current error
134    *
135    * @return
136    */

137   public void clearError() {
138     this.errorObj = null;
139   }
140
141   /**
142    * Sets info withouth possibility of overriding already existed info.
143    * @param info InfoException info object
144    */

145
146
147   /**
148    * Gets value of parameter, when parametrs are delimited with paramDelimiter
149    * @param parameters
150    * @param paramName
151    * @return value of parameter
152    */

153   protected String JavaDoc getParamValue(String JavaDoc parameters, String JavaDoc paramName) {
154     String JavaDoc retVal = "";
155     if (parameters != null && !parameters.equals("")) {
156       StringTokenizer JavaDoc st = new StringTokenizer JavaDoc(parameters, BasePO.paramDelimiter);
157       while (st.hasMoreTokens()) {
158         String JavaDoc param = st.nextToken();
159         String JavaDoc paramNameIn = param.substring(0, param.indexOf("="));
160         if (paramName.equalsIgnoreCase(paramNameIn)) {
161           retVal = param.substring(param.indexOf("=") + 1);
162         }
163       }
164     }
165     return retVal;
166   }
167
168   /**
169    * Method used to form list of parameters delimited with delimiter
170    * @param arg array of parameters and their values
171    * @return list of parameters delimited with delimiter
172    */

173   protected String JavaDoc formParameterList(String JavaDoc[] arg) {
174     StringBuffer JavaDoc retVal = new StringBuffer JavaDoc("");
175     for (int i = 0; i < arg.length; i++) {
176       if (i != 0)
177         retVal.append(paramDelimiter);
178       retVal.append(arg[i]);
179     }
180     return retVal.toString();
181   }
182
183   /**
184    * Method used to form array of parameters from string with parameters delimited with delimiter
185    * @param str parameters delimited with delimiter
186    * @return array of parameters
187    */

188   protected String JavaDoc[] reformParameterList(String JavaDoc str) {
189     StringTokenizer JavaDoc tokenizer = new StringTokenizer JavaDoc(str, paramDelimiter);
190     ArrayList JavaDoc list = new ArrayList JavaDoc();
191     while (tokenizer.hasMoreTokens())
192       list.add(tokenizer.nextToken());
193     return (String JavaDoc[]) list.toArray(new String JavaDoc[0]);
194   }
195
196   /**
197    * Find start search page from search path.
198    * @param searchPath
199    * @return start search page ( first page in search path )
200    */

201   protected String JavaDoc getStartSearchURL(String JavaDoc searchPath) {
202     StringTokenizer JavaDoc tokenizer = new StringTokenizer JavaDoc(searchPath, "/");
203     String JavaDoc returnPage = "";
204     if (tokenizer.hasMoreTokens())
205       returnPage = tokenizer.nextToken();
206
207     return returnPage;
208   }
209
210   /**
211    * Method will make new search path,one level up.
212    * @param searchPath searchPath
213    * @return new search path
214    */

215   protected String JavaDoc getLevelUp(String JavaDoc searchPath) {
216     String JavaDoc levelUpSearchPath = "";
217     int lastIndexOfSlach = searchPath.lastIndexOf("/");
218     if (lastIndexOfSlach != -1)
219       levelUpSearchPath = searchPath.substring(0, lastIndexOfSlach);
220     else
221       levelUpSearchPath = "";
222
223     return levelUpSearchPath;
224   }
225
226   /**
227    * Find return page from search path.
228    * @param searchPath
229    * @return return page ( last page in search path )
230    */

231   protected String JavaDoc getReturnURL(String JavaDoc searchPath) {
232     String JavaDoc returnPage = "";
233     StringTokenizer JavaDoc tokenizer = new StringTokenizer JavaDoc(searchPath, "/");
234     while (tokenizer.hasMoreTokens())
235       returnPage = tokenizer.nextToken();
236
237     return returnPage;
238   }
239
240   /**
241    * Find return page from search path.
242    * @param searchPath
243    * @return return page ( one before last page in search path )
244    */

245   protected String JavaDoc getFromURL(String JavaDoc searchPath) {
246     searchPath = getLevelUp(searchPath);
247     if (searchPath.equals(""))
248       return searchPath;
249
250     return getReturnURL(searchPath);
251   }
252
253   /**
254    * Create hidden field.
255    * @param name
256    * @param value
257    * @param document
258    * @return field
259    * @throws HttpPresentationException
260    */

261   protected void addHiddenInputField(String JavaDoc name, String JavaDoc value, HTMLElement root) {
262     HTMLInputElement field = (HTMLInputElement) root.getOwnerDocument().createElement("INPUT");
263     field.setAttribute("type", "hidden");
264     field.setAttribute("name", name);
265     field.setAttribute("value", value);
266     root.appendChild(field);
267   }
268
269   /**
270    * Create custom field.
271    * @param attributes
272    * @param document
273    * @return field
274    * @throws HttpPresentationException
275    */

276   protected HTMLInputElement createInputField(Hashtable JavaDoc attributes, Document JavaDoc document) {
277     HTMLInputElement field = (HTMLInputElement) document.createElement("INPUT");
278     Enumeration JavaDoc keys = attributes.keys();
279     String JavaDoc key = "";
280     String JavaDoc value = "";
281     while (keys.hasMoreElements()) {
282       key = keys.nextElement().toString();
283       value = attributes.get(key).toString();
284       field.setAttribute(key, value);
285     }
286     return field;
287   }
288
289   /**
290    * Dynamicaly creates an array of input html fields and append they to the
291    * passed root html element. Input fields are created for correspond attribute
292    * values which are passed via http request parameteres, and are specified by
293    * theirs prefix.
294    * @param paramNamePrefix prefix name for group of http request parameters (or
295    * full name of one parameter) which values (or value) should be used for
296    * creation input fielsd elements.
297    */

298   protected void addHiddenInputFields(String JavaDoc paramNamePrefix, HTMLElement root) throws HttpPresentationException {
299
300     Enumeration JavaDoc params = this.comms.request.getParameterNames();
301     while (params.hasMoreElements()) {
302       String JavaDoc name = (String JavaDoc) params.nextElement();
303       if (name.startsWith(paramNamePrefix))
304         this.addHiddenInputField(name, this.comms.request.getParameter(name), root);
305       else
306         continue;
307     }
308
309   }
310
311   /**
312    * Dynamicaly creates an array of input html fields and append they to the passed root html
313    * element. Input fields are created for correspond attribute values which are passed via http
314    * request parameteres, and are specified by defined prefix group string with defined excluded
315    * prefix names.
316    *
317    * @param paramNamePrefix
318    * prefix name for group of http request parameters (or full name of one parameter)
319    * which values (or value) should be used for creation input fielsd elements.
320    * @param exludePrefix
321    * array with prefix names which have to be excluded from group of http request
322    * parameters defined by paramNamePrefix attribute.
323    */

324   protected void addHiddenInputFields(String JavaDoc paramNamePrefix, HTMLElement root,
325                                       String JavaDoc[] exludePrefix) throws HttpPresentationException {
326
327     if (exludePrefix == null || exludePrefix.length == 0)
328       this.addHiddenInputFields(paramNamePrefix, root);
329     else {
330       Enumeration JavaDoc params = this.comms.request.getParameterNames();
331       while (params.hasMoreElements()) {
332         String JavaDoc name = (String JavaDoc) params.nextElement();
333         if (name.startsWith(paramNamePrefix) && !this.isIn(name, exludePrefix)) {
334           this.addHiddenInputField(name, this.comms.request.getParameter(name), root);
335         }
336         else {
337           continue;
338         }
339       }
340     }
341   }
342
343   public boolean isIn(String JavaDoc searchVal, String JavaDoc[] definedGroup) {
344     if (definedGroup == null || definedGroup.equals("")) {
345       return false;
346     }
347     for (int i = 0; i < definedGroup.length; i++) {
348       if (searchVal == null && definedGroup[i] == null) {
349         return true;
350       }
351       else if (searchVal != null && searchVal.equalsIgnoreCase(definedGroup[i])) {
352         return true;
353       }
354     }
355     return false;
356   }
357
358   /**
359    * Implementation of run() method from HttpPresentation interface.
360     * @param comms object passed to presentation objects that contains HTTP and
361     * Presentation Manager access and control objects
362    * @exception HttpPresentationException
363    */

364   public void run(HttpPresentationComms comms) throws HttpPresentationException {
365
366     boolean doCommit = true;
367     try {
368       initTransaction();
369       comms.request.getHttpServletRequest().setCharacterEncoding(BasePO.ENCODING);
370       this.comms = comms;
371
372       comms.response.setEncoding(BasePO.ENCODING);
373       XMLObject dom = this.getDOM();
374
375       // caching pages for back-form handling
376
// this.pageCache.setTempPageLink(this.comms, this.pageId);
377

378       
379       if (dom != null)
380         comms.response.writeDOM(dom);
381     }
382     catch (Exception JavaDoc ex) {
383       doCommit = false;
384       Log.logException(ex);
385
386     }
387     finally {
388         //org.enhydra.snapper.Log.logToFile("--------------- finally blok --------------------");
389
// releases connection pool if it exist
390
if (doCommit && this.getError() == null) {
391         try{
392         this.commitTransaction();
393         } catch (Exception JavaDoc e) {}
394          } else {
395             if(getError() != null)
396                 Log.logException(getError());
397             try{
398             this.releaseTransaction();
399             } catch (Exception JavaDoc e){}
400       }
401     }
402   }
403
404   /**
405    * Removes id attributes from given html tag (represented as Node implementation) and all it's
406    * sub tags.
407    *
408    * @param rootNode
409    * tag in html which has to be examined.
410    * @exception HttpPresentationException
411    */

412   public void removeIdAttrFromTree(Node JavaDoc rootNode) {
413
414     if (rootNode.hasAttributes()) {
415       NamedNodeMap JavaDoc nMap = rootNode.getAttributes();
416       for (int i = 0; i < nMap.getLength(); i++) { // removes "id" attributes
417
Node JavaDoc attribFromList = nMap.item(i);
418         if (attribFromList.getNodeName().equalsIgnoreCase("id")) {
419           Element JavaDoc parent = ( (Attr JavaDoc) attribFromList).getOwnerElement();
420           parent.removeAttributeNode( (Attr JavaDoc) attribFromList);
421           break; // because "id" attributes should be set only once per tag
422
}
423       }
424     }
425
426     if (rootNode.hasChildNodes()) {
427       NodeList JavaDoc nList = rootNode.getChildNodes();
428       for (int i = 0; i < nList.getLength(); i++) {
429         Node JavaDoc fromList = nList.item(i);
430         if (fromList.getNodeType() == Node.ELEMENT_NODE) { // if current html tag has nested
431
// tags
432
removeIdAttrFromTree(fromList);
433         }
434       }
435     }
436   }
437
438   /**
439    * Returns information about application configuration defined in config file via Config object.
440    *
441    * @return Config object which represents configuration file of VersMath application.
442    */

443   protected Config getAppConfiguration() {
444     return this.comms.application.getConfig();
445   }
446
447   /**
448    * Method is used to list all HTTP request parameters passed to presentation object, and their's
449    * corresponding values, to log file.
450    */

451   protected void listAllParameters() {
452     try {
453       Enumeration JavaDoc paramNames = this.comms.request.getParameterNames();
454       while (paramNames.hasMoreElements()) {
455         String JavaDoc parameter = (String JavaDoc) paramNames.nextElement();
456         String JavaDoc value = (String JavaDoc)this.comms.request.getParameter(parameter);
457         org.enhydra.snapper.Log.logToFile("parameter = " + parameter + ", value = " + value);
458       }
459     }
460     catch (Exception JavaDoc ex) {
461     }
462   }
463
464   /**
465    * This abstract method should be overriden by presentation class, and it is responsible for
466    * generation of http response to user in form of XMLObject instance.
467    *
468    * @return dynamically populated XMLObject generated as response to user http request.
469    * @throws BaseException
470    */

471   protected abstract XMLObject getDOM() throws Exception JavaDoc;
472
473   // Transaction methods ---------------------------------------------------------
474

475
476   /**
477    * Initialises transaction for current PO object.
478    */

479   private void initTransaction() throws Exception JavaDoc {
480     try {
481
482        this.dbTransaction = DODS.getDatabaseManager().createTransaction();
483     }
484     catch (Exception JavaDoc ex) {
485       throw new Exception JavaDoc("Could not init transaction", ex);
486     }
487   }
488
489   /**
490    * Commits passed transasaction and performes release of connection pool. In case of error
491    * durring the commit, error number 89 is specified, and no other activity is performed.
492    *
493    * @return true if commit success or false otherwise
494    */

495   private void commitTransaction() throws Exception JavaDoc {
496     try {
497       this.dbTransaction.commit();
498     }
499     catch (Throwable JavaDoc ex) {
500       Log.logException(ex);
501       throw new Exception JavaDoc("Could not commit transaction", ex);
502     }
503     finally {
504       this.releaseTransaction();
505     }
506   }
507
508   /**
509    * Rollbacks passed transasaction and performes release of connection pool. In case of error
510    * durring the rollback, error number 89 is specified, and no other activity is performed.
511    *
512    * @return true if commit success or false otherwise
513    */

514   /*
515    * private void rollbackTransaction() throws POException { try {
516    * SharkHandler.emptyCaches(this.sharkTransaction); if (this.dbTransaction != null) {
517    * this.sharkTransaction.rollback(); } else throw new POException(1020, this.user.getLang()); }
518    * catch (Throwable ex) { throw new POException(1020, this.user.getLang()); } }
519    */

520
521   private void releaseTransaction() throws Exception JavaDoc {
522       try {
523         dbTransaction.release();
524       }
525       catch (Exception JavaDoc ex) {
526         throw new Exception JavaDoc("Could not commit transaction", ex);
527       }
528     }
529  
530
531   public void writeTransaction() throws SQLException JavaDoc {
532     dbTransaction.write();
533   }
534
535   public static void printFreeMemory(String JavaDoc prefix) {
536     System.out.println("========================================================");
537     System.out.println(prefix + ", free memory = " + (Runtime.getRuntime().freeMemory() / 1024) / 1024 + " MB");
538     System.out.println(prefix + ", max memory = " + (Runtime.getRuntime().maxMemory() / 1024) / 1024 + " MB");
539     System.out.println(prefix + ", total memory = " + (Runtime.getRuntime().totalMemory() / 1024) / 1024 + " MB");
540   }
541
542   public static void show(String JavaDoc s) {
543     javax.swing.JOptionPane.showConfirmDialog(null, s);
544   }
545
546   /**
547    * Read value of parameter from http request.
548    *
549    * @param name
550    * parameter name
551    * @return parameter value
552    */

553   protected boolean getBoolParameter(String JavaDoc name) {
554     boolean retVal = false;
555     String JavaDoc value = null;
556     try {
557       value = this.comms.request.getParameter(name);
558       if (value != null && value.equals("true"))
559         retVal = true;
560     }
561     catch (Exception JavaDoc e) {
562       retVal = false;
563     }
564     return retVal;
565   }
566
567 }
Popular Tags