001: package org.enhydra.snapperAdmin.presentation;
002:
003: import java.util.ArrayList;
004: import java.util.Enumeration;
005: import java.util.Hashtable;
006: import java.util.StringTokenizer;
007:
008: import org.enhydra.snapperAdmin.presentation.BasePO;
009: import org.enhydra.snapperAdmin.Log;
010: import org.enhydra.xml.xmlc.XMLObject;
011: import org.w3c.dom.Attr;
012: import org.w3c.dom.Document;
013: import org.w3c.dom.Element;
014: import org.w3c.dom.NamedNodeMap;
015: import org.w3c.dom.Node;
016: import org.w3c.dom.NodeList;
017: import org.w3c.dom.html.HTMLElement;
018: import org.w3c.dom.html.HTMLInputElement;
019:
020: import com.lutris.appserver.server.httpPresentation.HttpPresentation;
021: import com.lutris.appserver.server.httpPresentation.HttpPresentationComms;
022: import com.lutris.appserver.server.httpPresentation.HttpPresentationException;
023: import com.lutris.util.Config;
024:
025: /**
026: * Base abstract presentation class used for dynamic representation of particular java DOM generated
027: * objects. This class is super class for all presentation objects used in Versicherungsmathemathik
028: * application.
029: */
030: public abstract class BasePO implements HttpPresentation {
031:
032: /**
033: * Storage for HttpPresentationComms object passed to presentation object.
034: */
035: protected HttpPresentationComms comms = null;
036:
037: /**
038: * Exception which was thrown during the generationg of presentation object and which error
039: * message should be displayed in current form or passed to other form.
040: */
041: Exception errorObj;
042:
043: /**
044: * Info passed from other page which should be shown on this page.
045: */
046: protected String infoText;
047:
048: /**
049: * Error passed from other page which should be shown on this page.
050: */
051: protected String errorText;
052:
053: /**
054: * Page identification (unique on session level)
055: */
056: protected int pageId = -1;
057:
058: // Parameters for common usage
059: // ---------------------------------------------------------------------
060:
061: /**
062: * Argument is used as parameter delimiter in bundled parameters.
063: */
064: public static String paramDelimiter = ";";
065:
066: /**
067: * Page Encoding definition.
068: */
069: public static String ENCODING = "UTF-8";
070:
071: /**
072: * Sets error withouth possibility of overriding already existed error.
073: * @param err BaseException error object
074: */
075: public void setError(Exception err) {
076: if (this .errorObj == null) {
077: Log.logException(err);
078: this .errorObj = err;
079: }
080: }
081:
082: /**
083: * Sets error with possibility of overriding already existed error.
084: * @param err BaseException error object
085: * @param override flag to indicate overriding (true) or rejecting of new error (false)
086: */
087: public void setError(Exception err, boolean override) {
088: if (override)
089: this .errorObj = err;
090: else if (this .errorObj == null)
091: this .errorObj = err;
092: }
093:
094: /**
095: * Returns the current error
096: * @return
097: */
098: public Exception getError() {
099: return this .errorObj;
100: }
101:
102: /**
103: * Clears the current error
104: *
105: * @return
106: */
107: public void clearError() {
108: this .errorObj = null;
109: }
110:
111: /**
112: * Sets info withouth possibility of overriding already existed info.
113: * @param info InfoException info object
114: */
115:
116: /**
117: * Gets value of parameter, when parametrs are delimited with paramDelimiter
118: * @param parameters
119: * @param paramName
120: * @return value of parameter
121: */
122: protected String getParamValue(String parameters, String paramName) {
123: String retVal = "";
124: if (parameters != null && !parameters.equals("")) {
125: StringTokenizer st = new StringTokenizer(parameters,
126: BasePO.paramDelimiter);
127: while (st.hasMoreTokens()) {
128: String param = st.nextToken();
129: String paramNameIn = param.substring(0, param
130: .indexOf("="));
131: if (paramName.equalsIgnoreCase(paramNameIn)) {
132: retVal = param.substring(param.indexOf("=") + 1);
133: }
134: }
135: }
136: return retVal;
137: }
138:
139: /**
140: * Method used to form list of parameters delimited with delimiter
141: * @param arg array of parameters and their values
142: * @return list of parameters delimited with delimiter
143: */
144: protected String formParameterList(String[] arg) {
145: StringBuffer retVal = new StringBuffer("");
146: for (int i = 0; i < arg.length; i++) {
147: if (i != 0)
148: retVal.append(paramDelimiter);
149: retVal.append(arg[i]);
150: }
151: return retVal.toString();
152: }
153:
154: /**
155: * Method used to form array of parameters from string with parameters delimited with delimiter
156: * @param str parameters delimited with delimiter
157: * @return array of parameters
158: */
159: protected String[] reformParameterList(String str) {
160: StringTokenizer tokenizer = new StringTokenizer(str,
161: paramDelimiter);
162: ArrayList list = new ArrayList();
163: while (tokenizer.hasMoreTokens())
164: list.add(tokenizer.nextToken());
165: return (String[]) list.toArray(new String[0]);
166: }
167:
168: /**
169: * Find start search page from search path.
170: * @param searchPath
171: * @return start search page ( first page in search path )
172: */
173: protected String getStartSearchURL(String searchPath) {
174: StringTokenizer tokenizer = new StringTokenizer(searchPath, "/");
175: String returnPage = "";
176: if (tokenizer.hasMoreTokens())
177: returnPage = tokenizer.nextToken();
178:
179: return returnPage;
180: }
181:
182: /**
183: * Method will make new search path,one level up.
184: * @param searchPath searchPath
185: * @return new search path
186: */
187: protected String getLevelUp(String searchPath) {
188: String levelUpSearchPath = "";
189: int lastIndexOfSlach = searchPath.lastIndexOf("/");
190: if (lastIndexOfSlach != -1)
191: levelUpSearchPath = searchPath.substring(0,
192: lastIndexOfSlach);
193: else
194: levelUpSearchPath = "";
195:
196: return levelUpSearchPath;
197: }
198:
199: /**
200: * Find return page from search path.
201: * @param searchPath
202: * @return return page ( last page in search path )
203: */
204: protected String getReturnURL(String searchPath) {
205: String returnPage = "";
206: StringTokenizer tokenizer = new StringTokenizer(searchPath, "/");
207: while (tokenizer.hasMoreTokens())
208: returnPage = tokenizer.nextToken();
209:
210: return returnPage;
211: }
212:
213: /**
214: * Find return page from search path.
215: * @param searchPath
216: * @return return page ( one before last page in search path )
217: */
218: protected String getFromURL(String searchPath) {
219: searchPath = getLevelUp(searchPath);
220: if (searchPath.equals(""))
221: return searchPath;
222:
223: return getReturnURL(searchPath);
224: }
225:
226: /**
227: * Create hidden field.
228: * @param name
229: * @param value
230: * @param document
231: * @return field
232: * @throws HttpPresentationException
233: */
234: protected void addHiddenInputField(String name, String value,
235: HTMLElement root) {
236: HTMLInputElement field = (HTMLInputElement) root
237: .getOwnerDocument().createElement("INPUT");
238: field.setAttribute("type", "hidden");
239: field.setAttribute("name", name);
240: field.setAttribute("value", value);
241: root.appendChild(field);
242: }
243:
244: /**
245: * Create custom field.
246: * @param attributes
247: * @param document
248: * @return field
249: * @throws HttpPresentationException
250: */
251: protected HTMLInputElement createInputField(Hashtable attributes,
252: Document document) {
253: HTMLInputElement field = (HTMLInputElement) document
254: .createElement("INPUT");
255: Enumeration keys = attributes.keys();
256: String key = "";
257: String value = "";
258: while (keys.hasMoreElements()) {
259: key = keys.nextElement().toString();
260: value = attributes.get(key).toString();
261: field.setAttribute(key, value);
262: }
263: return field;
264: }
265:
266: /**
267: * Dynamicaly creates an array of input html fields and append they to the
268: * passed root html element. Input fields are created for correspond attribute
269: * values which are passed via http request parameteres, and are specified by
270: * theirs prefix.
271: * @param paramNamePrefix prefix name for group of http request parameters (or
272: * full name of one parameter) which values (or value) should be used for
273: * creation input fielsd elements.
274: */
275: protected void addHiddenInputFields(String paramNamePrefix,
276: HTMLElement root) throws HttpPresentationException {
277:
278: Enumeration params = this .comms.request.getParameterNames();
279: while (params.hasMoreElements()) {
280: String name = (String) params.nextElement();
281: if (name.startsWith(paramNamePrefix))
282: this .addHiddenInputField(name, this .comms.request
283: .getParameter(name), root);
284: else
285: continue;
286: }
287:
288: }
289:
290: /**
291: * Dynamicaly creates an array of input html fields and append they to the passed root html
292: * element. Input fields are created for correspond attribute values which are passed via http
293: * request parameteres, and are specified by defined prefix group string with defined excluded
294: * prefix names.
295: *
296: * @param paramNamePrefix
297: * prefix name for group of http request parameters (or full name of one parameter)
298: * which values (or value) should be used for creation input fielsd elements.
299: * @param exludePrefix
300: * array with prefix names which have to be excluded from group of http request
301: * parameters defined by paramNamePrefix attribute.
302: */
303: protected void addHiddenInputFields(String paramNamePrefix,
304: HTMLElement root, String[] exludePrefix)
305: throws HttpPresentationException {
306:
307: if (exludePrefix == null || exludePrefix.length == 0)
308: this .addHiddenInputFields(paramNamePrefix, root);
309: else {
310: Enumeration params = this .comms.request.getParameterNames();
311: while (params.hasMoreElements()) {
312: String name = (String) params.nextElement();
313: if (name.startsWith(paramNamePrefix)
314: && !this .isIn(name, exludePrefix)) {
315: this .addHiddenInputField(name, this .comms.request
316: .getParameter(name), root);
317: } else {
318: continue;
319: }
320: }
321: }
322: }
323:
324: public boolean isIn(String searchVal, String[] definedGroup) {
325: if (definedGroup == null || definedGroup.equals("")) {
326: return false;
327: }
328: for (int i = 0; i < definedGroup.length; i++) {
329: if (searchVal == null && definedGroup[i] == null) {
330: return true;
331: } else if (searchVal != null
332: && searchVal.equalsIgnoreCase(definedGroup[i])) {
333: return true;
334: }
335: }
336: return false;
337: }
338:
339: /**
340: * Implementation of run() method from HttpPresentation interface.
341: * @param comms object passed to presentation objects that contains HTTP and
342: * Presentation Manager access and control objects
343: * @exception HttpPresentationException
344: */
345: public void run(HttpPresentationComms comms)
346: throws HttpPresentationException {
347:
348: boolean doCommit = true;
349: try {
350: comms.request.getHttpServletRequest().setCharacterEncoding(
351: BasePO.ENCODING);
352: this .comms = comms;
353:
354: //org.enhydra.snapper.Log.logToFile("--------------- " + comms.request.getPresentationURI() + " --------------------");
355:
356: XMLObject dom = this .getDOM();
357:
358: // caching pages for back-form handling
359: // this.pageCache.setTempPageLink(this.comms, this.pageId);
360:
361: comms.response.setEncoding(BasePO.ENCODING);
362: if (dom != null)
363: comms.response.writeDOM(dom);
364: } catch (Exception ex) {
365: doCommit = false;
366: Log.logException(ex);
367:
368: } finally {
369: if (doCommit && this .getError() == null) {
370: try {
371: } catch (Exception e) {
372: e.printStackTrace();
373: }
374: } else {
375: if (getError() != null)
376: Log.logException(getError());
377: try {
378: } catch (Exception e) {
379: e.printStackTrace();
380: }
381: }
382: }
383: }
384:
385: /**
386: * Removes id attributes from given html tag (represented as Node implementation) and all it's
387: * sub tags.
388: *
389: * @param rootNode
390: * tag in html which has to be examined.
391: * @exception HttpPresentationException
392: */
393: public void removeIdAttrFromTree(Node rootNode) {
394:
395: if (rootNode.hasAttributes()) {
396: NamedNodeMap nMap = rootNode.getAttributes();
397: for (int i = 0; i < nMap.getLength(); i++) { // removes "id" attributes
398: Node attribFromList = nMap.item(i);
399: if (attribFromList.getNodeName().equalsIgnoreCase("id")) {
400: Element parent = ((Attr) attribFromList)
401: .getOwnerElement();
402: parent.removeAttributeNode((Attr) attribFromList);
403: break; // because "id" attributes should be set only once per tag
404: }
405: }
406: }
407:
408: if (rootNode.hasChildNodes()) {
409: NodeList nList = rootNode.getChildNodes();
410: for (int i = 0; i < nList.getLength(); i++) {
411: Node fromList = nList.item(i);
412: if (fromList.getNodeType() == Node.ELEMENT_NODE) { // if current html tag has nested
413: // tags
414: removeIdAttrFromTree(fromList);
415: }
416: }
417: }
418: }
419:
420: /**
421: * Returns information about application configuration defined in config file via Config object.
422: *
423: * @return Config object which represents configuration file of VersMath application.
424: */
425: protected Config getAppConfiguration() {
426: return this .comms.application.getConfig();
427: }
428:
429: /**
430: * Method is used to list all HTTP request parameters passed to presentation object, and their's
431: * corresponding values, to log file.
432: */
433: protected void listAllParameters() {
434: try {
435: Enumeration paramNames = this .comms.request
436: .getParameterNames();
437: while (paramNames.hasMoreElements()) {
438: String parameter = (String) paramNames.nextElement();
439: String value = (String) this .comms.request
440: .getParameter(parameter);
441: org.enhydra.snapperAdmin.Log.logToFile("parameter = "
442: + parameter + ", value = " + value);
443: }
444: } catch (Exception ex) {
445: }
446: }
447:
448: /**
449: * This abstract method should be overriden by presentation class, and it is responsible for
450: * generation of http response to user in form of XMLObject instance.
451: *
452: * @return dynamically populated XMLObject generated as response to user http request.
453: * @throws BaseException
454: */
455: protected abstract XMLObject getDOM() throws Exception;
456:
457: public static void printFreeMemory(String prefix) {
458: System.out
459: .println("========================================================");
460: System.out.println(prefix + ", free memory = "
461: + (Runtime.getRuntime().freeMemory() / 1024) / 1024
462: + " MB");
463: System.out.println(prefix + ", max memory = "
464: + (Runtime.getRuntime().maxMemory() / 1024) / 1024
465: + " MB");
466: System.out.println(prefix + ", total memory = "
467: + (Runtime.getRuntime().totalMemory() / 1024) / 1024
468: + " MB");
469: }
470:
471: public static void show(String s) {
472: javax.swing.JOptionPane.showConfirmDialog(null, s);
473: }
474:
475: /**
476: * Read value of parameter from http request.
477: *
478: * @param name
479: * parameter name
480: * @return parameter value
481: */
482: protected boolean getBoolParameter(String name) {
483: boolean retVal = false;
484: String value = null;
485: try {
486: value = this .comms.request.getParameter(name);
487: if (value != null && value.equals("true"))
488: retVal = true;
489: } catch (Exception e) {
490: retVal = false;
491: }
492: return retVal;
493: }
494:
495: }
|