source: main/trunk/greenstone3/src/java/org/greenstone/gsdl3/util/GSXML.java@ 24214

Last change on this file since 24214 was 24214, checked in by sjm84, 13 years ago

Fixed a potential null pointer exception when printing XML nodes

  • Property svn:keywords set to Author Date Id Revision
File size: 34.7 KB
Line 
1/*
2 * GSXML.java
3 * Copyright (C) 2008 New Zealand Digital Library, http://www.nzdl.org
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18 */
19package org.greenstone.gsdl3.util;
20
21import org.w3c.dom.NamedNodeMap;
22import org.w3c.dom.Node;
23import org.w3c.dom.Element;
24import org.w3c.dom.NodeList;
25import org.w3c.dom.Document;
26import org.w3c.dom.Text;
27
28
29import javax.xml.transform.TransformerFactory;
30import javax.xml.transform.Transformer;
31import java.io.StringWriter;
32import javax.xml.transform.stream.StreamResult;
33import javax.xml.transform.dom.DOMSource;
34
35import java.util.Map;
36import java.util.Set;
37import java.util.HashMap;
38import java.util.Vector;
39import java.util.Iterator;
40import java.util.ArrayList;
41
42//import java.util.Locale;
43
44import org.apache.log4j.*;
45
46/** various functions for extracting info out of GS XML */
47public class GSXML {
48
49 static Logger logger = Logger.getLogger(org.greenstone.gsdl3.util.GSXML.class.getName());
50
51 // greenstone xml elements
52 public static final String MESSAGE_ELEM = "message";
53 public static final String REQUEST_ELEM = "request";
54 public static final String RESPONSE_ELEM = "response";
55 public static final String COLLECTION_ELEM = "collection";
56 public static final String SERVICE_ELEM = "service";
57 public static final String CLUSTER_ELEM = "serviceCluster";
58 public static final String SITE_ELEM = "site";
59 public static final String PARAM_ELEM = "param";
60 public static final String PARAM_OPTION_ELEM = "option";
61 public static final String CONTENT_ELEM = "content";
62 public static final String RESOURCE_ELEM = "resource";
63 public static final String DOCUMENT_ELEM = "document";
64 public static final String METADATA_ELEM = "metadata";
65 public static final String SERVICE_CLASS_ELEM = "serviceRack";
66 public static final String CLASSIFIER_ELEM = "classifier";
67 public static final String APPLET_ELEM = "applet";
68 public static final String APPLET_DATA_ELEM = "appletData";
69 public static final String CONFIGURE_ELEM = "configure";
70 public static final String STATUS_ELEM = "status";
71 public static final String ERROR_ELEM = "error";
72 public static final String DEFAULT_ELEM = "default";
73 public static final String STYLESHEET_ELEM = "format";//"stylesheet"; // any additional stylesheet stuff is carried in the message inside this elem
74 public static final String FORMAT_ELEM = "format"; // config files use format - should we use this instead of stylesheet??
75 public static final String TERM_ELEM = "term";
76 public static final String STOPWORD_ELEM = "stopword";
77 public static final String SYSTEM_ELEM = "system";
78 public static final String FORMAT_STRING_ELEM = "formatString";
79
80 //config file elems
81 public static final String COLLECTION_CONFIG_ELEM = "collectionConfig";
82 public static final String COLLECTION_BUILD_ELEM = "buildConfig";
83 public static final String COLLECTION_INIT_ELEM = "collectionInit";
84 public static final String RECOGNISE_ELEM = "recognise";
85 public static final String DOC_TYPE_ELEM = "docType";
86 public static final String SEARCH_ELEM = "search";
87 public static final String INDEX_ELEM = "index";
88 public static final String INDEX_STEM_ELEM = "indexStem";
89 public static final String INDEX_OPTION_ELEM = "indexOption";
90 public static final String BROWSE_ELEM = "browse";
91 public static final String DISPLAY_ELEM = "display";
92 public static final String LEVEL_ELEM = "level";
93
94 public static final String DBINFO_ELEM = "dbInfo";
95 public static final String DBNAME_ATT = "dbname";
96 public static final String DBPATH_ATT = "dbpath";
97 public static final String SQLSTATE_ATT = "sqlstate";
98 public static final String DATABASE_TYPE_ELEM = "databaseType";
99 public static final String SHORTNAME_ATT = "shortname";
100 public static final String NOTIFY_ELEM = "notify";
101 public static final String NOTIFY_HOST_ATT = "host";
102
103
104
105 // elems for the pages to be processed by xslt
106 public final static String PAGE_ELEM = "page";
107 public final static String CONFIGURATION_ELEM = "config";
108 public final static String PAGE_REQUEST_ELEM = "pageRequest";
109 public final static String PAGE_RESPONSE_ELEM = "pageResponse";
110 public final static String PAGE_EXTRA_ELEM = "pageExtra";
111
112 //public final static String DESCRIPTION_ELEM = "description";
113
114 public static final String ACTION_ELEM = "action";
115 public static final String SUBACTION_ELEM = "subaction";
116
117 // add on to another elem type to get a list of that type
118 public static final String LIST_MODIFIER = "List";
119
120 // greenstone xml attributes
121 public static final String NAME_ATT = "name";
122 public static final String TO_ATT = "to";
123 public static final String USER_ID_ATT = "uid";
124 public static final String FROM_ATT = "from";
125 public static final String LANG_ATT = "lang";
126 public static final String TYPE_ATT = "type";
127 public static final String VALUE_ATT = "value";
128 public static final String DEFAULT_ATT = "default";
129 public static final String INFO_ATT = "info";
130 public static final String ACTION_ATT = "action";
131 public static final String SUBACTION_ATT = "subaction";
132 public static final String OUTPUT_ATT = "output";
133 public static final String ADDRESS_ATT = "address";
134 public static final String LOCAL_SITE_ATT = "localSite";
135 public static final String LOCAL_SITE_NAME_ATT = "localSiteName";
136 public static final String STATUS_ERROR_CODE_ATT = "code";
137 public static final String STATUS_PROCESS_ID_ATT = "pid";
138 public static final String PARAM_SHORTNAME_ATT = "shortname";
139 public static final String PARAM_IGNORE_POS_ATT = "ignore";
140 public static final String CLASSIFIER_CONTENT_ATT = "content";
141 public static final String ERROR_TYPE_ATT = "type";
142 public static final String COLLECT_TYPE_ATT = "ct";
143 public static final String HIDDEN_ATT = "hidden";
144
145 // document stuff
146 public static final String DOC_TYPE_ATT = "docType";
147 public static final String DOC_NODE_ELEM = "documentNode";
148 public static final String NODE_CONTENT_ELEM = "nodeContent";
149 public static final String NODE_STRUCTURE_ELEM = "nodeStructure";
150 public static final String NODE_ID_ATT = "nodeID";
151 public static final String NODE_NAME_ATT = "nodeName";
152 public static final String NODE_TYPE_ATT = "nodeType";
153 public static final String NODE_RANK_ATT = "rank";
154 public static final String NODE_TYPE_ROOT = "root";
155 public static final String NODE_TYPE_INTERNAL = "internal";
156 public static final String NODE_TYPE_LEAF = "leaf";
157
158 public static final String DOC_TYPE_SIMPLE = "simple";
159 public static final String DOC_TYPE_PAGED = "paged";
160 public static final String DOC_TYPE_HIERARCHY = "hierarchy";
161
162 public static final String SESSION_EXPIRATION = "session_expiration";
163 public static final String USER_SESSION_CACHE_ATT = "user_session_cache";
164
165 // classifier stuff
166 public static final String CLASS_NODE_ELEM = "classifierNode";
167 public static final String CLASS_NODE_ORIENTATION_ATT = "orientation";
168
169 // parameter types
170 public static final String PARAM_TYPE_INTEGER = "integer";
171 public static final String PARAM_TYPE_BOOLEAN = "boolean";
172 public static final String PARAM_TYPE_ENUM_START = "enum";
173 public static final String PARAM_TYPE_ENUM_SINGLE = "enum_single";
174 public static final String PARAM_TYPE_ENUM_MULTI = "enum_multi";
175 public static final String PARAM_TYPE_STRING = "string";
176 public static final String PARAM_TYPE_TEXT = "text";
177 public static final String PARAM_TYPE_MULTI = "multi";
178 public static final String PARAM_TYPE_FILE = "file";
179 public static final String PARAM_TYPE_INVISIBLE = "invisible";
180 // stuff for text strings
181 public static final String DISPLAY_TEXT_ELEM = "displayItem";
182 // the following are used for the name attributes
183 public static final String DISPLAY_TEXT_NAME = "name";
184 public static final String DISPLAY_TEXT_SUBMIT = "submit";
185 public static final String DISPLAY_TEXT_DESCRIPTION = "description";
186
187 // request types
188 // get the module description
189 public static final String REQUEST_TYPE_DESCRIBE = "describe";
190 // startup a process
191 public static final String REQUEST_TYPE_PROCESS = "process";
192 // get the status of an ongoing process
193 public static final String REQUEST_TYPE_STATUS = "status";
194 // system type request - eg reload a collection
195 public static final String REQUEST_TYPE_SYSTEM = "system";
196 // page requests to the Receptionist/Actions
197 public static final String REQUEST_TYPE_PAGE = "page"; // used to be cgi
198 // get any format info for a service
199 public static final String REQUEST_TYPE_FORMAT = "format";
200 // modify the requests
201 public static final String REQUEST_TYPE_MESSAGING = "messaging";
202 // save the format string
203 public static final String REQUEST_TYPE_FORMAT_STRING = "formatString";
204
205 // service types
206 public static final String SERVICE_TYPE_QUERY = "query";
207 public static final String SERVICE_TYPE_RETRIEVE = "retrieve";
208 public static final String SERVICE_TYPE_BROWSE = "browse";
209 public static final String SERVICE_TYPE_APPLET = "applet";
210 public static final String SERVICE_TYPE_PROCESS = "process";
211 public static final String SERVICE_TYPE_ENRICH = "enrich";
212 public static final String SERVICE_TYPE_OAI = "oai";
213 public static final String FLAX_PAGE = "flaxPage";
214 public static final String FLAX_PAGE_GENERATION = "FlaxPageGeneration";
215
216 // system command types and attributes
217 public static final String SYSTEM_TYPE_CONFIGURE = "configure";
218 public static final String SYSTEM_TYPE_ACTIVATE = "activate";
219 public static final String SYSTEM_TYPE_DEACTIVATE = "deactivate";
220
221 public static final String SYSTEM_SUBSET_ATT = "subset";
222 public static final String SYSTEM_MODULE_TYPE_ATT = "moduleType";
223 public static final String SYSTEM_MODULE_NAME_ATT = "moduleName";
224
225 // communicator types
226 public static final String COMM_TYPE_SOAP_JAVA = "soap";
227
228 // error types
229 public static final String ERROR_TYPE_SYNTAX = "syntax";
230 public static final String ERROR_TYPE_SYSTEM = "system";
231 public static final String ERROR_TYPE_INVALID_ID = "invalid_id";
232 public static final String ERROR_TYPE_OTHER = "other";
233
234 // some system wide param names
235 public static final String SUBSET_PARAM = "subset";
236
237 //for plugin
238 public static final String PLUGIN_ELEM = "plugin";
239 public static final String IMPORT_ELEM = "import";
240
241 //for authentication
242 public static final String AUTHEN_NODE_ELEM="authenticationNode";
243 public static final String USER_NODE_ELEM="userNode";
244
245 //for configure action results
246 public static final String SUCCESS = "success";
247 public static final String ERROR = "error";
248
249 /** takes a list of elements, and returns an array of strings
250 * of the values of attribute att_name */
251 public static String [] getAttributeValuesFromList(Element list,
252 String att_name) {
253
254 NodeList children = list.getChildNodes();
255
256 int num_nodes = children.getLength();
257 String []ids = new String[num_nodes];
258 for (int i=0; i<num_nodes; i++) {
259 Element e = (Element)children.item(i);
260 String id = e.getAttribute(att_name);
261 ids[i] = id;
262 }
263
264 return ids;
265 }
266
267 public static HashMap extractParams(Element xml, boolean deep) {
268 return extractParams(xml, deep, null);
269 }
270
271 /** takes a paramList element, and gets a HashMap of name-value pairs
272 * if deep=true, extracts embedded params, otherwise just top level
273 * params*/
274 public static HashMap extractParams(Element xml, boolean deep, String toFind) {
275
276 if (!xml.getNodeName().equals(PARAM_ELEM+LIST_MODIFIER)) {
277 logger.error("paramList element should have been passed to extractParams, instead it was "+xml.getNodeName());
278 return null;
279 }
280
281 NodeList params = null;
282 if (deep) { // get all the nested ones
283 params = xml.getElementsByTagName(PARAM_ELEM);
284 } else { // just get the top level ones
285 params = xml.getChildNodes();
286 }
287 HashMap param_map = new HashMap();
288 for (int i=0; i<params.getLength(); i++) {
289 if (params.item(i).getNodeName().equals(PARAM_ELEM)) {
290 Element param = (Element)params.item(i);
291 String name=param.getAttribute(NAME_ATT);
292 String value=getValue(param); //att or content
293
294 // For only one parameter
295 if(toFind != null && name.equals(toFind)) {
296 param_map.put(name, value);
297 return param_map;
298 }
299 else if(toFind != null)
300 continue;
301
302 int pos = name.indexOf('.');
303 if (pos == -1) { // a base param
304 param_map.put(name, value);
305 } else { // a namespaced param
306
307 String namespace = name.substring(0, pos);
308 name = name.substring(pos+1);
309 HashMap map = (HashMap)param_map.get(namespace);
310 if (map == null) {
311 map = new HashMap();
312 param_map.put(namespace, map);
313 }
314 map.put(name, value);
315 }
316 }
317 }
318 return param_map;
319 }
320
321 /** gets the value att or the text content */
322 public static String getValue(Element e) {
323 String val = e.getAttribute(VALUE_ATT);
324 if (val ==null || val.equals("")) {
325 // have to get it out of the text
326 val=getNodeText(e);
327
328 } else {
329 // unescape the xml stuff
330 val = unXmlSafe(val);
331 }
332 return val;
333 }
334
335 /** extracts the text out of a node */
336 public static Node getNodeTextNode(Element param) {
337 param.normalize();
338 Node n = param.getFirstChild();
339 while (n!=null && n.getNodeType() !=Node.TEXT_NODE) {
340 n=n.getNextSibling();
341 }
342 return n;
343 }
344
345 /** extracts the text out of a node */
346 public static String getNodeText(Element param) {
347 Node text_node = getNodeTextNode(param);
348 if (text_node == null) {
349 return "";
350 }
351 return text_node.getNodeValue();
352 }
353
354 public static void setNodeText(Element elem, String text) {
355 Node old_text_node = getNodeTextNode(elem);
356 if (old_text_node != null) {
357 elem.removeChild(old_text_node);
358 }
359 Text t = elem.getOwnerDocument().createTextNode(text);
360 elem.appendChild(t);
361 }
362
363 /** add text to a document/subsection element */
364 public static boolean addDocText(Document owner, Element doc, String text) {
365
366 Element content = owner.createElement(NODE_CONTENT_ELEM);
367 Text t = owner.createTextNode(text);
368 content.appendChild(t);
369 doc.appendChild(content);
370 return true;
371 }
372
373 /** add an error message, unknown error type */
374 public static boolean addError(Document owner, Element doc, String text) {
375 return addError(owner, doc, text, ERROR_TYPE_OTHER);
376 }
377 /** add an error message */
378 public static boolean addError(Document owner, Element doc, String text,
379 String error_type) {
380
381 Element content = owner.createElement(ERROR_ELEM);
382 content.setAttribute(ERROR_TYPE_ATT, error_type);
383 Text t = owner.createTextNode(text);
384 content.appendChild(t);
385 doc.appendChild(content);
386 return true;
387 }
388
389 /** add an error message */
390 public static boolean addError(Document owner, Element doc, Throwable error) {
391 return addError(owner, doc, error, ERROR_TYPE_OTHER);
392 }
393
394 /** add an error message */
395 public static boolean addError(Document owner, Element doc,
396 Throwable error, String error_type) {
397 error.printStackTrace();
398 return addError(owner, doc, error.toString(), error_type);
399 }
400
401 public static Element createMetadataParamList(Document owner, Vector meta_values) {
402
403 Element meta_param_list = owner.createElement(PARAM_ELEM+LIST_MODIFIER);
404 Iterator i = meta_values.iterator();
405 while(i.hasNext()) {
406 String next = (String)i.next();
407 Element meta_param = owner.createElement(PARAM_ELEM);
408 meta_param_list.appendChild(meta_param);
409 meta_param.setAttribute(NAME_ATT, "metadata");
410 meta_param.setAttribute(VALUE_ATT, next);
411 }
412 return meta_param_list;
413 }
414
415 /** adds a metadata elem to a list */
416 public static boolean addMetadata(Document owner, Element list,
417 String meta_name, String meta_value) {
418 if (meta_value==null || meta_value.equals("")) {
419 return false;
420 }
421 Element data = owner.createElement(METADATA_ELEM);
422 data.setAttribute(NAME_ATT, meta_name);
423 Text t = owner.createTextNode(meta_value);
424 data.appendChild(t);
425 list.appendChild(data);
426 return true;
427
428 }
429
430 /** copies the metadata out of the metadataList of 'from' into
431 * the metadataList of 'to' */
432 public static boolean mergeMetadataLists(Node to, Node from) {
433 Node from_meta = getChildByTagName(from, METADATA_ELEM+LIST_MODIFIER);
434 if (from_meta == null) { // nothing to copy
435 return true;
436 }
437 return mergeMetadataFromList(to, from_meta);
438 }
439
440
441 /** copies the metadata out of the meta_list metadataList into
442 * the metadataList of 'to' */
443 public static boolean mergeMetadataFromList(Node to, Node meta_list) {
444 if (meta_list == null) return false;
445 Node to_meta = getChildByTagName(to, METADATA_ELEM+LIST_MODIFIER);
446 Document to_owner = to.getOwnerDocument();
447 if (to_meta == null) {
448 to.appendChild(to_owner.importNode(meta_list, true));
449 return true;
450 }
451 // copy individual metadata elements
452 NodeList meta_items = ((Element)meta_list).getElementsByTagName(METADATA_ELEM);
453 for (int i=0; i<meta_items.getLength(); i++) {
454 to_meta.appendChild(to_owner.importNode(meta_items.item(i),true));
455 }
456 return true;
457 }
458
459 /** copies all the children from from to to */
460 public static boolean mergeElements(Element to, Element from) {
461
462 Document owner = to.getOwnerDocument();
463 Node child = from.getFirstChild();
464 while (child != null) {
465 to.appendChild(owner.importNode(child, true));
466 child = child.getNextSibling();
467 }
468 return true;
469 }
470 /** returns the (first) element child of the node n */
471 public static Element getFirstElementChild(Node n) {
472
473 Node child = n.getFirstChild();
474 while (child!=null) {
475 if (child.getNodeType() == Node.ELEMENT_NODE) {
476 return (Element)child;
477 }
478 child = child.getNextSibling();
479 }
480 return null; //no element child found
481 }
482 /** returns the (first) child element with the given name */
483 public static Node getChildByTagName(Node n, String name) {
484 if(n != null) { // this line is an attempted solution to the NullPointerException mentioned
485 // in trac bug ticket #225. If n is null can't do n.getFirstChild() below. As per bug #225:
486 // GSXML.getNodeByPath() is called by GS2BrowseAction, which then calls this method.
487 // If n is null, null will be returned which GS2BrowseAction already checks for. It's here
488 // that the NullPointerException was thrown.
489
490 Node child = n.getFirstChild();
491 while (child!=null) {
492 if (child.getNodeName().equals(name)) {
493 return child;
494 }
495 child = child.getNextSibling();
496 }
497 }
498 return null; //not found
499 }
500
501 /** returns the (nth) child element with the given name
502 * index numbers start at 0 */
503 public static Node getChildByTagNameIndexed(Node n, String name, int index) {
504 if (index == -1) {
505 return getChildByTagName(n, name);
506 }
507 int count = 0;
508 Node child = n.getFirstChild();
509 while (child!=null) {
510 if (child.getNodeName().equals(name)) {
511 if (count == index) {
512 return child;
513 } else {
514 count++;
515 }
516 }
517 child = child.getNextSibling();
518 }
519 return null; //not found
520 }
521
522 /** takes an xpath type expression of the form name/name/...
523 * and returns the first node that matches, or null if not found */
524 public static Node getNodeByPath(Node n, String path) {
525
526 String link = GSPath.getFirstLink(path);
527 path = GSPath.removeFirstLink(path);
528 while (!link.equals("")) {
529 n = getChildByTagName(n, link);
530 if (n==null) {
531 return null;
532 }
533 link = GSPath.getFirstLink(path);
534 path = GSPath.removeFirstLink(path);
535 }
536 return n;
537 }
538
539 /** takes an xpath type expression of the form name/name/...
540 * and returns the first node that matches, or null if not found
541 * can include [i] indices. index numbers start at 0 */
542 public static Node getNodeByPathIndexed(Node n, String path) {
543
544 String link = GSPath.getFirstLink(path);
545 int index = GSPath.getIndex(link);
546 if (index != -1) {
547 link = GSPath.removeIndex(link);
548 }
549 path = GSPath.removeFirstLink(path);
550 while (!link.equals("")) {
551 n = getChildByTagNameIndexed(n, link, index);
552 if (n==null) {
553 return null;
554 }
555 link = GSPath.getFirstLink(path);
556 index = GSPath.getIndex(link);
557 if (index != -1) {
558 link = GSPath.removeIndex(link);
559 }
560 path = GSPath.removeFirstLink(path);
561 }
562 return n;
563 }
564
565 public static HashMap getChildrenMap(Node n) {
566
567 HashMap map= new HashMap();
568 Node child = n.getFirstChild();
569 while (child!=null) {
570 String name = child.getNodeName();
571 map.put(name, child);
572 child = child.getNextSibling();
573 }
574 return map;
575 }
576
577 public static NodeList getChildrenByTagName(Node n, String name) {
578 MyNodeList node_list = new MyNodeList();
579 Node child = n.getFirstChild();
580 while (child!=null) {
581 if (child.getNodeName().equals(name)) {
582 node_list.addNode(child);
583 }
584 child = child.getNextSibling();
585 }
586 return node_list;
587 }
588
589
590 /** Duplicates an element, but gives it a new name */
591 public static Element duplicateWithNewName(Document owner, Element element,
592 String element_name, boolean with_attributes) {
593 return duplicateWithNewNameNS(owner, element, element_name, null, with_attributes);
594 }
595
596 /** Duplicates an element, but gives it a new name */
597 public static Element duplicateWithNewNameNS(Document owner,
598 Element element,
599 String element_name,
600 String namespace_uri,
601 boolean with_attributes) {
602 Element duplicate;
603 if (namespace_uri == null) {
604 duplicate = owner.createElement(element_name);
605 } else {
606 duplicate = owner.createElementNS(namespace_uri, element_name);
607 }
608 // Copy element attributes
609 if (with_attributes) {
610 NamedNodeMap attributes = element.getAttributes();
611 for (int i = 0; i < attributes.getLength(); i++) {
612 Node attribute = attributes.item(i);
613 duplicate.setAttribute(attribute.getNodeName(), attribute.getNodeValue());
614 }
615 }
616
617 // Copy element children
618 NodeList children = element.getChildNodes();
619 for (int i = 0; i < children.getLength(); i++) {
620 Node child = children.item(i);
621 duplicate.appendChild(owner.importNode(child, true));
622 }
623
624 return duplicate;
625 }
626
627 public static void copyAllChildren(Element to, Element from) {
628
629 Document to_doc = to.getOwnerDocument();
630 Node child = from.getFirstChild();
631 while (child != null) {
632 to.appendChild(to_doc.importNode(child, true));
633 child = child.getNextSibling();
634 }
635 }
636 /** returns a basic request message */
637 public static Element createBasicRequest(Document owner,
638 String request_type, String to,
639 String lang,
640 String uid) {
641 Element request = owner.createElement(REQUEST_ELEM);
642 request.setAttribute(TYPE_ATT, request_type);
643 request.setAttribute(LANG_ATT, lang);
644 request.setAttribute(TO_ATT, to);
645 request.setAttribute(USER_ID_ATT, uid);
646 return request;
647 }
648
649 public static Element createTextElement(Document owner, String elem_name,
650 String text) {
651 Element e = owner.createElement(elem_name);
652 Text t = owner.createTextNode(text);
653 e.appendChild(t);
654 return e;
655
656 }
657
658 public static Element createTextElement(Document owner, String elem_name,
659 String text, String att_name, String att_value) {
660 Element e = owner.createElement(elem_name);
661 e.setAttribute(att_name, att_value);
662 Text t = owner.createTextNode(text);
663 e.appendChild(t);
664 return e;
665
666 }
667
668 public static Element createDisplayTextElement(Document owner,
669 String text_name,
670 String text) {
671 Element e = owner.createElement(DISPLAY_TEXT_ELEM);
672 e.setAttribute(NAME_ATT, text_name);
673 Text t = owner.createTextNode(text);
674 e.appendChild(t);
675 return e;
676
677 }
678
679
680 public static Element createParameter(Document owner, String name,
681 String value) {
682 Element param = owner.createElement(PARAM_ELEM);
683 param.setAttribute(NAME_ATT, name);
684 param.setAttribute(VALUE_ATT, value);
685 return param;
686 }
687
688 public static void addParametersToList(Document owner, Element param_list,
689 HashMap params) {
690 if (params == null)
691 {
692 return;
693 }
694
695 Set items = params.entrySet();
696 Iterator i = items.iterator();
697 while(i.hasNext()) {
698 Map.Entry m = (Map.Entry)i.next();
699 param_list.appendChild(createParameter(owner, (String)m.getKey(), (String)m.getValue()));
700 }
701
702 }
703
704 public static Element createParameterDescription(Document owner,
705 String id,
706 String display_name,
707 String type,
708 String default_value,
709 String []option_ids,
710 String []option_names) {
711
712
713 Element p = owner.createElement(PARAM_ELEM);
714 p.setAttribute(NAME_ATT, id);
715 p.setAttribute(TYPE_ATT, type);
716 p.appendChild(createDisplayTextElement(owner, GSXML.DISPLAY_TEXT_NAME, display_name));
717
718 if (default_value != null) {
719 p.setAttribute(DEFAULT_ATT, default_value);
720 }
721 if (option_ids!=null && option_names!=null) {
722 for (int i=0; i<option_ids.length; i++) {
723 Element e = owner.createElement(PARAM_OPTION_ELEM);
724 e.setAttribute(NAME_ATT, option_ids[i]);
725 e.appendChild(createDisplayTextElement(owner, GSXML.DISPLAY_TEXT_NAME, option_names[i]));
726 p.appendChild(e);
727 }
728 }
729 return p;
730 }
731 public static Element createParameterDescription2(Document owner,
732 String id,
733 String display_name,
734 String type,
735 String default_value,
736 ArrayList option_ids,
737 ArrayList option_names) {
738
739
740 Element p = owner.createElement(PARAM_ELEM);
741 p.setAttribute(NAME_ATT, id);
742 p.setAttribute(TYPE_ATT, type);
743 p.appendChild(createDisplayTextElement(owner, GSXML.DISPLAY_TEXT_NAME, display_name));
744 if (default_value != null) {
745 p.setAttribute(DEFAULT_ATT, default_value);
746 }
747 if (option_ids!=null && option_names!=null) {
748 for (int i=0; i<option_ids.size(); i++) {
749 Element e = owner.createElement(PARAM_OPTION_ELEM);
750 e.setAttribute(NAME_ATT, (String)option_ids.get(i));
751 e.appendChild(createDisplayTextElement(owner, GSXML.DISPLAY_TEXT_NAME, (String)option_names.get(i)));
752 p.appendChild(e);
753 }
754 }
755 return p;
756 }
757
758
759 /** returns the element parent/node_name[@attribute_name='attribute_value']
760 */
761 public static Element getNamedElement(Element parent, String node_name,
762 String attribute_name,
763 String attribute_value) {
764
765 NodeList children = parent.getChildNodes();
766 for (int i=0; i<children.getLength(); i++) {
767 Node child = children.item(i);
768 if (child.getNodeName().equals(node_name)) {
769 if (((Element)child).getAttribute(attribute_name).equals(attribute_value))
770 return (Element)child;
771 }
772 }
773 // not found
774 return null;
775 }
776 /** returns a NodeList of elements: ancestor/node_name[@attribute_name='attribute_value']
777 */
778 public static NodeList getNamedElements(Element ancestor, String node_name, String attribute_name, String attribute_value) {
779 MyNodeList node_list = new MyNodeList();
780 NodeList children = ancestor.getElementsByTagName(node_name);
781
782 if(children != null && children.getLength() > 0) {
783
784 for (int i=0; i<children.getLength(); i++) {
785 Node child = children.item(i);
786 if (child.getNodeName().equals(node_name)) {
787 if (((Element)child).getAttribute(attribute_name).equals(attribute_value))
788 node_list.addNode(child);
789 }
790 }
791 }
792 return node_list;
793 }
794
795 public static int SORT_TYPE_STRING = 0;
796 public static int SORT_TYPE_INT = 1;
797 public static int SORT_TYPE_FLOAT = 2;
798
799 // sort type:
800 public static Element insertIntoOrderedList(Element parent_node,
801 String node_name,
802 Element start_from_elem,
803 Element new_elem, String sort_att,
804 boolean descending) {
805 if (new_elem == null) return null;
806 Element cloned_elem = (Element)parent_node.getOwnerDocument().importNode(new_elem, true);
807 if (start_from_elem == null) {
808 parent_node.appendChild(cloned_elem);
809 return cloned_elem;
810 }
811
812 Node current_node = start_from_elem;
813 String insert_att = cloned_elem.getAttribute(sort_att);
814 String list_att = start_from_elem.getAttribute(sort_att);
815 while ((!descending && list_att.compareTo(insert_att)<0) || (descending && list_att.compareTo(insert_att)>0)) {
816 current_node = current_node.getNextSibling();
817 if (current_node == null) break; // end of the list
818 if (!current_node.getNodeName().equals(node_name)) {
819 continue; // not a valid node
820 }
821 list_att = ((Element)current_node).getAttribute(sort_att);
822 }
823
824 parent_node.insertBefore(cloned_elem, current_node);
825 return cloned_elem;
826 }
827
828
829 /** Returns the appropriate language element from a display elem,
830 * display is the containing element, name is the name of the element to
831 * look for, lang is the preferred language, lang_default is the fall back
832 * lang if neither lang is found, will return the first one it finds*/
833 public static String getDisplayText(Element display, String name,
834 String lang, String lang_default) {
835
836 String def = null;
837 String first = null;
838 NodeList elems = display.getElementsByTagName(DISPLAY_TEXT_ELEM);
839 if (elems.getLength() == 0) return "";
840 for (int i=0; i<elems.getLength(); i++) {
841 Element e = (Element)elems.item(i);
842 String n = e.getAttribute(NAME_ATT);
843 if (name.equals(n)) {
844 String l = e.getAttribute(LANG_ATT);
845 if (lang.equals(l)) {
846 return getNodeText(e);
847 } else if (lang_default.equals(l)) {
848 def = getNodeText(e);
849 } else if (first == null) {
850 first = getNodeText(e);
851 }
852 } else {
853 continue;
854 }
855 }
856
857 if (def != null) {
858 return def;
859 }
860 if (first != null) {
861 return first;
862 }
863 return "";
864 }
865
866 // replaces < > " ' & in the original with their entities
867 public static String xmlSafe(String original) {
868
869 StringBuffer filtered = new StringBuffer(original.length());
870 char c;
871 for (int i=0; i<original.length(); i++) {
872 c = original.charAt(i);
873 if (c == '>') {
874 filtered.append("&gt;");
875 } else if (c == '<') {
876 filtered.append("&lt;");
877 } else if (c == '"') {
878 filtered.append("&quot;");
879 } else if (c == '&') {
880 filtered.append("&amp;");
881 } else if (c == '\'') {
882 filtered.append("&apos;");
883 } else {
884 filtered.append(c);
885 }
886 }
887 return filtered.toString();
888 }
889
890
891 // replaces < > " ' & entities with their originals
892 public static String unXmlSafe(String original) {
893
894 StringBuffer filtered = new StringBuffer(original.length());
895 char c;
896 for (int i=0; i<original.length(); i++) {
897 c = original.charAt(i);
898 if (c == '&') {
899 int pos = original.indexOf(";", i);
900 String entity = original.substring(i+1, pos);
901 if (entity.equals("gt")) {
902 filtered.append(">");
903 } else if (entity.equals("lt")) {
904 filtered.append("<");
905 } else if (entity.equals("apos")) {
906 filtered.append("'");
907 } else if (entity.equals("amp")) {
908 filtered.append("&");
909 } else if (entity.equals("quot")) {
910 filtered.append("\"");
911 } else {
912 filtered.append("&"+entity+";");
913 }
914 i = pos;
915 } else {
916 filtered.append(c);
917 }
918 }
919 return filtered.toString();
920 }
921
922 public static void printXMLNode(Node e) {
923 printXMLNode(e, 0) ;
924 }
925
926 public static String xmlNodeToString(Node e){
927 StringBuffer sb = new StringBuffer("");
928 xmlNodeToString(sb,e,0);
929 return sb.toString();
930 }
931
932 private static void xmlNodeToString(StringBuffer sb, Node e, int depth){
933
934 for (int i=0 ; i<depth ; i++)
935 sb.append(' ') ;
936
937 if (e.getNodeType() == Node.TEXT_NODE){
938 sb.append("text") ;
939 return ;
940 }
941
942 sb.append('<');
943 sb.append(e.getNodeName());
944 NamedNodeMap attrs = e.getAttributes();
945 if(attrs != null)
946 {
947 for (int i = 0; i < attrs.getLength(); i++) {
948 Node attr = attrs.item(i);
949 sb.append(' ');
950 sb.append(attr.getNodeName());
951 sb.append("=\"");
952 sb.append(attr.getNodeValue());
953 sb.append('"');
954 }
955 }
956
957 NodeList children = e.getChildNodes();
958
959 if (children == null || children.getLength() == 0)
960 sb.append("/>\n") ;
961 else {
962
963 sb.append(">\n") ;
964
965 int len = children.getLength();
966 for (int i = 0; i < len; i++) {
967 xmlNodeToString(sb,children.item(i), depth + 1);
968 }
969
970 for (int i=0 ; i<depth ; i++)
971 sb.append(' ') ;
972
973 sb.append("</" + e.getNodeName() + ">\n");
974 }
975
976
977 }
978
979 public static void printXMLNode(Node e, int depth) { //recursive method call using DOM API...
980
981 for (int i=0 ; i<depth ; i++)
982 System.out.print(' ') ;
983
984 if (e.getNodeType() == Node.TEXT_NODE){
985 // shouldn't we actually print the text here????
986 System.out.println("text") ;
987 return ;
988 }
989
990 System.out.print('<');
991 System.out.print(e.getNodeName());
992 NamedNodeMap attrs = e.getAttributes();
993
994 if (attrs != null)
995 {
996 for (int i = 0; i < attrs.getLength(); i++) {
997 Node attr = attrs.item(i);
998 System.out.print(' ');
999 System.out.print(attr.getNodeName());
1000 System.out.print("=\"");
1001 System.out.print(attr.getNodeValue());
1002 System.out.print('"');
1003 }
1004 }
1005
1006 NodeList children = e.getChildNodes();
1007
1008 if (children == null || children.getLength() == 0)
1009 System.out.println("/>") ;
1010 else {
1011
1012 System.out.println('>') ;
1013
1014 int len = children.getLength();
1015 for (int i = 0; i < len; i++) {
1016 printXMLNode(children.item(i), depth + 1);
1017 }
1018
1019 for (int i=0 ; i<depth ; i++)
1020 System.out.print(' ') ;
1021
1022 System.out.println("</" + e.getNodeName() + ">");
1023 }
1024
1025 }
1026
1027 public static void elementToLogAsString(Element e) {
1028 try {
1029 TransformerFactory tf = TransformerFactory.newInstance();
1030 Transformer trans = tf.newTransformer();
1031 StringWriter sw = new StringWriter();
1032 trans.transform(new DOMSource(e), new StreamResult(sw));
1033 System.err.println( sw.toString() );
1034 } catch( Exception ex ) {
1035 System.err.println( "couldn't write " + e + " to log" );
1036 }
1037
1038 }
1039}
Note: See TracBrowser for help on using the repository browser.