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

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

modified createBasicRequest to use userContext methods, and to include editEnabled

  • Property svn:keywords set to Author Date Id Revision
File size: 52.7 KB
Line 
1/*
2 * GSXML.java
3 * Copyright (C) 2008 New Zealand Digital Library, http://www.nzdl.org
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18 */
19package org.greenstone.gsdl3.util;
20
21import java.io.Serializable;
22import java.io.StringWriter;
23import java.util.ArrayList;
24import java.util.HashMap;
25import java.util.Iterator;
26import java.util.Map;
27import java.util.Set;
28import java.util.Vector;
29
30import javax.xml.transform.OutputKeys;
31import javax.xml.transform.Transformer;
32import javax.xml.transform.TransformerFactory;
33import javax.xml.transform.dom.DOMSource;
34import javax.xml.transform.stream.StreamResult;
35
36import org.apache.log4j.Logger;
37import org.w3c.dom.Document;
38import org.w3c.dom.Element;
39import org.w3c.dom.NamedNodeMap;
40import org.w3c.dom.Node;
41import org.w3c.dom.NodeList;
42import org.w3c.dom.Text;
43
44import org.greenstone.gsdl3.util.MyNodeList;
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 EDIT_ENABLED_ATT = "editEnabled";
307 public static final String BASE_URL = "baseURL";
308
309 // only for authenticated-ping
310 public static final String PASSWORD_ATT = "password";
311
312 //for classifiers
313 public static final String CHILD_TYPE_ATT = "childType";
314 public static final String CLASSIFIER_STYLE_ATT = "classifierStyle";
315 public static final String HLIST = "HList";
316 public static final String VLIST = "VList";
317
318 //for namespaces
319 public static final String XSL_NAMESPACE = "http://www.w3.org/1999/XSL/Transform";
320 public static final String GSF_NAMESPACE = "http://www.greenstone.org/greenstone3/schema/ConfigFormat";
321 public static final String GSLIB_NAMESPACE = "http://www.greenstone.org/skinning";
322 public static final String JAVA_NAMESPACE = "http://xml.apache.org/xslt/java";
323 public static final String UTIL_NAMESPACE = "xalan://org.greenstone.gsdl3.util.XSLTUtil";
324
325 // all the namespaces in a string for easy addition to a string
326 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 +"' ";
327 public static final String STD_NAMESPACES_ATTS = "xmlns:gsf='" + GSF_NAMESPACE + "' xmlns:xsl='" + XSL_NAMESPACE + "' xmlns:gslib='" + GSLIB_NAMESPACE +"' ";
328
329 //Groups configuration
330 public static final String HIERARCHY_ELEM = "hierarchy";
331 public static final String GROUP_DESC_ELEM = "groupDescriptions";
332 public static final String TITLE_ELEM = "title";
333 public static final String DESCRIPTION_ELEM = "description";
334 public static final String SHORT_DESCRIPTION_ELEM = "shortDescription";
335 public static final String BACKGROUND_IMAGE_ELEM = "backgroundImage";
336 public static final String POSITION_ATT = "position";
337
338 /**
339 * takes a list of elements, and returns an array of strings of the values
340 * of attribute att_name
341 */
342 public static String[] getAttributeValuesFromList(Element list, String att_name)
343 {
344
345 NodeList children = list.getChildNodes();
346
347 int num_nodes = children.getLength();
348 String[] ids = new String[num_nodes];
349 for (int i = 0; i < num_nodes; i++)
350 {
351 Element e = (Element) children.item(i);
352 String id = e.getAttribute(att_name);
353 ids[i] = id;
354 }
355
356 return ids;
357 }
358
359 public static HashMap<String, String> getParamMap(NodeList params) {
360 HashMap<String, String> map = new HashMap<String, String>();
361 for(int i=0; i<params.getLength(); i++) {
362 Element param = (Element)params.item(i);
363 String param_name = param.getAttribute(NAME_ATT);
364 String param_value = param.getAttribute(VALUE_ATT);
365 map.put(param_name, param_value);
366 }
367 return map;
368 }
369
370 public static HashMap<String, Serializable> extractParams(Element xml, boolean deep)
371 {
372 return extractParams(xml, deep, null);
373 }
374
375 /**
376 * takes a paramList element, and gets a HashMap of name-value pairs if
377 * deep=true, extracts embedded params, otherwise just top level params
378 */
379 public static HashMap<String, Serializable> extractParams(Element xml, boolean deep, String toFind)
380 {
381 if (xml == null)
382 {
383 return null;
384 }
385
386 if (!xml.getNodeName().equals(PARAM_ELEM + LIST_MODIFIER))
387 {
388 logger.error("paramList element should have been passed to extractParams, instead it was " + xml.getNodeName());
389 return null;
390 }
391
392 NodeList params = null;
393 if (deep)
394 { // get all the nested ones
395 params = xml.getElementsByTagName(PARAM_ELEM);
396 }
397 else
398 { // just get the top level ones
399 params = xml.getChildNodes();
400 }
401 HashMap<String, Serializable> param_map = new HashMap<String, Serializable>();
402 for (int i = 0; i < params.getLength(); i++)
403 {
404 if (params.item(i).getNodeName().equals(PARAM_ELEM))
405 {
406 Element param = (Element) params.item(i);
407 String name = param.getAttribute(NAME_ATT);
408 String value = getValue(param); //att or content
409
410 // For only one parameter
411 if (toFind != null && name.equals(toFind))
412 {
413 param_map.put(name, value);
414 return param_map;
415 }
416 else if (toFind != null)
417 continue;
418
419 int pos = name.indexOf('.');
420 if (pos == -1)
421 { // a base param
422 param_map.put(name, value);
423 }
424 else
425 { // a namespaced param
426
427 String namespace = name.substring(0, pos);
428 name = name.substring(pos + 1);
429 HashMap<String, String> map = (HashMap<String, String>) param_map.get(namespace);
430 if (map == null)
431 {
432 map = new HashMap<String, String>();
433 param_map.put(namespace, map);
434 }
435 map.put(name, value);
436 }
437 }
438 }
439 return param_map;
440 }
441
442 /** gets the value att or the text content */
443 public static String getValue(Element e)
444 {
445 String val = e.getAttribute(VALUE_ATT);
446 if (val == null || val.equals(""))
447 {
448 // have to get it out of the text
449 val = getNodeText(e);
450
451 }
452 else
453 {
454 // unescape the xml stuff
455 val = unXmlSafe(val);
456 }
457 return val;
458 }
459
460 /** extracts the text out of a node */
461 public static Node getNodeTextNode(Element param)
462 {
463 param.normalize();
464 Node n = param.getFirstChild();
465 while (n != null && n.getNodeType() != Node.TEXT_NODE)
466 {
467 n = n.getNextSibling();
468 }
469 return n;
470 }
471
472 /** extracts the text out of a node */
473 public static String getNodeText(Element param)
474 {
475 Node text_node = getNodeTextNode(param);
476 if (text_node == null)
477 {
478 return "";
479 }
480 return text_node.getNodeValue();
481 }
482
483 public static void setNodeText(Element elem, String text)
484 {
485 Node old_text_node = getNodeTextNode(elem);
486 if (old_text_node != null)
487 {
488 elem.removeChild(old_text_node);
489 }
490 Text t = elem.getOwnerDocument().createTextNode(text);
491 elem.appendChild(t);
492 }
493
494 /** add text to a document/subsection element */
495 public static boolean addDocText(Element doc, String text)
496 {
497
498 Element content = doc.getOwnerDocument().createElement(NODE_CONTENT_ELEM);
499 Text t = doc.getOwnerDocument().createTextNode(text);
500 content.appendChild(t);
501 doc.appendChild(content);
502 return true;
503 }
504
505 /** add an error message, unknown error type */
506 public static boolean addError(Element doc, String text)
507 {
508 return addError(doc, text, ERROR_TYPE_OTHER);
509 }
510
511 /** add an error message */
512 public static boolean addError(Element doc, String text, String error_type)
513 {
514
515 Element content = doc.getOwnerDocument().createElement(ERROR_ELEM);
516 content.setAttribute(ERROR_TYPE_ATT, error_type);
517 Text t = doc.getOwnerDocument().createTextNode(text);
518 content.appendChild(t);
519 doc.appendChild(content);
520 return true;
521 }
522
523 /** add an error message */
524 public static boolean addError(Element doc, Throwable error)
525 {
526 return addError(doc, error, ERROR_TYPE_OTHER);
527 }
528
529 /** add an error message */
530 public static boolean addError(Element doc, Throwable error, String error_type)
531 {
532 error.printStackTrace();
533 return addError(doc, error.toString(), error_type);
534 }
535
536 public static boolean addGSNamespaces(Element elem, boolean include_extension_ns) {
537 if (elem == null) {
538 return false;
539 }
540 elem.setAttribute("xmlns:gsf", GSF_NAMESPACE);
541 elem.setAttribute("xmlns:xsl", XSL_NAMESPACE);
542 elem.setAttribute("xmlns:gslib", GSLIB_NAMESPACE);
543 if (include_extension_ns) {
544 elem.setAttribute("xmlns:util", UTIL_NAMESPACE);
545 elem.setAttribute("xmlns:java", JAVA_NAMESPACE);
546 }
547 return true;
548 }
549 public static Element createMetadataParamList(Document owner, Vector meta_values)
550 {
551
552 Element meta_param_list = owner.createElement(PARAM_ELEM + LIST_MODIFIER);
553 Iterator i = meta_values.iterator();
554 while (i.hasNext())
555 {
556 String next = (String) i.next();
557 Element meta_param = owner.createElement(PARAM_ELEM);
558 meta_param_list.appendChild(meta_param);
559 meta_param.setAttribute(NAME_ATT, "metadata");
560 meta_param.setAttribute(VALUE_ATT, next);
561 }
562 return meta_param_list;
563 }
564
565 /** adds a metadata elem to a list */
566 public static boolean addMetadata(Element list, String meta_name, String meta_value)
567 {
568 if (meta_value == null || meta_value.equals(""))
569 {
570 return false;
571 }
572 Document owner = list.getOwnerDocument();
573 Element data = owner.createElement(METADATA_ELEM);
574 data.setAttribute(NAME_ATT, meta_name);
575 Text t = owner.createTextNode(meta_value);
576 data.appendChild(t);
577 list.appendChild(data);
578 return true;
579
580 }
581
582 /**
583 * copies the metadata out of the metadataList of 'from' into the
584 * metadataList of 'to'
585 */
586 public static boolean mergeMetadataLists(Node to, Node from) {
587 return mergeSpecifiedLists(to, from, METADATA_ELEM);
588 }
589
590 /** copies metadata from meta_list into the metadataList of to **/
591 public static boolean mergeMetadataFromList(Node to, Node meta_list) {
592 return mergeSpecifiedFromList(to, meta_list, METADATA_ELEM);
593 }
594
595
596 public static boolean mergeSpecifiedLists(Node to, Node from, String element_name) {
597 // find the list in the from element
598 Node from_list = getChildByTagName(from, element_name+LIST_MODIFIER);
599 if (from_list == null) {
600 // nothing to copy
601 return false;
602 }
603
604 return mergeSpecifiedFromList(to, from_list, element_name);
605 }
606 public static boolean mergeSpecifiedFromList(Node to, Node from_list, String element_name) {
607 if (from_list == null) {
608 return false;
609 }
610 Document to_owner = to.getOwnerDocument();
611 Node to_list = getChildByTagName(to, element_name+LIST_MODIFIER);
612 if (to_list == null) {
613 // just copy over the whole list
614 to.appendChild(to_owner.importNode(from_list, true));
615 return true;
616 }
617 // otherwise we copy all the elements
618 NodeList from_items = ((Element) from_list).getElementsByTagName(element_name);
619
620 for (int i = 0; i < from_items.getLength(); i++)
621 {
622 to_list.appendChild(to_owner.importNode(from_items.item(i), true));
623 }
624 return true;
625
626 }
627
628 /** copies all the children from from to to */
629 public static boolean mergeElements(Element to, Element from)
630 {
631
632 Document owner = to.getOwnerDocument();
633 Node child = from.getFirstChild();
634 while (child != null)
635 {
636 to.appendChild(owner.importNode(child, true));
637 child = child.getNextSibling();
638 }
639 return true;
640 }
641
642 /** returns the (first) element child of the node n */
643 public static Element getFirstElementChild(Node n)
644 {
645
646 Node child = n.getFirstChild();
647 while (child != null)
648 {
649 if (child.getNodeType() == Node.ELEMENT_NODE)
650 {
651 return (Element) child;
652 }
653 child = child.getNextSibling();
654 }
655 return null; //no element child found
656 }
657
658 /** returns the (first) child element with the given name */
659 public static Node getChildByTagName(Node n, String name)
660 {
661 if (n != null)
662 { // this line is an attempted solution to the NullPointerException mentioned
663 // in trac bug ticket #225. If n is null can't do n.getFirstChild() below. As per bug #225:
664 // getNodeByPath() is called by GS2BrowseAction, which then calls this method.
665 // If n is null, null will be returned which GS2BrowseAction already checks for. It's here
666 // that the NullPointerException was thrown.
667
668 Node child = n.getFirstChild();
669 while (child != null)
670 {
671 if (child.getNodeName().equals(name))
672 {
673 return child;
674 }
675 child = child.getNextSibling();
676 }
677 }
678 return null; //not found
679 }
680
681 /**
682 * returns the (nth) child element with the given name index numbers start
683 * at 0
684 */
685 public static Node getChildByTagNameIndexed(Node n, String name, int index)
686 {
687 if (index == -1)
688 {
689 return getChildByTagName(n, name);
690 }
691 int count = 0;
692 Node child = n.getFirstChild();
693 while (child != null)
694 {
695 if (child.getNodeName().equals(name))
696 {
697 if (count == index)
698 {
699 return child;
700 }
701 else
702 {
703 count++;
704 }
705 }
706 child = child.getNextSibling();
707 }
708 return null; //not found
709 }
710
711 /**
712 * takes an xpath type expression of the form name/name/... and returns the
713 * first node that matches, or null if not found
714 */
715 public static Node getNodeByPath(Node n, String path)
716 {
717
718 String link = GSPath.getFirstLink(path);
719 path = GSPath.removeFirstLink(path);
720 while (!link.equals(""))
721 {
722 n = getChildByTagName(n, link);
723 if (n == null)
724 {
725 return null;
726 }
727 link = GSPath.getFirstLink(path);
728 path = GSPath.removeFirstLink(path);
729 }
730 return n;
731 }
732
733 /**
734 * takes an xpath type expression of the form name/name/... and returns the
735 * first node that matches, or null if not found can include [i] indices.
736 * index numbers start at 0
737 */
738 public static Node getNodeByPathIndexed(Node n, String path)
739 {
740
741 String link = GSPath.getFirstLink(path);
742 int index = GSPath.getIndex(link);
743 if (index != -1)
744 {
745 link = GSPath.removeIndex(link);
746 }
747 path = GSPath.removeFirstLink(path);
748 while (!link.equals(""))
749 {
750 n = getChildByTagNameIndexed(n, link, index);
751 if (n == null)
752 {
753 return null;
754 }
755 link = GSPath.getFirstLink(path);
756 index = GSPath.getIndex(link);
757 if (index != -1)
758 {
759 link = GSPath.removeIndex(link);
760 }
761 path = GSPath.removeFirstLink(path);
762 }
763 return n;
764 }
765
766 public static HashMap<String, Node> getChildrenMap(Node n)
767 {
768
769 HashMap<String, Node> map = new HashMap<String, Node>();
770 Node child = n.getFirstChild();
771 while (child != null)
772 {
773 String name = child.getNodeName();
774 map.put(name, child);
775 child = child.getNextSibling();
776 }
777 return map;
778 }
779
780 public static NodeList getChildrenByTagName(Node n, String name)
781 {
782 MyNodeList node_list = new MyNodeList();
783 Node child = n.getFirstChild();
784 while (child != null)
785 {
786 if (child.getNodeName().equals(name))
787 {
788 node_list.addNode(child);
789 }
790 child = child.getNextSibling();
791 }
792 return node_list;
793 }
794
795 public static NodeList getChildrenByTagNameNS(Node n, String namespace, String local_name)
796 {
797 MyNodeList node_list = new MyNodeList();
798 Node child = n.getFirstChild();
799 while (child != null)
800 {
801 if (child.getNodeType() == Node.ELEMENT_NODE && child.getNamespaceURI() != null && child.getNamespaceURI().equals(namespace) && child.getLocalName() != null && child.getLocalName().equals(local_name))
802 {
803 node_list.addNode(child);
804 }
805 child = child.getNextSibling();
806 }
807 return node_list;
808 }
809
810 /** Duplicates an element, but gives it a new name */
811 public static Element duplicateWithNewName(Document owner, Element element, String element_name, boolean with_attributes)
812 {
813 return duplicateWithNewNameNS(owner, element, element_name, null, with_attributes);
814 }
815
816 /** Duplicates an element, but gives it a new name */
817 public static Element duplicateWithNewNameNS(Document owner, Element element, String element_name, String namespace_uri, boolean with_attributes)
818 {
819 Element duplicate;
820 if (namespace_uri == null)
821 {
822 duplicate = owner.createElement(element_name);
823 }
824 else
825 {
826 duplicate = owner.createElementNS(namespace_uri, element_name);
827 }
828
829 // Copy element attributes
830 if (with_attributes)
831 {
832 NamedNodeMap attributes = element.getAttributes();
833 for (int i = 0; i < attributes.getLength(); i++)
834 {
835 Node attribute = attributes.item(i);
836 duplicate.setAttribute(attribute.getNodeName(), attribute.getNodeValue());
837 }
838 }
839
840 // Copy element children
841 NodeList children = element.getChildNodes();
842 for (int i = 0; i < children.getLength(); i++)
843 {
844 Node child = children.item(i);
845 duplicate.appendChild(owner.importNode(child, true));
846 }
847
848 return duplicate;
849 }
850
851 public static void copyAllChildren(Element to, Element from)
852 {
853
854 Document to_doc = to.getOwnerDocument();
855 Node child = from.getFirstChild();
856 while (child != null)
857 {
858 to.appendChild(to_doc.importNode(child, true));
859 child = child.getNextSibling();
860 }
861 }
862
863 public static void copyNode(Element to_elem, Node original_element) {
864 to_elem.appendChild(to_elem.getOwnerDocument().importNode(original_element, true));
865
866 }
867
868 public static void copyNamedElement(Element to, Element from, String elem_name) {
869
870 Document to_doc = to.getOwnerDocument();
871 Node child = from.getFirstChild();
872 while (child != null) {
873 if (child.getNodeName().equals(elem_name)) {
874 to.appendChild(to_doc.importNode(child, true));
875 return;
876 }
877 child = child.getNextSibling();
878 }
879 }
880
881 /* Have an element with a set of children, attributes name="x". Replace the specified item in the list with new_item. */
882 /* 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 */
883 public static void replaceNamedItemInList(Element item_list, String item_node_name, String name_att, String item_name, Element new_item) {
884 Node child = item_list.getFirstChild();
885 while(child != null) {
886 if (child.getNodeName().equals(item_node_name) && ((Element)child).getAttribute(name_att).equals(item_name)) {
887 //replace the element
888 item_list.insertBefore(item_list.getOwnerDocument().importNode(new_item, true), child);
889 item_list.removeChild(child);
890 return;
891 }
892 child = child.getNextSibling();
893 }
894
895 }
896 /**
897 * Given a Node representing an Element or Document, will return the
898 * Element/docroot Element. Returns null if the Node was not an element.
899 */
900 public static Element nodeToElement(Node node)
901 {
902 if (node == null)
903 {
904 return null;
905 }
906 short nodeType = node.getNodeType();
907
908 if (nodeType == Node.DOCUMENT_NODE)
909 {
910 Document docNode = (Document) node;
911 return docNode.getDocumentElement();
912 }
913 else if (nodeType == Node.ELEMENT_NODE)
914 {
915 return (Element) node;
916 }
917 else
918 {
919 String message = "Expecting Document or Element node type but got " + node.getNodeName() + "\nReturning null";
920 System.err.println(message);
921 logger.warn(message);
922 return null;
923 }
924 }
925
926
927 /** returns a basic request message */
928 public static Element createBasicRequest(Document owner, String request_type, String to, UserContext userContext)
929 {
930 Element request = owner.createElement(REQUEST_ELEM);
931 request.setAttribute(TO_ATT, to);
932 request.setAttribute(TYPE_ATT, request_type);
933 if (userContext == null) {
934 return request; // should we allow this??
935 }
936 request.setAttribute(LANG_ATT, userContext.getLanguage());
937 Element userContextElem = owner.createElement("userContext");
938 request.appendChild(userContextElem);
939 userContextElem.setAttribute(LANG_ATT, userContext.getLanguage());
940 userContextElem.setAttribute(USERNAME_ATT, userContext.getUsername());
941 userContextElem.setAttribute(USER_ID_ATT, userContext.getUserID());
942 userContextElem.setAttribute(GROUPS_ATT, userContext.getGroupsString());
943 userContextElem.setAttribute(EDIT_ENABLED_ATT, userContext.getEditEnabled());
944
945 return request;
946 }
947
948 public static Element createBasicResponse(Document owner, String from)
949 {
950 Element response = owner.createElement(RESPONSE_ELEM);
951 response.setAttribute(FROM_ATT, from);
952 response.setAttribute(TYPE_ATT, REQUEST_TYPE_PROCESS);
953 return response;
954 }
955
956 public static Element createMetadataElement(Document owner, String name, String value)
957 {
958 Element metaElem = owner.createElement(METADATA_ELEM);
959 metaElem.setAttribute(NAME_ATT, name);
960 metaElem.setAttribute(VALUE_ATT, value);
961 return metaElem;
962 }
963
964 public static Element createTextElement(Document owner, String elem_name, String text)
965 {
966 Element e = owner.createElement(elem_name);
967 Text t = owner.createTextNode(text);
968 e.appendChild(t);
969 return e;
970
971 }
972
973 public static Element createTextElement(Document owner, String elem_name, String text, String att_name, String att_value)
974 {
975 Element e = owner.createElement(elem_name);
976 e.setAttribute(att_name, att_value);
977 Text t = owner.createTextNode(text);
978 e.appendChild(t);
979 return e;
980
981 }
982
983 public static Element createDisplayTextElement(Document owner, String text_name, String text)
984 {
985 Element e = owner.createElement(DISPLAY_TEXT_ELEM);
986 e.setAttribute(NAME_ATT, text_name);
987 Text t = owner.createTextNode(text);
988 e.appendChild(t);
989 return e;
990
991 }
992
993 // for parameters where value is an attribute
994 public static Element createParameter(Document owner, String name, String value)
995 {
996 Element param = owner.createElement(PARAM_ELEM);
997 param.setAttribute(NAME_ATT, name);
998 param.setAttribute(VALUE_ATT, value);
999 return param;
1000 }
1001
1002 // for parameters where value is a text node
1003 public static Element createParameter2(Document owner, String name, String value) {
1004 Element param = owner.createElement(PARAM_ELEM);
1005 param.setAttribute(NAME_ATT, name);
1006 param.appendChild(owner.createTextNode(value));
1007 return param;
1008 }
1009
1010 public static void addParameterToList(Element param_list, String name, String value) {
1011 Element p = createParameter(param_list.getOwnerDocument(), name, value);
1012 param_list.appendChild(p);
1013 }
1014 public static void addParameter2ToList(Element param_list, String name, String value) {
1015 Element p = createParameter2(param_list.getOwnerDocument(), name, value);
1016 param_list.appendChild(p);
1017 }
1018 public static void addParametersToList(Element param_list, HashMap params)
1019 {
1020 if (params == null)
1021 {
1022 return;
1023 }
1024
1025 Set items = params.entrySet();
1026 Iterator i = items.iterator();
1027 Document owner = param_list.getOwnerDocument();
1028 while (i.hasNext())
1029 {
1030 Map.Entry m = (Map.Entry) i.next();
1031 param_list.appendChild(createParameter(owner, (String) m.getKey(), (String) m.getValue()));
1032 }
1033
1034 }
1035
1036 public static Element createParameterDescription(Document owner, String id, String display_name, String type, String default_value, String[] option_ids, String[] option_names)
1037 {
1038
1039 Element p = owner.createElement(PARAM_ELEM);
1040 p.setAttribute(NAME_ATT, id);
1041 p.setAttribute(TYPE_ATT, type);
1042 p.appendChild(createDisplayTextElement(owner, DISPLAY_TEXT_NAME, display_name));
1043
1044 if (default_value != null)
1045 {
1046 p.setAttribute(DEFAULT_ATT, default_value);
1047 }
1048 if (option_ids != null && option_names != null)
1049 {
1050 for (int i = 0; i < option_ids.length; i++)
1051 {
1052 Element e = owner.createElement(PARAM_OPTION_ELEM);
1053 e.setAttribute(NAME_ATT, option_ids[i]);
1054 e.appendChild(createDisplayTextElement(owner, DISPLAY_TEXT_NAME, option_names[i]));
1055 p.appendChild(e);
1056 }
1057 }
1058 return p;
1059 }
1060
1061 public static Element createParameterDescription2(Document owner, String id, String display_name, String type, String default_value, ArrayList<String> option_ids, ArrayList<String> option_names)
1062 {
1063
1064 Element p = owner.createElement(PARAM_ELEM);
1065 p.setAttribute(NAME_ATT, id);
1066 p.setAttribute(TYPE_ATT, type);
1067 p.appendChild(createDisplayTextElement(owner, DISPLAY_TEXT_NAME, display_name));
1068 if (default_value != null)
1069 {
1070 p.setAttribute(DEFAULT_ATT, default_value);
1071 }
1072 if (option_ids != null && option_names != null)
1073 {
1074 for (int i = 0; i < option_ids.size(); i++)
1075 {
1076 Element e = owner.createElement(PARAM_OPTION_ELEM);
1077 e.setAttribute(NAME_ATT, option_ids.get(i));
1078 e.appendChild(createDisplayTextElement(owner, DISPLAY_TEXT_NAME, option_names.get(i)));
1079 p.appendChild(e);
1080 }
1081 }
1082 return p;
1083 }
1084
1085 /** returns the element parent/node_name[@attribute_name='attribute_value']
1086 if attribute_value is null, just returns the first one with that attribute */
1087 public static Element getNamedElement(Element parent, String node_name, String attribute_name, String attribute_value)
1088 {
1089
1090 NodeList children = parent.getChildNodes();
1091 for (int i = 0; i < children.getLength(); i++)
1092 {
1093 Node child = children.item(i);
1094 if (child.getNodeName().equals(node_name))
1095 {
1096 String att_val = ((Element) child).getAttribute(attribute_name);
1097 if (!att_val.equals("") ) {
1098 if (attribute_value == null || att_val.equals(attribute_value)) {
1099 return (Element) child;
1100 }
1101 }
1102 }
1103 } // for each child
1104 // not found
1105 return null;
1106 }
1107
1108 public static Element getNamedElementNS(Element parent, String namespace_uri, String node_local_name, String attribute_name, String attribute_value)
1109 {
1110 NodeList children = parent.getChildNodes();
1111 for (int i = 0; i < children.getLength(); i++)
1112 {
1113 Node child = children.item(i);
1114 if (child.getNodeType() == Node.ELEMENT_NODE && child.getNamespaceURI() != null && child.getNamespaceURI().equals(namespace_uri) && child.getLocalName().equals(node_local_name))
1115 {
1116 if (((Element) child).getAttribute(attribute_name).equals(attribute_value))
1117 return (Element) child;
1118 }
1119 }
1120 // not found
1121 return null;
1122 }
1123
1124 public static NodeList getNamedElementsNS(Element parent, String namespace_uri, String node_local_name, String attribute_name, String attribute_value)
1125 {
1126 MyNodeList result = new MyNodeList();
1127 NodeList children = parent.getChildNodes();
1128 for (int i = 0; i < children.getLength(); i++)
1129 {
1130 Node child = children.item(i);
1131 if (child.getNodeType() == Node.ELEMENT_NODE && child.getNamespaceURI() != null && child.getNamespaceURI().equals(namespace_uri) && child.getLocalName().equals(node_local_name))
1132 {
1133 if (((Element) child).getAttribute(attribute_name).equals(attribute_value))
1134 result.addNode(child);
1135 }
1136 }
1137 return result;
1138 }
1139
1140 public static NodeList getElementsWithAttributesNS(Element parent, String namespace_uri, String node_local_name, String[] attribute_names, String[] attribute_values)
1141 {
1142 if (attribute_names.length == 0 || attribute_names.length != attribute_values.length)
1143 {
1144 return new MyNodeList();
1145 }
1146
1147 MyNodeList result = new MyNodeList();
1148
1149 NodeList matchingNodes = getNamedElementsNS(parent, namespace_uri, node_local_name, attribute_names[0], attribute_values[0]);
1150 for (int i = 0; i < matchingNodes.getLength(); i++)
1151 {
1152 Element current = (Element) matchingNodes.item(i);
1153 boolean nodeMatches = true;
1154 for (int j = 1; j < attribute_names.length; j++)
1155 {
1156 String currentName = attribute_names[j];
1157 String currentValue = attribute_values[j];
1158 if (!current.getAttribute(currentName).equals(currentValue))
1159 {
1160 nodeMatches = false;
1161 break;
1162 }
1163 }
1164
1165 if (nodeMatches)
1166 {
1167 result.addNode(current);
1168 }
1169 }
1170
1171 return result;
1172 }
1173
1174 public static void removeElementsWithAttributesNS(Element parent, String namespace_uri, String node_local_name, String[] attribute_names, String[] attribute_values)
1175 {
1176 NodeList matchingNodes = getElementsWithAttributesNS(parent, namespace_uri, node_local_name, attribute_names, attribute_values);
1177 for (int i = 0; i < matchingNodes.getLength(); i++)
1178 {
1179 parent.removeChild(matchingNodes.item(i));
1180 }
1181 }
1182
1183 // In element main, tries to find any previous occurrence of elements with xsl-template-name=templateName,
1184 // and whose named attribute (attributeName) has the same value as the same attribute in node.
1185 // If this is the case, such a previous occurrence is removed from element main, since
1186 // the new node will contain a more specific redefinition of this element.
1187 public static void removeNamedElementNS(Element parent, String namespace_uri, String node_local_name, String attribute_name, String attribute_value)
1188 {
1189 if (attribute_value.equals(""))
1190 {
1191 // it has no identifying attribute, so we can't find any matches
1192 return;
1193 }
1194
1195 Element old_elem = getNamedElementNS(parent, namespace_uri, node_local_name, attribute_name, attribute_value);
1196 if (old_elem != null)
1197 {
1198 parent.removeChild(old_elem);
1199 }
1200 }
1201
1202 public static void removeNamedElementsNS(Element parent, String namespace, String node_local_name, String attribute_name, String attribute_value)
1203 {
1204 if (attribute_value.equals(""))
1205 {
1206 // it has no identifying attribute, so we can't find any matches
1207 return;
1208 }
1209
1210 NodeList children = parent.getChildNodes();
1211 for (int i = children.getLength() - 1; i >= 0; i--)
1212 {
1213 Node child = children.item(i);
1214 if (child.getNodeType() == Node.ELEMENT_NODE && child.getNamespaceURI() != null && child.getNamespaceURI().equals(namespace) && child.getLocalName() != null && child.getLocalName().equals(node_local_name))
1215 {
1216 if (((Element) child).getAttribute(attribute_name).equals(attribute_value))
1217 parent.removeChild(child);
1218 }
1219 }
1220 }
1221
1222 /**
1223 * returns a NodeList of elements:
1224 * ancestor/node_name[@attribute_name='attribute_value']
1225 */
1226 public static NodeList getNamedElements(Element ancestor, String node_name, String attribute_name, String attribute_value)
1227 {
1228 MyNodeList node_list = new MyNodeList();
1229 NodeList children = ancestor.getElementsByTagName(node_name);
1230
1231 if (children != null && children.getLength() > 0)
1232 {
1233
1234 for (int i = 0; i < children.getLength(); i++)
1235 {
1236 Node child = children.item(i);
1237 if (child.getNodeName().equals(node_name))
1238 {
1239 if (((Element) child).getAttribute(attribute_name).equals(attribute_value))
1240 node_list.addNode(child);
1241 }
1242 }
1243 }
1244 return node_list;
1245 }
1246
1247 public static Element getLastElementByTagNameNS(Element main, String namespace, String node_name)
1248 {
1249 NodeList nodes = main.getElementsByTagNameNS(namespace, node_name);
1250 int len = nodes.getLength();
1251 if (len == 0)
1252 {
1253 return null;
1254 }
1255 return (Element) nodes.item(len - 1);
1256 }
1257
1258 public static int SORT_TYPE_STRING = 0;
1259 public static int SORT_TYPE_INT = 1;
1260 public static int SORT_TYPE_FLOAT = 2;
1261
1262 // sort type:
1263 public static Element insertIntoOrderedList(Element parent_node, String node_name, Element start_from_elem, Element new_elem, String sort_att, boolean descending)
1264 {
1265 if (new_elem == null)
1266 return null;
1267 Element cloned_elem = (Element) parent_node.getOwnerDocument().importNode(new_elem, true);
1268 if (start_from_elem == null)
1269 {
1270 parent_node.appendChild(cloned_elem);
1271 return cloned_elem;
1272 }
1273
1274 Node current_node = start_from_elem;
1275 String insert_att = cloned_elem.getAttribute(sort_att);
1276 String list_att = start_from_elem.getAttribute(sort_att);
1277 while ((!descending && list_att.compareTo(insert_att) < 0) || (descending && list_att.compareTo(insert_att) > 0))
1278 {
1279 current_node = current_node.getNextSibling();
1280 if (current_node == null)
1281 break; // end of the list
1282 if (!current_node.getNodeName().equals(node_name))
1283 {
1284 continue; // not a valid node
1285 }
1286 list_att = ((Element) current_node).getAttribute(sort_att);
1287 }
1288
1289 parent_node.insertBefore(cloned_elem, current_node);
1290 return cloned_elem;
1291 }
1292
1293 public static String getMetadataValue(Element metadata_list, String name) {
1294 Element meta = getNamedElement(metadata_list, METADATA_ELEM, NAME_ATT, name);
1295 if (meta == null) {
1296 return "";
1297 }
1298 String att_value = meta.getAttribute(VALUE_ATT);
1299 if (att_value.equals("")) {
1300 // try the text
1301 att_value = getNodeText(meta);
1302 }
1303 return att_value;
1304 }
1305
1306 // replaces < > " ' & in the original with their entities
1307 public static String xmlSafe(String original)
1308 {
1309
1310 StringBuffer filtered = new StringBuffer(original.length());
1311 char c;
1312 for (int i = 0; i < original.length(); i++)
1313 {
1314 c = original.charAt(i);
1315 if (c == '>')
1316 {
1317 filtered.append("&gt;");
1318 }
1319 else if (c == '<')
1320 {
1321 filtered.append("&lt;");
1322 }
1323 else if (c == '"')
1324 {
1325 filtered.append("&quot;");
1326 }
1327 else if (c == '&')
1328 {
1329 filtered.append("&amp;");
1330 }
1331 else if (c == '\'')
1332 {
1333 filtered.append("&apos;");
1334 }
1335 else
1336 {
1337 filtered.append(c);
1338 }
1339 }
1340 return filtered.toString();
1341 }
1342
1343 // replaces < > " ' & entities with their originals
1344 public static String unXmlSafe(String original)
1345 {
1346
1347 StringBuffer filtered = new StringBuffer(original.length());
1348 char c;
1349 for (int i = 0; i < original.length(); i++)
1350 {
1351 c = original.charAt(i);
1352 if (c == '&')
1353 {
1354 int pos = original.indexOf(";", i);
1355 String entity = original.substring(i + 1, pos);
1356 if (entity.equals("gt"))
1357 {
1358 filtered.append(">");
1359 }
1360 else if (entity.equals("lt"))
1361 {
1362 filtered.append("<");
1363 }
1364 else if (entity.equals("apos"))
1365 {
1366 filtered.append("'");
1367 }
1368 else if (entity.equals("amp"))
1369 {
1370 filtered.append("&");
1371 }
1372 else if (entity.equals("quot"))
1373 {
1374 filtered.append("\"");
1375 }
1376 else
1377 {
1378 filtered.append("&" + entity + ";");
1379 }
1380 i = pos;
1381 }
1382 else
1383 {
1384 filtered.append(c);
1385 }
1386 }
1387 return filtered.toString();
1388 }
1389
1390 public static void printXMLNode(Node e, boolean printText)
1391 {
1392 printXMLNode(e, 0, printText);
1393 }
1394
1395 public static String xmlNodeToString(Node e)
1396 {
1397 StringBuffer sb = new StringBuffer("");
1398 xmlNodeToString(sb, e, true, "\t", 0);
1399 return sb.toString();
1400 }
1401
1402 public static void xmlNodeToString(StringBuffer sb, Node e, boolean indent, String indentString, int depth)
1403 {
1404 if (e.getNodeType() == Node.TEXT_NODE)
1405 {
1406 if (e.getNodeValue() != "")
1407 {
1408 String text = e.getNodeValue();
1409 if (text != null)
1410 {
1411 text = text.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("^[\\n\\r\\t\\s]*", "").replaceAll("[\\n\\r\\t\\s]*$", "");
1412 sb.append(text);
1413 }
1414 }
1415 return;
1416 }
1417
1418 if (e.getNodeType() == Node.COMMENT_NODE)
1419 {
1420 if (e.getNodeValue() != "")
1421 {
1422 sb.append("<!--" + e.getNodeValue() + "-->");
1423 }
1424 return;
1425 }
1426
1427 if (indent)
1428 {
1429 for (int i = 0; i < depth; i++)
1430 {
1431 sb.append(indentString);
1432 }
1433 }
1434
1435 sb.append('<');
1436 sb.append(e.getNodeName());
1437 NamedNodeMap attrs = e.getAttributes();
1438 if (attrs != null)
1439 {
1440 for (int i = 0; i < attrs.getLength(); i++)
1441 {
1442 Node attr = attrs.item(i);
1443 sb.append(' ');
1444 sb.append(attr.getNodeName());
1445 sb.append("=\"");
1446 sb.append(attr.getNodeValue().replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;"));
1447 sb.append('"');
1448 }
1449 }
1450
1451 if (e.hasChildNodes())
1452 {
1453 boolean hasElements = false;
1454 boolean indentSwapped = false;
1455
1456 Node child = e.getFirstChild();
1457 do
1458 {
1459 if (child.getNodeType() == Node.ELEMENT_NODE)
1460 {
1461 hasElements = true;
1462 }
1463 if (child.getNodeType() == Node.TEXT_NODE && indent)
1464 {
1465 if (child.getNodeValue() != null && child.getNodeValue().trim().length() > 0)
1466 {
1467 indentSwapped = true;
1468 indent = false;
1469 }
1470 }
1471 } while ((child = child.getNextSibling()) != null);
1472
1473 sb.append(">");
1474 if (hasElements && indent)
1475 {
1476 sb.append("\n");
1477 }
1478
1479 child = e.getFirstChild();
1480 do
1481 {
1482 xmlNodeToString(sb, child, indent, indentString, depth + 1);
1483 } while ((child = child.getNextSibling()) != null);
1484
1485 if (indent)
1486 {
1487 for (int i = 0; i < depth; i++)
1488 {
1489 sb.append(indentString);
1490 }
1491 }
1492
1493 sb.append("</" + e.getNodeName() + ">");
1494
1495 if ((hasElements && indent) || indentSwapped)
1496 {
1497 sb.append("\n");
1498 }
1499 }
1500 else
1501 {
1502 sb.append("/>");
1503
1504 if (indent)
1505 {
1506 sb.append("\n");
1507 }
1508 }
1509
1510 /*
1511 boolean hasElements = false;
1512 boolean indentSwapped = false;
1513 for (int i = 0; i < children.getLength(); i++)
1514 {
1515 if (children.item(i).getNodeType() == Node.ELEMENT_NODE)
1516 {
1517 hasElements = true;
1518 }
1519 if (children.item(i).getNodeType() == Node.TEXT_NODE && indent)
1520 {
1521 if (children.item(i).getNodeValue() != null && children.item(i).getNodeValue().trim().length() > 0)
1522 {
1523 indentSwapped = true;
1524 indent = false;
1525 }
1526 }
1527 }
1528
1529 if (children == null || children.getLength() == 0)
1530 {
1531 sb.append("/>");
1532
1533 if (indent)
1534 {
1535 sb.append("\n");
1536 }
1537 }
1538 else
1539 {
1540 sb.append(">");
1541 if (hasElements && indent)
1542 {
1543 sb.append("\n");
1544 }
1545
1546 int len = children.getLength();
1547 for (int i = 0; i < len; i++)
1548 {
1549 xmlNodeToString(sb, children.item(i), indent, indentString, depth + 1);
1550 }
1551
1552 if (indent)
1553 {
1554 for (int i = 0; i < depth; i++)
1555 {
1556 sb.append(indentString);
1557 }
1558 }
1559
1560 sb.append("</" + e.getNodeName() + ">");
1561
1562 if ((hasElements && indent) || indentSwapped)
1563 {
1564 sb.append("\n");
1565 }
1566 }
1567 */
1568 }
1569
1570 public static void printXMLNode(Node e, int depth, boolean printText)
1571 { //recursive method call using DOM API...
1572
1573 if (e == null)
1574 {
1575 return;
1576 }
1577
1578 for (int i = 0; i < depth; i++)
1579 System.out.print(' ');
1580
1581 if (e.getNodeType() == Node.TEXT_NODE)
1582 {
1583 if (printText)
1584 {
1585 System.out.println(e.getNodeValue());
1586 }
1587 else
1588 {
1589 System.out.println("text");
1590 }
1591 return;
1592 }
1593
1594 System.out.print('<');
1595 System.out.print(e.getNodeName());
1596 NamedNodeMap attrs = e.getAttributes();
1597
1598 if (attrs != null)
1599 {
1600 for (int i = 0; i < attrs.getLength(); i++)
1601 {
1602 Node attr = attrs.item(i);
1603 System.out.print(' ');
1604 System.out.print(attr.getNodeName());
1605 System.out.print("=\"");
1606 System.out.print(attr.getNodeValue());
1607 System.out.print('"');
1608 }
1609 }
1610
1611 NodeList children = e.getChildNodes();
1612
1613 if (children == null || children.getLength() == 0)
1614 System.out.println("/>");
1615 else
1616 {
1617
1618 System.out.println('>');
1619
1620 int len = children.getLength();
1621 for (int i = 0; i < len; i++)
1622 {
1623 printXMLNode(children.item(i), depth + 1, printText);
1624 }
1625
1626 for (int i = 0; i < depth; i++)
1627 System.out.print(' ');
1628
1629 System.out.println("</" + e.getNodeName() + ">");
1630 }
1631 }
1632
1633 private static void elementToLogAsString(String prefix, Element e, boolean indent, boolean debugEncoding)
1634 {
1635 String str = prefix + "\n" + elementToString(e, indent, debugEncoding);
1636 System.err.println(str);
1637 logger.info(str);
1638 }
1639
1640 // hex/unicode codepoint used only for those chars that are beyond printable/basic ASCII
1641 public static void elementToLogAsUnicodeDebugString(String prefix, Element e, boolean indent)
1642 {
1643 elementToLogAsString(prefix, e, indent, true);
1644 }
1645
1646 public static void elementToLogAsString(String prefix, Element e, boolean indent)
1647 {
1648 elementToLogAsString(prefix, e, indent, false);
1649 }
1650
1651 // pass in debugEncoding=true to investigate encoding issues. This function will then return non-basic ASCII characters in hex
1652 private static String elementToString(Element e, boolean indent, boolean debugEncoding)
1653 {
1654 String str = "";
1655 try
1656 {
1657 TransformerFactory tf = TransformerFactory.newInstance();
1658 Transformer trans = tf.newTransformer();
1659 StringWriter sw = new StringWriter();
1660 if (indent)
1661 {
1662 trans.setOutputProperty(OutputKeys.INDENT, "yes");
1663 }
1664 else
1665 {
1666 trans.setOutputProperty(OutputKeys.INDENT, "no");
1667 }
1668 trans.transform(new DOMSource(e), new StreamResult(sw));
1669 str += sw.toString();
1670
1671 // if debugging encoding issues, then encode unicode code pts as hex for all but non-alphanumeric and space/tab/newline chars
1672 if(debugEncoding) str = Misc.debugUnicodeString(str);
1673 }
1674 catch (Exception ex)
1675 {
1676 str += "Exception: couldn't write " + e + " to log";
1677 }
1678 finally
1679 {
1680 return str;
1681 }
1682 }
1683
1684 public static String elementToString(Element e, boolean indent)
1685 {
1686 return elementToString(e, indent, false);
1687 }
1688
1689 // hex/unicode codepoint used only for those chars that are beyond printable/basic ASCII
1690 public static String elementToUnicodeDebugString(Element e, boolean indent)
1691 {
1692 return elementToString(e, indent, true);
1693 }
1694
1695 public static ArrayList<String> getGroupsFromSecurityResponse(Element securityResponse)
1696 {
1697 ArrayList<String> groups = new ArrayList<String>();
1698
1699 Element groupList = (Element) getChildByTagName(securityResponse, GROUP_ELEM + LIST_MODIFIER);
1700 if (groupList == null)
1701 {
1702 return groups;
1703 }
1704
1705 NodeList groupElems = getChildrenByTagName(groupList, GROUP_ELEM);
1706
1707 for (int i = 0; i < groupElems.getLength(); i++)
1708 {
1709 Element groupElem = (Element) groupElems.item(i);
1710 // an empty attribute will return "". some code depends on having "" for groups, so leave it in for now.
1711 groups.add(groupElem.getAttribute(NAME_ATT));
1712 }
1713
1714 return groups;
1715 }
1716
1717}
Note: See TracBrowser for help on using the repository browser.