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

Last change on this file since 14641 was 14641, checked in by anna, 17 years ago

Added the collection type (ct) parameter.

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