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

Last change on this file since 30666 was 30666, checked in by kjdon, 8 years ago

if att value is null for getNamedElement, will now return the first one with the specified attribute, regardless of value

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