source: greenstone3/branches/customizingGreenstone3/src/java/org/greenstone/gsdl3/util/GSXML.java@ 15787

Last change on this file since 15787 was 15787, checked in by oranfry, 16 years ago

updating from trunk: brought in trunk changes from r15191 to r15785

  • Property svn:keywords set to Author Date Id Revision
File size: 31.7 KB
Line 
1package org.greenstone.gsdl3.util;
2
3import org.w3c.dom.NamedNodeMap;
4import org.w3c.dom.Node;
5import org.w3c.dom.Element;
6import org.w3c.dom.NodeList;
7import org.w3c.dom.Document;
8import org.w3c.dom.Text;
9
10import java.util.Map;
11import java.util.Set;
12import java.util.HashMap;
13import java.util.Vector;
14import java.util.Iterator;
15import java.util.ArrayList;
16
17//import java.util.Locale;
18
19import org.apache.log4j.*;
20
21/** various functions for extracting info out of GS XML */
22public class GSXML {
23
24 static Logger logger = Logger.getLogger(org.greenstone.gsdl3.util.GSXML.class.getName());
25
26 // greenstone xml elements
27 public static final String MESSAGE_ELEM = "message";
28 public static final String REQUEST_ELEM = "request";
29 public static final String RESPONSE_ELEM = "response";
30 public static final String COLLECTION_ELEM = "collection";
31 public static final String SERVICE_ELEM = "service";
32 public static final String CLUSTER_ELEM = "serviceCluster";
33 public static final String SITE_ELEM = "site";
34 public static final String PARAM_ELEM = "param";
35 public static final String PARAM_OPTION_ELEM = "option";
36 public static final String CONTENT_ELEM = "content";
37 public static final String RESOURCE_ELEM = "resource";
38 public static final String DOCUMENT_ELEM = "document";
39 public static final String METADATA_ELEM = "metadata";
40 public static final String SERVICE_CLASS_ELEM = "serviceRack";
41 public static final String CLASSIFIER_ELEM = "classifier";
42 public static final String APPLET_ELEM = "applet";
43 public static final String APPLET_DATA_ELEM = "appletData";
44 public static final String CONFIGURE_ELEM = "configure";
45 public static final String STATUS_ELEM = "status";
46 public static final String ERROR_ELEM = "error";
47 public static final String DEFAULT_ELEM = "default";
48 public static final String STYLESHEET_ELEM = "format";//"stylesheet"; // any additional stylesheet stuff is carried in the message inside this elem
49 public static final String FORMAT_ELEM = "format"; // config files use format - should we use this instead of stylesheet??
50 public static final String TERM_ELEM = "term";
51 public static final String SYSTEM_ELEM = "system";
52
53 //config file elems
54 public static final String COLLECTION_CONFIG_ELEM = "collectionConfig";
55 public static final String COLLECTION_BUILD_ELEM = "buildConfig";
56 public static final String COLLECTION_INIT_ELEM = "collectionInit";
57 public static final String RECOGNISE_ELEM = "recognise";
58 public static final String DOC_TYPE_ELEM = "docType";
59 public static final String SEARCH_ELEM = "search";
60 public static final String INDEX_ELEM = "index";
61 public static final String INDEX_STEM_ELEM = "indexStem";
62 public static final String INDEX_OPTION_ELEM = "indexOption";
63 public static final String BROWSE_ELEM = "browse";
64 public static final String DISPLAY_ELEM = "display";
65 public static final String LEVEL_ELEM = "level";
66 public static final String DATABASE_TYPE_ELEM = "databaseType";
67 public static final String SHORTNAME_ATT = "shortname";
68 public static final String NOTIFY_ELEM = "notify";
69 public static final String NOTIFY_HOST_ATT = "host";
70 // 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 if(n != null) { // this line is an attempted solution to the NullPointerException mentioned
426 // in trac bug ticket #225. If n is null can't do n.getFirstChild() below. As per bug #225:
427 // GSXML.getNodeByPath() is called by GS2BrowseAction, which then calls this method.
428 // If n is null, null will be returned which GS2BrowseAction already checks for. It's here
429 // that the NullPointerException was thrown.
430
431 Node child = n.getFirstChild();
432 while (child!=null) {
433 if (child.getNodeName().equals(name)) {
434 return child;
435 }
436 child = child.getNextSibling();
437 }
438 }
439 return null; //not found
440 }
441
442 /** returns the (nth) child element with the given name
443 * index numbers start at 0 */
444 public static Node getChildByTagNameIndexed(Node n, String name, int index) {
445 if (index == -1) {
446 return getChildByTagName(n, name);
447 }
448 int count = 0;
449 Node child = n.getFirstChild();
450 while (child!=null) {
451 if (child.getNodeName().equals(name)) {
452 if (count == index) {
453 return child;
454 } else {
455 count++;
456 }
457 }
458 child = child.getNextSibling();
459 }
460 return null; //not found
461 }
462
463 /** takes an xpath type expression of the form name/name/...
464 * and returns the first node that matches, or null if not found */
465 public static Node getNodeByPath(Node n, String path) {
466
467 String link = GSPath.getFirstLink(path);
468 path = GSPath.removeFirstLink(path);
469 while (!link.equals("")) {
470 n = getChildByTagName(n, link);
471 if (n==null) {
472 return null;
473 }
474 link = GSPath.getFirstLink(path);
475 path = GSPath.removeFirstLink(path);
476 }
477 return n;
478 }
479
480 /** takes an xpath type expression of the form name/name/...
481 * and returns the first node that matches, or null if not found
482 * can include [i] indices. index numbers start at 0 */
483 public static Node getNodeByPathIndexed(Node n, String path) {
484
485 String link = GSPath.getFirstLink(path);
486 int index = GSPath.getIndex(link);
487 if (index != -1) {
488 link = GSPath.removeIndex(link);
489 }
490 path = GSPath.removeFirstLink(path);
491 while (!link.equals("")) {
492 n = getChildByTagNameIndexed(n, link, index);
493 if (n==null) {
494 return null;
495 }
496 link = GSPath.getFirstLink(path);
497 index = GSPath.getIndex(link);
498 if (index != -1) {
499 link = GSPath.removeIndex(link);
500 }
501 path = GSPath.removeFirstLink(path);
502 }
503 return n;
504 }
505
506 public static HashMap getChildrenMap(Node n) {
507
508 HashMap map= new HashMap();
509 Node child = n.getFirstChild();
510 while (child!=null) {
511 String name = child.getNodeName();
512 map.put(name, child);
513 child = child.getNextSibling();
514 }
515 return map;
516 }
517
518 public static NodeList getChildrenByTagName(Node n, String name) {
519 MyNodeList node_list = new MyNodeList();
520 Node child = n.getFirstChild();
521 while (child!=null) {
522 if (child.getNodeName().equals(name)) {
523 node_list.addNode(child);
524 }
525 child = child.getNextSibling();
526 }
527 return node_list;
528 }
529
530
531 /** Duplicates an element, but gives it a new name */
532 public static Element duplicateWithNewName(Document owner, Element element,
533 String element_name, boolean with_attributes) {
534 return duplicateWithNewNameNS(owner, element, element_name, null, with_attributes);
535 }
536
537 /** Duplicates an element, but gives it a new name */
538 public static Element duplicateWithNewNameNS(Document owner,
539 Element element,
540 String element_name,
541 String namespace_uri,
542 boolean with_attributes) {
543 Element duplicate;
544 if (namespace_uri == null) {
545 duplicate = owner.createElement(element_name);
546 } else {
547 duplicate = owner.createElementNS(namespace_uri, element_name);
548 }
549 // Copy element attributes
550 if (with_attributes) {
551 NamedNodeMap attributes = element.getAttributes();
552 for (int i = 0; i < attributes.getLength(); i++) {
553 Node attribute = attributes.item(i);
554 duplicate.setAttribute(attribute.getNodeName(), attribute.getNodeValue());
555 }
556 }
557
558 // Copy element children
559 NodeList children = element.getChildNodes();
560 for (int i = 0; i < children.getLength(); i++) {
561 Node child = children.item(i);
562 duplicate.appendChild(owner.importNode(child, true));
563 }
564
565 return duplicate;
566 }
567
568 public static void copyAllChildren(Element to, Element from) {
569
570 Document to_doc = to.getOwnerDocument();
571 Node child = from.getFirstChild();
572 while (child != null) {
573 to.appendChild(to_doc.importNode(child, true));
574 child = child.getNextSibling();
575 }
576 }
577 /** returns a basic request message */
578 public static Element createBasicRequest(Document owner,
579 String request_type, String to,
580 String lang,
581 String uid) {
582 Element request = owner.createElement(REQUEST_ELEM);
583 request.setAttribute(TYPE_ATT, request_type);
584 request.setAttribute(LANG_ATT, lang);
585 request.setAttribute(TO_ATT, to);
586 request.setAttribute(USER_ID_ATT, uid);
587 return request;
588 }
589
590 public static Element createTextElement(Document owner, String elem_name,
591 String text) {
592 Element e = owner.createElement(elem_name);
593 Text t = owner.createTextNode(text);
594 e.appendChild(t);
595 return e;
596
597 }
598
599 public static Element createDisplayTextElement(Document owner,
600 String text_name,
601 String text) {
602 Element e = owner.createElement(DISPLAY_TEXT_ELEM);
603 e.setAttribute(NAME_ATT, text_name);
604 Text t = owner.createTextNode(text);
605 e.appendChild(t);
606 return e;
607
608 }
609
610
611 public static Element createParameter(Document owner, String name,
612 String value) {
613 Element param = owner.createElement(PARAM_ELEM);
614 param.setAttribute(NAME_ATT, name);
615 param.setAttribute(VALUE_ATT, value);
616 return param;
617 }
618
619 public static void addParametersToList(Document owner, Element param_list,
620 HashMap params) {
621 Set items = params.entrySet();
622 Iterator i = items.iterator();
623 while(i.hasNext()) {
624 Map.Entry m = (Map.Entry)i.next();
625 param_list.appendChild(createParameter(owner, (String)m.getKey(), (String)m.getValue()));
626 }
627
628 }
629
630 public static Element createParameterDescription(Document owner,
631 String id,
632 String display_name,
633 String type,
634 String default_value,
635 String []option_ids,
636 String []option_names) {
637
638
639 Element p = owner.createElement(PARAM_ELEM);
640 p.setAttribute(NAME_ATT, id);
641 p.setAttribute(TYPE_ATT, type);
642 p.appendChild(createDisplayTextElement(owner, GSXML.DISPLAY_TEXT_NAME, display_name));
643
644 if (default_value != null) {
645 p.setAttribute(DEFAULT_ATT, default_value);
646 }
647 if (option_ids!=null && option_names!=null) {
648 for (int i=0; i<option_ids.length; i++) {
649 Element e = owner.createElement(PARAM_OPTION_ELEM);
650 e.setAttribute(NAME_ATT, option_ids[i]);
651 e.appendChild(createDisplayTextElement(owner, GSXML.DISPLAY_TEXT_NAME, option_names[i]));
652 p.appendChild(e);
653 }
654 }
655 return p;
656 }
657 public static Element createParameterDescription2(Document owner,
658 String id,
659 String display_name,
660 String type,
661 String default_value,
662 ArrayList option_ids,
663 ArrayList option_names) {
664
665
666 Element p = owner.createElement(PARAM_ELEM);
667 p.setAttribute(NAME_ATT, id);
668 p.setAttribute(TYPE_ATT, type);
669 p.appendChild(createDisplayTextElement(owner, GSXML.DISPLAY_TEXT_NAME, display_name));
670 if (default_value != null) {
671 p.setAttribute(DEFAULT_ATT, default_value);
672 }
673 if (option_ids!=null && option_names!=null) {
674 for (int i=0; i<option_ids.size(); i++) {
675 Element e = owner.createElement(PARAM_OPTION_ELEM);
676 e.setAttribute(NAME_ATT, (String)option_ids.get(i));
677 e.appendChild(createDisplayTextElement(owner, GSXML.DISPLAY_TEXT_NAME, (String)option_names.get(i)));
678 p.appendChild(e);
679 }
680 }
681 return p;
682 }
683
684
685 /** returns the element parent/node_name[@attribute_name='attribute_value']
686 */
687 public static Element getNamedElement(Element parent, String node_name,
688 String attribute_name,
689 String attribute_value) {
690
691 NodeList children = parent.getChildNodes();
692 for (int i=0; i<children.getLength(); i++) {
693 Node child = children.item(i);
694 if (child.getNodeName().equals(node_name)) {
695 if (((Element)child).getAttribute(attribute_name).equals(attribute_value))
696 return (Element)child;
697 }
698 }
699 // not found
700 return null;
701 }
702 /** returns a NodeList of elements: ancestor/node_name[@attribute_name='attribute_value']
703 */
704 public static NodeList getNamedElements(Element ancestor, String node_name, String attribute_name, String attribute_value) {
705 MyNodeList node_list = new MyNodeList();
706 NodeList children = ancestor.getElementsByTagName(node_name);
707
708 if(children != null && children.getLength() > 0) {
709
710 for (int i=0; i<children.getLength(); i++) {
711 Node child = children.item(i);
712 if (child.getNodeName().equals(node_name)) {
713 if (((Element)child).getAttribute(attribute_name).equals(attribute_value))
714 node_list.addNode(child);
715 }
716 }
717 }
718 return node_list;
719 }
720
721 public static int SORT_TYPE_STRING = 0;
722 public static int SORT_TYPE_INT = 1;
723 public static int SORT_TYPE_FLOAT = 2;
724
725 // sort type:
726 public static Element insertIntoOrderedList(Element parent_node,
727 String node_name,
728 Element start_from_elem,
729 Element new_elem, String sort_att,
730 boolean descending) {
731 if (new_elem == null) return null;
732 Element cloned_elem = (Element)parent_node.getOwnerDocument().importNode(new_elem, true);
733 if (start_from_elem == null) {
734 parent_node.appendChild(cloned_elem);
735 return cloned_elem;
736 }
737
738 Node current_node = start_from_elem;
739 String insert_att = cloned_elem.getAttribute(sort_att);
740 String list_att = start_from_elem.getAttribute(sort_att);
741 while ((!descending && list_att.compareTo(insert_att)<0) || (descending && list_att.compareTo(insert_att)>0)) {
742 current_node = current_node.getNextSibling();
743 if (current_node == null) break; // end of the list
744 if (!current_node.getNodeName().equals(node_name)) {
745 continue; // not a valid node
746 }
747 list_att = ((Element)current_node).getAttribute(sort_att);
748 }
749
750 parent_node.insertBefore(cloned_elem, current_node);
751 return cloned_elem;
752 }
753
754
755 /** Returns the appropriate language element from a display elem,
756 * display is the containing element, name is the name of the element to
757 * look for, lang is the preferred language, lang_default is the fall back
758 * lang if neither lang is found, will return the first one it finds*/
759 public static String getDisplayText(Element display, String name,
760 String lang, String lang_default) {
761
762 String def = null;
763 String first = null;
764 NodeList elems = display.getElementsByTagName(DISPLAY_TEXT_ELEM);
765 if (elems.getLength() == 0) return "";
766 for (int i=0; i<elems.getLength(); i++) {
767 Element e = (Element)elems.item(i);
768 String n = e.getAttribute(NAME_ATT);
769 if (name.equals(n)) {
770 String l = e.getAttribute(LANG_ATT);
771 if (lang.equals(l)) {
772 return getNodeText(e);
773 } else if (lang_default.equals(l)) {
774 def = getNodeText(e);
775 } else if (first == null) {
776 first = getNodeText(e);
777 }
778 } else {
779 continue;
780 }
781 }
782
783 if (def != null) {
784 return def;
785 }
786 if (first != null) {
787 return first;
788 }
789 return "";
790 }
791
792 // replaces < > " ' & in the original with their entities
793 public static String xmlSafe(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 filtered.append("&gt;");
801 } else if (c == '<') {
802 filtered.append("&lt;");
803 } else if (c == '"') {
804 filtered.append("&quot;");
805 } else if (c == '&') {
806 filtered.append("&amp;");
807 } else if (c == '\'') {
808 filtered.append("&apos;");
809 } else {
810 filtered.append(c);
811 }
812 }
813 return filtered.toString();
814 }
815
816
817 // replaces < > " ' & entities with their originals
818 public static String unXmlSafe(String original) {
819
820 StringBuffer filtered = new StringBuffer(original.length());
821 char c;
822 for (int i=0; i<original.length(); i++) {
823 c = original.charAt(i);
824 if (c == '&') {
825 int pos = original.indexOf(";", i);
826 String entity = original.substring(i+1, pos);
827 if (entity.equals("gt")) {
828 filtered.append(">");
829 } else if (entity.equals("lt")) {
830 filtered.append("<");
831 } else if (entity.equals("apos")) {
832 filtered.append("'");
833 } else if (entity.equals("amp")) {
834 filtered.append("&");
835 } else if (entity.equals("quot")) {
836 filtered.append("\"");
837 } else {
838 filtered.append("&"+entity+";");
839 }
840 i = pos;
841 } else {
842 filtered.append(c);
843 }
844 }
845 return filtered.toString();
846 }
847
848 public static void printXMLNode(Node e) {
849 printXMLNode(e, 0) ;
850 }
851
852 public static String xmlNodeToString(Node e){
853 StringBuffer sb = new StringBuffer("");
854 xmlNodeToString(sb,e,0);
855 return sb.toString();
856 }
857
858 private static void xmlNodeToString(StringBuffer sb, Node e, int depth){
859
860 for (int i=0 ; i<depth ; i++)
861 sb.append(' ') ;
862
863 if (e.getNodeType() == Node.TEXT_NODE){
864 sb.append("text") ;
865 return ;
866 }
867
868 sb.append('<');
869 sb.append(e.getNodeName());
870 NamedNodeMap attrs = e.getAttributes();
871 for (int i = 0; i < attrs.getLength(); i++) {
872 Node attr = attrs.item(i);
873 sb.append(' ');
874 sb.append(attr.getNodeName());
875 sb.append("=\"");
876 sb.append(attr.getNodeValue());
877 sb.append('"');
878 }
879
880 NodeList children = e.getChildNodes();
881
882 if (children == null || children.getLength() == 0)
883 sb.append("/>\n") ;
884 else {
885
886 sb.append(">\n") ;
887
888 int len = children.getLength();
889 for (int i = 0; i < len; i++) {
890 xmlNodeToString(sb,children.item(i), depth + 1);
891 }
892
893 for (int i=0 ; i<depth ; i++)
894 sb.append(' ') ;
895
896 sb.append("</" + e.getNodeName() + ">\n");
897 }
898
899
900 }
901
902 public static void printXMLNode(Node e, int depth) { //recursive method call using DOM API...
903
904 for (int i=0 ; i<depth ; i++)
905 System.out.print(' ') ;
906
907 if (e.getNodeType() == Node.TEXT_NODE){
908 // shouldn't we actually print the text here????
909 System.out.println("text") ;
910 return ;
911 }
912
913 System.out.print('<');
914 System.out.print(e.getNodeName());
915 NamedNodeMap attrs = e.getAttributes();
916 for (int i = 0; i < attrs.getLength(); i++) {
917 Node attr = attrs.item(i);
918 System.out.print(' ');
919 System.out.print(attr.getNodeName());
920 System.out.print("=\"");
921 System.out.print(attr.getNodeValue());
922 System.out.print('"');
923 }
924
925 NodeList children = e.getChildNodes();
926
927 if (children == null || children.getLength() == 0)
928 System.out.println("/>") ;
929 else {
930
931 System.out.println('>') ;
932
933 int len = children.getLength();
934 for (int i = 0; i < len; i++) {
935 printXMLNode(children.item(i), depth + 1);
936 }
937
938 for (int i=0 ; i<depth ; i++)
939 System.out.print(' ') ;
940
941 System.out.println("</" + e.getNodeName() + ">");
942 }
943
944 }
945}
Note: See TracBrowser for help on using the repository browser.