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

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

added a couple of convenience methods and changed the name of another method to better reflect what it is doing

  • Property svn:keywords set to Author Date Id Revision
File size: 47.9 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 copyNode(Element to_elem, Node original_element) {
811 to_elem.appendChild(to_elem.getOwnerDocument().importNode(original_element, true));
812
813 }
814
815 public static void copyNamedElement(Element to, Element from, String elem_name) {
816
817 Document to_doc = to.getOwnerDocument();
818 Node child = from.getFirstChild();
819 while (child != null) {
820 if (child.getNodeName().equals(elem_name)) {
821 to.appendChild(to_doc.importNode(child, true));
822 return;
823 }
824 child = child.getNextSibling();
825 }
826 }
827
828 /**
829 * Given a Node representing an Element or Document, will return the
830 * Element/docroot Element. Returns null if the Node was not an element.
831 */
832 public static Element nodeToElement(Node node)
833 {
834 if (node == null)
835 {
836 return null;
837 }
838 short nodeType = node.getNodeType();
839
840 if (nodeType == Node.DOCUMENT_NODE)
841 {
842 Document docNode = (Document) node;
843 return docNode.getDocumentElement();
844 }
845 else if (nodeType == Node.ELEMENT_NODE)
846 {
847 return (Element) node;
848 }
849 else
850 {
851 String message = "Expecting Document or Element node type but got " + node.getNodeName() + "\nReturning null";
852 System.err.println(message);
853 logger.warn(message);
854 return null;
855 }
856 }
857
858
859 /** returns a basic request message */
860 public static Element createBasicRequest(Document owner, String request_type, String to, UserContext userContext)
861 {
862 Element request = owner.createElement(REQUEST_ELEM);
863 request.setAttribute(TO_ATT, to);
864 request.setAttribute(TYPE_ATT, request_type);
865 if (userContext != null) { // should we allow this??
866 request.setAttribute(LANG_ATT, userContext._lang);
867 Element userContextElem = owner.createElement("userContext");
868 request.appendChild(userContextElem);
869 userContextElem.setAttribute(LANG_ATT, userContext._lang);
870 userContextElem.setAttribute(USERNAME_ATT, userContext._username);
871 userContextElem.setAttribute(USER_ID_ATT, userContext._userID);
872
873 if (userContext._groups != null)
874 {
875 String groupString = "";
876 for (int i = 0; i < userContext._groups.length; i++)
877 {
878 groupString += userContext._groups[i];
879 if (i != userContext._groups.length - 1)
880 {
881 groupString += ",";
882 }
883 }
884
885 if (groupString.length() > 0)
886 {
887 userContextElem.setAttribute(GROUPS_ATT, groupString);
888 }
889 }
890 }
891 return request;
892 }
893
894 public static Element createBasicResponse(Document owner, String from)
895 {
896 Element response = owner.createElement(GSXML.RESPONSE_ELEM);
897 response.setAttribute(GSXML.FROM_ATT, from);
898 response.setAttribute(GSXML.TYPE_ATT, GSXML.REQUEST_TYPE_PROCESS);
899 return response;
900 }
901
902 public static Element createMetadataElement(Document owner, String name, String value)
903 {
904 Element metaElem = owner.createElement(GSXML.METADATA_ELEM);
905 metaElem.setAttribute(GSXML.NAME_ATT, name);
906 metaElem.setAttribute(GSXML.VALUE_ATT, value);
907 return metaElem;
908 }
909
910 public static Element createTextElement(Document owner, String elem_name, String text)
911 {
912 Element e = owner.createElement(elem_name);
913 Text t = owner.createTextNode(text);
914 e.appendChild(t);
915 return e;
916
917 }
918
919 public static Element createTextElement(Document owner, String elem_name, String text, String att_name, String att_value)
920 {
921 Element e = owner.createElement(elem_name);
922 e.setAttribute(att_name, att_value);
923 Text t = owner.createTextNode(text);
924 e.appendChild(t);
925 return e;
926
927 }
928
929 public static Element createDisplayTextElement(Document owner, String text_name, String text)
930 {
931 Element e = owner.createElement(DISPLAY_TEXT_ELEM);
932 e.setAttribute(NAME_ATT, text_name);
933 Text t = owner.createTextNode(text);
934 e.appendChild(t);
935 return e;
936
937 }
938
939 public static Element createParameter(Document owner, String name, String value)
940 {
941 Element param = owner.createElement(PARAM_ELEM);
942 param.setAttribute(NAME_ATT, name);
943 param.setAttribute(VALUE_ATT, value);
944 return param;
945 }
946
947 public static void addParameterToList(Element param_list, String name, String value) {
948 Element p = createParameter(param_list.getOwnerDocument(), name, value);
949 param_list.appendChild(p);
950 }
951 public static void addParametersToList(Element param_list, HashMap params)
952 {
953 if (params == null)
954 {
955 return;
956 }
957
958 Set items = params.entrySet();
959 Iterator i = items.iterator();
960 Document owner = param_list.getOwnerDocument();
961 while (i.hasNext())
962 {
963 Map.Entry m = (Map.Entry) i.next();
964 param_list.appendChild(createParameter(owner, (String) m.getKey(), (String) m.getValue()));
965 }
966
967 }
968
969 public static Element createParameterDescription(Document owner, String id, String display_name, String type, String default_value, String[] option_ids, String[] option_names)
970 {
971
972 Element p = owner.createElement(PARAM_ELEM);
973 p.setAttribute(NAME_ATT, id);
974 p.setAttribute(TYPE_ATT, type);
975 p.appendChild(createDisplayTextElement(owner, GSXML.DISPLAY_TEXT_NAME, display_name));
976
977 if (default_value != null)
978 {
979 p.setAttribute(DEFAULT_ATT, default_value);
980 }
981 if (option_ids != null && option_names != null)
982 {
983 for (int i = 0; i < option_ids.length; i++)
984 {
985 Element e = owner.createElement(PARAM_OPTION_ELEM);
986 e.setAttribute(NAME_ATT, option_ids[i]);
987 e.appendChild(createDisplayTextElement(owner, GSXML.DISPLAY_TEXT_NAME, option_names[i]));
988 p.appendChild(e);
989 }
990 }
991 return p;
992 }
993
994 public static Element createParameterDescription2(Document owner, String id, String display_name, String type, String default_value, ArrayList<String> option_ids, ArrayList<String> option_names)
995 {
996
997 Element p = owner.createElement(PARAM_ELEM);
998 p.setAttribute(NAME_ATT, id);
999 p.setAttribute(TYPE_ATT, type);
1000 p.appendChild(createDisplayTextElement(owner, GSXML.DISPLAY_TEXT_NAME, display_name));
1001 if (default_value != null)
1002 {
1003 p.setAttribute(DEFAULT_ATT, default_value);
1004 }
1005 if (option_ids != null && option_names != null)
1006 {
1007 for (int i = 0; i < option_ids.size(); i++)
1008 {
1009 Element e = owner.createElement(PARAM_OPTION_ELEM);
1010 e.setAttribute(NAME_ATT, option_ids.get(i));
1011 e.appendChild(createDisplayTextElement(owner, GSXML.DISPLAY_TEXT_NAME, option_names.get(i)));
1012 p.appendChild(e);
1013 }
1014 }
1015 return p;
1016 }
1017
1018 /** returns the element parent/node_name[@attribute_name='attribute_value'] */
1019 public static Element getNamedElement(Element parent, String node_name, String attribute_name, String attribute_value)
1020 {
1021
1022 NodeList children = parent.getChildNodes();
1023 for (int i = 0; i < children.getLength(); i++)
1024 {
1025 Node child = children.item(i);
1026 if (child.getNodeName().equals(node_name))
1027 {
1028 if (((Element) child).getAttribute(attribute_name).equals(attribute_value))
1029 return (Element) child;
1030 }
1031 }
1032 // not found
1033 return null;
1034 }
1035
1036 public static Element getNamedElementNS(Element parent, String namespace_uri, String node_local_name, String attribute_name, String attribute_value)
1037 {
1038 NodeList children = parent.getChildNodes();
1039 for (int i = 0; i < children.getLength(); i++)
1040 {
1041 Node child = children.item(i);
1042 if (child.getNodeType() == Node.ELEMENT_NODE && child.getNamespaceURI().equals(namespace_uri) && child.getLocalName().equals(node_local_name))
1043 {
1044 if (((Element) child).getAttribute(attribute_name).equals(attribute_value))
1045 return (Element) child;
1046 }
1047 }
1048 // not found
1049 return null;
1050 }
1051
1052 public static NodeList getNamedElementsNS(Element parent, String namespace_uri, String node_local_name, String attribute_name, String attribute_value)
1053 {
1054 MyNodeList result = new MyNodeList();
1055 NodeList children = parent.getChildNodes();
1056 for (int i = 0; i < children.getLength(); i++)
1057 {
1058 Node child = children.item(i);
1059 if (child.getNodeType() == Node.ELEMENT_NODE && child.getNamespaceURI().equals(namespace_uri) && child.getLocalName().equals(node_local_name))
1060 {
1061 if (((Element) child).getAttribute(attribute_name).equals(attribute_value))
1062 result.addNode(child);
1063 }
1064 }
1065 return result;
1066 }
1067
1068 public static NodeList getElementsWithAttributesNS(Element parent, String namespace_uri, String node_local_name, String[] attribute_names, String[] attribute_values)
1069 {
1070 if (attribute_names.length == 0 || attribute_names.length != attribute_values.length)
1071 {
1072 return new MyNodeList();
1073 }
1074
1075 MyNodeList result = new MyNodeList();
1076
1077 NodeList matchingNodes = GSXML.getNamedElementsNS(parent, namespace_uri, node_local_name, attribute_names[0], attribute_values[0]);
1078 for (int i = 0; i < matchingNodes.getLength(); i++)
1079 {
1080 Element current = (Element) matchingNodes.item(i);
1081 boolean nodeMatches = true;
1082 for (int j = 1; j < attribute_names.length; j++)
1083 {
1084 String currentName = attribute_names[j];
1085 String currentValue = attribute_values[j];
1086 if (!current.getAttribute(currentName).equals(currentValue))
1087 {
1088 nodeMatches = false;
1089 break;
1090 }
1091 }
1092
1093 if (nodeMatches)
1094 {
1095 result.addNode(current);
1096 }
1097 }
1098
1099 return result;
1100 }
1101
1102 public static void removeElementsWithAttributesNS(Element parent, String namespace_uri, String node_local_name, String[] attribute_names, String[] attribute_values)
1103 {
1104 NodeList matchingNodes = GSXML.getElementsWithAttributesNS(parent, namespace_uri, node_local_name, attribute_names, attribute_values);
1105 for (int i = 0; i < matchingNodes.getLength(); i++)
1106 {
1107 parent.removeChild(matchingNodes.item(i));
1108 }
1109 }
1110
1111 // In element main, tries to find any previous occurrence of elements with xsl-template-name=templateName,
1112 // and whose named attribute (attributeName) has the same value as the same attribute in node.
1113 // If this is the case, such a previous occurrence is removed from element main, since
1114 // the new node will contain a more specific redefinition of this element.
1115 public static void removeNamedElementNS(Element parent, String namespace_uri, String node_local_name, String attribute_name, String attribute_value)
1116 {
1117 if (attribute_value.equals(""))
1118 {
1119 // it has no identifying attribute, so we can't find any matches
1120 return;
1121 }
1122
1123 Element old_elem = GSXML.getNamedElementNS(parent, namespace_uri, node_local_name, attribute_name, attribute_value);
1124 if (old_elem != null)
1125 {
1126 parent.removeChild(old_elem);
1127 }
1128 }
1129
1130 public static void removeNamedElementsNS(Element parent, String namespace, String node_local_name, String attribute_name, String attribute_value)
1131 {
1132 if (attribute_value.equals(""))
1133 {
1134 // it has no identifying attribute, so we can't find any matches
1135 return;
1136 }
1137
1138 NodeList children = parent.getChildNodes();
1139 for (int i = children.getLength() - 1; i >= 0; i--)
1140 {
1141 Node child = children.item(i);
1142 if (child.getNodeType() == Node.ELEMENT_NODE && child.getNamespaceURI().equals(namespace) && child.getLocalName() != null && child.getLocalName().equals(node_local_name))
1143 {
1144 if (((Element) child).getAttribute(attribute_name).equals(attribute_value))
1145 parent.removeChild(child);
1146 }
1147 }
1148 }
1149
1150 /**
1151 * returns a NodeList of elements:
1152 * ancestor/node_name[@attribute_name='attribute_value']
1153 */
1154 public static NodeList getNamedElements(Element ancestor, String node_name, String attribute_name, String attribute_value)
1155 {
1156 MyNodeList node_list = new MyNodeList();
1157 NodeList children = ancestor.getElementsByTagName(node_name);
1158
1159 if (children != null && children.getLength() > 0)
1160 {
1161
1162 for (int i = 0; i < children.getLength(); i++)
1163 {
1164 Node child = children.item(i);
1165 if (child.getNodeName().equals(node_name))
1166 {
1167 if (((Element) child).getAttribute(attribute_name).equals(attribute_value))
1168 node_list.addNode(child);
1169 }
1170 }
1171 }
1172 return node_list;
1173 }
1174
1175 public static Element getLastElementByTagNameNS(Element main, String namespace, String node_name)
1176 {
1177 NodeList nodes = main.getElementsByTagNameNS(namespace, node_name);
1178 int len = nodes.getLength();
1179 if (len == 0)
1180 {
1181 return null;
1182 }
1183 return (Element) nodes.item(len - 1);
1184 }
1185
1186 public static int SORT_TYPE_STRING = 0;
1187 public static int SORT_TYPE_INT = 1;
1188 public static int SORT_TYPE_FLOAT = 2;
1189
1190 // sort type:
1191 public static Element insertIntoOrderedList(Element parent_node, String node_name, Element start_from_elem, Element new_elem, String sort_att, boolean descending)
1192 {
1193 if (new_elem == null)
1194 return null;
1195 Element cloned_elem = (Element) parent_node.getOwnerDocument().importNode(new_elem, true);
1196 if (start_from_elem == null)
1197 {
1198 parent_node.appendChild(cloned_elem);
1199 return cloned_elem;
1200 }
1201
1202 Node current_node = start_from_elem;
1203 String insert_att = cloned_elem.getAttribute(sort_att);
1204 String list_att = start_from_elem.getAttribute(sort_att);
1205 while ((!descending && list_att.compareTo(insert_att) < 0) || (descending && list_att.compareTo(insert_att) > 0))
1206 {
1207 current_node = current_node.getNextSibling();
1208 if (current_node == null)
1209 break; // end of the list
1210 if (!current_node.getNodeName().equals(node_name))
1211 {
1212 continue; // not a valid node
1213 }
1214 list_att = ((Element) current_node).getAttribute(sort_att);
1215 }
1216
1217 parent_node.insertBefore(cloned_elem, current_node);
1218 return cloned_elem;
1219 }
1220
1221 /**
1222 * Returns the appropriate language element from a display elem, display is
1223 * the containing element, name is the name of the element to look for, lang
1224 * is the preferred language, lang_default is the fall back lang if neither
1225 * lang is found, will return the first one it finds
1226 */
1227 public static String getDisplayText(Element display, String name, String lang, String lang_default)
1228 {
1229
1230 String def = null;
1231 String first = null;
1232 NodeList elems = display.getElementsByTagName(DISPLAY_TEXT_ELEM);
1233 if (elems.getLength() == 0)
1234 return "";
1235 for (int i = 0; i < elems.getLength(); i++)
1236 {
1237 Element e = (Element) elems.item(i);
1238 String n = e.getAttribute(NAME_ATT);
1239 if (name.equals(n))
1240 {
1241 String l = e.getAttribute(LANG_ATT);
1242 if (lang.equals(l))
1243 {
1244 return getNodeText(e);
1245 }
1246 else if (lang_default.equals(l))
1247 {
1248 def = getNodeText(e);
1249 }
1250 else if (first == null)
1251 {
1252 first = getNodeText(e);
1253 }
1254 }
1255 else
1256 {
1257 continue;
1258 }
1259 }
1260
1261 if (def != null)
1262 {
1263 return def;
1264 }
1265 if (first != null)
1266 {
1267 return first;
1268 }
1269 return "";
1270 }
1271
1272 // replaces < > " ' & in the original with their entities
1273 public static String xmlSafe(String original)
1274 {
1275
1276 StringBuffer filtered = new StringBuffer(original.length());
1277 char c;
1278 for (int i = 0; i < original.length(); i++)
1279 {
1280 c = original.charAt(i);
1281 if (c == '>')
1282 {
1283 filtered.append("&gt;");
1284 }
1285 else if (c == '<')
1286 {
1287 filtered.append("&lt;");
1288 }
1289 else if (c == '"')
1290 {
1291 filtered.append("&quot;");
1292 }
1293 else if (c == '&')
1294 {
1295 filtered.append("&amp;");
1296 }
1297 else if (c == '\'')
1298 {
1299 filtered.append("&apos;");
1300 }
1301 else
1302 {
1303 filtered.append(c);
1304 }
1305 }
1306 return filtered.toString();
1307 }
1308
1309 // replaces < > " ' & entities with their originals
1310 public static String unXmlSafe(String original)
1311 {
1312
1313 StringBuffer filtered = new StringBuffer(original.length());
1314 char c;
1315 for (int i = 0; i < original.length(); i++)
1316 {
1317 c = original.charAt(i);
1318 if (c == '&')
1319 {
1320 int pos = original.indexOf(";", i);
1321 String entity = original.substring(i + 1, pos);
1322 if (entity.equals("gt"))
1323 {
1324 filtered.append(">");
1325 }
1326 else if (entity.equals("lt"))
1327 {
1328 filtered.append("<");
1329 }
1330 else if (entity.equals("apos"))
1331 {
1332 filtered.append("'");
1333 }
1334 else if (entity.equals("amp"))
1335 {
1336 filtered.append("&");
1337 }
1338 else if (entity.equals("quot"))
1339 {
1340 filtered.append("\"");
1341 }
1342 else
1343 {
1344 filtered.append("&" + entity + ";");
1345 }
1346 i = pos;
1347 }
1348 else
1349 {
1350 filtered.append(c);
1351 }
1352 }
1353 return filtered.toString();
1354 }
1355
1356 public static void printXMLNode(Node e, boolean printText)
1357 {
1358 printXMLNode(e, 0, printText);
1359 }
1360
1361 public static String xmlNodeToString(Node e)
1362 {
1363 StringBuffer sb = new StringBuffer("");
1364 xmlNodeToString(sb, e, true, "\t", 0);
1365 return sb.toString();
1366 }
1367
1368 public static void xmlNodeToString(StringBuffer sb, Node e, boolean indent, String indentString, int depth)
1369 {
1370 if (e.getNodeType() == Node.TEXT_NODE)
1371 {
1372 if (e.getNodeValue() != "")
1373 {
1374 String text = e.getNodeValue();
1375 if (text != null)
1376 {
1377 text = text.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("^[\\n\\r\\t\\s]*", "").replaceAll("[\\n\\r\\t\\s]*$", "");
1378 sb.append(text);
1379 }
1380 }
1381 return;
1382 }
1383
1384 if (e.getNodeType() == Node.COMMENT_NODE)
1385 {
1386 if (e.getNodeValue() != "")
1387 {
1388 sb.append("<!--" + e.getNodeValue() + "-->");
1389 }
1390 return;
1391 }
1392
1393 if (indent)
1394 {
1395 for (int i = 0; i < depth; i++)
1396 {
1397 sb.append(indentString);
1398 }
1399 }
1400
1401 sb.append('<');
1402 sb.append(e.getNodeName());
1403 NamedNodeMap attrs = e.getAttributes();
1404 if (attrs != null)
1405 {
1406 for (int i = 0; i < attrs.getLength(); i++)
1407 {
1408 Node attr = attrs.item(i);
1409 sb.append(' ');
1410 sb.append(attr.getNodeName());
1411 sb.append("=\"");
1412 sb.append(attr.getNodeValue().replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;"));
1413 sb.append('"');
1414 }
1415 }
1416
1417 if (e.hasChildNodes())
1418 {
1419 boolean hasElements = false;
1420 boolean indentSwapped = false;
1421
1422 Node child = e.getFirstChild();
1423 do
1424 {
1425 if (child.getNodeType() == Node.ELEMENT_NODE)
1426 {
1427 hasElements = true;
1428 }
1429 if (child.getNodeType() == Node.TEXT_NODE && indent)
1430 {
1431 if (child.getNodeValue() != null && child.getNodeValue().trim().length() > 0)
1432 {
1433 indentSwapped = true;
1434 indent = false;
1435 }
1436 }
1437 } while ((child = child.getNextSibling()) != null);
1438
1439 sb.append(">");
1440 if (hasElements && indent)
1441 {
1442 sb.append("\n");
1443 }
1444
1445 child = e.getFirstChild();
1446 do
1447 {
1448 xmlNodeToString(sb, child, indent, indentString, depth + 1);
1449 } while ((child = child.getNextSibling()) != null);
1450
1451 if (indent)
1452 {
1453 for (int i = 0; i < depth; i++)
1454 {
1455 sb.append(indentString);
1456 }
1457 }
1458
1459 sb.append("</" + e.getNodeName() + ">");
1460
1461 if ((hasElements && indent) || indentSwapped)
1462 {
1463 sb.append("\n");
1464 }
1465 }
1466 else
1467 {
1468 sb.append("/>");
1469
1470 if (indent)
1471 {
1472 sb.append("\n");
1473 }
1474 }
1475
1476 /*
1477 boolean hasElements = false;
1478 boolean indentSwapped = false;
1479 for (int i = 0; i < children.getLength(); i++)
1480 {
1481 if (children.item(i).getNodeType() == Node.ELEMENT_NODE)
1482 {
1483 hasElements = true;
1484 }
1485 if (children.item(i).getNodeType() == Node.TEXT_NODE && indent)
1486 {
1487 if (children.item(i).getNodeValue() != null && children.item(i).getNodeValue().trim().length() > 0)
1488 {
1489 indentSwapped = true;
1490 indent = false;
1491 }
1492 }
1493 }
1494
1495 if (children == null || children.getLength() == 0)
1496 {
1497 sb.append("/>");
1498
1499 if (indent)
1500 {
1501 sb.append("\n");
1502 }
1503 }
1504 else
1505 {
1506 sb.append(">");
1507 if (hasElements && indent)
1508 {
1509 sb.append("\n");
1510 }
1511
1512 int len = children.getLength();
1513 for (int i = 0; i < len; i++)
1514 {
1515 xmlNodeToString(sb, children.item(i), indent, indentString, depth + 1);
1516 }
1517
1518 if (indent)
1519 {
1520 for (int i = 0; i < depth; i++)
1521 {
1522 sb.append(indentString);
1523 }
1524 }
1525
1526 sb.append("</" + e.getNodeName() + ">");
1527
1528 if ((hasElements && indent) || indentSwapped)
1529 {
1530 sb.append("\n");
1531 }
1532 }
1533 */
1534 }
1535
1536 public static void printXMLNode(Node e, int depth, boolean printText)
1537 { //recursive method call using DOM API...
1538
1539 if (e == null)
1540 {
1541 return;
1542 }
1543
1544 for (int i = 0; i < depth; i++)
1545 System.out.print(' ');
1546
1547 if (e.getNodeType() == Node.TEXT_NODE)
1548 {
1549 if (printText)
1550 {
1551 System.out.println(e.getNodeValue());
1552 }
1553 else
1554 {
1555 System.out.println("text");
1556 }
1557 return;
1558 }
1559
1560 System.out.print('<');
1561 System.out.print(e.getNodeName());
1562 NamedNodeMap attrs = e.getAttributes();
1563
1564 if (attrs != null)
1565 {
1566 for (int i = 0; i < attrs.getLength(); i++)
1567 {
1568 Node attr = attrs.item(i);
1569 System.out.print(' ');
1570 System.out.print(attr.getNodeName());
1571 System.out.print("=\"");
1572 System.out.print(attr.getNodeValue());
1573 System.out.print('"');
1574 }
1575 }
1576
1577 NodeList children = e.getChildNodes();
1578
1579 if (children == null || children.getLength() == 0)
1580 System.out.println("/>");
1581 else
1582 {
1583
1584 System.out.println('>');
1585
1586 int len = children.getLength();
1587 for (int i = 0; i < len; i++)
1588 {
1589 printXMLNode(children.item(i), depth + 1, printText);
1590 }
1591
1592 for (int i = 0; i < depth; i++)
1593 System.out.print(' ');
1594
1595 System.out.println("</" + e.getNodeName() + ">");
1596 }
1597 }
1598
1599 public static void elementToLogAsString(Element e, boolean indent)
1600 {
1601 String str = elementToString(e, indent);
1602 System.err.println(str);
1603 logger.error(str);
1604 }
1605
1606 public static String elementToString(Element e, boolean indent)
1607 {
1608 String str = "";
1609 try
1610 {
1611 TransformerFactory tf = TransformerFactory.newInstance();
1612 Transformer trans = tf.newTransformer();
1613 StringWriter sw = new StringWriter();
1614 if (indent)
1615 {
1616 trans.setOutputProperty(OutputKeys.INDENT, "yes");
1617 }
1618 else
1619 {
1620 trans.setOutputProperty(OutputKeys.INDENT, "no");
1621 }
1622 trans.transform(new DOMSource(e), new StreamResult(sw));
1623 str += sw.toString();
1624 }
1625 catch (Exception ex)
1626 {
1627 str += "Exception: couldn't write " + e + " to log";
1628 }
1629 finally
1630 {
1631 return str;
1632 }
1633 }
1634
1635 public static ArrayList<String> getGroupsFromSecurityResponse(Element securityResponse)
1636 {
1637 ArrayList<String> groups = new ArrayList<String>();
1638
1639 Element groupList = (Element) GSXML.getChildByTagName(securityResponse, GSXML.GROUP_ELEM + GSXML.LIST_MODIFIER);
1640 if (groupList == null)
1641 {
1642 return groups;
1643 }
1644
1645 NodeList groupElems = GSXML.getChildrenByTagName(groupList, GSXML.GROUP_ELEM);
1646
1647 for (int i = 0; i < groupElems.getLength(); i++)
1648 {
1649 Element groupElem = (Element) groupElems.item(i);
1650 groups.add(groupElem.getAttribute(GSXML.NAME_ATT));
1651 }
1652
1653 return groups;
1654 }
1655
1656}
Note: See TracBrowser for help on using the repository browser.