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

Last change on this file since 13541 was 13541, checked in by shaoqun, 17 years ago

added the method that output a xml node to a nicely formatted string

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