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

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

added disabled attribute - used in security element

  • Property svn:keywords set to Author Date Id Revision
File size: 48.0 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 DISABLED_ATT = "disabled";
280 public static final String SCOPE_ATT = "scope";
281 public static final String DEFAULT_ACCESS_ATT = "default_access";
282 public static final String EXCEPTION_ELEM = "exception";
283 public static final String DOCUMENT_SET_ELEM = "documentSet";
284 public static final String GROUP_ELEM = "group";
285 public static final String MATCH_ELEM = "match";
286 public static final String FIELD_ATT = "field";
287 public static final String USER_INFORMATION_ELEM = "userInformation";
288 public static final String USERNAME_ATT = "username";
289 public static final String GROUPS_ATT = "groups";
290 public static final String BASE_URL = "baseURL";
291
292 // only for authenticated-ping
293 public static final String PASSWORD_ATT = "password";
294
295 //for classifiers
296 public static final String CHILD_TYPE_ATT = "childType";
297 public static final String CLASSIFIER_STYLE_ATT = "classifierStyle";
298 public static final String HLIST = "HList";
299 public static final String VLIST = "VList";
300
301 //for namespaces
302 public static final String XSL_NAMESPACE = "http://www.w3.org/1999/XSL/Transform";
303 public static final String GSF_NAMESPACE = "http://www.greenstone.org/greenstone3/schema/ConfigFormat";
304 public static final String JAVA_NAMESPACE = "http://xml.apache.org/xslt/java";
305 public static final String UTIL_NAMESPACE = "xalan://org.greenstone.gsdl3.util.XSLTUtil";
306
307 /**
308 * takes a list of elements, and returns an array of strings of the values
309 * of attribute att_name
310 */
311 public static String[] getAttributeValuesFromList(Element list, String att_name)
312 {
313
314 NodeList children = list.getChildNodes();
315
316 int num_nodes = children.getLength();
317 String[] ids = new String[num_nodes];
318 for (int i = 0; i < num_nodes; i++)
319 {
320 Element e = (Element) children.item(i);
321 String id = e.getAttribute(att_name);
322 ids[i] = id;
323 }
324
325 return ids;
326 }
327
328 public static HashMap<String, String> getParamMap(NodeList params) {
329 HashMap<String, String> map = new HashMap<String, String>();
330 for(int i=0; i<params.getLength(); i++) {
331 Element param = (Element)params.item(i);
332 String param_name = param.getAttribute(NAME_ATT);
333 String param_value = param.getAttribute(VALUE_ATT);
334 map.put(param_name, param_value);
335 }
336 return map;
337 }
338
339 public static HashMap<String, Serializable> extractParams(Element xml, boolean deep)
340 {
341 return extractParams(xml, deep, null);
342 }
343
344 /**
345 * takes a paramList element, and gets a HashMap of name-value pairs if
346 * deep=true, extracts embedded params, otherwise just top level params
347 */
348 public static HashMap<String, Serializable> extractParams(Element xml, boolean deep, String toFind)
349 {
350 if (xml == null)
351 {
352 return null;
353 }
354
355 if (!xml.getNodeName().equals(PARAM_ELEM + LIST_MODIFIER))
356 {
357 logger.error("paramList element should have been passed to extractParams, instead it was " + xml.getNodeName());
358 return null;
359 }
360
361 NodeList params = null;
362 if (deep)
363 { // get all the nested ones
364 params = xml.getElementsByTagName(PARAM_ELEM);
365 }
366 else
367 { // just get the top level ones
368 params = xml.getChildNodes();
369 }
370 HashMap<String, Serializable> param_map = new HashMap<String, Serializable>();
371 for (int i = 0; i < params.getLength(); i++)
372 {
373 if (params.item(i).getNodeName().equals(PARAM_ELEM))
374 {
375 Element param = (Element) params.item(i);
376 String name = param.getAttribute(NAME_ATT);
377 String value = getValue(param); //att or content
378
379 // For only one parameter
380 if (toFind != null && name.equals(toFind))
381 {
382 param_map.put(name, value);
383 return param_map;
384 }
385 else if (toFind != null)
386 continue;
387
388 int pos = name.indexOf('.');
389 if (pos == -1)
390 { // a base param
391 param_map.put(name, value);
392 }
393 else
394 { // a namespaced param
395
396 String namespace = name.substring(0, pos);
397 name = name.substring(pos + 1);
398 HashMap<String, String> map = (HashMap<String, String>) param_map.get(namespace);
399 if (map == null)
400 {
401 map = new HashMap<String, String>();
402 param_map.put(namespace, map);
403 }
404 map.put(name, value);
405 }
406 }
407 }
408 return param_map;
409 }
410
411 /** gets the value att or the text content */
412 public static String getValue(Element e)
413 {
414 String val = e.getAttribute(VALUE_ATT);
415 if (val == null || val.equals(""))
416 {
417 // have to get it out of the text
418 val = getNodeText(e);
419
420 }
421 else
422 {
423 // unescape the xml stuff
424 val = unXmlSafe(val);
425 }
426 return val;
427 }
428
429 /** extracts the text out of a node */
430 public static Node getNodeTextNode(Element param)
431 {
432 param.normalize();
433 Node n = param.getFirstChild();
434 while (n != null && n.getNodeType() != Node.TEXT_NODE)
435 {
436 n = n.getNextSibling();
437 }
438 return n;
439 }
440
441 /** extracts the text out of a node */
442 public static String getNodeText(Element param)
443 {
444 Node text_node = getNodeTextNode(param);
445 if (text_node == null)
446 {
447 return "";
448 }
449 return text_node.getNodeValue();
450 }
451
452 public static void setNodeText(Element elem, String text)
453 {
454 Node old_text_node = getNodeTextNode(elem);
455 if (old_text_node != null)
456 {
457 elem.removeChild(old_text_node);
458 }
459 Text t = elem.getOwnerDocument().createTextNode(text);
460 elem.appendChild(t);
461 }
462
463 /** add text to a document/subsection element */
464 public static boolean addDocText(Element doc, String text)
465 {
466
467 Element content = doc.getOwnerDocument().createElement(NODE_CONTENT_ELEM);
468 Text t = doc.getOwnerDocument().createTextNode(text);
469 content.appendChild(t);
470 doc.appendChild(content);
471 return true;
472 }
473
474 /** add an error message, unknown error type */
475 public static boolean addError(Element doc, String text)
476 {
477 return addError(doc, text, ERROR_TYPE_OTHER);
478 }
479
480 /** add an error message */
481 public static boolean addError(Element doc, String text, String error_type)
482 {
483
484 Element content = doc.getOwnerDocument().createElement(ERROR_ELEM);
485 content.setAttribute(ERROR_TYPE_ATT, error_type);
486 Text t = doc.getOwnerDocument().createTextNode(text);
487 content.appendChild(t);
488 doc.appendChild(content);
489 return true;
490 }
491
492 /** add an error message */
493 public static boolean addError(Element doc, Throwable error)
494 {
495 return addError(doc, error, ERROR_TYPE_OTHER);
496 }
497
498 /** add an error message */
499 public static boolean addError(Element doc, Throwable error, String error_type)
500 {
501 error.printStackTrace();
502 return addError(doc, error.toString(), error_type);
503 }
504
505 public static Element createMetadataParamList(Document owner, Vector meta_values)
506 {
507
508 Element meta_param_list = owner.createElement(PARAM_ELEM + LIST_MODIFIER);
509 Iterator i = meta_values.iterator();
510 while (i.hasNext())
511 {
512 String next = (String) i.next();
513 Element meta_param = owner.createElement(PARAM_ELEM);
514 meta_param_list.appendChild(meta_param);
515 meta_param.setAttribute(NAME_ATT, "metadata");
516 meta_param.setAttribute(VALUE_ATT, next);
517 }
518 return meta_param_list;
519 }
520
521 /** adds a metadata elem to a list */
522 public static boolean addMetadata(Element list, String meta_name, String meta_value)
523 {
524 if (meta_value == null || meta_value.equals(""))
525 {
526 return false;
527 }
528 Document owner = list.getOwnerDocument();
529 Element data = owner.createElement(METADATA_ELEM);
530 data.setAttribute(NAME_ATT, meta_name);
531 Text t = owner.createTextNode(meta_value);
532 data.appendChild(t);
533 list.appendChild(data);
534 return true;
535
536 }
537
538 /**
539 * copies the metadata out of the metadataList of 'from' into the
540 * metadataList of 'to'
541 */
542 public static boolean mergeMetadataLists(Node to, Node from)
543 {
544 Node from_meta = getChildByTagName(from, METADATA_ELEM + LIST_MODIFIER);
545 if (from_meta == null)
546 { // nothing to copy
547 return true;
548 }
549 return mergeMetadataFromList(to, from_meta);
550 }
551
552 /**
553 * copies the metadata out of the meta_list metadataList into the
554 * metadataList of 'to'
555 */
556 public static boolean mergeMetadataFromList(Node to, Node meta_list)
557 {
558 if (meta_list == null)
559 return false;
560 Node to_meta = getChildByTagName(to, METADATA_ELEM + LIST_MODIFIER);
561 Document to_owner = to.getOwnerDocument();
562 if (to_meta == null)
563 {
564 to.appendChild(to_owner.importNode(meta_list, true));
565 return true;
566 }
567 // copy individual metadata elements
568 NodeList meta_items = ((Element) meta_list).getElementsByTagName(METADATA_ELEM);
569 for (int i = 0; i < meta_items.getLength(); i++)
570 {
571 to_meta.appendChild(to_owner.importNode(meta_items.item(i), true));
572 }
573 return true;
574 }
575
576 /** copies all the children from from to to */
577 public static boolean mergeElements(Element to, Element from)
578 {
579
580 Document owner = to.getOwnerDocument();
581 Node child = from.getFirstChild();
582 while (child != null)
583 {
584 to.appendChild(owner.importNode(child, true));
585 child = child.getNextSibling();
586 }
587 return true;
588 }
589
590 /** returns the (first) element child of the node n */
591 public static Element getFirstElementChild(Node n)
592 {
593
594 Node child = n.getFirstChild();
595 while (child != null)
596 {
597 if (child.getNodeType() == Node.ELEMENT_NODE)
598 {
599 return (Element) child;
600 }
601 child = child.getNextSibling();
602 }
603 return null; //no element child found
604 }
605
606 /** returns the (first) child element with the given name */
607 public static Node getChildByTagName(Node n, String name)
608 {
609 if (n != null)
610 { // this line is an attempted solution to the NullPointerException mentioned
611 // in trac bug ticket #225. If n is null can't do n.getFirstChild() below. As per bug #225:
612 // GSXML.getNodeByPath() is called by GS2BrowseAction, which then calls this method.
613 // If n is null, null will be returned which GS2BrowseAction already checks for. It's here
614 // that the NullPointerException was thrown.
615
616 Node child = n.getFirstChild();
617 while (child != null)
618 {
619 if (child.getNodeName().equals(name))
620 {
621 return child;
622 }
623 child = child.getNextSibling();
624 }
625 }
626 return null; //not found
627 }
628
629 /**
630 * returns the (nth) child element with the given name index numbers start
631 * at 0
632 */
633 public static Node getChildByTagNameIndexed(Node n, String name, int index)
634 {
635 if (index == -1)
636 {
637 return getChildByTagName(n, name);
638 }
639 int count = 0;
640 Node child = n.getFirstChild();
641 while (child != null)
642 {
643 if (child.getNodeName().equals(name))
644 {
645 if (count == index)
646 {
647 return child;
648 }
649 else
650 {
651 count++;
652 }
653 }
654 child = child.getNextSibling();
655 }
656 return null; //not found
657 }
658
659 /**
660 * takes an xpath type expression of the form name/name/... and returns the
661 * first node that matches, or null if not found
662 */
663 public static Node getNodeByPath(Node n, String path)
664 {
665
666 String link = GSPath.getFirstLink(path);
667 path = GSPath.removeFirstLink(path);
668 while (!link.equals(""))
669 {
670 n = getChildByTagName(n, link);
671 if (n == null)
672 {
673 return null;
674 }
675 link = GSPath.getFirstLink(path);
676 path = GSPath.removeFirstLink(path);
677 }
678 return n;
679 }
680
681 /**
682 * takes an xpath type expression of the form name/name/... and returns the
683 * first node that matches, or null if not found can include [i] indices.
684 * index numbers start at 0
685 */
686 public static Node getNodeByPathIndexed(Node n, String path)
687 {
688
689 String link = GSPath.getFirstLink(path);
690 int index = GSPath.getIndex(link);
691 if (index != -1)
692 {
693 link = GSPath.removeIndex(link);
694 }
695 path = GSPath.removeFirstLink(path);
696 while (!link.equals(""))
697 {
698 n = getChildByTagNameIndexed(n, link, index);
699 if (n == null)
700 {
701 return null;
702 }
703 link = GSPath.getFirstLink(path);
704 index = GSPath.getIndex(link);
705 if (index != -1)
706 {
707 link = GSPath.removeIndex(link);
708 }
709 path = GSPath.removeFirstLink(path);
710 }
711 return n;
712 }
713
714 public static HashMap<String, Node> getChildrenMap(Node n)
715 {
716
717 HashMap<String, Node> map = new HashMap<String, Node>();
718 Node child = n.getFirstChild();
719 while (child != null)
720 {
721 String name = child.getNodeName();
722 map.put(name, child);
723 child = child.getNextSibling();
724 }
725 return map;
726 }
727
728 public static NodeList getChildrenByTagName(Node n, String name)
729 {
730 MyNodeList node_list = new MyNodeList();
731 Node child = n.getFirstChild();
732 while (child != null)
733 {
734 if (child.getNodeName().equals(name))
735 {
736 node_list.addNode(child);
737 }
738 child = child.getNextSibling();
739 }
740 return node_list;
741 }
742
743 public static NodeList getChildrenByTagNameNS(Node n, String namespace, String local_name)
744 {
745 MyNodeList node_list = new MyNodeList();
746 Node child = n.getFirstChild();
747 while (child != null)
748 {
749 if (child.getNodeType() == Node.ELEMENT_NODE && child.getNamespaceURI() != null && child.getNamespaceURI().equals(namespace) && child.getLocalName() != null && child.getLocalName().equals(local_name))
750 {
751 node_list.addNode(child);
752 }
753 child = child.getNextSibling();
754 }
755 return node_list;
756 }
757
758 /** Duplicates an element, but gives it a new name */
759 public static Element duplicateWithNewName(Document owner, Element element, String element_name, boolean with_attributes)
760 {
761 return duplicateWithNewNameNS(owner, element, element_name, null, with_attributes);
762 }
763
764 /** Duplicates an element, but gives it a new name */
765 public static Element duplicateWithNewNameNS(Document owner, Element element, String element_name, String namespace_uri, boolean with_attributes)
766 {
767 Element duplicate;
768 if (namespace_uri == null)
769 {
770 duplicate = owner.createElement(element_name);
771 }
772 else
773 {
774 duplicate = owner.createElementNS(namespace_uri, element_name);
775 }
776
777 // Copy element attributes
778 if (with_attributes)
779 {
780 NamedNodeMap attributes = element.getAttributes();
781 for (int i = 0; i < attributes.getLength(); i++)
782 {
783 Node attribute = attributes.item(i);
784 duplicate.setAttribute(attribute.getNodeName(), attribute.getNodeValue());
785 }
786 }
787
788 // Copy element children
789 NodeList children = element.getChildNodes();
790 for (int i = 0; i < children.getLength(); i++)
791 {
792 Node child = children.item(i);
793 duplicate.appendChild(owner.importNode(child, true));
794 }
795
796 return duplicate;
797 }
798
799 public static void copyAllChildren(Element to, Element from)
800 {
801
802 Document to_doc = to.getOwnerDocument();
803 Node child = from.getFirstChild();
804 while (child != null)
805 {
806 to.appendChild(to_doc.importNode(child, true));
807 child = child.getNextSibling();
808 }
809 }
810
811 public static void copyNode(Element to_elem, Node original_element) {
812 to_elem.appendChild(to_elem.getOwnerDocument().importNode(original_element, true));
813
814 }
815
816 public static void copyNamedElement(Element to, Element from, String elem_name) {
817
818 Document to_doc = to.getOwnerDocument();
819 Node child = from.getFirstChild();
820 while (child != null) {
821 if (child.getNodeName().equals(elem_name)) {
822 to.appendChild(to_doc.importNode(child, true));
823 return;
824 }
825 child = child.getNextSibling();
826 }
827 }
828
829 /**
830 * Given a Node representing an Element or Document, will return the
831 * Element/docroot Element. Returns null if the Node was not an element.
832 */
833 public static Element nodeToElement(Node node)
834 {
835 if (node == null)
836 {
837 return null;
838 }
839 short nodeType = node.getNodeType();
840
841 if (nodeType == Node.DOCUMENT_NODE)
842 {
843 Document docNode = (Document) node;
844 return docNode.getDocumentElement();
845 }
846 else if (nodeType == Node.ELEMENT_NODE)
847 {
848 return (Element) node;
849 }
850 else
851 {
852 String message = "Expecting Document or Element node type but got " + node.getNodeName() + "\nReturning null";
853 System.err.println(message);
854 logger.warn(message);
855 return null;
856 }
857 }
858
859
860 /** returns a basic request message */
861 public static Element createBasicRequest(Document owner, String request_type, String to, UserContext userContext)
862 {
863 Element request = owner.createElement(REQUEST_ELEM);
864 request.setAttribute(TO_ATT, to);
865 request.setAttribute(TYPE_ATT, request_type);
866 if (userContext != null) { // should we allow this??
867 request.setAttribute(LANG_ATT, userContext._lang);
868 Element userContextElem = owner.createElement("userContext");
869 request.appendChild(userContextElem);
870 userContextElem.setAttribute(LANG_ATT, userContext._lang);
871 userContextElem.setAttribute(USERNAME_ATT, userContext._username);
872 userContextElem.setAttribute(USER_ID_ATT, userContext._userID);
873
874 if (userContext._groups != null)
875 {
876 String groupString = "";
877 for (int i = 0; i < userContext._groups.length; i++)
878 {
879 groupString += userContext._groups[i];
880 if (i != userContext._groups.length - 1)
881 {
882 groupString += ",";
883 }
884 }
885
886 if (groupString.length() > 0)
887 {
888 userContextElem.setAttribute(GROUPS_ATT, groupString);
889 }
890 }
891 }
892 return request;
893 }
894
895 public static Element createBasicResponse(Document owner, String from)
896 {
897 Element response = owner.createElement(GSXML.RESPONSE_ELEM);
898 response.setAttribute(GSXML.FROM_ATT, from);
899 response.setAttribute(GSXML.TYPE_ATT, GSXML.REQUEST_TYPE_PROCESS);
900 return response;
901 }
902
903 public static Element createMetadataElement(Document owner, String name, String value)
904 {
905 Element metaElem = owner.createElement(GSXML.METADATA_ELEM);
906 metaElem.setAttribute(GSXML.NAME_ATT, name);
907 metaElem.setAttribute(GSXML.VALUE_ATT, value);
908 return metaElem;
909 }
910
911 public static Element createTextElement(Document owner, String elem_name, String text)
912 {
913 Element e = owner.createElement(elem_name);
914 Text t = owner.createTextNode(text);
915 e.appendChild(t);
916 return e;
917
918 }
919
920 public static Element createTextElement(Document owner, String elem_name, String text, String att_name, String att_value)
921 {
922 Element e = owner.createElement(elem_name);
923 e.setAttribute(att_name, att_value);
924 Text t = owner.createTextNode(text);
925 e.appendChild(t);
926 return e;
927
928 }
929
930 public static Element createDisplayTextElement(Document owner, String text_name, String text)
931 {
932 Element e = owner.createElement(DISPLAY_TEXT_ELEM);
933 e.setAttribute(NAME_ATT, text_name);
934 Text t = owner.createTextNode(text);
935 e.appendChild(t);
936 return e;
937
938 }
939
940 public static Element createParameter(Document owner, String name, String value)
941 {
942 Element param = owner.createElement(PARAM_ELEM);
943 param.setAttribute(NAME_ATT, name);
944 param.setAttribute(VALUE_ATT, value);
945 return param;
946 }
947
948 public static void addParameterToList(Element param_list, String name, String value) {
949 Element p = createParameter(param_list.getOwnerDocument(), name, value);
950 param_list.appendChild(p);
951 }
952 public static void addParametersToList(Element param_list, HashMap params)
953 {
954 if (params == null)
955 {
956 return;
957 }
958
959 Set items = params.entrySet();
960 Iterator i = items.iterator();
961 Document owner = param_list.getOwnerDocument();
962 while (i.hasNext())
963 {
964 Map.Entry m = (Map.Entry) i.next();
965 param_list.appendChild(createParameter(owner, (String) m.getKey(), (String) m.getValue()));
966 }
967
968 }
969
970 public static Element createParameterDescription(Document owner, String id, String display_name, String type, String default_value, String[] option_ids, String[] option_names)
971 {
972
973 Element p = owner.createElement(PARAM_ELEM);
974 p.setAttribute(NAME_ATT, id);
975 p.setAttribute(TYPE_ATT, type);
976 p.appendChild(createDisplayTextElement(owner, GSXML.DISPLAY_TEXT_NAME, display_name));
977
978 if (default_value != null)
979 {
980 p.setAttribute(DEFAULT_ATT, default_value);
981 }
982 if (option_ids != null && option_names != null)
983 {
984 for (int i = 0; i < option_ids.length; i++)
985 {
986 Element e = owner.createElement(PARAM_OPTION_ELEM);
987 e.setAttribute(NAME_ATT, option_ids[i]);
988 e.appendChild(createDisplayTextElement(owner, GSXML.DISPLAY_TEXT_NAME, option_names[i]));
989 p.appendChild(e);
990 }
991 }
992 return p;
993 }
994
995 public static Element createParameterDescription2(Document owner, String id, String display_name, String type, String default_value, ArrayList<String> option_ids, ArrayList<String> option_names)
996 {
997
998 Element p = owner.createElement(PARAM_ELEM);
999 p.setAttribute(NAME_ATT, id);
1000 p.setAttribute(TYPE_ATT, type);
1001 p.appendChild(createDisplayTextElement(owner, GSXML.DISPLAY_TEXT_NAME, display_name));
1002 if (default_value != null)
1003 {
1004 p.setAttribute(DEFAULT_ATT, default_value);
1005 }
1006 if (option_ids != null && option_names != null)
1007 {
1008 for (int i = 0; i < option_ids.size(); i++)
1009 {
1010 Element e = owner.createElement(PARAM_OPTION_ELEM);
1011 e.setAttribute(NAME_ATT, option_ids.get(i));
1012 e.appendChild(createDisplayTextElement(owner, GSXML.DISPLAY_TEXT_NAME, option_names.get(i)));
1013 p.appendChild(e);
1014 }
1015 }
1016 return p;
1017 }
1018
1019 /** returns the element parent/node_name[@attribute_name='attribute_value'] */
1020 public static Element getNamedElement(Element parent, String node_name, String attribute_name, String attribute_value)
1021 {
1022
1023 NodeList children = parent.getChildNodes();
1024 for (int i = 0; i < children.getLength(); i++)
1025 {
1026 Node child = children.item(i);
1027 if (child.getNodeName().equals(node_name))
1028 {
1029 if (((Element) child).getAttribute(attribute_name).equals(attribute_value))
1030 return (Element) child;
1031 }
1032 }
1033 // not found
1034 return null;
1035 }
1036
1037 public static Element getNamedElementNS(Element parent, String namespace_uri, String node_local_name, String attribute_name, String attribute_value)
1038 {
1039 NodeList children = parent.getChildNodes();
1040 for (int i = 0; i < children.getLength(); i++)
1041 {
1042 Node child = children.item(i);
1043 if (child.getNodeType() == Node.ELEMENT_NODE && child.getNamespaceURI().equals(namespace_uri) && child.getLocalName().equals(node_local_name))
1044 {
1045 if (((Element) child).getAttribute(attribute_name).equals(attribute_value))
1046 return (Element) child;
1047 }
1048 }
1049 // not found
1050 return null;
1051 }
1052
1053 public static NodeList getNamedElementsNS(Element parent, String namespace_uri, String node_local_name, String attribute_name, String attribute_value)
1054 {
1055 MyNodeList result = new MyNodeList();
1056 NodeList children = parent.getChildNodes();
1057 for (int i = 0; i < children.getLength(); i++)
1058 {
1059 Node child = children.item(i);
1060 if (child.getNodeType() == Node.ELEMENT_NODE && child.getNamespaceURI().equals(namespace_uri) && child.getLocalName().equals(node_local_name))
1061 {
1062 if (((Element) child).getAttribute(attribute_name).equals(attribute_value))
1063 result.addNode(child);
1064 }
1065 }
1066 return result;
1067 }
1068
1069 public static NodeList getElementsWithAttributesNS(Element parent, String namespace_uri, String node_local_name, String[] attribute_names, String[] attribute_values)
1070 {
1071 if (attribute_names.length == 0 || attribute_names.length != attribute_values.length)
1072 {
1073 return new MyNodeList();
1074 }
1075
1076 MyNodeList result = new MyNodeList();
1077
1078 NodeList matchingNodes = GSXML.getNamedElementsNS(parent, namespace_uri, node_local_name, attribute_names[0], attribute_values[0]);
1079 for (int i = 0; i < matchingNodes.getLength(); i++)
1080 {
1081 Element current = (Element) matchingNodes.item(i);
1082 boolean nodeMatches = true;
1083 for (int j = 1; j < attribute_names.length; j++)
1084 {
1085 String currentName = attribute_names[j];
1086 String currentValue = attribute_values[j];
1087 if (!current.getAttribute(currentName).equals(currentValue))
1088 {
1089 nodeMatches = false;
1090 break;
1091 }
1092 }
1093
1094 if (nodeMatches)
1095 {
1096 result.addNode(current);
1097 }
1098 }
1099
1100 return result;
1101 }
1102
1103 public static void removeElementsWithAttributesNS(Element parent, String namespace_uri, String node_local_name, String[] attribute_names, String[] attribute_values)
1104 {
1105 NodeList matchingNodes = GSXML.getElementsWithAttributesNS(parent, namespace_uri, node_local_name, attribute_names, attribute_values);
1106 for (int i = 0; i < matchingNodes.getLength(); i++)
1107 {
1108 parent.removeChild(matchingNodes.item(i));
1109 }
1110 }
1111
1112 // In element main, tries to find any previous occurrence of elements with xsl-template-name=templateName,
1113 // and whose named attribute (attributeName) has the same value as the same attribute in node.
1114 // If this is the case, such a previous occurrence is removed from element main, since
1115 // the new node will contain a more specific redefinition of this element.
1116 public static void removeNamedElementNS(Element parent, String namespace_uri, String node_local_name, String attribute_name, String attribute_value)
1117 {
1118 if (attribute_value.equals(""))
1119 {
1120 // it has no identifying attribute, so we can't find any matches
1121 return;
1122 }
1123
1124 Element old_elem = GSXML.getNamedElementNS(parent, namespace_uri, node_local_name, attribute_name, attribute_value);
1125 if (old_elem != null)
1126 {
1127 parent.removeChild(old_elem);
1128 }
1129 }
1130
1131 public static void removeNamedElementsNS(Element parent, String namespace, String node_local_name, String attribute_name, String attribute_value)
1132 {
1133 if (attribute_value.equals(""))
1134 {
1135 // it has no identifying attribute, so we can't find any matches
1136 return;
1137 }
1138
1139 NodeList children = parent.getChildNodes();
1140 for (int i = children.getLength() - 1; i >= 0; i--)
1141 {
1142 Node child = children.item(i);
1143 if (child.getNodeType() == Node.ELEMENT_NODE && child.getNamespaceURI().equals(namespace) && child.getLocalName() != null && child.getLocalName().equals(node_local_name))
1144 {
1145 if (((Element) child).getAttribute(attribute_name).equals(attribute_value))
1146 parent.removeChild(child);
1147 }
1148 }
1149 }
1150
1151 /**
1152 * returns a NodeList of elements:
1153 * ancestor/node_name[@attribute_name='attribute_value']
1154 */
1155 public static NodeList getNamedElements(Element ancestor, String node_name, String attribute_name, String attribute_value)
1156 {
1157 MyNodeList node_list = new MyNodeList();
1158 NodeList children = ancestor.getElementsByTagName(node_name);
1159
1160 if (children != null && children.getLength() > 0)
1161 {
1162
1163 for (int i = 0; i < children.getLength(); i++)
1164 {
1165 Node child = children.item(i);
1166 if (child.getNodeName().equals(node_name))
1167 {
1168 if (((Element) child).getAttribute(attribute_name).equals(attribute_value))
1169 node_list.addNode(child);
1170 }
1171 }
1172 }
1173 return node_list;
1174 }
1175
1176 public static Element getLastElementByTagNameNS(Element main, String namespace, String node_name)
1177 {
1178 NodeList nodes = main.getElementsByTagNameNS(namespace, node_name);
1179 int len = nodes.getLength();
1180 if (len == 0)
1181 {
1182 return null;
1183 }
1184 return (Element) nodes.item(len - 1);
1185 }
1186
1187 public static int SORT_TYPE_STRING = 0;
1188 public static int SORT_TYPE_INT = 1;
1189 public static int SORT_TYPE_FLOAT = 2;
1190
1191 // sort type:
1192 public static Element insertIntoOrderedList(Element parent_node, String node_name, Element start_from_elem, Element new_elem, String sort_att, boolean descending)
1193 {
1194 if (new_elem == null)
1195 return null;
1196 Element cloned_elem = (Element) parent_node.getOwnerDocument().importNode(new_elem, true);
1197 if (start_from_elem == null)
1198 {
1199 parent_node.appendChild(cloned_elem);
1200 return cloned_elem;
1201 }
1202
1203 Node current_node = start_from_elem;
1204 String insert_att = cloned_elem.getAttribute(sort_att);
1205 String list_att = start_from_elem.getAttribute(sort_att);
1206 while ((!descending && list_att.compareTo(insert_att) < 0) || (descending && list_att.compareTo(insert_att) > 0))
1207 {
1208 current_node = current_node.getNextSibling();
1209 if (current_node == null)
1210 break; // end of the list
1211 if (!current_node.getNodeName().equals(node_name))
1212 {
1213 continue; // not a valid node
1214 }
1215 list_att = ((Element) current_node).getAttribute(sort_att);
1216 }
1217
1218 parent_node.insertBefore(cloned_elem, current_node);
1219 return cloned_elem;
1220 }
1221
1222 /**
1223 * Returns the appropriate language element from a display elem, display is
1224 * the containing element, name is the name of the element to look for, lang
1225 * is the preferred language, lang_default is the fall back lang if neither
1226 * lang is found, will return the first one it finds
1227 */
1228 public static String getDisplayText(Element display, String name, String lang, String lang_default)
1229 {
1230
1231 String def = null;
1232 String first = null;
1233 NodeList elems = display.getElementsByTagName(DISPLAY_TEXT_ELEM);
1234 if (elems.getLength() == 0)
1235 return "";
1236 for (int i = 0; i < elems.getLength(); i++)
1237 {
1238 Element e = (Element) elems.item(i);
1239 String n = e.getAttribute(NAME_ATT);
1240 if (name.equals(n))
1241 {
1242 String l = e.getAttribute(LANG_ATT);
1243 if (lang.equals(l))
1244 {
1245 return getNodeText(e);
1246 }
1247 else if (lang_default.equals(l))
1248 {
1249 def = getNodeText(e);
1250 }
1251 else if (first == null)
1252 {
1253 first = getNodeText(e);
1254 }
1255 }
1256 else
1257 {
1258 continue;
1259 }
1260 }
1261
1262 if (def != null)
1263 {
1264 return def;
1265 }
1266 if (first != null)
1267 {
1268 return first;
1269 }
1270 return "";
1271 }
1272
1273 // replaces < > " ' & in the original with their entities
1274 public static String xmlSafe(String original)
1275 {
1276
1277 StringBuffer filtered = new StringBuffer(original.length());
1278 char c;
1279 for (int i = 0; i < original.length(); i++)
1280 {
1281 c = original.charAt(i);
1282 if (c == '>')
1283 {
1284 filtered.append("&gt;");
1285 }
1286 else if (c == '<')
1287 {
1288 filtered.append("&lt;");
1289 }
1290 else if (c == '"')
1291 {
1292 filtered.append("&quot;");
1293 }
1294 else if (c == '&')
1295 {
1296 filtered.append("&amp;");
1297 }
1298 else if (c == '\'')
1299 {
1300 filtered.append("&apos;");
1301 }
1302 else
1303 {
1304 filtered.append(c);
1305 }
1306 }
1307 return filtered.toString();
1308 }
1309
1310 // replaces < > " ' & entities with their originals
1311 public static String unXmlSafe(String original)
1312 {
1313
1314 StringBuffer filtered = new StringBuffer(original.length());
1315 char c;
1316 for (int i = 0; i < original.length(); i++)
1317 {
1318 c = original.charAt(i);
1319 if (c == '&')
1320 {
1321 int pos = original.indexOf(";", i);
1322 String entity = original.substring(i + 1, pos);
1323 if (entity.equals("gt"))
1324 {
1325 filtered.append(">");
1326 }
1327 else if (entity.equals("lt"))
1328 {
1329 filtered.append("<");
1330 }
1331 else if (entity.equals("apos"))
1332 {
1333 filtered.append("'");
1334 }
1335 else if (entity.equals("amp"))
1336 {
1337 filtered.append("&");
1338 }
1339 else if (entity.equals("quot"))
1340 {
1341 filtered.append("\"");
1342 }
1343 else
1344 {
1345 filtered.append("&" + entity + ";");
1346 }
1347 i = pos;
1348 }
1349 else
1350 {
1351 filtered.append(c);
1352 }
1353 }
1354 return filtered.toString();
1355 }
1356
1357 public static void printXMLNode(Node e, boolean printText)
1358 {
1359 printXMLNode(e, 0, printText);
1360 }
1361
1362 public static String xmlNodeToString(Node e)
1363 {
1364 StringBuffer sb = new StringBuffer("");
1365 xmlNodeToString(sb, e, true, "\t", 0);
1366 return sb.toString();
1367 }
1368
1369 public static void xmlNodeToString(StringBuffer sb, Node e, boolean indent, String indentString, int depth)
1370 {
1371 if (e.getNodeType() == Node.TEXT_NODE)
1372 {
1373 if (e.getNodeValue() != "")
1374 {
1375 String text = e.getNodeValue();
1376 if (text != null)
1377 {
1378 text = text.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("^[\\n\\r\\t\\s]*", "").replaceAll("[\\n\\r\\t\\s]*$", "");
1379 sb.append(text);
1380 }
1381 }
1382 return;
1383 }
1384
1385 if (e.getNodeType() == Node.COMMENT_NODE)
1386 {
1387 if (e.getNodeValue() != "")
1388 {
1389 sb.append("<!--" + e.getNodeValue() + "-->");
1390 }
1391 return;
1392 }
1393
1394 if (indent)
1395 {
1396 for (int i = 0; i < depth; i++)
1397 {
1398 sb.append(indentString);
1399 }
1400 }
1401
1402 sb.append('<');
1403 sb.append(e.getNodeName());
1404 NamedNodeMap attrs = e.getAttributes();
1405 if (attrs != null)
1406 {
1407 for (int i = 0; i < attrs.getLength(); i++)
1408 {
1409 Node attr = attrs.item(i);
1410 sb.append(' ');
1411 sb.append(attr.getNodeName());
1412 sb.append("=\"");
1413 sb.append(attr.getNodeValue().replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;"));
1414 sb.append('"');
1415 }
1416 }
1417
1418 if (e.hasChildNodes())
1419 {
1420 boolean hasElements = false;
1421 boolean indentSwapped = false;
1422
1423 Node child = e.getFirstChild();
1424 do
1425 {
1426 if (child.getNodeType() == Node.ELEMENT_NODE)
1427 {
1428 hasElements = true;
1429 }
1430 if (child.getNodeType() == Node.TEXT_NODE && indent)
1431 {
1432 if (child.getNodeValue() != null && child.getNodeValue().trim().length() > 0)
1433 {
1434 indentSwapped = true;
1435 indent = false;
1436 }
1437 }
1438 } while ((child = child.getNextSibling()) != null);
1439
1440 sb.append(">");
1441 if (hasElements && indent)
1442 {
1443 sb.append("\n");
1444 }
1445
1446 child = e.getFirstChild();
1447 do
1448 {
1449 xmlNodeToString(sb, child, indent, indentString, depth + 1);
1450 } while ((child = child.getNextSibling()) != null);
1451
1452 if (indent)
1453 {
1454 for (int i = 0; i < depth; i++)
1455 {
1456 sb.append(indentString);
1457 }
1458 }
1459
1460 sb.append("</" + e.getNodeName() + ">");
1461
1462 if ((hasElements && indent) || indentSwapped)
1463 {
1464 sb.append("\n");
1465 }
1466 }
1467 else
1468 {
1469 sb.append("/>");
1470
1471 if (indent)
1472 {
1473 sb.append("\n");
1474 }
1475 }
1476
1477 /*
1478 boolean hasElements = false;
1479 boolean indentSwapped = false;
1480 for (int i = 0; i < children.getLength(); i++)
1481 {
1482 if (children.item(i).getNodeType() == Node.ELEMENT_NODE)
1483 {
1484 hasElements = true;
1485 }
1486 if (children.item(i).getNodeType() == Node.TEXT_NODE && indent)
1487 {
1488 if (children.item(i).getNodeValue() != null && children.item(i).getNodeValue().trim().length() > 0)
1489 {
1490 indentSwapped = true;
1491 indent = false;
1492 }
1493 }
1494 }
1495
1496 if (children == null || children.getLength() == 0)
1497 {
1498 sb.append("/>");
1499
1500 if (indent)
1501 {
1502 sb.append("\n");
1503 }
1504 }
1505 else
1506 {
1507 sb.append(">");
1508 if (hasElements && indent)
1509 {
1510 sb.append("\n");
1511 }
1512
1513 int len = children.getLength();
1514 for (int i = 0; i < len; i++)
1515 {
1516 xmlNodeToString(sb, children.item(i), indent, indentString, depth + 1);
1517 }
1518
1519 if (indent)
1520 {
1521 for (int i = 0; i < depth; i++)
1522 {
1523 sb.append(indentString);
1524 }
1525 }
1526
1527 sb.append("</" + e.getNodeName() + ">");
1528
1529 if ((hasElements && indent) || indentSwapped)
1530 {
1531 sb.append("\n");
1532 }
1533 }
1534 */
1535 }
1536
1537 public static void printXMLNode(Node e, int depth, boolean printText)
1538 { //recursive method call using DOM API...
1539
1540 if (e == null)
1541 {
1542 return;
1543 }
1544
1545 for (int i = 0; i < depth; i++)
1546 System.out.print(' ');
1547
1548 if (e.getNodeType() == Node.TEXT_NODE)
1549 {
1550 if (printText)
1551 {
1552 System.out.println(e.getNodeValue());
1553 }
1554 else
1555 {
1556 System.out.println("text");
1557 }
1558 return;
1559 }
1560
1561 System.out.print('<');
1562 System.out.print(e.getNodeName());
1563 NamedNodeMap attrs = e.getAttributes();
1564
1565 if (attrs != null)
1566 {
1567 for (int i = 0; i < attrs.getLength(); i++)
1568 {
1569 Node attr = attrs.item(i);
1570 System.out.print(' ');
1571 System.out.print(attr.getNodeName());
1572 System.out.print("=\"");
1573 System.out.print(attr.getNodeValue());
1574 System.out.print('"');
1575 }
1576 }
1577
1578 NodeList children = e.getChildNodes();
1579
1580 if (children == null || children.getLength() == 0)
1581 System.out.println("/>");
1582 else
1583 {
1584
1585 System.out.println('>');
1586
1587 int len = children.getLength();
1588 for (int i = 0; i < len; i++)
1589 {
1590 printXMLNode(children.item(i), depth + 1, printText);
1591 }
1592
1593 for (int i = 0; i < depth; i++)
1594 System.out.print(' ');
1595
1596 System.out.println("</" + e.getNodeName() + ">");
1597 }
1598 }
1599
1600 public static void elementToLogAsString(Element e, boolean indent)
1601 {
1602 String str = elementToString(e, indent);
1603 System.err.println(str);
1604 logger.error(str);
1605 }
1606
1607 public static String elementToString(Element e, boolean indent)
1608 {
1609 String str = "";
1610 try
1611 {
1612 TransformerFactory tf = TransformerFactory.newInstance();
1613 Transformer trans = tf.newTransformer();
1614 StringWriter sw = new StringWriter();
1615 if (indent)
1616 {
1617 trans.setOutputProperty(OutputKeys.INDENT, "yes");
1618 }
1619 else
1620 {
1621 trans.setOutputProperty(OutputKeys.INDENT, "no");
1622 }
1623 trans.transform(new DOMSource(e), new StreamResult(sw));
1624 str += sw.toString();
1625 }
1626 catch (Exception ex)
1627 {
1628 str += "Exception: couldn't write " + e + " to log";
1629 }
1630 finally
1631 {
1632 return str;
1633 }
1634 }
1635
1636 public static ArrayList<String> getGroupsFromSecurityResponse(Element securityResponse)
1637 {
1638 ArrayList<String> groups = new ArrayList<String>();
1639
1640 Element groupList = (Element) GSXML.getChildByTagName(securityResponse, GSXML.GROUP_ELEM + GSXML.LIST_MODIFIER);
1641 if (groupList == null)
1642 {
1643 return groups;
1644 }
1645
1646 NodeList groupElems = GSXML.getChildrenByTagName(groupList, GSXML.GROUP_ELEM);
1647
1648 for (int i = 0; i < groupElems.getLength(); i++)
1649 {
1650 Element groupElem = (Element) groupElems.item(i);
1651 groups.add(groupElem.getAttribute(GSXML.NAME_ATT));
1652 }
1653
1654 return groups;
1655 }
1656
1657}
Note: See TracBrowser for help on using the repository browser.