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

Last change on this file since 28283 was 28283, checked in by sjm84, 11 years ago

Trying a new method for printing XML

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