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

Last change on this file since 14401 was 14401, checked in by xiao, 17 years ago

add in two constant strings.

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