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

Last change on this file since 28965 was 28963, checked in by kjdon, 10 years ago

moved a method here from XMLConverter. Removed Document param from methods that take an Element - now we get the Element's owner document and use that to create nodes. So now no chance that you can pass in the wrong Document for the Element thatyou are adding nodes to

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