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

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

moved getDisplayText into ServiceRack from GSXML so that if there is a key specified we can use getTextString to look it up

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