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

Last change on this file since 25300 was 25300, checked in by kjdon, 12 years ago

a little bit of tidying up. adding a few more string constants to GSParams

  • Property svn:keywords set to Author Date Id Revision
File size: 36.4 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 javax.xml.transform.TransformerFactory;
29import javax.xml.transform.Transformer;
30import java.io.StringWriter;
31import javax.xml.transform.stream.StreamResult;
32import javax.xml.transform.dom.DOMSource;
33
34import java.util.Map;
35import java.util.Set;
36import java.util.HashMap;
37import java.util.Vector;
38import java.util.Iterator;
39import java.util.ArrayList;
40
41//import java.util.Locale;
42
43import org.apache.log4j.*;
44
45/** various functions for extracting info out of GS XML */
46public class GSXML
47{
48
49 static Logger logger = Logger.getLogger(org.greenstone.gsdl3.util.GSXML.class.getName());
50
51 // greenstone message xml elements
52 public static final String MESSAGE_ELEM = "message";
53 public static final String REQUEST_ELEM = "request";
54 public static final String RESPONSE_ELEM = "response";
55 public static final String COLLECTION_ELEM = "collection";
56 public static final String SERVICE_ELEM = "service";
57 public static final String CLUSTER_ELEM = "serviceCluster";
58 public static final String SITE_ELEM = "site";
59 public static final String PARAM_ELEM = "param";
60 public static final String PARAM_OPTION_ELEM = "option";
61 public static final String CONTENT_ELEM = "content";
62 public static final String RESOURCE_ELEM = "resource";
63 public static final String DOCUMENT_ELEM = "document";
64 public static final String METADATA_ELEM = "metadata";
65 public static final String SERVICE_CLASS_ELEM = "serviceRack";
66 public static final String CLASSIFIER_ELEM = "classifier";
67 public static final String APPLET_ELEM = "applet";
68 public static final String APPLET_DATA_ELEM = "appletData";
69 public static final String CONFIGURE_ELEM = "configure";
70 public static final String STATUS_ELEM = "status";
71 public static final String ERROR_ELEM = "error";
72 public static final String DEFAULT_ELEM = "default";
73 public static final String STYLESHEET_ELEM = "format";//"stylesheet"; // any additional stylesheet stuff is carried in the message inside this elem
74 public static final String FORMAT_ELEM = "format"; // config files use format - should we use this instead of stylesheet??
75 public static final String TERM_ELEM = "term";
76 public static final String STOPWORD_ELEM = "stopword";
77 public static final String SYSTEM_ELEM = "system";
78 public static final String FORMAT_STRING_ELEM = "formatString";
79
80 //config file elems
81 public static final String COLLECTION_CONFIG_ELEM = "collectionConfig";
82 public static final String COLLECTION_BUILD_ELEM = "buildConfig";
83 public static final String COLLECTION_INIT_ELEM = "collectionInit";
84 public static final String RECOGNISE_ELEM = "recognise";
85 public static final String DOC_TYPE_ELEM = "docType";
86 public static final String SEARCH_ELEM = "search";
87 public static final String INFODB_ELEM = "infodb";
88 public static final String INDEX_ELEM = "index";
89 public static final String INDEX_STEM_ELEM = "indexStem";
90 public static final String INDEX_OPTION_ELEM = "indexOption";
91 public static final String BROWSE_ELEM = "browse";
92 public static final String DISPLAY_ELEM = "display";
93 public static final String LEVEL_ELEM = "level";
94 public static final String REPLACE_ELEM = "replace";
95
96 public static final String DBINFO_ELEM = "dbInfo";
97 public static final String DBNAME_ATT = "dbname";
98 public static final String DBPATH_ATT = "dbpath";
99 public static final String SQLSTATE_ATT = "sqlstate";
100 public static final String DATABASE_TYPE_ELEM = "databaseType";
101 public static final String SHORTNAME_ATT = "shortname";
102 public static final String NOTIFY_ELEM = "notify";
103 public static final String NOTIFY_HOST_ATT = "host";
104
105 //doc.xml file elems
106 public static final String DOCXML_SECTION_ELEM = "Section";
107 public static final String DOCXML_DESCRIPTION_ELEM = "Description";
108 public static final String DOCXML_METADATA_ELEM = "Metadata";
109 public static final String DOCXML_CONTENT_ELEM = "Content";
110
111 // elems for the pages to be processed by xslt
112 public final static String PAGE_ELEM = "page";
113 public final static String CONFIGURATION_ELEM = "config";
114 public final static String PAGE_REQUEST_ELEM = "pageRequest";
115 public final static String PAGE_RESPONSE_ELEM = "pageResponse";
116 public final static String PAGE_EXTRA_ELEM = "pageExtra";
117
118 //public final static String DESCRIPTION_ELEM = "description";
119
120 public static final String ACTION_ELEM = "action";
121 public static final String SUBACTION_ELEM = "subaction";
122
123 // add on to another elem type to get a list of that type
124 public static final String LIST_MODIFIER = "List";
125 // used to refer back to another element type
126 public static final String REF_MODIFIER = "Ref";
127 // greenstone xml attributes
128 public static final String COLLECTION_ATT = "collection";
129 public static final String NAME_ATT = "name";
130 public static final String TO_ATT = "to";
131 public static final String USER_ID_ATT = "uid";
132 public static final String FROM_ATT = "from";
133 public static final String LANG_ATT = "lang";
134 public static final String TYPE_ATT = "type";
135 public static final String DB_TYPE_ATT = "dbType";
136 public static final String VALUE_ATT = "value";
137 public static final String DEFAULT_ATT = "default";
138 public static final String INFO_ATT = "info";
139 public static final String ACTION_ATT = "action";
140 public static final String SUBACTION_ATT = "subaction";
141 public static final String OUTPUT_ATT = "output";
142 public static final String ADDRESS_ATT = "address";
143 public static final String LOCAL_SITE_ATT = "localSite";
144 public static final String LOCAL_SITE_NAME_ATT = "localSiteName";
145 public static final String STATUS_ERROR_CODE_ATT = "code";
146 public static final String STATUS_PROCESS_ID_ATT = "pid";
147 public static final String PARAM_SHORTNAME_ATT = "shortname";
148 public static final String PARAM_IGNORE_POS_ATT = "ignore";
149 public static final String CLASSIFIER_CONTENT_ATT = "content";
150 public static final String ERROR_TYPE_ATT = "type";
151 public static final String COLLECT_TYPE_ATT = "ct";
152 public static final String HIDDEN_ATT = "hidden";
153
154 // document stuff
155 public static final String DOC_TYPE_ATT = "docType";
156 public static final String DOC_NODE_ELEM = "documentNode";
157 public static final String NODE_CONTENT_ELEM = "nodeContent";
158 public static final String NODE_STRUCTURE_ELEM = "nodeStructure";
159 public static final String NODE_ID_ATT = "nodeID";
160 public static final String HREF_ID_ATT = "hrefId"; // for ids that need translating
161 public static final String ID_MOD_ATT = "idMod"; // might hold .rt etc for hrefIds
162 public static final String NODE_OID = "oid";
163 public static final String NODE_NAME_ATT = "nodeName";
164 public static final String NODE_TYPE_ATT = "nodeType";
165 public static final String NODE_RANK_ATT = "rank";
166 public static final String NODE_TYPE_ROOT = "root";
167 public static final String NODE_TYPE_INTERNAL = "internal";
168 public static final String NODE_TYPE_LEAF = "leaf";
169
170 public static final String DOC_TYPE_SIMPLE = "simple";
171 public static final String DOC_TYPE_PAGED = "paged";
172 public static final String DOC_TYPE_HIERARCHY = "hierarchy";
173
174 public static final String SESSION_EXPIRATION = "session_expiration";
175 public static final String USER_SESSION_CACHE_ATT = "user_session_cache";
176
177 // classifier stuff
178 public static final String CLASS_NODE_ELEM = "classifierNode";
179 public static final String CLASS_NODE_ORIENTATION_ATT = "orientation";
180
181 // parameter types
182 public static final String PARAM_TYPE_INTEGER = "integer";
183 public static final String PARAM_TYPE_BOOLEAN = "boolean";
184 public static final String PARAM_TYPE_ENUM_START = "enum";
185 public static final String PARAM_TYPE_ENUM_SINGLE = "enum_single";
186 public static final String PARAM_TYPE_ENUM_MULTI = "enum_multi";
187 public static final String PARAM_TYPE_STRING = "string";
188 public static final String PARAM_TYPE_TEXT = "text";
189 public static final String PARAM_TYPE_MULTI = "multi";
190 public static final String PARAM_TYPE_FILE = "file";
191 public static final String PARAM_TYPE_INVISIBLE = "invisible";
192 // stuff for text strings
193 public static final String DISPLAY_TEXT_ELEM = "displayItem";
194 // the following are used for the name attributes
195 public static final String DISPLAY_TEXT_NAME = "name";
196 public static final String DISPLAY_TEXT_SUBMIT = "submit";
197 public static final String DISPLAY_TEXT_DESCRIPTION = "description";
198
199 // request types
200 // get the module description
201 public static final String REQUEST_TYPE_DESCRIBE = "describe";
202 // startup a process
203 public static final String REQUEST_TYPE_PROCESS = "process";
204 // get the status of an ongoing process
205 public static final String REQUEST_TYPE_STATUS = "status";
206 // system type request - eg reload a collection
207 public static final String REQUEST_TYPE_SYSTEM = "system";
208 // page requests to the Receptionist/Actions
209 public static final String REQUEST_TYPE_PAGE = "page"; // used to be cgi
210 // get any format info for a service
211 public static final String REQUEST_TYPE_FORMAT = "format";
212 // modify the requests
213 public static final String REQUEST_TYPE_MESSAGING = "messaging";
214 // save the format string
215 public static final String REQUEST_TYPE_FORMAT_STRING = "formatString";
216 // check credentials
217 public static final String REQUEST_TYPE_SECURITY = "security";
218
219 // service types
220 public static final String SERVICE_TYPE_QUERY = "query";
221 public static final String SERVICE_TYPE_RETRIEVE = "retrieve";
222 public static final String SERVICE_TYPE_BROWSE = "browse";
223 public static final String SERVICE_TYPE_APPLET = "applet";
224 public static final String SERVICE_TYPE_PROCESS = "process";
225 public static final String SERVICE_TYPE_ENRICH = "enrich";
226 public static final String SERVICE_TYPE_OAI = "oai";
227 public static final String FLAX_PAGE = "flaxPage";
228 public static final String FLAX_PAGE_GENERATION = "FlaxPageGeneration";
229
230 // system command types and attributes
231 public static final String SYSTEM_TYPE_CONFIGURE = "configure";
232 public static final String SYSTEM_TYPE_ACTIVATE = "activate";
233 public static final String SYSTEM_TYPE_DEACTIVATE = "deactivate";
234
235 public static final String SYSTEM_SUBSET_ATT = "subset";
236 public static final String SYSTEM_MODULE_TYPE_ATT = "moduleType";
237 public static final String SYSTEM_MODULE_NAME_ATT = "moduleName";
238
239 // communicator types
240 public static final String COMM_TYPE_SOAP_JAVA = "soap";
241
242 // error types
243 public static final String ERROR_TYPE_SYNTAX = "syntax";
244 public static final String ERROR_TYPE_SYSTEM = "system";
245 public static final String ERROR_TYPE_INVALID_ID = "invalid_id";
246 public static final String ERROR_TYPE_OTHER = "other";
247
248 // some system wide param names
249 public static final String SUBSET_PARAM = "subset";
250
251 //for plugin
252 public static final String PLUGIN_ELEM = "plugin";
253 public static final String IMPORT_ELEM = "import";
254
255 //for authentication
256 public static final String AUTHEN_NODE_ELEM = "authenticationNode";
257 public static final String USER_NODE_ELEM = "userNode";
258
259 //for configure action results
260 public static final String SUCCESS = "success";
261 public static final String ERROR = "error";
262
263 //security tags and attributes
264 public static final String SECURITY_ELEM = "security";
265 public static final String SCOPE_ATT = "scope";
266 public static final String DEFAULT_ACCESS_ATT = "default_access";
267 public static final String EXCEPTION_ELEM = "exception";
268 public static final String DOCUMENT_SET_ELEM = "documentSet";
269 public static final String GROUP_ELEM = "group";
270 public static final String MATCH_ELEM = "match";
271 public static final String FIELD_ATT = "field";
272 public static final String USER_INFORMATION_ELEM = "userInformation";
273 public static final String USERNAME_ATT = "username";
274 public static final String GROUPS_ATT = "groups";
275 public static final String BASE_URL = "baseURL";
276
277 /**
278 * takes a list of elements, and returns an array of strings of the values
279 * of attribute att_name
280 */
281 public static String[] getAttributeValuesFromList(Element list, String att_name)
282 {
283
284 NodeList children = list.getChildNodes();
285
286 int num_nodes = children.getLength();
287 String[] ids = new String[num_nodes];
288 for (int i = 0; i < num_nodes; i++)
289 {
290 Element e = (Element) children.item(i);
291 String id = e.getAttribute(att_name);
292 ids[i] = id;
293 }
294
295 return ids;
296 }
297
298 public static HashMap extractParams(Element xml, boolean deep)
299 {
300 return extractParams(xml, deep, null);
301 }
302
303 /**
304 * takes a paramList element, and gets a HashMap of name-value pairs if
305 * deep=true, extracts embedded params, otherwise just top level params
306 */
307 public static HashMap extractParams(Element xml, boolean deep, String toFind)
308 {
309
310 if (!xml.getNodeName().equals(PARAM_ELEM + LIST_MODIFIER))
311 {
312 logger.error("paramList element should have been passed to extractParams, instead it was " + xml.getNodeName());
313 return null;
314 }
315
316 NodeList params = null;
317 if (deep)
318 { // get all the nested ones
319 params = xml.getElementsByTagName(PARAM_ELEM);
320 }
321 else
322 { // just get the top level ones
323 params = xml.getChildNodes();
324 }
325 HashMap param_map = new HashMap();
326 for (int i = 0; i < params.getLength(); i++)
327 {
328 if (params.item(i).getNodeName().equals(PARAM_ELEM))
329 {
330 Element param = (Element) params.item(i);
331 String name = param.getAttribute(NAME_ATT);
332 String value = getValue(param); //att or content
333
334 // For only one parameter
335 if (toFind != null && name.equals(toFind))
336 {
337 param_map.put(name, value);
338 return param_map;
339 }
340 else if (toFind != null)
341 continue;
342
343 int pos = name.indexOf('.');
344 if (pos == -1)
345 { // a base param
346 param_map.put(name, value);
347 }
348 else
349 { // a namespaced param
350
351 String namespace = name.substring(0, pos);
352 name = name.substring(pos + 1);
353 HashMap map = (HashMap) param_map.get(namespace);
354 if (map == null)
355 {
356 map = new HashMap();
357 param_map.put(namespace, map);
358 }
359 map.put(name, value);
360 }
361 }
362 }
363 return param_map;
364 }
365
366 /** gets the value att or the text content */
367 public static String getValue(Element e)
368 {
369 String val = e.getAttribute(VALUE_ATT);
370 if (val == null || val.equals(""))
371 {
372 // have to get it out of the text
373 val = getNodeText(e);
374
375 }
376 else
377 {
378 // unescape the xml stuff
379 val = unXmlSafe(val);
380 }
381 return val;
382 }
383
384 /** extracts the text out of a node */
385 public static Node getNodeTextNode(Element param)
386 {
387 param.normalize();
388 Node n = param.getFirstChild();
389 while (n != null && n.getNodeType() != Node.TEXT_NODE)
390 {
391 n = n.getNextSibling();
392 }
393 return n;
394 }
395
396 /** extracts the text out of a node */
397 public static String getNodeText(Element param)
398 {
399 Node text_node = getNodeTextNode(param);
400 if (text_node == null)
401 {
402 return "";
403 }
404 return text_node.getNodeValue();
405 }
406
407 public static void setNodeText(Element elem, String text)
408 {
409 Node old_text_node = getNodeTextNode(elem);
410 if (old_text_node != null)
411 {
412 elem.removeChild(old_text_node);
413 }
414 Text t = elem.getOwnerDocument().createTextNode(text);
415 elem.appendChild(t);
416 }
417
418 /** add text to a document/subsection element */
419 public static boolean addDocText(Document owner, Element doc, String text)
420 {
421
422 Element content = owner.createElement(NODE_CONTENT_ELEM);
423 Text t = owner.createTextNode(text);
424 content.appendChild(t);
425 doc.appendChild(content);
426 return true;
427 }
428
429 /** add an error message, unknown error type */
430 public static boolean addError(Document owner, Element doc, String text)
431 {
432 return addError(owner, doc, text, ERROR_TYPE_OTHER);
433 }
434
435 /** add an error message */
436 public static boolean addError(Document owner, Element doc, String text, String error_type)
437 {
438
439 Element content = owner.createElement(ERROR_ELEM);
440 content.setAttribute(ERROR_TYPE_ATT, error_type);
441 Text t = owner.createTextNode(text);
442 content.appendChild(t);
443 doc.appendChild(content);
444 return true;
445 }
446
447 /** add an error message */
448 public static boolean addError(Document owner, Element doc, Throwable error)
449 {
450 return addError(owner, doc, error, ERROR_TYPE_OTHER);
451 }
452
453 /** add an error message */
454 public static boolean addError(Document owner, Element doc, Throwable error, String error_type)
455 {
456 error.printStackTrace();
457 return addError(owner, doc, error.toString(), error_type);
458 }
459
460 public static Element createMetadataParamList(Document owner, Vector meta_values)
461 {
462
463 Element meta_param_list = owner.createElement(PARAM_ELEM + LIST_MODIFIER);
464 Iterator i = meta_values.iterator();
465 while (i.hasNext())
466 {
467 String next = (String) i.next();
468 Element meta_param = owner.createElement(PARAM_ELEM);
469 meta_param_list.appendChild(meta_param);
470 meta_param.setAttribute(NAME_ATT, "metadata");
471 meta_param.setAttribute(VALUE_ATT, next);
472 }
473 return meta_param_list;
474 }
475
476 /** adds a metadata elem to a list */
477 public static boolean addMetadata(Document owner, Element list, String meta_name, String meta_value)
478 {
479 if (meta_value == null || meta_value.equals(""))
480 {
481 return false;
482 }
483 Element data = owner.createElement(METADATA_ELEM);
484 data.setAttribute(NAME_ATT, meta_name);
485 Text t = owner.createTextNode(meta_value);
486 data.appendChild(t);
487 list.appendChild(data);
488 return true;
489
490 }
491
492 /**
493 * copies the metadata out of the metadataList of 'from' into the
494 * metadataList of 'to'
495 */
496 public static boolean mergeMetadataLists(Node to, Node from)
497 {
498 Node from_meta = getChildByTagName(from, METADATA_ELEM + LIST_MODIFIER);
499 if (from_meta == null)
500 { // nothing to copy
501 return true;
502 }
503 return mergeMetadataFromList(to, from_meta);
504 }
505
506 /**
507 * copies the metadata out of the meta_list metadataList into the
508 * metadataList of 'to'
509 */
510 public static boolean mergeMetadataFromList(Node to, Node meta_list)
511 {
512 if (meta_list == null)
513 return false;
514 Node to_meta = getChildByTagName(to, METADATA_ELEM + LIST_MODIFIER);
515 Document to_owner = to.getOwnerDocument();
516 if (to_meta == null)
517 {
518 to.appendChild(to_owner.importNode(meta_list, true));
519 return true;
520 }
521 // copy individual metadata elements
522 NodeList meta_items = ((Element) meta_list).getElementsByTagName(METADATA_ELEM);
523 for (int i = 0; i < meta_items.getLength(); i++)
524 {
525 to_meta.appendChild(to_owner.importNode(meta_items.item(i), true));
526 }
527 return true;
528 }
529
530 /** copies all the children from from to to */
531 public static boolean mergeElements(Element to, Element from)
532 {
533
534 Document owner = to.getOwnerDocument();
535 Node child = from.getFirstChild();
536 while (child != null)
537 {
538 to.appendChild(owner.importNode(child, true));
539 child = child.getNextSibling();
540 }
541 return true;
542 }
543
544 /** returns the (first) element child of the node n */
545 public static Element getFirstElementChild(Node n)
546 {
547
548 Node child = n.getFirstChild();
549 while (child != null)
550 {
551 if (child.getNodeType() == Node.ELEMENT_NODE)
552 {
553 return (Element) child;
554 }
555 child = child.getNextSibling();
556 }
557 return null; //no element child found
558 }
559
560 /** returns the (first) child element with the given name */
561 public static Node getChildByTagName(Node n, String name)
562 {
563 if (n != null)
564 { // this line is an attempted solution to the NullPointerException mentioned
565 // in trac bug ticket #225. If n is null can't do n.getFirstChild() below. As per bug #225:
566 // GSXML.getNodeByPath() is called by GS2BrowseAction, which then calls this method.
567 // If n is null, null will be returned which GS2BrowseAction already checks for. It's here
568 // that the NullPointerException was thrown.
569
570 Node child = n.getFirstChild();
571 while (child != null)
572 {
573 if (child.getNodeName().equals(name))
574 {
575 return child;
576 }
577 child = child.getNextSibling();
578 }
579 }
580 return null; //not found
581 }
582
583 /**
584 * returns the (nth) child element with the given name index numbers start
585 * at 0
586 */
587 public static Node getChildByTagNameIndexed(Node n, String name, int index)
588 {
589 if (index == -1)
590 {
591 return getChildByTagName(n, name);
592 }
593 int count = 0;
594 Node child = n.getFirstChild();
595 while (child != null)
596 {
597 if (child.getNodeName().equals(name))
598 {
599 if (count == index)
600 {
601 return child;
602 }
603 else
604 {
605 count++;
606 }
607 }
608 child = child.getNextSibling();
609 }
610 return null; //not found
611 }
612
613 /**
614 * takes an xpath type expression of the form name/name/... and returns the
615 * first node that matches, or null if not found
616 */
617 public static Node getNodeByPath(Node n, String path)
618 {
619
620 String link = GSPath.getFirstLink(path);
621 path = GSPath.removeFirstLink(path);
622 while (!link.equals(""))
623 {
624 n = getChildByTagName(n, link);
625 if (n == null)
626 {
627 return null;
628 }
629 link = GSPath.getFirstLink(path);
630 path = GSPath.removeFirstLink(path);
631 }
632 return n;
633 }
634
635 /**
636 * takes an xpath type expression of the form name/name/... and returns the
637 * first node that matches, or null if not found can include [i] indices.
638 * index numbers start at 0
639 */
640 public static Node getNodeByPathIndexed(Node n, String path)
641 {
642
643 String link = GSPath.getFirstLink(path);
644 int index = GSPath.getIndex(link);
645 if (index != -1)
646 {
647 link = GSPath.removeIndex(link);
648 }
649 path = GSPath.removeFirstLink(path);
650 while (!link.equals(""))
651 {
652 n = getChildByTagNameIndexed(n, link, index);
653 if (n == null)
654 {
655 return null;
656 }
657 link = GSPath.getFirstLink(path);
658 index = GSPath.getIndex(link);
659 if (index != -1)
660 {
661 link = GSPath.removeIndex(link);
662 }
663 path = GSPath.removeFirstLink(path);
664 }
665 return n;
666 }
667
668 public static HashMap getChildrenMap(Node n)
669 {
670
671 HashMap map = new HashMap();
672 Node child = n.getFirstChild();
673 while (child != null)
674 {
675 String name = child.getNodeName();
676 map.put(name, child);
677 child = child.getNextSibling();
678 }
679 return map;
680 }
681
682 public static NodeList getChildrenByTagName(Node n, String name)
683 {
684 MyNodeList node_list = new MyNodeList();
685 Node child = n.getFirstChild();
686 while (child != null)
687 {
688 if (child.getNodeName().equals(name))
689 {
690 node_list.addNode(child);
691 }
692 child = child.getNextSibling();
693 }
694 return node_list;
695 }
696
697 /** Duplicates an element, but gives it a new name */
698 public static Element duplicateWithNewName(Document owner, Element element, String element_name, boolean with_attributes)
699 {
700 return duplicateWithNewNameNS(owner, element, element_name, null, with_attributes);
701 }
702
703 /** Duplicates an element, but gives it a new name */
704 public static Element duplicateWithNewNameNS(Document owner, Element element, String element_name, String namespace_uri, boolean with_attributes)
705 {
706 Element duplicate;
707 if (namespace_uri == null)
708 {
709 duplicate = owner.createElement(element_name);
710 }
711 else
712 {
713 duplicate = owner.createElementNS(namespace_uri, element_name);
714 }
715 // Copy element attributes
716 if (with_attributes)
717 {
718 NamedNodeMap attributes = element.getAttributes();
719 for (int i = 0; i < attributes.getLength(); i++)
720 {
721 Node attribute = attributes.item(i);
722 duplicate.setAttribute(attribute.getNodeName(), attribute.getNodeValue());
723 }
724 }
725
726 // Copy element children
727 NodeList children = element.getChildNodes();
728 for (int i = 0; i < children.getLength(); i++)
729 {
730 Node child = children.item(i);
731 duplicate.appendChild(owner.importNode(child, true));
732 }
733
734 return duplicate;
735 }
736
737 public static void copyAllChildren(Element to, Element from)
738 {
739
740 Document to_doc = to.getOwnerDocument();
741 Node child = from.getFirstChild();
742 while (child != null)
743 {
744 to.appendChild(to_doc.importNode(child, true));
745 child = child.getNextSibling();
746 }
747 }
748
749 /** returns a basic request message */
750 public static Element createBasicRequest(Document owner, String request_type, String to, UserContext userContext)
751 {
752 Element request = owner.createElement(REQUEST_ELEM);
753 request.setAttribute(TYPE_ATT, request_type);
754 request.setAttribute(LANG_ATT, userContext._lang);
755 request.setAttribute(TO_ATT, to);
756 request.setAttribute(USER_ID_ATT, userContext._userID);
757 return request;
758 }
759
760 public static Element createBasicResponse(Document owner, String from)
761 {
762 Element response = owner.createElement(GSXML.RESPONSE_ELEM);
763 response.setAttribute(GSXML.FROM_ATT, from);
764 response.setAttribute(GSXML.TYPE_ATT, GSXML.REQUEST_TYPE_PROCESS);
765 return response;
766 }
767
768 public static Element createMetadataElement(Document owner, String name, String value)
769 {
770 Element metaElem = owner.createElement(GSXML.METADATA_ELEM);
771 metaElem.setAttribute(GSXML.NAME_ATT, name);
772 metaElem.setAttribute(GSXML.VALUE_ATT, value);
773 return metaElem;
774 }
775
776 public static Element createTextElement(Document owner, String elem_name, String text)
777 {
778 Element e = owner.createElement(elem_name);
779 Text t = owner.createTextNode(text);
780 e.appendChild(t);
781 return e;
782
783 }
784
785 public static Element createTextElement(Document owner, String elem_name, String text, String att_name, String att_value)
786 {
787 Element e = owner.createElement(elem_name);
788 e.setAttribute(att_name, att_value);
789 Text t = owner.createTextNode(text);
790 e.appendChild(t);
791 return e;
792
793 }
794
795 public static Element createDisplayTextElement(Document owner, String text_name, String text)
796 {
797 Element e = owner.createElement(DISPLAY_TEXT_ELEM);
798 e.setAttribute(NAME_ATT, text_name);
799 Text t = owner.createTextNode(text);
800 e.appendChild(t);
801 return e;
802
803 }
804
805 public static Element createParameter(Document owner, String name, String value)
806 {
807 Element param = owner.createElement(PARAM_ELEM);
808 param.setAttribute(NAME_ATT, name);
809 param.setAttribute(VALUE_ATT, value);
810 return param;
811 }
812
813 public static void addParametersToList(Document owner, Element param_list, HashMap params)
814 {
815 if (params == null)
816 {
817 return;
818 }
819
820 Set items = params.entrySet();
821 Iterator i = items.iterator();
822 while (i.hasNext())
823 {
824 Map.Entry m = (Map.Entry) i.next();
825 param_list.appendChild(createParameter(owner, (String) m.getKey(), (String) m.getValue()));
826 }
827
828 }
829
830 public static Element createParameterDescription(Document owner, String id, String display_name, String type, String default_value, String[] option_ids, String[] option_names)
831 {
832
833 Element p = owner.createElement(PARAM_ELEM);
834 p.setAttribute(NAME_ATT, id);
835 p.setAttribute(TYPE_ATT, type);
836 p.appendChild(createDisplayTextElement(owner, GSXML.DISPLAY_TEXT_NAME, display_name));
837
838 if (default_value != null)
839 {
840 p.setAttribute(DEFAULT_ATT, default_value);
841 }
842 if (option_ids != null && option_names != null)
843 {
844 for (int i = 0; i < option_ids.length; i++)
845 {
846 Element e = owner.createElement(PARAM_OPTION_ELEM);
847 e.setAttribute(NAME_ATT, option_ids[i]);
848 e.appendChild(createDisplayTextElement(owner, GSXML.DISPLAY_TEXT_NAME, option_names[i]));
849 p.appendChild(e);
850 }
851 }
852 return p;
853 }
854
855 public static Element createParameterDescription2(Document owner, String id, String display_name, String type, String default_value, ArrayList option_ids, ArrayList option_names)
856 {
857
858 Element p = owner.createElement(PARAM_ELEM);
859 p.setAttribute(NAME_ATT, id);
860 p.setAttribute(TYPE_ATT, type);
861 p.appendChild(createDisplayTextElement(owner, GSXML.DISPLAY_TEXT_NAME, display_name));
862 if (default_value != null)
863 {
864 p.setAttribute(DEFAULT_ATT, default_value);
865 }
866 if (option_ids != null && option_names != null)
867 {
868 for (int i = 0; i < option_ids.size(); i++)
869 {
870 Element e = owner.createElement(PARAM_OPTION_ELEM);
871 e.setAttribute(NAME_ATT, (String) option_ids.get(i));
872 e.appendChild(createDisplayTextElement(owner, GSXML.DISPLAY_TEXT_NAME, (String) option_names.get(i)));
873 p.appendChild(e);
874 }
875 }
876 return p;
877 }
878
879 /** returns the element parent/node_name[@attribute_name='attribute_value'] */
880 public static Element getNamedElement(Element parent, String node_name, String attribute_name, String attribute_value)
881 {
882
883 NodeList children = parent.getChildNodes();
884 for (int i = 0; i < children.getLength(); i++)
885 {
886 Node child = children.item(i);
887 if (child.getNodeName().equals(node_name))
888 {
889 if (((Element) child).getAttribute(attribute_name).equals(attribute_value))
890 return (Element) child;
891 }
892 }
893 // not found
894 return null;
895 }
896
897 /**
898 * returns a NodeList of elements:
899 * ancestor/node_name[@attribute_name='attribute_value']
900 */
901 public static NodeList getNamedElements(Element ancestor, String node_name, String attribute_name, String attribute_value)
902 {
903 MyNodeList node_list = new MyNodeList();
904 NodeList children = ancestor.getElementsByTagName(node_name);
905
906 if (children != null && children.getLength() > 0)
907 {
908
909 for (int i = 0; i < children.getLength(); i++)
910 {
911 Node child = children.item(i);
912 if (child.getNodeName().equals(node_name))
913 {
914 if (((Element) child).getAttribute(attribute_name).equals(attribute_value))
915 node_list.addNode(child);
916 }
917 }
918 }
919 return node_list;
920 }
921
922 public static int SORT_TYPE_STRING = 0;
923 public static int SORT_TYPE_INT = 1;
924 public static int SORT_TYPE_FLOAT = 2;
925
926 // sort type:
927 public static Element insertIntoOrderedList(Element parent_node, String node_name, Element start_from_elem, Element new_elem, String sort_att, boolean descending)
928 {
929 if (new_elem == null)
930 return null;
931 Element cloned_elem = (Element) parent_node.getOwnerDocument().importNode(new_elem, true);
932 if (start_from_elem == null)
933 {
934 parent_node.appendChild(cloned_elem);
935 return cloned_elem;
936 }
937
938 Node current_node = start_from_elem;
939 String insert_att = cloned_elem.getAttribute(sort_att);
940 String list_att = start_from_elem.getAttribute(sort_att);
941 while ((!descending && list_att.compareTo(insert_att) < 0) || (descending && list_att.compareTo(insert_att) > 0))
942 {
943 current_node = current_node.getNextSibling();
944 if (current_node == null)
945 break; // end of the list
946 if (!current_node.getNodeName().equals(node_name))
947 {
948 continue; // not a valid node
949 }
950 list_att = ((Element) current_node).getAttribute(sort_att);
951 }
952
953 parent_node.insertBefore(cloned_elem, current_node);
954 return cloned_elem;
955 }
956
957 /**
958 * Returns the appropriate language element from a display elem, display is
959 * the containing element, name is the name of the element to look for, lang
960 * is the preferred language, lang_default is the fall back lang if neither
961 * lang is found, will return the first one it finds
962 */
963 public static String getDisplayText(Element display, String name, String lang, String lang_default)
964 {
965
966 String def = null;
967 String first = null;
968 NodeList elems = display.getElementsByTagName(DISPLAY_TEXT_ELEM);
969 if (elems.getLength() == 0)
970 return "";
971 for (int i = 0; i < elems.getLength(); i++)
972 {
973 Element e = (Element) elems.item(i);
974 String n = e.getAttribute(NAME_ATT);
975 if (name.equals(n))
976 {
977 String l = e.getAttribute(LANG_ATT);
978 if (lang.equals(l))
979 {
980 return getNodeText(e);
981 }
982 else if (lang_default.equals(l))
983 {
984 def = getNodeText(e);
985 }
986 else if (first == null)
987 {
988 first = getNodeText(e);
989 }
990 }
991 else
992 {
993 continue;
994 }
995 }
996
997 if (def != null)
998 {
999 return def;
1000 }
1001 if (first != null)
1002 {
1003 return first;
1004 }
1005 return "";
1006 }
1007
1008 // replaces < > " ' & in the original with their entities
1009 public static String xmlSafe(String original)
1010 {
1011
1012 StringBuffer filtered = new StringBuffer(original.length());
1013 char c;
1014 for (int i = 0; i < original.length(); i++)
1015 {
1016 c = original.charAt(i);
1017 if (c == '>')
1018 {
1019 filtered.append("&gt;");
1020 }
1021 else if (c == '<')
1022 {
1023 filtered.append("&lt;");
1024 }
1025 else if (c == '"')
1026 {
1027 filtered.append("&quot;");
1028 }
1029 else if (c == '&')
1030 {
1031 filtered.append("&amp;");
1032 }
1033 else if (c == '\'')
1034 {
1035 filtered.append("&apos;");
1036 }
1037 else
1038 {
1039 filtered.append(c);
1040 }
1041 }
1042 return filtered.toString();
1043 }
1044
1045 // replaces < > " ' & entities with their originals
1046 public static String unXmlSafe(String original)
1047 {
1048
1049 StringBuffer filtered = new StringBuffer(original.length());
1050 char c;
1051 for (int i = 0; i < original.length(); i++)
1052 {
1053 c = original.charAt(i);
1054 if (c == '&')
1055 {
1056 int pos = original.indexOf(";", i);
1057 String entity = original.substring(i + 1, pos);
1058 if (entity.equals("gt"))
1059 {
1060 filtered.append(">");
1061 }
1062 else if (entity.equals("lt"))
1063 {
1064 filtered.append("<");
1065 }
1066 else if (entity.equals("apos"))
1067 {
1068 filtered.append("'");
1069 }
1070 else if (entity.equals("amp"))
1071 {
1072 filtered.append("&");
1073 }
1074 else if (entity.equals("quot"))
1075 {
1076 filtered.append("\"");
1077 }
1078 else
1079 {
1080 filtered.append("&" + entity + ";");
1081 }
1082 i = pos;
1083 }
1084 else
1085 {
1086 filtered.append(c);
1087 }
1088 }
1089 return filtered.toString();
1090 }
1091
1092 public static void printXMLNode(Node e, boolean printText)
1093 {
1094 printXMLNode(e, 0, printText);
1095 }
1096
1097 public static String xmlNodeToString(Node e)
1098 {
1099 StringBuffer sb = new StringBuffer("");
1100 xmlNodeToString(sb, e, 0, true);
1101 return sb.toString();
1102 }
1103
1104 public static String xmlNodeToString(Node e, boolean printText)
1105 {
1106 StringBuffer sb = new StringBuffer("");
1107 xmlNodeToString(sb, e, 0, printText);
1108 return sb.toString();
1109 }
1110
1111 private static void xmlNodeToString(StringBuffer sb, Node e, int depth, boolean printText)
1112 {
1113 if(e == null)
1114 {
1115 return;
1116 }
1117
1118 for (int i = 0; i < depth; i++)
1119 sb.append(' ');
1120
1121 if (e.getNodeType() == Node.TEXT_NODE)
1122 {
1123 if (printText)
1124 {
1125 sb.append(e.getNodeValue());
1126 }
1127 else
1128 {
1129 sb.append("text");
1130 }
1131 return;
1132 }
1133
1134 sb.append('<');
1135 sb.append(e.getNodeName());
1136 NamedNodeMap attrs = e.getAttributes();
1137 if (attrs != null)
1138 {
1139 for (int i = 0; i < attrs.getLength(); i++)
1140 {
1141 Node attr = attrs.item(i);
1142 sb.append(' ');
1143 sb.append(attr.getNodeName());
1144 sb.append("=\"");
1145 sb.append(attr.getNodeValue());
1146 sb.append('"');
1147 }
1148 }
1149
1150 NodeList children = e.getChildNodes();
1151
1152 if (children == null || children.getLength() == 0)
1153 sb.append("/>\n");
1154 else
1155 {
1156
1157 sb.append(">\n");
1158
1159 int len = children.getLength();
1160 for (int i = 0; i < len; i++)
1161 {
1162 xmlNodeToString(sb, children.item(i), depth + 1, printText);
1163 }
1164
1165 for (int i = 0; i < depth; i++)
1166 sb.append(' ');
1167
1168 sb.append("</" + e.getNodeName() + ">\n");
1169 }
1170
1171 }
1172
1173 public static void printXMLNode(Node e, int depth, boolean printText)
1174 { //recursive method call using DOM API...
1175
1176 if (e == null)
1177 {
1178 return;
1179 }
1180
1181 for (int i = 0; i < depth; i++)
1182 System.out.print(' ');
1183
1184 if (e.getNodeType() == Node.TEXT_NODE)
1185 {
1186 if (printText)
1187 {
1188 System.out.println(e.getNodeValue());
1189 }
1190 else
1191 {
1192 System.out.println("text");
1193 }
1194 return;
1195 }
1196
1197 System.out.print('<');
1198 System.out.print(e.getNodeName());
1199 NamedNodeMap attrs = e.getAttributes();
1200
1201 if (attrs != null)
1202 {
1203 for (int i = 0; i < attrs.getLength(); i++)
1204 {
1205 Node attr = attrs.item(i);
1206 System.out.print(' ');
1207 System.out.print(attr.getNodeName());
1208 System.out.print("=\"");
1209 System.out.print(attr.getNodeValue());
1210 System.out.print('"');
1211 }
1212 }
1213
1214 NodeList children = e.getChildNodes();
1215
1216 if (children == null || children.getLength() == 0)
1217 System.out.println("/>");
1218 else
1219 {
1220
1221 System.out.println('>');
1222
1223 int len = children.getLength();
1224 for (int i = 0; i < len; i++)
1225 {
1226 printXMLNode(children.item(i), depth + 1, printText);
1227 }
1228
1229 for (int i = 0; i < depth; i++)
1230 System.out.print(' ');
1231
1232 System.out.println("</" + e.getNodeName() + ">");
1233 }
1234 }
1235
1236 public static void elementToLogAsString(Element e)
1237 {
1238 try
1239 {
1240 TransformerFactory tf = TransformerFactory.newInstance();
1241 Transformer trans = tf.newTransformer();
1242 StringWriter sw = new StringWriter();
1243 trans.transform(new DOMSource(e), new StreamResult(sw));
1244 System.err.println(sw.toString());
1245 }
1246 catch (Exception ex)
1247 {
1248 System.err.println("couldn't write " + e + " to log");
1249 }
1250 }
1251
1252 public static ArrayList<String> getGroupsFromSecurityResponse(Element securityResponse)
1253 {
1254 ArrayList<String> groups = new ArrayList<String>();
1255
1256 Element groupList = (Element) GSXML.getChildByTagName(securityResponse, GSXML.GROUP_ELEM + GSXML.LIST_MODIFIER);
1257 if(groupList == null)
1258 {
1259 return groups;
1260 }
1261
1262 NodeList groupElems = GSXML.getChildrenByTagName(groupList, GSXML.GROUP_ELEM);
1263
1264 for(int i = 0; i < groupElems.getLength(); i++)
1265 {
1266 Element groupElem = (Element) groupElems.item(i);
1267 groups.add(groupElem.getAttribute(GSXML.NAME_ATT));
1268 }
1269
1270 return groups;
1271 }
1272}
Note: See TracBrowser for help on using the repository browser.