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