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

Last change on this file since 31868 was 31868, checked in by kjdon, 7 years ago

added new method replaceNamedItemInList

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