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

Last change on this file since 33629 was 33629, checked in by kjdon, 4 years ago

added methods using Parameter2 - for params with text node values

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