source: trunk/gsdl3/src/java/org/greenstone/gsdl3/util/GSXML.java@ 13908

Last change on this file since 13908 was 13908, checked in by kjdon, 17 years ago

don't use FIELD_ELEM anymore

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