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

Last change on this file since 28958 was 28958, checked in by davidb, 10 years ago

Remote Greenstone user authenticaton stopped working, because the code working with the DerbyWrapper had changed, and now gliserver.pl could no longer instantiate another JVM that would access the Derby DB (via the users2DBtxt.java) when wanting to check if a user authenticates. Instead, a new GS3 service has been written, Authentication.remoteAuthentication(). This is called from the authentication-ping system action URL that the new ServletRealmCheck.java pings when it is called by gliserver.pl

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