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

Last change on this file since 28847 was 28847, checked in by shaoqun, 10 years ago
  • Property svn:keywords set to Author Date Id Revision
File size: 45.7 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 java.io.Serializable;
22import java.io.StringWriter;
23import java.util.ArrayList;
24import java.util.HashMap;
25import java.util.Iterator;
26import java.util.Map;
27import java.util.Set;
28import java.util.Vector;
29
30import javax.xml.transform.OutputKeys;
31import javax.xml.transform.Transformer;
32import javax.xml.transform.TransformerFactory;
33import javax.xml.transform.dom.DOMSource;
34import javax.xml.transform.stream.StreamResult;
35
36import org.apache.log4j.Logger;
37import org.w3c.dom.Document;
38import org.w3c.dom.Element;
39import org.w3c.dom.NamedNodeMap;
40import org.w3c.dom.Node;
41import org.w3c.dom.NodeList;
42import org.w3c.dom.Text;
43
44import org.greenstone.gsdl3.util.MyNodeList;
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 GLOBAL_FORMAT_ELEM = "globalFormat";
76 public static final String TERM_ELEM = "term";
77 public static final String STOPWORD_ELEM = "stopword";
78 public static final String FACET_ELEM = "facet";
79 public static final String COUNT_ELEM = "count";
80 public static final String SYSTEM_ELEM = "system";
81 public static final String FORMAT_STRING_ELEM = "formatString";
82 public static final String EXTRA_METADATA = "extraMetadata";
83
84 //config file elems
85 public static final String COLLECTION_CONFIG_ELEM = "collectionConfig";
86 public static final String COLLECTION_BUILD_ELEM = "buildConfig";
87 public static final String COLLECTION_INIT_ELEM = "collectionInit";
88 public static final String RECOGNISE_ELEM = "recognise";
89 public static final String DOC_TYPE_ELEM = "docType";
90 public static final String SEARCH_ELEM = "search";
91 public static final String INFODB_ELEM = "infodb";
92 public static final String INDEX_ELEM = "index";
93 public static final String INDEX_STEM_ELEM = "indexStem";
94 public static final String INDEX_OPTION_ELEM = "indexOption";
95 public static final String PARAM_DEFAULT_ELEM = "paramDefault";
96 public static final String BROWSE_ELEM = "browse";
97 public static final String DISPLAY_ELEM = "display";
98 public static final String LEVEL_ELEM = "level";
99 public static final String REPLACE_ELEM = "replace";
100
101 public static final String DBINFO_ELEM = "dbInfo";
102 public static final String DBNAME_ATT = "dbname";
103 public static final String DBPATH_ATT = "dbpath";
104 public static final String SQLSTATE_ATT = "sqlstate";
105 public static final String DATABASE_TYPE_ELEM = "databaseType";
106 public static final String SHORTNAME_ATT = "shortname";
107 public static final String NOTIFY_ELEM = "notify";
108 public static final String NOTIFY_HOST_ATT = "host";
109
110 //doc.xml file elems
111 public static final String DOCXML_SECTION_ELEM = "Section";
112 public static final String DOCXML_DESCRIPTION_ELEM = "Description";
113 public static final String DOCXML_METADATA_ELEM = "Metadata";
114 public static final String DOCXML_CONTENT_ELEM = "Content";
115
116 // elems for the pages to be processed by xslt
117 public final static String PAGE_ELEM = "page";
118 public final static String CONFIGURATION_ELEM = "config";
119 public final static String PAGE_REQUEST_ELEM = "pageRequest";
120 public final static String PAGE_RESPONSE_ELEM = "pageResponse";
121 public final static String PAGE_EXTRA_ELEM = "pageExtra";
122
123 //public final static String DESCRIPTION_ELEM = "description";
124
125 public static final String ACTION_ELEM = "action";
126 public static final String SUBACTION_ELEM = "subaction";
127
128 // add on to another elem type to get a list of that type
129 public static final String LIST_MODIFIER = "List";
130 // used to refer back to another element type
131 public static final String REF_MODIFIER = "Ref";
132 // greenstone xml attributes
133 public static final String COLLECTION_ATT = "collection";
134 public static final String NAME_ATT = "name";
135 public static final String MATCH_ATT = "match";
136 public static final String TO_ATT = "to";
137 public static final String USER_ID_ATT = "uid";
138 public static final String FROM_ATT = "from";
139 public static final String LANG_ATT = "lang";
140 public static final String HREF_ATT = "href";
141 public static final String TYPE_ATT = "type";
142 public static final String DB_TYPE_ATT = "dbType";
143 public static final String VALUE_ATT = "value";
144 public static final String DEFAULT_ATT = "default";
145 public static final String INFO_ATT = "info";
146 public static final String ACTION_ATT = "action";
147 public static final String SUBACTION_ATT = "subaction";
148 public static final String OUTPUT_ATT = "output";
149 public static final String ADDRESS_ATT = "address";
150 public static final String LOCAL_SITE_ATT = "localSite";
151 public static final String LOCAL_SITE_NAME_ATT = "localSiteName";
152 public static final String STATUS_ERROR_CODE_ATT = "code";
153 public static final String STATUS_PROCESS_ID_ATT = "pid";
154 public static final String PARAM_SHORTNAME_ATT = "shortname";
155 public static final String PARAM_IGNORE_POS_ATT = "ignore";
156 public static final String CLASSIFIER_CONTENT_ATT = "content";
157 public static final String ERROR_TYPE_ATT = "type";
158 public static final String COLLECT_TYPE_ATT = "ct";
159 public static final String HIDDEN_ATT = "hidden";
160 public static final String FACET_ATT = "facet";
161
162 // document stuff
163 public static final String DOC_TYPE_ATT = "docType";
164 public static final String DOC_NODE_ELEM = "documentNode";
165 public static final String NODE_CONTENT_ELEM = "nodeContent";
166 public static final String NODE_STRUCTURE_ELEM = "nodeStructure";
167 public static final String NODE_ID_ATT = "nodeID";
168 public static final String HREF_ID_ATT = "hrefId"; // for ids that need translating
169 public static final String ID_MOD_ATT = "idMod"; // might hold .rt etc for hrefIds
170 public static final String NODE_OID = "oid";
171 public static final String NODE_NAME_ATT = "nodeName";
172 public static final String NODE_TYPE_ATT = "nodeType";
173 public static final String NODE_RANK_ATT = "rank";
174 public static final String NODE_TYPE_ROOT = "root";
175 public static final String NODE_TYPE_INTERNAL = "internal";
176 public static final String NODE_TYPE_LEAF = "leaf";
177
178 public static final String DOC_TYPE_SIMPLE = "simple";
179 public static final String DOC_TYPE_PAGED = "paged";
180 public static final String DOC_TYPE_HIERARCHY = "hierarchy";
181 public static final String DOC_TYPE_PAGED_HIERARCHY = "pagedhierarchy";
182
183 public static final String SESSION_EXPIRATION = "session_expiration";
184 public static final String USER_SESSION_CACHE_ATT = "user_session_cache";
185
186 // classifier stuff
187 public static final String CLASS_NODE_ELEM = "classifierNode";
188 public static final String CLASS_NODE_ORIENTATION_ATT = "orientation";
189
190 // parameter types
191 public static final String PARAM_TYPE_INTEGER = "integer";
192 public static final String PARAM_TYPE_BOOLEAN = "boolean";
193 public static final String PARAM_TYPE_ENUM_START = "enum";
194 public static final String PARAM_TYPE_ENUM_SINGLE = "enum_single";
195 public static final String PARAM_TYPE_ENUM_MULTI = "enum_multi";
196 public static final String PARAM_TYPE_STRING = "string";
197 public static final String PARAM_TYPE_TEXT = "text";
198 public static final String PARAM_TYPE_MULTI = "multi";
199 public static final String PARAM_TYPE_FILE = "file";
200 public static final String PARAM_TYPE_INVISIBLE = "invisible";
201 public static final String PARAM_TYPE_CHECKBOX_LIST = "checkbox_list";
202 // stuff for text strings
203 public static final String DISPLAY_TEXT_ELEM = "displayItem";
204 // the following are used for the name attributes
205 public static final String DISPLAY_TEXT_NAME = "name";
206 public static final String DISPLAY_TEXT_SUBMIT = "submit";
207 public static final String DISPLAY_TEXT_DESCRIPTION = "description";
208
209 // request types
210 // get the module description
211 public static final String REQUEST_TYPE_DESCRIBE = "describe";
212 // startup a process
213 public static final String REQUEST_TYPE_PROCESS = "process";
214 // get the status of an ongoing process
215 public static final String REQUEST_TYPE_STATUS = "status";
216 // system type request - eg reload a collection
217 public static final String REQUEST_TYPE_SYSTEM = "system";
218 // page requests to the Receptionist/Actions
219 public static final String REQUEST_TYPE_PAGE = "page"; // used to be cgi
220 // get any format info for a service
221 public static final String REQUEST_TYPE_FORMAT = "format";
222 // modify the requests
223 public static final String REQUEST_TYPE_MESSAGING = "messaging";
224 // save the format string
225 public static final String REQUEST_TYPE_FORMAT_STRING = "formatString";
226 // check credentials
227 public static final String REQUEST_TYPE_SECURITY = "security";
228
229 // service types
230 public static final String SERVICE_TYPE_QUERY = "query";
231 public static final String SERVICE_TYPE_RETRIEVE = "retrieve";
232 public static final String SERVICE_TYPE_BROWSE = "browse";
233 public static final String SERVICE_TYPE_APPLET = "applet";
234 public static final String SERVICE_TYPE_PROCESS = "process";
235 public static final String SERVICE_TYPE_ENRICH = "enrich";
236 public static final String SERVICE_TYPE_OAI = "oai";
237 public static final String FLAX_PAGE = "flaxPage";
238 public static final String FLAX_PAGE_GENERATION = "FlaxPageGeneration";
239
240 // system command types and attributes
241 public static final String SYSTEM_TYPE_CONFIGURE = "configure";
242 public static final String SYSTEM_TYPE_ACTIVATE = "activate";
243 public static final String SYSTEM_TYPE_DEACTIVATE = "deactivate";
244 public static final String SYSTEM_TYPE_PING = "ping";
245 //public static final String SYSTEM_TYPE_ISPERSISTENT = "is-persistent";
246
247 public static final String SYSTEM_SUBSET_ATT = "subset";
248 public static final String SYSTEM_MODULE_TYPE_ATT = "moduleType";
249 public static final String SYSTEM_MODULE_NAME_ATT = "moduleName";
250
251 // communicator types
252 public static final String COMM_TYPE_SOAP_JAVA = "soap";
253
254 // error types
255 public static final String ERROR_TYPE_SYNTAX = "syntax";
256 public static final String ERROR_TYPE_SYSTEM = "system";
257 public static final String ERROR_TYPE_INVALID_ID = "invalid_id";
258 public static final String ERROR_TYPE_OTHER = "other";
259
260 // some system wide param names
261 public static final String SUBSET_PARAM = "subset";
262
263 //for plugin
264 public static final String PLUGIN_ELEM = "plugin";
265 public static final String IMPORT_ELEM = "import";
266
267 //for authentication
268 public static final String AUTHEN_NODE_ELEM = "authenticationNode";
269 public static final String USER_NODE_ELEM = "userNode";
270
271 //for configure action results
272 public static final String SUCCESS = "success";
273 public static final String ERROR = "error";
274
275 //security tags and attributes
276 public static final String SECURITY_ELEM = "security";
277 public static final String SCOPE_ATT = "scope";
278 public static final String DEFAULT_ACCESS_ATT = "default_access";
279 public static final String EXCEPTION_ELEM = "exception";
280 public static final String DOCUMENT_SET_ELEM = "documentSet";
281 public static final String GROUP_ELEM = "group";
282 public static final String MATCH_ELEM = "match";
283 public static final String FIELD_ATT = "field";
284 public static final String USER_INFORMATION_ELEM = "userInformation";
285 public static final String USERNAME_ATT = "username";
286 public static final String GROUPS_ATT = "groups";
287 public static final String BASE_URL = "baseURL";
288
289 //for classifiers
290 public static final String CHILD_TYPE_ATT = "childType";
291 public static final String CLASSIFIER_STYLE_ATT = "classifierStyle";
292 public static final String HLIST = "HList";
293 public static final String VLIST = "VList";
294
295 //for namespaces
296 public static final String XSL_NAMESPACE = "http://www.w3.org/1999/XSL/Transform";
297 public static final String GSF_NAMESPACE = "http://www.greenstone.org/greenstone3/schema/ConfigFormat";
298 public static final String JAVA_NAMESPACE = "http://xml.apache.org/xslt/java";
299 public static final String UTIL_NAMESPACE = "xalan://org.greenstone.gsdl3.util.XSLTUtil";
300
301 /**
302 * takes a list of elements, and returns an array of strings of the values
303 * of attribute att_name
304 */
305 public static String[] getAttributeValuesFromList(Element list, String att_name)
306 {
307
308 NodeList children = list.getChildNodes();
309
310 int num_nodes = children.getLength();
311 String[] ids = new String[num_nodes];
312 for (int i = 0; i < num_nodes; i++)
313 {
314 Element e = (Element) children.item(i);
315 String id = e.getAttribute(att_name);
316 ids[i] = id;
317 }
318
319 return ids;
320 }
321
322 public static HashMap<String, Serializable> extractParams(Element xml, boolean deep)
323 {
324 return extractParams(xml, deep, null);
325 }
326
327 /**
328 * takes a paramList element, and gets a HashMap of name-value pairs if
329 * deep=true, extracts embedded params, otherwise just top level params
330 */
331 public static HashMap<String, Serializable> extractParams(Element xml, boolean deep, String toFind)
332 {
333 if (xml == null)
334 {
335 return null;
336 }
337
338 if (!xml.getNodeName().equals(PARAM_ELEM + LIST_MODIFIER))
339 {
340 logger.error("paramList element should have been passed to extractParams, instead it was " + xml.getNodeName());
341 return null;
342 }
343
344 NodeList params = null;
345 if (deep)
346 { // get all the nested ones
347 params = xml.getElementsByTagName(PARAM_ELEM);
348 }
349 else
350 { // just get the top level ones
351 params = xml.getChildNodes();
352 }
353 HashMap<String, Serializable> param_map = new HashMap<String, Serializable>();
354 for (int i = 0; i < params.getLength(); i++)
355 {
356 if (params.item(i).getNodeName().equals(PARAM_ELEM))
357 {
358 Element param = (Element) params.item(i);
359 String name = param.getAttribute(NAME_ATT);
360 String value = getValue(param); //att or content
361
362 // For only one parameter
363 if (toFind != null && name.equals(toFind))
364 {
365 param_map.put(name, value);
366 return param_map;
367 }
368 else if (toFind != null)
369 continue;
370
371 int pos = name.indexOf('.');
372 if (pos == -1)
373 { // a base param
374 param_map.put(name, value);
375 }
376 else
377 { // a namespaced param
378
379 String namespace = name.substring(0, pos);
380 name = name.substring(pos + 1);
381 HashMap<String, String> map = (HashMap<String, String>) param_map.get(namespace);
382 if (map == null)
383 {
384 map = new HashMap<String, String>();
385 param_map.put(namespace, map);
386 }
387 map.put(name, value);
388 }
389 }
390 }
391 return param_map;
392 }
393
394 /** gets the value att or the text content */
395 public static String getValue(Element e)
396 {
397 String val = e.getAttribute(VALUE_ATT);
398 if (val == null || val.equals(""))
399 {
400 // have to get it out of the text
401 val = getNodeText(e);
402
403 }
404 else
405 {
406 // unescape the xml stuff
407 val = unXmlSafe(val);
408 }
409 return val;
410 }
411
412 /** extracts the text out of a node */
413 public static Node getNodeTextNode(Element param)
414 {
415 param.normalize();
416 Node n = param.getFirstChild();
417 while (n != null && n.getNodeType() != Node.TEXT_NODE)
418 {
419 n = n.getNextSibling();
420 }
421 return n;
422 }
423
424 /** extracts the text out of a node */
425 public static String getNodeText(Element param)
426 {
427 Node text_node = getNodeTextNode(param);
428 if (text_node == null)
429 {
430 return "";
431 }
432 return text_node.getNodeValue();
433 }
434
435 public static void setNodeText(Element elem, String text)
436 {
437 Node old_text_node = getNodeTextNode(elem);
438 if (old_text_node != null)
439 {
440 elem.removeChild(old_text_node);
441 }
442 Text t = elem.getOwnerDocument().createTextNode(text);
443 elem.appendChild(t);
444 }
445
446 /** add text to a document/subsection element */
447 public static boolean addDocText(Document owner, Element doc, String text)
448 {
449
450 Element content = owner.createElement(NODE_CONTENT_ELEM);
451 Text t = owner.createTextNode(text);
452 content.appendChild(t);
453 doc.appendChild(content);
454 return true;
455 }
456
457 /** add an error message, unknown error type */
458 public static boolean addError(Document owner, Element doc, String text)
459 {
460 return addError(owner, doc, text, ERROR_TYPE_OTHER);
461 }
462
463 /** add an error message */
464 public static boolean addError(Document owner, Element doc, String text, String error_type)
465 {
466
467 Element content = owner.createElement(ERROR_ELEM);
468 content.setAttribute(ERROR_TYPE_ATT, error_type);
469 Text t = owner.createTextNode(text);
470 content.appendChild(t);
471 doc.appendChild(content);
472 return true;
473 }
474
475 /** add an error message */
476 public static boolean addError(Document owner, Element doc, Throwable error)
477 {
478 return addError(owner, doc, error, ERROR_TYPE_OTHER);
479 }
480
481 /** add an error message */
482 public static boolean addError(Document owner, Element doc, Throwable error, String error_type)
483 {
484 error.printStackTrace();
485 return addError(owner, doc, error.toString(), error_type);
486 }
487
488 public static Element createMetadataParamList(Document owner, Vector meta_values)
489 {
490
491 Element meta_param_list = owner.createElement(PARAM_ELEM + LIST_MODIFIER);
492 Iterator i = meta_values.iterator();
493 while (i.hasNext())
494 {
495 String next = (String) i.next();
496 Element meta_param = owner.createElement(PARAM_ELEM);
497 meta_param_list.appendChild(meta_param);
498 meta_param.setAttribute(NAME_ATT, "metadata");
499 meta_param.setAttribute(VALUE_ATT, next);
500 }
501 return meta_param_list;
502 }
503
504 /** adds a metadata elem to a list */
505 public static boolean addMetadata(Document owner, Element list, String meta_name, String meta_value)
506 {
507 if (meta_value == null || meta_value.equals(""))
508 {
509 return false;
510 }
511 Element data = owner.createElement(METADATA_ELEM);
512 data.setAttribute(NAME_ATT, meta_name);
513 Text t = owner.createTextNode(meta_value);
514 data.appendChild(t);
515 list.appendChild(data);
516 return true;
517
518 }
519
520 /**
521 * copies the metadata out of the metadataList of 'from' into the
522 * metadataList of 'to'
523 */
524 public static boolean mergeMetadataLists(Node to, Node from)
525 {
526 Node from_meta = getChildByTagName(from, METADATA_ELEM + LIST_MODIFIER);
527 if (from_meta == null)
528 { // nothing to copy
529 return true;
530 }
531 return mergeMetadataFromList(to, from_meta);
532 }
533
534 /**
535 * copies the metadata out of the meta_list metadataList into the
536 * metadataList of 'to'
537 */
538 public static boolean mergeMetadataFromList(Node to, Node meta_list)
539 {
540 if (meta_list == null)
541 return false;
542 Node to_meta = getChildByTagName(to, METADATA_ELEM + LIST_MODIFIER);
543 Document to_owner = to.getOwnerDocument();
544 if (to_meta == null)
545 {
546 to.appendChild(to_owner.importNode(meta_list, true));
547 return true;
548 }
549 // copy individual metadata elements
550 NodeList meta_items = ((Element) meta_list).getElementsByTagName(METADATA_ELEM);
551 for (int i = 0; i < meta_items.getLength(); i++)
552 {
553 to_meta.appendChild(to_owner.importNode(meta_items.item(i), true));
554 }
555 return true;
556 }
557
558 /** copies all the children from from to to */
559 public static boolean mergeElements(Element to, Element from)
560 {
561
562 Document owner = to.getOwnerDocument();
563 Node child = from.getFirstChild();
564 while (child != null)
565 {
566 to.appendChild(owner.importNode(child, true));
567 child = child.getNextSibling();
568 }
569 return true;
570 }
571
572 /** returns the (first) element child of the node n */
573 public static Element getFirstElementChild(Node n)
574 {
575
576 Node child = n.getFirstChild();
577 while (child != null)
578 {
579 if (child.getNodeType() == Node.ELEMENT_NODE)
580 {
581 return (Element) child;
582 }
583 child = child.getNextSibling();
584 }
585 return null; //no element child found
586 }
587
588 /** returns the (first) child element with the given name */
589 public static Node getChildByTagName(Node n, String name)
590 {
591 if (n != null)
592 { // this line is an attempted solution to the NullPointerException mentioned
593 // in trac bug ticket #225. If n is null can't do n.getFirstChild() below. As per bug #225:
594 // GSXML.getNodeByPath() is called by GS2BrowseAction, which then calls this method.
595 // If n is null, null will be returned which GS2BrowseAction already checks for. It's here
596 // that the NullPointerException was thrown.
597
598 Node child = n.getFirstChild();
599 while (child != null)
600 {
601 if (child.getNodeName().equals(name))
602 {
603 return child;
604 }
605 child = child.getNextSibling();
606 }
607 }
608 return null; //not found
609 }
610
611 /**
612 * returns the (nth) child element with the given name index numbers start
613 * at 0
614 */
615 public static Node getChildByTagNameIndexed(Node n, String name, int index)
616 {
617 if (index == -1)
618 {
619 return getChildByTagName(n, name);
620 }
621 int count = 0;
622 Node child = n.getFirstChild();
623 while (child != null)
624 {
625 if (child.getNodeName().equals(name))
626 {
627 if (count == index)
628 {
629 return child;
630 }
631 else
632 {
633 count++;
634 }
635 }
636 child = child.getNextSibling();
637 }
638 return null; //not found
639 }
640
641 /**
642 * takes an xpath type expression of the form name/name/... and returns the
643 * first node that matches, or null if not found
644 */
645 public static Node getNodeByPath(Node n, String path)
646 {
647
648 String link = GSPath.getFirstLink(path);
649 path = GSPath.removeFirstLink(path);
650 while (!link.equals(""))
651 {
652 n = getChildByTagName(n, link);
653 if (n == null)
654 {
655 return null;
656 }
657 link = GSPath.getFirstLink(path);
658 path = GSPath.removeFirstLink(path);
659 }
660 return n;
661 }
662
663 /**
664 * takes an xpath type expression of the form name/name/... and returns the
665 * first node that matches, or null if not found can include [i] indices.
666 * index numbers start at 0
667 */
668 public static Node getNodeByPathIndexed(Node n, String path)
669 {
670
671 String link = GSPath.getFirstLink(path);
672 int index = GSPath.getIndex(link);
673 if (index != -1)
674 {
675 link = GSPath.removeIndex(link);
676 }
677 path = GSPath.removeFirstLink(path);
678 while (!link.equals(""))
679 {
680 n = getChildByTagNameIndexed(n, link, index);
681 if (n == null)
682 {
683 return null;
684 }
685 link = GSPath.getFirstLink(path);
686 index = GSPath.getIndex(link);
687 if (index != -1)
688 {
689 link = GSPath.removeIndex(link);
690 }
691 path = GSPath.removeFirstLink(path);
692 }
693 return n;
694 }
695
696 public static HashMap<String, Node> getChildrenMap(Node n)
697 {
698
699 HashMap<String, Node> map = new HashMap<String, Node>();
700 Node child = n.getFirstChild();
701 while (child != null)
702 {
703 String name = child.getNodeName();
704 map.put(name, child);
705 child = child.getNextSibling();
706 }
707 return map;
708 }
709
710 public static NodeList getChildrenByTagName(Node n, String name)
711 {
712 MyNodeList node_list = new MyNodeList();
713 Node child = n.getFirstChild();
714 while (child != null)
715 {
716 if (child.getNodeName().equals(name))
717 {
718 node_list.addNode(child);
719 }
720 child = child.getNextSibling();
721 }
722 return node_list;
723 }
724
725 public static NodeList getChildrenByTagNameNS(Node n, String namespace, String local_name)
726 {
727 MyNodeList node_list = new MyNodeList();
728 Node child = n.getFirstChild();
729 while (child != null)
730 {
731 if (child.getNodeType() == Node.ELEMENT_NODE && child.getNamespaceURI() != null && child.getNamespaceURI().equals(namespace) && child.getLocalName() != null && child.getLocalName().equals(local_name))
732 {
733 node_list.addNode(child);
734 }
735 child = child.getNextSibling();
736 }
737 return node_list;
738 }
739
740 /** Duplicates an element, but gives it a new name */
741 public static Element duplicateWithNewName(Document owner, Element element, String element_name, boolean with_attributes)
742 {
743 return duplicateWithNewNameNS(owner, element, element_name, null, with_attributes);
744 }
745
746 /** Duplicates an element, but gives it a new name */
747 public static Element duplicateWithNewNameNS(Document owner, Element element, String element_name, String namespace_uri, boolean with_attributes)
748 {
749 Element duplicate;
750 if (namespace_uri == null)
751 {
752 duplicate = owner.createElement(element_name);
753 }
754 else
755 {
756 duplicate = owner.createElementNS(namespace_uri, element_name);
757 }
758
759 // Copy element attributes
760 if (with_attributes)
761 {
762 NamedNodeMap attributes = element.getAttributes();
763 for (int i = 0; i < attributes.getLength(); i++)
764 {
765 Node attribute = attributes.item(i);
766 duplicate.setAttribute(attribute.getNodeName(), attribute.getNodeValue());
767 }
768 }
769
770 // Copy element children
771 NodeList children = element.getChildNodes();
772 for (int i = 0; i < children.getLength(); i++)
773 {
774 Node child = children.item(i);
775 duplicate.appendChild(owner.importNode(child, true));
776 }
777
778 return duplicate;
779 }
780
781 public static void copyAllChildren(Element to, Element from)
782 {
783
784 Document to_doc = to.getOwnerDocument();
785 Node child = from.getFirstChild();
786 while (child != null)
787 {
788 to.appendChild(to_doc.importNode(child, true));
789 child = child.getNextSibling();
790 }
791 }
792
793 /** returns a basic request message */
794 public static Element createBasicRequest(Document owner, String request_type, String to, UserContext userContext)
795 {
796 Element request = owner.createElement(REQUEST_ELEM);
797 request.setAttribute(TO_ATT, to);
798 request.setAttribute(TYPE_ATT, request_type);
799 request.setAttribute(LANG_ATT, userContext._lang);
800 Element userContextElem = owner.createElement("userContext");
801 request.appendChild(userContextElem);
802 userContextElem.setAttribute(LANG_ATT, userContext._lang);
803 userContextElem.setAttribute(USERNAME_ATT, userContext._username);
804 userContextElem.setAttribute(USER_ID_ATT, userContext._userID);
805
806 if (userContext._groups != null)
807 {
808 String groupString = "";
809 for (int i = 0; i < userContext._groups.length; i++)
810 {
811 groupString += userContext._groups[i];
812 if (i != userContext._groups.length - 1)
813 {
814 groupString += ",";
815 }
816 }
817
818 if (groupString.length() > 0)
819 {
820 userContextElem.setAttribute(GROUPS_ATT, groupString);
821 }
822 }
823
824 return request;
825 }
826
827 public static Element createBasicResponse(Document owner, String from)
828 {
829 Element response = owner.createElement(GSXML.RESPONSE_ELEM);
830 response.setAttribute(GSXML.FROM_ATT, from);
831 response.setAttribute(GSXML.TYPE_ATT, GSXML.REQUEST_TYPE_PROCESS);
832 return response;
833 }
834
835 public static Element createMetadataElement(Document owner, String name, String value)
836 {
837 Element metaElem = owner.createElement(GSXML.METADATA_ELEM);
838 metaElem.setAttribute(GSXML.NAME_ATT, name);
839 metaElem.setAttribute(GSXML.VALUE_ATT, value);
840 return metaElem;
841 }
842
843 public static Element createTextElement(Document owner, String elem_name, String text)
844 {
845 Element e = owner.createElement(elem_name);
846 Text t = owner.createTextNode(text);
847 e.appendChild(t);
848 return e;
849
850 }
851
852 public static Element createTextElement(Document owner, String elem_name, String text, String att_name, String att_value)
853 {
854 Element e = owner.createElement(elem_name);
855 e.setAttribute(att_name, att_value);
856 Text t = owner.createTextNode(text);
857 e.appendChild(t);
858 return e;
859
860 }
861
862 public static Element createDisplayTextElement(Document owner, String text_name, String text)
863 {
864 Element e = owner.createElement(DISPLAY_TEXT_ELEM);
865 e.setAttribute(NAME_ATT, text_name);
866 Text t = owner.createTextNode(text);
867 e.appendChild(t);
868 return e;
869
870 }
871
872 public static Element createParameter(Document owner, String name, String value)
873 {
874 Element param = owner.createElement(PARAM_ELEM);
875 param.setAttribute(NAME_ATT, name);
876 param.setAttribute(VALUE_ATT, value);
877 return param;
878 }
879
880 public static void addParametersToList(Document owner, Element param_list, HashMap params)
881 {
882 if (params == null)
883 {
884 return;
885 }
886
887 Set items = params.entrySet();
888 Iterator i = items.iterator();
889 while (i.hasNext())
890 {
891 Map.Entry m = (Map.Entry) i.next();
892 param_list.appendChild(createParameter(owner, (String) m.getKey(), (String) m.getValue()));
893 }
894
895 }
896
897 public static Element createParameterDescription(Document owner, String id, String display_name, String type, String default_value, String[] option_ids, String[] option_names)
898 {
899
900 Element p = owner.createElement(PARAM_ELEM);
901 p.setAttribute(NAME_ATT, id);
902 p.setAttribute(TYPE_ATT, type);
903 p.appendChild(createDisplayTextElement(owner, GSXML.DISPLAY_TEXT_NAME, display_name));
904
905 if (default_value != null)
906 {
907 p.setAttribute(DEFAULT_ATT, default_value);
908 }
909 if (option_ids != null && option_names != null)
910 {
911 for (int i = 0; i < option_ids.length; i++)
912 {
913 Element e = owner.createElement(PARAM_OPTION_ELEM);
914 e.setAttribute(NAME_ATT, option_ids[i]);
915 e.appendChild(createDisplayTextElement(owner, GSXML.DISPLAY_TEXT_NAME, option_names[i]));
916 p.appendChild(e);
917 }
918 }
919 return p;
920 }
921
922 public static Element createParameterDescription2(Document owner, String id, String display_name, String type, String default_value, ArrayList<String> option_ids, ArrayList<String> option_names)
923 {
924
925 Element p = owner.createElement(PARAM_ELEM);
926 p.setAttribute(NAME_ATT, id);
927 p.setAttribute(TYPE_ATT, type);
928 p.appendChild(createDisplayTextElement(owner, GSXML.DISPLAY_TEXT_NAME, display_name));
929 if (default_value != null)
930 {
931 p.setAttribute(DEFAULT_ATT, default_value);
932 }
933 if (option_ids != null && option_names != null)
934 {
935 for (int i = 0; i < option_ids.size(); i++)
936 {
937 Element e = owner.createElement(PARAM_OPTION_ELEM);
938 e.setAttribute(NAME_ATT, option_ids.get(i));
939 e.appendChild(createDisplayTextElement(owner, GSXML.DISPLAY_TEXT_NAME, option_names.get(i)));
940 p.appendChild(e);
941 }
942 }
943 return p;
944 }
945
946 /** returns the element parent/node_name[@attribute_name='attribute_value'] */
947 public static Element getNamedElement(Element parent, String node_name, String attribute_name, String attribute_value)
948 {
949
950 NodeList children = parent.getChildNodes();
951 for (int i = 0; i < children.getLength(); i++)
952 {
953 Node child = children.item(i);
954 if (child.getNodeName().equals(node_name))
955 {
956 if (((Element) child).getAttribute(attribute_name).equals(attribute_value))
957 return (Element) child;
958 }
959 }
960 // not found
961 return null;
962 }
963
964 public static Element getNamedElementNS(Element parent, String namespace_uri, String node_local_name, String attribute_name, String attribute_value)
965 {
966 NodeList children = parent.getChildNodes();
967 for (int i = 0; i < children.getLength(); i++)
968 {
969 Node child = children.item(i);
970 if (child.getNodeType() == Node.ELEMENT_NODE && child.getNamespaceURI().equals(namespace_uri) && child.getLocalName().equals(node_local_name))
971 {
972 if (((Element) child).getAttribute(attribute_name).equals(attribute_value))
973 return (Element) child;
974 }
975 }
976 // not found
977 return null;
978 }
979
980 public static NodeList getNamedElementsNS(Element parent, String namespace_uri, String node_local_name, String attribute_name, String attribute_value)
981 {
982 MyNodeList result = new MyNodeList();
983 NodeList children = parent.getChildNodes();
984 for (int i = 0; i < children.getLength(); i++)
985 {
986 Node child = children.item(i);
987 if (child.getNodeType() == Node.ELEMENT_NODE && child.getNamespaceURI().equals(namespace_uri) && child.getLocalName().equals(node_local_name))
988 {
989 if (((Element) child).getAttribute(attribute_name).equals(attribute_value))
990 result.addNode(child);
991 }
992 }
993 return result;
994 }
995
996 public static NodeList getElementsWithAttributesNS(Element parent, String namespace_uri, String node_local_name, String[] attribute_names, String[] attribute_values)
997 {
998 if (attribute_names.length == 0 || attribute_names.length != attribute_values.length)
999 {
1000 return new MyNodeList();
1001 }
1002
1003 MyNodeList result = new MyNodeList();
1004
1005 NodeList matchingNodes = GSXML.getNamedElementsNS(parent, namespace_uri, node_local_name, attribute_names[0], attribute_values[0]);
1006 for (int i = 0; i < matchingNodes.getLength(); i++)
1007 {
1008 Element current = (Element) matchingNodes.item(i);
1009 boolean nodeMatches = true;
1010 for (int j = 1; j < attribute_names.length; j++)
1011 {
1012 String currentName = attribute_names[j];
1013 String currentValue = attribute_values[j];
1014 if (!current.getAttribute(currentName).equals(currentValue))
1015 {
1016 nodeMatches = false;
1017 break;
1018 }
1019 }
1020
1021 if (nodeMatches)
1022 {
1023 result.addNode(current);
1024 }
1025 }
1026
1027 return result;
1028 }
1029
1030 public static void removeElementsWithAttributesNS(Element parent, String namespace_uri, String node_local_name, String[] attribute_names, String[] attribute_values)
1031 {
1032 NodeList matchingNodes = GSXML.getElementsWithAttributesNS(parent, namespace_uri, node_local_name, attribute_names, attribute_values);
1033 for (int i = 0; i < matchingNodes.getLength(); i++)
1034 {
1035 parent.removeChild(matchingNodes.item(i));
1036 }
1037 }
1038
1039 // In element main, tries to find any previous occurrence of elements with xsl-template-name=templateName,
1040 // and whose named attribute (attributeName) has the same value as the same attribute in node.
1041 // If this is the case, such a previous occurrence is removed from element main, since
1042 // the new node will contain a more specific redefinition of this element.
1043 public static void removeNamedElementNS(Element parent, String namespace_uri, String node_local_name, String attribute_name, String attribute_value)
1044 {
1045 if (attribute_value.equals(""))
1046 {
1047 // it has no identifying attribute, so we can't find any matches
1048 return;
1049 }
1050
1051 Element old_elem = GSXML.getNamedElementNS(parent, namespace_uri, node_local_name, attribute_name, attribute_value);
1052 if (old_elem != null)
1053 {
1054 parent.removeChild(old_elem);
1055 }
1056 }
1057
1058 public static void removeNamedElementsNS(Element parent, String namespace, String node_local_name, String attribute_name, String attribute_value)
1059 {
1060 if (attribute_value.equals(""))
1061 {
1062 // it has no identifying attribute, so we can't find any matches
1063 return;
1064 }
1065
1066 NodeList children = parent.getChildNodes();
1067 for (int i = children.getLength() - 1; i >= 0; i--)
1068 {
1069 Node child = children.item(i);
1070 if (child.getNodeType() == Node.ELEMENT_NODE && child.getNamespaceURI().equals(namespace) && child.getLocalName() != null && child.getLocalName().equals(node_local_name))
1071 {
1072 if (((Element) child).getAttribute(attribute_name).equals(attribute_value))
1073 parent.removeChild(child);
1074 }
1075 }
1076 }
1077
1078 /**
1079 * returns a NodeList of elements:
1080 * ancestor/node_name[@attribute_name='attribute_value']
1081 */
1082 public static NodeList getNamedElements(Element ancestor, String node_name, String attribute_name, String attribute_value)
1083 {
1084 MyNodeList node_list = new MyNodeList();
1085 NodeList children = ancestor.getElementsByTagName(node_name);
1086
1087 if (children != null && children.getLength() > 0)
1088 {
1089
1090 for (int i = 0; i < children.getLength(); i++)
1091 {
1092 Node child = children.item(i);
1093 if (child.getNodeName().equals(node_name))
1094 {
1095 if (((Element) child).getAttribute(attribute_name).equals(attribute_value))
1096 node_list.addNode(child);
1097 }
1098 }
1099 }
1100 return node_list;
1101 }
1102
1103 public static Element getLastElementByTagNameNS(Element main, String namespace, String node_name)
1104 {
1105 NodeList nodes = main.getElementsByTagNameNS(namespace, node_name);
1106 int len = nodes.getLength();
1107 if (len == 0)
1108 {
1109 return null;
1110 }
1111 return (Element) nodes.item(len - 1);
1112 }
1113
1114 public static int SORT_TYPE_STRING = 0;
1115 public static int SORT_TYPE_INT = 1;
1116 public static int SORT_TYPE_FLOAT = 2;
1117
1118 // sort type:
1119 public static Element insertIntoOrderedList(Element parent_node, String node_name, Element start_from_elem, Element new_elem, String sort_att, boolean descending)
1120 {
1121 if (new_elem == null)
1122 return null;
1123 Element cloned_elem = (Element) parent_node.getOwnerDocument().importNode(new_elem, true);
1124 if (start_from_elem == null)
1125 {
1126 parent_node.appendChild(cloned_elem);
1127 return cloned_elem;
1128 }
1129
1130 Node current_node = start_from_elem;
1131 String insert_att = cloned_elem.getAttribute(sort_att);
1132 String list_att = start_from_elem.getAttribute(sort_att);
1133 while ((!descending && list_att.compareTo(insert_att) < 0) || (descending && list_att.compareTo(insert_att) > 0))
1134 {
1135 current_node = current_node.getNextSibling();
1136 if (current_node == null)
1137 break; // end of the list
1138 if (!current_node.getNodeName().equals(node_name))
1139 {
1140 continue; // not a valid node
1141 }
1142 list_att = ((Element) current_node).getAttribute(sort_att);
1143 }
1144
1145 parent_node.insertBefore(cloned_elem, current_node);
1146 return cloned_elem;
1147 }
1148
1149 /**
1150 * Returns the appropriate language element from a display elem, display is
1151 * the containing element, name is the name of the element to look for, lang
1152 * is the preferred language, lang_default is the fall back lang if neither
1153 * lang is found, will return the first one it finds
1154 */
1155 public static String getDisplayText(Element display, String name, String lang, String lang_default)
1156 {
1157
1158 String def = null;
1159 String first = null;
1160 NodeList elems = display.getElementsByTagName(DISPLAY_TEXT_ELEM);
1161 if (elems.getLength() == 0)
1162 return "";
1163 for (int i = 0; i < elems.getLength(); i++)
1164 {
1165 Element e = (Element) elems.item(i);
1166 String n = e.getAttribute(NAME_ATT);
1167 if (name.equals(n))
1168 {
1169 String l = e.getAttribute(LANG_ATT);
1170 if (lang.equals(l))
1171 {
1172 return getNodeText(e);
1173 }
1174 else if (lang_default.equals(l))
1175 {
1176 def = getNodeText(e);
1177 }
1178 else if (first == null)
1179 {
1180 first = getNodeText(e);
1181 }
1182 }
1183 else
1184 {
1185 continue;
1186 }
1187 }
1188
1189 if (def != null)
1190 {
1191 return def;
1192 }
1193 if (first != null)
1194 {
1195 return first;
1196 }
1197 return "";
1198 }
1199
1200 // replaces < > " ' & in the original with their entities
1201 public static String xmlSafe(String original)
1202 {
1203
1204 StringBuffer filtered = new StringBuffer(original.length());
1205 char c;
1206 for (int i = 0; i < original.length(); i++)
1207 {
1208 c = original.charAt(i);
1209 if (c == '>')
1210 {
1211 filtered.append("&gt;");
1212 }
1213 else if (c == '<')
1214 {
1215 filtered.append("&lt;");
1216 }
1217 else if (c == '"')
1218 {
1219 filtered.append("&quot;");
1220 }
1221 else if (c == '&')
1222 {
1223 filtered.append("&amp;");
1224 }
1225 else if (c == '\'')
1226 {
1227 filtered.append("&apos;");
1228 }
1229 else
1230 {
1231 filtered.append(c);
1232 }
1233 }
1234 return filtered.toString();
1235 }
1236
1237 // replaces < > " ' & entities with their originals
1238 public static String unXmlSafe(String original)
1239 {
1240
1241 StringBuffer filtered = new StringBuffer(original.length());
1242 char c;
1243 for (int i = 0; i < original.length(); i++)
1244 {
1245 c = original.charAt(i);
1246 if (c == '&')
1247 {
1248 int pos = original.indexOf(";", i);
1249 String entity = original.substring(i + 1, pos);
1250 if (entity.equals("gt"))
1251 {
1252 filtered.append(">");
1253 }
1254 else if (entity.equals("lt"))
1255 {
1256 filtered.append("<");
1257 }
1258 else if (entity.equals("apos"))
1259 {
1260 filtered.append("'");
1261 }
1262 else if (entity.equals("amp"))
1263 {
1264 filtered.append("&");
1265 }
1266 else if (entity.equals("quot"))
1267 {
1268 filtered.append("\"");
1269 }
1270 else
1271 {
1272 filtered.append("&" + entity + ";");
1273 }
1274 i = pos;
1275 }
1276 else
1277 {
1278 filtered.append(c);
1279 }
1280 }
1281 return filtered.toString();
1282 }
1283
1284 public static void printXMLNode(Node e, boolean printText)
1285 {
1286 printXMLNode(e, 0, printText);
1287 }
1288
1289 public static String xmlNodeToString(Node e)
1290 {
1291 StringBuffer sb = new StringBuffer("");
1292 xmlNodeToString(sb, e, true, "\t", 0);
1293 return sb.toString();
1294 }
1295
1296 public static void xmlNodeToString(StringBuffer sb, Node e, boolean indent, String indentString, int depth)
1297 {
1298 if (e.getNodeType() == Node.TEXT_NODE)
1299 {
1300 if (e.getNodeValue() != "")
1301 {
1302 String text = e.getNodeValue();
1303 if (text != null)
1304 {
1305 text = text.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("^[\\n\\r\\t\\s]*", "").replaceAll("[\\n\\r\\t\\s]*$", "");
1306 sb.append(text);
1307 }
1308 }
1309 return;
1310 }
1311
1312 if (e.getNodeType() == Node.COMMENT_NODE)
1313 {
1314 if (e.getNodeValue() != "")
1315 {
1316 sb.append("<!--" + e.getNodeValue() + "-->");
1317 }
1318 return;
1319 }
1320
1321 if (indent)
1322 {
1323 for (int i = 0; i < depth; i++)
1324 {
1325 sb.append(indentString);
1326 }
1327 }
1328
1329 sb.append('<');
1330 sb.append(e.getNodeName());
1331 NamedNodeMap attrs = e.getAttributes();
1332 if (attrs != null)
1333 {
1334 for (int i = 0; i < attrs.getLength(); i++)
1335 {
1336 Node attr = attrs.item(i);
1337 sb.append(' ');
1338 sb.append(attr.getNodeName());
1339 sb.append("=\"");
1340 sb.append(attr.getNodeValue().replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;"));
1341 sb.append('"');
1342 }
1343 }
1344
1345 if (e.hasChildNodes())
1346 {
1347 boolean hasElements = false;
1348 boolean indentSwapped = false;
1349
1350 Node child = e.getFirstChild();
1351 do
1352 {
1353 if (child.getNodeType() == Node.ELEMENT_NODE)
1354 {
1355 hasElements = true;
1356 }
1357 if (child.getNodeType() == Node.TEXT_NODE && indent)
1358 {
1359 if (child.getNodeValue() != null && child.getNodeValue().trim().length() > 0)
1360 {
1361 indentSwapped = true;
1362 indent = false;
1363 }
1364 }
1365 } while ((child = child.getNextSibling()) != null);
1366
1367 sb.append(">");
1368 if (hasElements && indent)
1369 {
1370 sb.append("\n");
1371 }
1372
1373 child = e.getFirstChild();
1374 do
1375 {
1376 xmlNodeToString(sb, child, indent, indentString, depth + 1);
1377 } while ((child = child.getNextSibling()) != null);
1378
1379 if (indent)
1380 {
1381 for (int i = 0; i < depth; i++)
1382 {
1383 sb.append(indentString);
1384 }
1385 }
1386
1387 sb.append("</" + e.getNodeName() + ">");
1388
1389 if ((hasElements && indent) || indentSwapped)
1390 {
1391 sb.append("\n");
1392 }
1393 }
1394 else
1395 {
1396 sb.append("/>");
1397
1398 if (indent)
1399 {
1400 sb.append("\n");
1401 }
1402 }
1403
1404 /*
1405 boolean hasElements = false;
1406 boolean indentSwapped = false;
1407 for (int i = 0; i < children.getLength(); i++)
1408 {
1409 if (children.item(i).getNodeType() == Node.ELEMENT_NODE)
1410 {
1411 hasElements = true;
1412 }
1413 if (children.item(i).getNodeType() == Node.TEXT_NODE && indent)
1414 {
1415 if (children.item(i).getNodeValue() != null && children.item(i).getNodeValue().trim().length() > 0)
1416 {
1417 indentSwapped = true;
1418 indent = false;
1419 }
1420 }
1421 }
1422
1423 if (children == null || children.getLength() == 0)
1424 {
1425 sb.append("/>");
1426
1427 if (indent)
1428 {
1429 sb.append("\n");
1430 }
1431 }
1432 else
1433 {
1434 sb.append(">");
1435 if (hasElements && indent)
1436 {
1437 sb.append("\n");
1438 }
1439
1440 int len = children.getLength();
1441 for (int i = 0; i < len; i++)
1442 {
1443 xmlNodeToString(sb, children.item(i), indent, indentString, depth + 1);
1444 }
1445
1446 if (indent)
1447 {
1448 for (int i = 0; i < depth; i++)
1449 {
1450 sb.append(indentString);
1451 }
1452 }
1453
1454 sb.append("</" + e.getNodeName() + ">");
1455
1456 if ((hasElements && indent) || indentSwapped)
1457 {
1458 sb.append("\n");
1459 }
1460 }
1461 */
1462 }
1463
1464 public static void printXMLNode(Node e, int depth, boolean printText)
1465 { //recursive method call using DOM API...
1466
1467 if (e == null)
1468 {
1469 return;
1470 }
1471
1472 for (int i = 0; i < depth; i++)
1473 System.out.print(' ');
1474
1475 if (e.getNodeType() == Node.TEXT_NODE)
1476 {
1477 if (printText)
1478 {
1479 System.out.println(e.getNodeValue());
1480 }
1481 else
1482 {
1483 System.out.println("text");
1484 }
1485 return;
1486 }
1487
1488 System.out.print('<');
1489 System.out.print(e.getNodeName());
1490 NamedNodeMap attrs = e.getAttributes();
1491
1492 if (attrs != null)
1493 {
1494 for (int i = 0; i < attrs.getLength(); i++)
1495 {
1496 Node attr = attrs.item(i);
1497 System.out.print(' ');
1498 System.out.print(attr.getNodeName());
1499 System.out.print("=\"");
1500 System.out.print(attr.getNodeValue());
1501 System.out.print('"');
1502 }
1503 }
1504
1505 NodeList children = e.getChildNodes();
1506
1507 if (children == null || children.getLength() == 0)
1508 System.out.println("/>");
1509 else
1510 {
1511
1512 System.out.println('>');
1513
1514 int len = children.getLength();
1515 for (int i = 0; i < len; i++)
1516 {
1517 printXMLNode(children.item(i), depth + 1, printText);
1518 }
1519
1520 for (int i = 0; i < depth; i++)
1521 System.out.print(' ');
1522
1523 System.out.println("</" + e.getNodeName() + ">");
1524 }
1525 }
1526
1527 public static void elementToLogAsString(Element e, boolean indent)
1528 {
1529 String str = elementToString(e, indent);
1530 System.err.println(str);
1531 logger.error(str);
1532 }
1533
1534 public static String elementToString(Element e, boolean indent)
1535 {
1536 String str = "";
1537 try
1538 {
1539 TransformerFactory tf = TransformerFactory.newInstance();
1540 Transformer trans = tf.newTransformer();
1541 StringWriter sw = new StringWriter();
1542 if (indent)
1543 {
1544 trans.setOutputProperty(OutputKeys.INDENT, "yes");
1545 }
1546 else
1547 {
1548 trans.setOutputProperty(OutputKeys.INDENT, "no");
1549 }
1550 trans.transform(new DOMSource(e), new StreamResult(sw));
1551 str += sw.toString();
1552 }
1553 catch (Exception ex)
1554 {
1555 str += "Exception: couldn't write " + e + " to log";
1556 }
1557 finally
1558 {
1559 return str;
1560 }
1561 }
1562
1563 public static ArrayList<String> getGroupsFromSecurityResponse(Element securityResponse)
1564 {
1565 ArrayList<String> groups = new ArrayList<String>();
1566
1567 Element groupList = (Element) GSXML.getChildByTagName(securityResponse, GSXML.GROUP_ELEM + GSXML.LIST_MODIFIER);
1568 if (groupList == null)
1569 {
1570 return groups;
1571 }
1572
1573 NodeList groupElems = GSXML.getChildrenByTagName(groupList, GSXML.GROUP_ELEM);
1574
1575 for (int i = 0; i < groupElems.getLength(); i++)
1576 {
1577 Element groupElem = (Element) groupElems.item(i);
1578 groups.add(groupElem.getAttribute(GSXML.NAME_ATT));
1579 }
1580
1581 return groups;
1582 }
1583}
Note: See TracBrowser for help on using the repository browser.