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

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

added more generalised versions of mergeMetadataLists and mergeMetadataFromList, so we can use them for merging displayItemLists too

  • Property svn:keywords set to Author Date Id Revision
File size: 49.7 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 return mergeSpecifiedLists(to, from, METADATA_ELEM);
575 }
576
577 /** copies metadata from meta_list into the metadataList of to **/
578 public static boolean mergeMetadataFromList(Node to, Node meta_list) {
579 return mergeSpecifiedFromList(to, meta_list, METADATA_ELEM);
580 }
581
582
583 public static boolean mergeSpecifiedLists(Node to, Node from, String element_name) {
584 // find the list in the from element
585 Node from_list = getChildByTagName(from, element_name+LIST_MODIFIER);
586 if (from_list == null) {
587 // nothing to copy
588 return false;
589 }
590
591 return mergeSpecifiedFromList(to, from_list, element_name);
592 }
593 public static boolean mergeSpecifiedFromList(Node to, Node from_list, String element_name) {
594 if (from_list == null) {
595 return false;
596 }
597 Document to_owner = to.getOwnerDocument();
598 Node to_list = getChildByTagName(to, element_name+LIST_MODIFIER);
599 if (to_list == null) {
600 // just copy over the whole list
601 to.appendChild(to_owner.importNode(from_list, true));
602 return true;
603 }
604 // otherwise we copy all the elements
605 NodeList from_items = ((Element) from_list).getElementsByTagName(element_name);
606
607 for (int i = 0; i < from_items.getLength(); i++)
608 {
609 to_list.appendChild(to_owner.importNode(from_items.item(i), true));
610 }
611 return true;
612
613 }
614
615 /** copies all the children from from to to */
616 public static boolean mergeElements(Element to, Element from)
617 {
618
619 Document owner = to.getOwnerDocument();
620 Node child = from.getFirstChild();
621 while (child != null)
622 {
623 to.appendChild(owner.importNode(child, true));
624 child = child.getNextSibling();
625 }
626 return true;
627 }
628
629 /** returns the (first) element child of the node n */
630 public static Element getFirstElementChild(Node n)
631 {
632
633 Node child = n.getFirstChild();
634 while (child != null)
635 {
636 if (child.getNodeType() == Node.ELEMENT_NODE)
637 {
638 return (Element) child;
639 }
640 child = child.getNextSibling();
641 }
642 return null; //no element child found
643 }
644
645 /** returns the (first) child element with the given name */
646 public static Node getChildByTagName(Node n, String name)
647 {
648 if (n != null)
649 { // this line is an attempted solution to the NullPointerException mentioned
650 // in trac bug ticket #225. If n is null can't do n.getFirstChild() below. As per bug #225:
651 // GSXML.getNodeByPath() is called by GS2BrowseAction, which then calls this method.
652 // If n is null, null will be returned which GS2BrowseAction already checks for. It's here
653 // that the NullPointerException was thrown.
654
655 Node child = n.getFirstChild();
656 while (child != null)
657 {
658 if (child.getNodeName().equals(name))
659 {
660 return child;
661 }
662 child = child.getNextSibling();
663 }
664 }
665 return null; //not found
666 }
667
668 /**
669 * returns the (nth) child element with the given name index numbers start
670 * at 0
671 */
672 public static Node getChildByTagNameIndexed(Node n, String name, int index)
673 {
674 if (index == -1)
675 {
676 return getChildByTagName(n, name);
677 }
678 int count = 0;
679 Node child = n.getFirstChild();
680 while (child != null)
681 {
682 if (child.getNodeName().equals(name))
683 {
684 if (count == index)
685 {
686 return child;
687 }
688 else
689 {
690 count++;
691 }
692 }
693 child = child.getNextSibling();
694 }
695 return null; //not found
696 }
697
698 /**
699 * takes an xpath type expression of the form name/name/... and returns the
700 * first node that matches, or null if not found
701 */
702 public static Node getNodeByPath(Node n, String path)
703 {
704
705 String link = GSPath.getFirstLink(path);
706 path = GSPath.removeFirstLink(path);
707 while (!link.equals(""))
708 {
709 n = getChildByTagName(n, link);
710 if (n == null)
711 {
712 return null;
713 }
714 link = GSPath.getFirstLink(path);
715 path = GSPath.removeFirstLink(path);
716 }
717 return n;
718 }
719
720 /**
721 * takes an xpath type expression of the form name/name/... and returns the
722 * first node that matches, or null if not found can include [i] indices.
723 * index numbers start at 0
724 */
725 public static Node getNodeByPathIndexed(Node n, String path)
726 {
727
728 String link = GSPath.getFirstLink(path);
729 int index = GSPath.getIndex(link);
730 if (index != -1)
731 {
732 link = GSPath.removeIndex(link);
733 }
734 path = GSPath.removeFirstLink(path);
735 while (!link.equals(""))
736 {
737 n = getChildByTagNameIndexed(n, link, index);
738 if (n == null)
739 {
740 return null;
741 }
742 link = GSPath.getFirstLink(path);
743 index = GSPath.getIndex(link);
744 if (index != -1)
745 {
746 link = GSPath.removeIndex(link);
747 }
748 path = GSPath.removeFirstLink(path);
749 }
750 return n;
751 }
752
753 public static HashMap<String, Node> getChildrenMap(Node n)
754 {
755
756 HashMap<String, Node> map = new HashMap<String, Node>();
757 Node child = n.getFirstChild();
758 while (child != null)
759 {
760 String name = child.getNodeName();
761 map.put(name, child);
762 child = child.getNextSibling();
763 }
764 return map;
765 }
766
767 public static NodeList getChildrenByTagName(Node n, String name)
768 {
769 MyNodeList node_list = new MyNodeList();
770 Node child = n.getFirstChild();
771 while (child != null)
772 {
773 if (child.getNodeName().equals(name))
774 {
775 node_list.addNode(child);
776 }
777 child = child.getNextSibling();
778 }
779 return node_list;
780 }
781
782 public static NodeList getChildrenByTagNameNS(Node n, String namespace, String local_name)
783 {
784 MyNodeList node_list = new MyNodeList();
785 Node child = n.getFirstChild();
786 while (child != null)
787 {
788 if (child.getNodeType() == Node.ELEMENT_NODE && child.getNamespaceURI() != null && child.getNamespaceURI().equals(namespace) && child.getLocalName() != null && child.getLocalName().equals(local_name))
789 {
790 node_list.addNode(child);
791 }
792 child = child.getNextSibling();
793 }
794 return node_list;
795 }
796
797 /** Duplicates an element, but gives it a new name */
798 public static Element duplicateWithNewName(Document owner, Element element, String element_name, boolean with_attributes)
799 {
800 return duplicateWithNewNameNS(owner, element, element_name, null, with_attributes);
801 }
802
803 /** Duplicates an element, but gives it a new name */
804 public static Element duplicateWithNewNameNS(Document owner, Element element, String element_name, String namespace_uri, boolean with_attributes)
805 {
806 Element duplicate;
807 if (namespace_uri == null)
808 {
809 duplicate = owner.createElement(element_name);
810 }
811 else
812 {
813 duplicate = owner.createElementNS(namespace_uri, element_name);
814 }
815
816 // Copy element attributes
817 if (with_attributes)
818 {
819 NamedNodeMap attributes = element.getAttributes();
820 for (int i = 0; i < attributes.getLength(); i++)
821 {
822 Node attribute = attributes.item(i);
823 duplicate.setAttribute(attribute.getNodeName(), attribute.getNodeValue());
824 }
825 }
826
827 // Copy element children
828 NodeList children = element.getChildNodes();
829 for (int i = 0; i < children.getLength(); i++)
830 {
831 Node child = children.item(i);
832 duplicate.appendChild(owner.importNode(child, true));
833 }
834
835 return duplicate;
836 }
837
838 public static void copyAllChildren(Element to, Element from)
839 {
840
841 Document to_doc = to.getOwnerDocument();
842 Node child = from.getFirstChild();
843 while (child != null)
844 {
845 to.appendChild(to_doc.importNode(child, true));
846 child = child.getNextSibling();
847 }
848 }
849
850 public static void copyNode(Element to_elem, Node original_element) {
851 to_elem.appendChild(to_elem.getOwnerDocument().importNode(original_element, true));
852
853 }
854
855 public static void copyNamedElement(Element to, Element from, String elem_name) {
856
857 Document to_doc = to.getOwnerDocument();
858 Node child = from.getFirstChild();
859 while (child != null) {
860 if (child.getNodeName().equals(elem_name)) {
861 to.appendChild(to_doc.importNode(child, true));
862 return;
863 }
864 child = child.getNextSibling();
865 }
866 }
867
868 /**
869 * Given a Node representing an Element or Document, will return the
870 * Element/docroot Element. Returns null if the Node was not an element.
871 */
872 public static Element nodeToElement(Node node)
873 {
874 if (node == null)
875 {
876 return null;
877 }
878 short nodeType = node.getNodeType();
879
880 if (nodeType == Node.DOCUMENT_NODE)
881 {
882 Document docNode = (Document) node;
883 return docNode.getDocumentElement();
884 }
885 else if (nodeType == Node.ELEMENT_NODE)
886 {
887 return (Element) node;
888 }
889 else
890 {
891 String message = "Expecting Document or Element node type but got " + node.getNodeName() + "\nReturning null";
892 System.err.println(message);
893 logger.warn(message);
894 return null;
895 }
896 }
897
898
899 /** returns a basic request message */
900 public static Element createBasicRequest(Document owner, String request_type, String to, UserContext userContext)
901 {
902 Element request = owner.createElement(REQUEST_ELEM);
903 request.setAttribute(TO_ATT, to);
904 request.setAttribute(TYPE_ATT, request_type);
905 if (userContext != null) { // should we allow this??
906 request.setAttribute(LANG_ATT, userContext._lang);
907 Element userContextElem = owner.createElement("userContext");
908 request.appendChild(userContextElem);
909 userContextElem.setAttribute(LANG_ATT, userContext._lang);
910 userContextElem.setAttribute(USERNAME_ATT, userContext._username);
911 userContextElem.setAttribute(USER_ID_ATT, userContext._userID);
912
913 if (userContext._groups != null)
914 {
915 String groupString = "";
916 for (int i = 0; i < userContext._groups.length; i++)
917 {
918 groupString += userContext._groups[i];
919 if (i != userContext._groups.length - 1)
920 {
921 groupString += ",";
922 }
923 }
924
925 if (groupString.length() > 0)
926 {
927 userContextElem.setAttribute(GROUPS_ATT, groupString);
928 }
929 }
930 }
931 return request;
932 }
933
934 public static Element createBasicResponse(Document owner, String from)
935 {
936 Element response = owner.createElement(GSXML.RESPONSE_ELEM);
937 response.setAttribute(GSXML.FROM_ATT, from);
938 response.setAttribute(GSXML.TYPE_ATT, GSXML.REQUEST_TYPE_PROCESS);
939 return response;
940 }
941
942 public static Element createMetadataElement(Document owner, String name, String value)
943 {
944 Element metaElem = owner.createElement(GSXML.METADATA_ELEM);
945 metaElem.setAttribute(GSXML.NAME_ATT, name);
946 metaElem.setAttribute(GSXML.VALUE_ATT, value);
947 return metaElem;
948 }
949
950 public static Element createTextElement(Document owner, String elem_name, String text)
951 {
952 Element e = owner.createElement(elem_name);
953 Text t = owner.createTextNode(text);
954 e.appendChild(t);
955 return e;
956
957 }
958
959 public static Element createTextElement(Document owner, String elem_name, String text, String att_name, String att_value)
960 {
961 Element e = owner.createElement(elem_name);
962 e.setAttribute(att_name, att_value);
963 Text t = owner.createTextNode(text);
964 e.appendChild(t);
965 return e;
966
967 }
968
969 public static Element createDisplayTextElement(Document owner, String text_name, String text)
970 {
971 Element e = owner.createElement(DISPLAY_TEXT_ELEM);
972 e.setAttribute(NAME_ATT, text_name);
973 Text t = owner.createTextNode(text);
974 e.appendChild(t);
975 return e;
976
977 }
978
979 public static Element createParameter(Document owner, String name, String value)
980 {
981 Element param = owner.createElement(PARAM_ELEM);
982 param.setAttribute(NAME_ATT, name);
983 param.setAttribute(VALUE_ATT, value);
984 return param;
985 }
986
987 public static void addParameterToList(Element param_list, String name, String value) {
988 Element p = createParameter(param_list.getOwnerDocument(), name, value);
989 param_list.appendChild(p);
990 }
991 public static void addParametersToList(Element param_list, HashMap params)
992 {
993 if (params == null)
994 {
995 return;
996 }
997
998 Set items = params.entrySet();
999 Iterator i = items.iterator();
1000 Document owner = param_list.getOwnerDocument();
1001 while (i.hasNext())
1002 {
1003 Map.Entry m = (Map.Entry) i.next();
1004 param_list.appendChild(createParameter(owner, (String) m.getKey(), (String) m.getValue()));
1005 }
1006
1007 }
1008
1009 public static Element createParameterDescription(Document owner, String id, String display_name, String type, String default_value, String[] option_ids, String[] option_names)
1010 {
1011
1012 Element p = owner.createElement(PARAM_ELEM);
1013 p.setAttribute(NAME_ATT, id);
1014 p.setAttribute(TYPE_ATT, type);
1015 p.appendChild(createDisplayTextElement(owner, GSXML.DISPLAY_TEXT_NAME, display_name));
1016
1017 if (default_value != null)
1018 {
1019 p.setAttribute(DEFAULT_ATT, default_value);
1020 }
1021 if (option_ids != null && option_names != null)
1022 {
1023 for (int i = 0; i < option_ids.length; i++)
1024 {
1025 Element e = owner.createElement(PARAM_OPTION_ELEM);
1026 e.setAttribute(NAME_ATT, option_ids[i]);
1027 e.appendChild(createDisplayTextElement(owner, GSXML.DISPLAY_TEXT_NAME, option_names[i]));
1028 p.appendChild(e);
1029 }
1030 }
1031 return p;
1032 }
1033
1034 public static Element createParameterDescription2(Document owner, String id, String display_name, String type, String default_value, ArrayList<String> option_ids, ArrayList<String> option_names)
1035 {
1036
1037 Element p = owner.createElement(PARAM_ELEM);
1038 p.setAttribute(NAME_ATT, id);
1039 p.setAttribute(TYPE_ATT, type);
1040 p.appendChild(createDisplayTextElement(owner, GSXML.DISPLAY_TEXT_NAME, display_name));
1041 if (default_value != null)
1042 {
1043 p.setAttribute(DEFAULT_ATT, default_value);
1044 }
1045 if (option_ids != null && option_names != null)
1046 {
1047 for (int i = 0; i < option_ids.size(); i++)
1048 {
1049 Element e = owner.createElement(PARAM_OPTION_ELEM);
1050 e.setAttribute(NAME_ATT, option_ids.get(i));
1051 e.appendChild(createDisplayTextElement(owner, GSXML.DISPLAY_TEXT_NAME, option_names.get(i)));
1052 p.appendChild(e);
1053 }
1054 }
1055 return p;
1056 }
1057
1058 /** returns the element parent/node_name[@attribute_name='attribute_value']
1059 if attribute_value is null, just returns the first one with that attribute */
1060 public static Element getNamedElement(Element parent, String node_name, String attribute_name, String attribute_value)
1061 {
1062
1063 NodeList children = parent.getChildNodes();
1064 for (int i = 0; i < children.getLength(); i++)
1065 {
1066 Node child = children.item(i);
1067 if (child.getNodeName().equals(node_name))
1068 {
1069 String att_val = ((Element) child).getAttribute(attribute_name);
1070 if (!att_val.equals("") ) {
1071 if (attribute_value == null || att_val.equals(attribute_value)) {
1072 return (Element) child;
1073 }
1074 }
1075 }
1076 } // for each child
1077 // not found
1078 return null;
1079 }
1080
1081 public static Element getNamedElementNS(Element parent, String namespace_uri, String node_local_name, String attribute_name, String attribute_value)
1082 {
1083 NodeList children = parent.getChildNodes();
1084 for (int i = 0; i < children.getLength(); i++)
1085 {
1086 Node child = children.item(i);
1087 if (child.getNodeType() == Node.ELEMENT_NODE && child.getNamespaceURI() != null && child.getNamespaceURI().equals(namespace_uri) && child.getLocalName().equals(node_local_name))
1088 {
1089 if (((Element) child).getAttribute(attribute_name).equals(attribute_value))
1090 return (Element) child;
1091 }
1092 }
1093 // not found
1094 return null;
1095 }
1096
1097 public static NodeList getNamedElementsNS(Element parent, String namespace_uri, String node_local_name, String attribute_name, String attribute_value)
1098 {
1099 MyNodeList result = new MyNodeList();
1100 NodeList children = parent.getChildNodes();
1101 for (int i = 0; i < children.getLength(); i++)
1102 {
1103 Node child = children.item(i);
1104 if (child.getNodeType() == Node.ELEMENT_NODE && child.getNamespaceURI() != null && child.getNamespaceURI().equals(namespace_uri) && child.getLocalName().equals(node_local_name))
1105 {
1106 if (((Element) child).getAttribute(attribute_name).equals(attribute_value))
1107 result.addNode(child);
1108 }
1109 }
1110 return result;
1111 }
1112
1113 public static NodeList getElementsWithAttributesNS(Element parent, String namespace_uri, String node_local_name, String[] attribute_names, String[] attribute_values)
1114 {
1115 if (attribute_names.length == 0 || attribute_names.length != attribute_values.length)
1116 {
1117 return new MyNodeList();
1118 }
1119
1120 MyNodeList result = new MyNodeList();
1121
1122 NodeList matchingNodes = GSXML.getNamedElementsNS(parent, namespace_uri, node_local_name, attribute_names[0], attribute_values[0]);
1123 for (int i = 0; i < matchingNodes.getLength(); i++)
1124 {
1125 Element current = (Element) matchingNodes.item(i);
1126 boolean nodeMatches = true;
1127 for (int j = 1; j < attribute_names.length; j++)
1128 {
1129 String currentName = attribute_names[j];
1130 String currentValue = attribute_values[j];
1131 if (!current.getAttribute(currentName).equals(currentValue))
1132 {
1133 nodeMatches = false;
1134 break;
1135 }
1136 }
1137
1138 if (nodeMatches)
1139 {
1140 result.addNode(current);
1141 }
1142 }
1143
1144 return result;
1145 }
1146
1147 public static void removeElementsWithAttributesNS(Element parent, String namespace_uri, String node_local_name, String[] attribute_names, String[] attribute_values)
1148 {
1149 NodeList matchingNodes = GSXML.getElementsWithAttributesNS(parent, namespace_uri, node_local_name, attribute_names, attribute_values);
1150 for (int i = 0; i < matchingNodes.getLength(); i++)
1151 {
1152 parent.removeChild(matchingNodes.item(i));
1153 }
1154 }
1155
1156 // In element main, tries to find any previous occurrence of elements with xsl-template-name=templateName,
1157 // and whose named attribute (attributeName) has the same value as the same attribute in node.
1158 // If this is the case, such a previous occurrence is removed from element main, since
1159 // the new node will contain a more specific redefinition of this element.
1160 public static void removeNamedElementNS(Element parent, String namespace_uri, String node_local_name, String attribute_name, String attribute_value)
1161 {
1162 if (attribute_value.equals(""))
1163 {
1164 // it has no identifying attribute, so we can't find any matches
1165 return;
1166 }
1167
1168 Element old_elem = GSXML.getNamedElementNS(parent, namespace_uri, node_local_name, attribute_name, attribute_value);
1169 if (old_elem != null)
1170 {
1171 parent.removeChild(old_elem);
1172 }
1173 }
1174
1175 public static void removeNamedElementsNS(Element parent, String namespace, String node_local_name, String attribute_name, String attribute_value)
1176 {
1177 if (attribute_value.equals(""))
1178 {
1179 // it has no identifying attribute, so we can't find any matches
1180 return;
1181 }
1182
1183 NodeList children = parent.getChildNodes();
1184 for (int i = children.getLength() - 1; i >= 0; i--)
1185 {
1186 Node child = children.item(i);
1187 if (child.getNodeType() == Node.ELEMENT_NODE && child.getNamespaceURI() != null && child.getNamespaceURI().equals(namespace) && child.getLocalName() != null && child.getLocalName().equals(node_local_name))
1188 {
1189 if (((Element) child).getAttribute(attribute_name).equals(attribute_value))
1190 parent.removeChild(child);
1191 }
1192 }
1193 }
1194
1195 /**
1196 * returns a NodeList of elements:
1197 * ancestor/node_name[@attribute_name='attribute_value']
1198 */
1199 public static NodeList getNamedElements(Element ancestor, String node_name, String attribute_name, String attribute_value)
1200 {
1201 MyNodeList node_list = new MyNodeList();
1202 NodeList children = ancestor.getElementsByTagName(node_name);
1203
1204 if (children != null && children.getLength() > 0)
1205 {
1206
1207 for (int i = 0; i < children.getLength(); i++)
1208 {
1209 Node child = children.item(i);
1210 if (child.getNodeName().equals(node_name))
1211 {
1212 if (((Element) child).getAttribute(attribute_name).equals(attribute_value))
1213 node_list.addNode(child);
1214 }
1215 }
1216 }
1217 return node_list;
1218 }
1219
1220 public static Element getLastElementByTagNameNS(Element main, String namespace, String node_name)
1221 {
1222 NodeList nodes = main.getElementsByTagNameNS(namespace, node_name);
1223 int len = nodes.getLength();
1224 if (len == 0)
1225 {
1226 return null;
1227 }
1228 return (Element) nodes.item(len - 1);
1229 }
1230
1231 public static int SORT_TYPE_STRING = 0;
1232 public static int SORT_TYPE_INT = 1;
1233 public static int SORT_TYPE_FLOAT = 2;
1234
1235 // sort type:
1236 public static Element insertIntoOrderedList(Element parent_node, String node_name, Element start_from_elem, Element new_elem, String sort_att, boolean descending)
1237 {
1238 if (new_elem == null)
1239 return null;
1240 Element cloned_elem = (Element) parent_node.getOwnerDocument().importNode(new_elem, true);
1241 if (start_from_elem == null)
1242 {
1243 parent_node.appendChild(cloned_elem);
1244 return cloned_elem;
1245 }
1246
1247 Node current_node = start_from_elem;
1248 String insert_att = cloned_elem.getAttribute(sort_att);
1249 String list_att = start_from_elem.getAttribute(sort_att);
1250 while ((!descending && list_att.compareTo(insert_att) < 0) || (descending && list_att.compareTo(insert_att) > 0))
1251 {
1252 current_node = current_node.getNextSibling();
1253 if (current_node == null)
1254 break; // end of the list
1255 if (!current_node.getNodeName().equals(node_name))
1256 {
1257 continue; // not a valid node
1258 }
1259 list_att = ((Element) current_node).getAttribute(sort_att);
1260 }
1261
1262 parent_node.insertBefore(cloned_elem, current_node);
1263 return cloned_elem;
1264 }
1265
1266 public static String getMetadataValue(Element metadata_list, String name) {
1267 Element meta = getNamedElement(metadata_list, METADATA_ELEM, NAME_ATT, name);
1268 if (meta == null) {
1269 return "";
1270 }
1271 String att_value = meta.getAttribute(VALUE_ATT);
1272 if (att_value.equals("")) {
1273 // try the text
1274 att_value = getNodeText(meta);
1275 }
1276 return att_value;
1277 }
1278
1279 // replaces < > " ' & in the original with their entities
1280 public static String xmlSafe(String original)
1281 {
1282
1283 StringBuffer filtered = new StringBuffer(original.length());
1284 char c;
1285 for (int i = 0; i < original.length(); i++)
1286 {
1287 c = original.charAt(i);
1288 if (c == '>')
1289 {
1290 filtered.append("&gt;");
1291 }
1292 else if (c == '<')
1293 {
1294 filtered.append("&lt;");
1295 }
1296 else if (c == '"')
1297 {
1298 filtered.append("&quot;");
1299 }
1300 else if (c == '&')
1301 {
1302 filtered.append("&amp;");
1303 }
1304 else if (c == '\'')
1305 {
1306 filtered.append("&apos;");
1307 }
1308 else
1309 {
1310 filtered.append(c);
1311 }
1312 }
1313 return filtered.toString();
1314 }
1315
1316 // replaces < > " ' & entities with their originals
1317 public static String unXmlSafe(String original)
1318 {
1319
1320 StringBuffer filtered = new StringBuffer(original.length());
1321 char c;
1322 for (int i = 0; i < original.length(); i++)
1323 {
1324 c = original.charAt(i);
1325 if (c == '&')
1326 {
1327 int pos = original.indexOf(";", i);
1328 String entity = original.substring(i + 1, pos);
1329 if (entity.equals("gt"))
1330 {
1331 filtered.append(">");
1332 }
1333 else if (entity.equals("lt"))
1334 {
1335 filtered.append("<");
1336 }
1337 else if (entity.equals("apos"))
1338 {
1339 filtered.append("'");
1340 }
1341 else if (entity.equals("amp"))
1342 {
1343 filtered.append("&");
1344 }
1345 else if (entity.equals("quot"))
1346 {
1347 filtered.append("\"");
1348 }
1349 else
1350 {
1351 filtered.append("&" + entity + ";");
1352 }
1353 i = pos;
1354 }
1355 else
1356 {
1357 filtered.append(c);
1358 }
1359 }
1360 return filtered.toString();
1361 }
1362
1363 public static void printXMLNode(Node e, boolean printText)
1364 {
1365 printXMLNode(e, 0, printText);
1366 }
1367
1368 public static String xmlNodeToString(Node e)
1369 {
1370 StringBuffer sb = new StringBuffer("");
1371 xmlNodeToString(sb, e, true, "\t", 0);
1372 return sb.toString();
1373 }
1374
1375 public static void xmlNodeToString(StringBuffer sb, Node e, boolean indent, String indentString, int depth)
1376 {
1377 if (e.getNodeType() == Node.TEXT_NODE)
1378 {
1379 if (e.getNodeValue() != "")
1380 {
1381 String text = e.getNodeValue();
1382 if (text != null)
1383 {
1384 text = text.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("^[\\n\\r\\t\\s]*", "").replaceAll("[\\n\\r\\t\\s]*$", "");
1385 sb.append(text);
1386 }
1387 }
1388 return;
1389 }
1390
1391 if (e.getNodeType() == Node.COMMENT_NODE)
1392 {
1393 if (e.getNodeValue() != "")
1394 {
1395 sb.append("<!--" + e.getNodeValue() + "-->");
1396 }
1397 return;
1398 }
1399
1400 if (indent)
1401 {
1402 for (int i = 0; i < depth; i++)
1403 {
1404 sb.append(indentString);
1405 }
1406 }
1407
1408 sb.append('<');
1409 sb.append(e.getNodeName());
1410 NamedNodeMap attrs = e.getAttributes();
1411 if (attrs != null)
1412 {
1413 for (int i = 0; i < attrs.getLength(); i++)
1414 {
1415 Node attr = attrs.item(i);
1416 sb.append(' ');
1417 sb.append(attr.getNodeName());
1418 sb.append("=\"");
1419 sb.append(attr.getNodeValue().replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;"));
1420 sb.append('"');
1421 }
1422 }
1423
1424 if (e.hasChildNodes())
1425 {
1426 boolean hasElements = false;
1427 boolean indentSwapped = false;
1428
1429 Node child = e.getFirstChild();
1430 do
1431 {
1432 if (child.getNodeType() == Node.ELEMENT_NODE)
1433 {
1434 hasElements = true;
1435 }
1436 if (child.getNodeType() == Node.TEXT_NODE && indent)
1437 {
1438 if (child.getNodeValue() != null && child.getNodeValue().trim().length() > 0)
1439 {
1440 indentSwapped = true;
1441 indent = false;
1442 }
1443 }
1444 } while ((child = child.getNextSibling()) != null);
1445
1446 sb.append(">");
1447 if (hasElements && indent)
1448 {
1449 sb.append("\n");
1450 }
1451
1452 child = e.getFirstChild();
1453 do
1454 {
1455 xmlNodeToString(sb, child, indent, indentString, depth + 1);
1456 } while ((child = child.getNextSibling()) != null);
1457
1458 if (indent)
1459 {
1460 for (int i = 0; i < depth; i++)
1461 {
1462 sb.append(indentString);
1463 }
1464 }
1465
1466 sb.append("</" + e.getNodeName() + ">");
1467
1468 if ((hasElements && indent) || indentSwapped)
1469 {
1470 sb.append("\n");
1471 }
1472 }
1473 else
1474 {
1475 sb.append("/>");
1476
1477 if (indent)
1478 {
1479 sb.append("\n");
1480 }
1481 }
1482
1483 /*
1484 boolean hasElements = false;
1485 boolean indentSwapped = false;
1486 for (int i = 0; i < children.getLength(); i++)
1487 {
1488 if (children.item(i).getNodeType() == Node.ELEMENT_NODE)
1489 {
1490 hasElements = true;
1491 }
1492 if (children.item(i).getNodeType() == Node.TEXT_NODE && indent)
1493 {
1494 if (children.item(i).getNodeValue() != null && children.item(i).getNodeValue().trim().length() > 0)
1495 {
1496 indentSwapped = true;
1497 indent = false;
1498 }
1499 }
1500 }
1501
1502 if (children == null || children.getLength() == 0)
1503 {
1504 sb.append("/>");
1505
1506 if (indent)
1507 {
1508 sb.append("\n");
1509 }
1510 }
1511 else
1512 {
1513 sb.append(">");
1514 if (hasElements && indent)
1515 {
1516 sb.append("\n");
1517 }
1518
1519 int len = children.getLength();
1520 for (int i = 0; i < len; i++)
1521 {
1522 xmlNodeToString(sb, children.item(i), indent, indentString, depth + 1);
1523 }
1524
1525 if (indent)
1526 {
1527 for (int i = 0; i < depth; i++)
1528 {
1529 sb.append(indentString);
1530 }
1531 }
1532
1533 sb.append("</" + e.getNodeName() + ">");
1534
1535 if ((hasElements && indent) || indentSwapped)
1536 {
1537 sb.append("\n");
1538 }
1539 }
1540 */
1541 }
1542
1543 public static void printXMLNode(Node e, int depth, boolean printText)
1544 { //recursive method call using DOM API...
1545
1546 if (e == null)
1547 {
1548 return;
1549 }
1550
1551 for (int i = 0; i < depth; i++)
1552 System.out.print(' ');
1553
1554 if (e.getNodeType() == Node.TEXT_NODE)
1555 {
1556 if (printText)
1557 {
1558 System.out.println(e.getNodeValue());
1559 }
1560 else
1561 {
1562 System.out.println("text");
1563 }
1564 return;
1565 }
1566
1567 System.out.print('<');
1568 System.out.print(e.getNodeName());
1569 NamedNodeMap attrs = e.getAttributes();
1570
1571 if (attrs != null)
1572 {
1573 for (int i = 0; i < attrs.getLength(); i++)
1574 {
1575 Node attr = attrs.item(i);
1576 System.out.print(' ');
1577 System.out.print(attr.getNodeName());
1578 System.out.print("=\"");
1579 System.out.print(attr.getNodeValue());
1580 System.out.print('"');
1581 }
1582 }
1583
1584 NodeList children = e.getChildNodes();
1585
1586 if (children == null || children.getLength() == 0)
1587 System.out.println("/>");
1588 else
1589 {
1590
1591 System.out.println('>');
1592
1593 int len = children.getLength();
1594 for (int i = 0; i < len; i++)
1595 {
1596 printXMLNode(children.item(i), depth + 1, printText);
1597 }
1598
1599 for (int i = 0; i < depth; i++)
1600 System.out.print(' ');
1601
1602 System.out.println("</" + e.getNodeName() + ">");
1603 }
1604 }
1605
1606 public static void elementToLogAsString(Element e, boolean indent)
1607 {
1608 String str = elementToString(e, indent);
1609 System.err.println(str);
1610 logger.error(str);
1611 }
1612
1613 public static String elementToString(Element e, boolean indent)
1614 {
1615 String str = "";
1616 try
1617 {
1618 TransformerFactory tf = TransformerFactory.newInstance();
1619 Transformer trans = tf.newTransformer();
1620 StringWriter sw = new StringWriter();
1621 if (indent)
1622 {
1623 trans.setOutputProperty(OutputKeys.INDENT, "yes");
1624 }
1625 else
1626 {
1627 trans.setOutputProperty(OutputKeys.INDENT, "no");
1628 }
1629 trans.transform(new DOMSource(e), new StreamResult(sw));
1630 str += sw.toString();
1631 }
1632 catch (Exception ex)
1633 {
1634 str += "Exception: couldn't write " + e + " to log";
1635 }
1636 finally
1637 {
1638 return str;
1639 }
1640 }
1641
1642 public static ArrayList<String> getGroupsFromSecurityResponse(Element securityResponse)
1643 {
1644 ArrayList<String> groups = new ArrayList<String>();
1645
1646 Element groupList = (Element) GSXML.getChildByTagName(securityResponse, GSXML.GROUP_ELEM + GSXML.LIST_MODIFIER);
1647 if (groupList == null)
1648 {
1649 return groups;
1650 }
1651
1652 NodeList groupElems = GSXML.getChildrenByTagName(groupList, GSXML.GROUP_ELEM);
1653
1654 for (int i = 0; i < groupElems.getLength(); i++)
1655 {
1656 Element groupElem = (Element) groupElems.item(i);
1657 groups.add(groupElem.getAttribute(GSXML.NAME_ATT));
1658 }
1659
1660 return groups;
1661 }
1662
1663}
Note: See TracBrowser for help on using the repository browser.