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

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

add in few constant strings.

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