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

Last change on this file since 16869 was 16869, checked in by kjdon, 16 years ago

added license message

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