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

Last change on this file since 33177 was 33177, checked in by kjdon, 5 years ago

adding some more string constants

  • Property svn:keywords set to Author Date Id Revision
File size: 52.4 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 public static final String USER_SESSION_CACHE_ATT = "user_session_cache";
194
195 // classifier stuff
196 public static final String CLASS_NODE_ELEM = "classifierNode";
197 public static final String CLASS_NODE_ORIENTATION_ATT = "orientation";
198
199 // parameter types
200 public static final String PARAM_TYPE_INTEGER = "integer";
201 public static final String PARAM_TYPE_BOOLEAN = "boolean";
202 public static final String PARAM_TYPE_ENUM_START = "enum";
203 public static final String PARAM_TYPE_ENUM_SINGLE = "enum_single";
204 public static final String PARAM_TYPE_ENUM_MULTI = "enum_multi";
205 public static final String PARAM_TYPE_STRING = "string";
206 public static final String PARAM_TYPE_TEXT = "text";
207 public static final String PARAM_TYPE_MULTI = "multi";
208 public static final String PARAM_TYPE_FILE = "file";
209 public static final String PARAM_TYPE_INVISIBLE = "invisible";
210 public static final String PARAM_TYPE_CHECKBOX_LIST = "checkbox_list";
211 // stuff for text strings
212 public static final String DISPLAY_TEXT_ELEM = "displayItem";
213 // the following are used for the name attributes
214 public static final String DISPLAY_TEXT_NAME = "name";
215 public static final String DISPLAY_TEXT_SUBMIT = "submit";
216 public static final String DISPLAY_TEXT_DESCRIPTION = "description";
217
218 // request types
219 // get the module description
220 public static final String REQUEST_TYPE_DESCRIBE = "describe";
221 // startup a process
222 public static final String REQUEST_TYPE_PROCESS = "process";
223 // get the status of an ongoing process
224 public static final String REQUEST_TYPE_STATUS = "status";
225 // system type request - eg reload a collection
226 public static final String REQUEST_TYPE_SYSTEM = "system";
227 // page requests to the Receptionist/Actions
228 public static final String REQUEST_TYPE_PAGE = "page"; // used to be cgi
229 // get any format info for a service
230 public static final String REQUEST_TYPE_FORMAT = "format";
231 // modify the requests
232 public static final String REQUEST_TYPE_MESSAGING = "messaging";
233 // save the format string
234 public static final String REQUEST_TYPE_FORMAT_STRING = "formatString";
235 // check credentials
236 public static final String REQUEST_TYPE_SECURITY = "security";
237
238 // service types
239 public static final String SERVICE_TYPE_QUERY = "query";
240 public static final String SERVICE_TYPE_RETRIEVE = "retrieve";
241 public static final String SERVICE_TYPE_BROWSE = "browse";
242 public static final String SERVICE_TYPE_GROUPINFO = "groupinfo";
243 public static final String SERVICE_TYPE_APPLET = "applet";
244 public static final String SERVICE_TYPE_PROCESS = "process";
245 public static final String SERVICE_TYPE_ENRICH = "enrich";
246 public static final String SERVICE_TYPE_OAI = "oai";
247 public static final String FLAX_PAGE = "flaxPage";
248 public static final String FLAX_PAGE_GENERATION = "FlaxPageGeneration";
249
250 // system command types and attributes
251 public static final String SYSTEM_TYPE_CONFIGURE = "configure";
252 public static final String SYSTEM_TYPE_ACTIVATE = "activate";
253 public static final String SYSTEM_TYPE_DEACTIVATE = "deactivate";
254 public static final String SYSTEM_TYPE_PING = "ping";
255 public static final String SYSTEM_TYPE_AUTHENTICATED_PING = "authenticated-ping";
256 //public static final String SYSTEM_TYPE_ISPERSISTENT = "is-persistent";
257
258 public static final String SYSTEM_SUBSET_ATT = "subset";
259 public static final String SYSTEM_MODULE_TYPE_ATT = "moduleType";
260 public static final String SYSTEM_MODULE_NAME_ATT = "moduleName";
261
262 // communicator types
263 public static final String COMM_TYPE_SOAP_JAVA = "soap";
264
265 // error types
266 public static final String ERROR_TYPE_SYNTAX = "syntax";
267 public static final String ERROR_TYPE_SYSTEM = "system";
268 public static final String ERROR_TYPE_INVALID_ID = "invalid_id";
269 public static final String ERROR_TYPE_OTHER = "other";
270
271 // some system wide param names
272 public static final String SUBSET_PARAM = "subset";
273
274 //for plugin
275 public static final String PLUGIN_ELEM = "plugin";
276 public static final String IMPORT_ELEM = "import";
277
278 //for authentication
279 public static final String AUTHEN_NODE_ELEM = "authenticationNode";
280 public static final String USER_NODE_ELEM = "userNode";
281
282 //for configure action results
283 public static final String SUCCESS = "success";
284 public static final String ERROR = "error";
285
286 //security tags and attributes
287 public static final String SECURITY_ELEM = "security";
288 public static final String DISABLED_ATT = "disabled";
289 public static final String SCOPE_ATT = "scope";
290 public static final String SCOPE_COLLECTION = "collection";
291 public static final String SCOPE_DOCUMENT = "document";
292 public static final String DEFAULT_ACCESS_ATT = "default_access";
293 public static final String ACCESS_PUBLIC = "public";
294 public static final String ACCESS_PRIVATE = "private";
295 public static final String VERIFY_ATT = "humanVerify";
296 public static final String SITE_KEY_ATT = "siteKey";
297 public static final String SECRET_KEY_ATT = "secretKey";
298 public static final String USE_RECAPTCHA_ATT = "useRecaptcha";
299 public static final String EXCEPTION_ELEM = "exception";
300 public static final String DOCUMENT_SET_ELEM = "documentSet";
301 public static final String GROUP_ELEM = "group";
302 public static final String MATCH_ELEM = "match";
303 public static final String FIELD_ATT = "field";
304 public static final String USER_INFORMATION_ELEM = "userInformation";
305 public static final String USERNAME_ATT = "username";
306 public static final String GROUPS_ATT = "groups";
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) { // should we allow this??
934 request.setAttribute(LANG_ATT, userContext._lang);
935 Element userContextElem = owner.createElement("userContext");
936 request.appendChild(userContextElem);
937 userContextElem.setAttribute(LANG_ATT, userContext._lang);
938 userContextElem.setAttribute(USERNAME_ATT, userContext._username);
939 userContextElem.setAttribute(USER_ID_ATT, userContext._userID);
940
941 if (userContext._groups != null)
942 {
943 String groupString = "";
944 for (int i = 0; i < userContext._groups.length; i++)
945 {
946 groupString += userContext._groups[i];
947 if (i != userContext._groups.length - 1)
948 {
949 groupString += ",";
950 }
951 }
952
953 if (groupString.length() > 0)
954 {
955 userContextElem.setAttribute(GROUPS_ATT, groupString);
956 }
957 }
958 }
959 return request;
960 }
961
962 public static Element createBasicResponse(Document owner, String from)
963 {
964 Element response = owner.createElement(RESPONSE_ELEM);
965 response.setAttribute(FROM_ATT, from);
966 response.setAttribute(TYPE_ATT, REQUEST_TYPE_PROCESS);
967 return response;
968 }
969
970 public static Element createMetadataElement(Document owner, String name, String value)
971 {
972 Element metaElem = owner.createElement(METADATA_ELEM);
973 metaElem.setAttribute(NAME_ATT, name);
974 metaElem.setAttribute(VALUE_ATT, value);
975 return metaElem;
976 }
977
978 public static Element createTextElement(Document owner, String elem_name, String text)
979 {
980 Element e = owner.createElement(elem_name);
981 Text t = owner.createTextNode(text);
982 e.appendChild(t);
983 return e;
984
985 }
986
987 public static Element createTextElement(Document owner, String elem_name, String text, String att_name, String att_value)
988 {
989 Element e = owner.createElement(elem_name);
990 e.setAttribute(att_name, att_value);
991 Text t = owner.createTextNode(text);
992 e.appendChild(t);
993 return e;
994
995 }
996
997 public static Element createDisplayTextElement(Document owner, String text_name, String text)
998 {
999 Element e = owner.createElement(DISPLAY_TEXT_ELEM);
1000 e.setAttribute(NAME_ATT, text_name);
1001 Text t = owner.createTextNode(text);
1002 e.appendChild(t);
1003 return e;
1004
1005 }
1006
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 public static void addParameterToList(Element param_list, String name, String value) {
1016 Element p = createParameter(param_list.getOwnerDocument(), name, value);
1017 param_list.appendChild(p);
1018 }
1019 public static void addParametersToList(Element param_list, HashMap params)
1020 {
1021 if (params == null)
1022 {
1023 return;
1024 }
1025
1026 Set items = params.entrySet();
1027 Iterator i = items.iterator();
1028 Document owner = param_list.getOwnerDocument();
1029 while (i.hasNext())
1030 {
1031 Map.Entry m = (Map.Entry) i.next();
1032 param_list.appendChild(createParameter(owner, (String) m.getKey(), (String) m.getValue()));
1033 }
1034
1035 }
1036
1037 public static Element createParameterDescription(Document owner, String id, String display_name, String type, String default_value, String[] option_ids, String[] option_names)
1038 {
1039
1040 Element p = owner.createElement(PARAM_ELEM);
1041 p.setAttribute(NAME_ATT, id);
1042 p.setAttribute(TYPE_ATT, type);
1043 p.appendChild(createDisplayTextElement(owner, DISPLAY_TEXT_NAME, display_name));
1044
1045 if (default_value != null)
1046 {
1047 p.setAttribute(DEFAULT_ATT, default_value);
1048 }
1049 if (option_ids != null && option_names != null)
1050 {
1051 for (int i = 0; i < option_ids.length; i++)
1052 {
1053 Element e = owner.createElement(PARAM_OPTION_ELEM);
1054 e.setAttribute(NAME_ATT, option_ids[i]);
1055 e.appendChild(createDisplayTextElement(owner, DISPLAY_TEXT_NAME, option_names[i]));
1056 p.appendChild(e);
1057 }
1058 }
1059 return p;
1060 }
1061
1062 public static Element createParameterDescription2(Document owner, String id, String display_name, String type, String default_value, ArrayList<String> option_ids, ArrayList<String> option_names)
1063 {
1064
1065 Element p = owner.createElement(PARAM_ELEM);
1066 p.setAttribute(NAME_ATT, id);
1067 p.setAttribute(TYPE_ATT, type);
1068 p.appendChild(createDisplayTextElement(owner, DISPLAY_TEXT_NAME, display_name));
1069 if (default_value != null)
1070 {
1071 p.setAttribute(DEFAULT_ATT, default_value);
1072 }
1073 if (option_ids != null && option_names != null)
1074 {
1075 for (int i = 0; i < option_ids.size(); i++)
1076 {
1077 Element e = owner.createElement(PARAM_OPTION_ELEM);
1078 e.setAttribute(NAME_ATT, option_ids.get(i));
1079 e.appendChild(createDisplayTextElement(owner, DISPLAY_TEXT_NAME, option_names.get(i)));
1080 p.appendChild(e);
1081 }
1082 }
1083 return p;
1084 }
1085
1086 /** returns the element parent/node_name[@attribute_name='attribute_value']
1087 if attribute_value is null, just returns the first one with that attribute */
1088 public static Element getNamedElement(Element parent, String node_name, String attribute_name, String attribute_value)
1089 {
1090
1091 NodeList children = parent.getChildNodes();
1092 for (int i = 0; i < children.getLength(); i++)
1093 {
1094 Node child = children.item(i);
1095 if (child.getNodeName().equals(node_name))
1096 {
1097 String att_val = ((Element) child).getAttribute(attribute_name);
1098 if (!att_val.equals("") ) {
1099 if (attribute_value == null || att_val.equals(attribute_value)) {
1100 return (Element) child;
1101 }
1102 }
1103 }
1104 } // for each child
1105 // not found
1106 return null;
1107 }
1108
1109 public static Element getNamedElementNS(Element parent, String namespace_uri, String node_local_name, String attribute_name, String attribute_value)
1110 {
1111 NodeList children = parent.getChildNodes();
1112 for (int i = 0; i < children.getLength(); i++)
1113 {
1114 Node child = children.item(i);
1115 if (child.getNodeType() == Node.ELEMENT_NODE && child.getNamespaceURI() != null && child.getNamespaceURI().equals(namespace_uri) && child.getLocalName().equals(node_local_name))
1116 {
1117 if (((Element) child).getAttribute(attribute_name).equals(attribute_value))
1118 return (Element) child;
1119 }
1120 }
1121 // not found
1122 return null;
1123 }
1124
1125 public static NodeList getNamedElementsNS(Element parent, String namespace_uri, String node_local_name, String attribute_name, String attribute_value)
1126 {
1127 MyNodeList result = new MyNodeList();
1128 NodeList children = parent.getChildNodes();
1129 for (int i = 0; i < children.getLength(); i++)
1130 {
1131 Node child = children.item(i);
1132 if (child.getNodeType() == Node.ELEMENT_NODE && child.getNamespaceURI() != null && child.getNamespaceURI().equals(namespace_uri) && child.getLocalName().equals(node_local_name))
1133 {
1134 if (((Element) child).getAttribute(attribute_name).equals(attribute_value))
1135 result.addNode(child);
1136 }
1137 }
1138 return result;
1139 }
1140
1141 public static NodeList getElementsWithAttributesNS(Element parent, String namespace_uri, String node_local_name, String[] attribute_names, String[] attribute_values)
1142 {
1143 if (attribute_names.length == 0 || attribute_names.length != attribute_values.length)
1144 {
1145 return new MyNodeList();
1146 }
1147
1148 MyNodeList result = new MyNodeList();
1149
1150 NodeList matchingNodes = getNamedElementsNS(parent, namespace_uri, node_local_name, attribute_names[0], attribute_values[0]);
1151 for (int i = 0; i < matchingNodes.getLength(); i++)
1152 {
1153 Element current = (Element) matchingNodes.item(i);
1154 boolean nodeMatches = true;
1155 for (int j = 1; j < attribute_names.length; j++)
1156 {
1157 String currentName = attribute_names[j];
1158 String currentValue = attribute_values[j];
1159 if (!current.getAttribute(currentName).equals(currentValue))
1160 {
1161 nodeMatches = false;
1162 break;
1163 }
1164 }
1165
1166 if (nodeMatches)
1167 {
1168 result.addNode(current);
1169 }
1170 }
1171
1172 return result;
1173 }
1174
1175 public static void removeElementsWithAttributesNS(Element parent, String namespace_uri, String node_local_name, String[] attribute_names, String[] attribute_values)
1176 {
1177 NodeList matchingNodes = getElementsWithAttributesNS(parent, namespace_uri, node_local_name, attribute_names, attribute_values);
1178 for (int i = 0; i < matchingNodes.getLength(); i++)
1179 {
1180 parent.removeChild(matchingNodes.item(i));
1181 }
1182 }
1183
1184 // In element main, tries to find any previous occurrence of elements with xsl-template-name=templateName,
1185 // and whose named attribute (attributeName) has the same value as the same attribute in node.
1186 // If this is the case, such a previous occurrence is removed from element main, since
1187 // the new node will contain a more specific redefinition of this element.
1188 public static void removeNamedElementNS(Element parent, String namespace_uri, String node_local_name, String attribute_name, String attribute_value)
1189 {
1190 if (attribute_value.equals(""))
1191 {
1192 // it has no identifying attribute, so we can't find any matches
1193 return;
1194 }
1195
1196 Element old_elem = getNamedElementNS(parent, namespace_uri, node_local_name, attribute_name, attribute_value);
1197 if (old_elem != null)
1198 {
1199 parent.removeChild(old_elem);
1200 }
1201 }
1202
1203 public static void removeNamedElementsNS(Element parent, String namespace, String node_local_name, String attribute_name, String attribute_value)
1204 {
1205 if (attribute_value.equals(""))
1206 {
1207 // it has no identifying attribute, so we can't find any matches
1208 return;
1209 }
1210
1211 NodeList children = parent.getChildNodes();
1212 for (int i = children.getLength() - 1; i >= 0; i--)
1213 {
1214 Node child = children.item(i);
1215 if (child.getNodeType() == Node.ELEMENT_NODE && child.getNamespaceURI() != null && child.getNamespaceURI().equals(namespace) && child.getLocalName() != null && child.getLocalName().equals(node_local_name))
1216 {
1217 if (((Element) child).getAttribute(attribute_name).equals(attribute_value))
1218 parent.removeChild(child);
1219 }
1220 }
1221 }
1222
1223 /**
1224 * returns a NodeList of elements:
1225 * ancestor/node_name[@attribute_name='attribute_value']
1226 */
1227 public static NodeList getNamedElements(Element ancestor, String node_name, String attribute_name, String attribute_value)
1228 {
1229 MyNodeList node_list = new MyNodeList();
1230 NodeList children = ancestor.getElementsByTagName(node_name);
1231
1232 if (children != null && children.getLength() > 0)
1233 {
1234
1235 for (int i = 0; i < children.getLength(); i++)
1236 {
1237 Node child = children.item(i);
1238 if (child.getNodeName().equals(node_name))
1239 {
1240 if (((Element) child).getAttribute(attribute_name).equals(attribute_value))
1241 node_list.addNode(child);
1242 }
1243 }
1244 }
1245 return node_list;
1246 }
1247
1248 public static Element getLastElementByTagNameNS(Element main, String namespace, String node_name)
1249 {
1250 NodeList nodes = main.getElementsByTagNameNS(namespace, node_name);
1251 int len = nodes.getLength();
1252 if (len == 0)
1253 {
1254 return null;
1255 }
1256 return (Element) nodes.item(len - 1);
1257 }
1258
1259 public static int SORT_TYPE_STRING = 0;
1260 public static int SORT_TYPE_INT = 1;
1261 public static int SORT_TYPE_FLOAT = 2;
1262
1263 // sort type:
1264 public static Element insertIntoOrderedList(Element parent_node, String node_name, Element start_from_elem, Element new_elem, String sort_att, boolean descending)
1265 {
1266 if (new_elem == null)
1267 return null;
1268 Element cloned_elem = (Element) parent_node.getOwnerDocument().importNode(new_elem, true);
1269 if (start_from_elem == null)
1270 {
1271 parent_node.appendChild(cloned_elem);
1272 return cloned_elem;
1273 }
1274
1275 Node current_node = start_from_elem;
1276 String insert_att = cloned_elem.getAttribute(sort_att);
1277 String list_att = start_from_elem.getAttribute(sort_att);
1278 while ((!descending && list_att.compareTo(insert_att) < 0) || (descending && list_att.compareTo(insert_att) > 0))
1279 {
1280 current_node = current_node.getNextSibling();
1281 if (current_node == null)
1282 break; // end of the list
1283 if (!current_node.getNodeName().equals(node_name))
1284 {
1285 continue; // not a valid node
1286 }
1287 list_att = ((Element) current_node).getAttribute(sort_att);
1288 }
1289
1290 parent_node.insertBefore(cloned_elem, current_node);
1291 return cloned_elem;
1292 }
1293
1294 public static String getMetadataValue(Element metadata_list, String name) {
1295 Element meta = getNamedElement(metadata_list, METADATA_ELEM, NAME_ATT, name);
1296 if (meta == null) {
1297 return "";
1298 }
1299 String att_value = meta.getAttribute(VALUE_ATT);
1300 if (att_value.equals("")) {
1301 // try the text
1302 att_value = getNodeText(meta);
1303 }
1304 return att_value;
1305 }
1306
1307 // replaces < > " ' & in the original with their entities
1308 public static String xmlSafe(String original)
1309 {
1310
1311 StringBuffer filtered = new StringBuffer(original.length());
1312 char c;
1313 for (int i = 0; i < original.length(); i++)
1314 {
1315 c = original.charAt(i);
1316 if (c == '>')
1317 {
1318 filtered.append("&gt;");
1319 }
1320 else if (c == '<')
1321 {
1322 filtered.append("&lt;");
1323 }
1324 else if (c == '"')
1325 {
1326 filtered.append("&quot;");
1327 }
1328 else if (c == '&')
1329 {
1330 filtered.append("&amp;");
1331 }
1332 else if (c == '\'')
1333 {
1334 filtered.append("&apos;");
1335 }
1336 else
1337 {
1338 filtered.append(c);
1339 }
1340 }
1341 return filtered.toString();
1342 }
1343
1344 // replaces < > " ' & entities with their originals
1345 public static String unXmlSafe(String original)
1346 {
1347
1348 StringBuffer filtered = new StringBuffer(original.length());
1349 char c;
1350 for (int i = 0; i < original.length(); i++)
1351 {
1352 c = original.charAt(i);
1353 if (c == '&')
1354 {
1355 int pos = original.indexOf(";", i);
1356 String entity = original.substring(i + 1, pos);
1357 if (entity.equals("gt"))
1358 {
1359 filtered.append(">");
1360 }
1361 else if (entity.equals("lt"))
1362 {
1363 filtered.append("<");
1364 }
1365 else if (entity.equals("apos"))
1366 {
1367 filtered.append("'");
1368 }
1369 else if (entity.equals("amp"))
1370 {
1371 filtered.append("&");
1372 }
1373 else if (entity.equals("quot"))
1374 {
1375 filtered.append("\"");
1376 }
1377 else
1378 {
1379 filtered.append("&" + entity + ";");
1380 }
1381 i = pos;
1382 }
1383 else
1384 {
1385 filtered.append(c);
1386 }
1387 }
1388 return filtered.toString();
1389 }
1390
1391 public static void printXMLNode(Node e, boolean printText)
1392 {
1393 printXMLNode(e, 0, printText);
1394 }
1395
1396 public static String xmlNodeToString(Node e)
1397 {
1398 StringBuffer sb = new StringBuffer("");
1399 xmlNodeToString(sb, e, true, "\t", 0);
1400 return sb.toString();
1401 }
1402
1403 public static void xmlNodeToString(StringBuffer sb, Node e, boolean indent, String indentString, int depth)
1404 {
1405 if (e.getNodeType() == Node.TEXT_NODE)
1406 {
1407 if (e.getNodeValue() != "")
1408 {
1409 String text = e.getNodeValue();
1410 if (text != null)
1411 {
1412 text = text.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("^[\\n\\r\\t\\s]*", "").replaceAll("[\\n\\r\\t\\s]*$", "");
1413 sb.append(text);
1414 }
1415 }
1416 return;
1417 }
1418
1419 if (e.getNodeType() == Node.COMMENT_NODE)
1420 {
1421 if (e.getNodeValue() != "")
1422 {
1423 sb.append("<!--" + e.getNodeValue() + "-->");
1424 }
1425 return;
1426 }
1427
1428 if (indent)
1429 {
1430 for (int i = 0; i < depth; i++)
1431 {
1432 sb.append(indentString);
1433 }
1434 }
1435
1436 sb.append('<');
1437 sb.append(e.getNodeName());
1438 NamedNodeMap attrs = e.getAttributes();
1439 if (attrs != null)
1440 {
1441 for (int i = 0; i < attrs.getLength(); i++)
1442 {
1443 Node attr = attrs.item(i);
1444 sb.append(' ');
1445 sb.append(attr.getNodeName());
1446 sb.append("=\"");
1447 sb.append(attr.getNodeValue().replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;"));
1448 sb.append('"');
1449 }
1450 }
1451
1452 if (e.hasChildNodes())
1453 {
1454 boolean hasElements = false;
1455 boolean indentSwapped = false;
1456
1457 Node child = e.getFirstChild();
1458 do
1459 {
1460 if (child.getNodeType() == Node.ELEMENT_NODE)
1461 {
1462 hasElements = true;
1463 }
1464 if (child.getNodeType() == Node.TEXT_NODE && indent)
1465 {
1466 if (child.getNodeValue() != null && child.getNodeValue().trim().length() > 0)
1467 {
1468 indentSwapped = true;
1469 indent = false;
1470 }
1471 }
1472 } while ((child = child.getNextSibling()) != null);
1473
1474 sb.append(">");
1475 if (hasElements && indent)
1476 {
1477 sb.append("\n");
1478 }
1479
1480 child = e.getFirstChild();
1481 do
1482 {
1483 xmlNodeToString(sb, child, indent, indentString, depth + 1);
1484 } while ((child = child.getNextSibling()) != null);
1485
1486 if (indent)
1487 {
1488 for (int i = 0; i < depth; i++)
1489 {
1490 sb.append(indentString);
1491 }
1492 }
1493
1494 sb.append("</" + e.getNodeName() + ">");
1495
1496 if ((hasElements && indent) || indentSwapped)
1497 {
1498 sb.append("\n");
1499 }
1500 }
1501 else
1502 {
1503 sb.append("/>");
1504
1505 if (indent)
1506 {
1507 sb.append("\n");
1508 }
1509 }
1510
1511 /*
1512 boolean hasElements = false;
1513 boolean indentSwapped = false;
1514 for (int i = 0; i < children.getLength(); i++)
1515 {
1516 if (children.item(i).getNodeType() == Node.ELEMENT_NODE)
1517 {
1518 hasElements = true;
1519 }
1520 if (children.item(i).getNodeType() == Node.TEXT_NODE && indent)
1521 {
1522 if (children.item(i).getNodeValue() != null && children.item(i).getNodeValue().trim().length() > 0)
1523 {
1524 indentSwapped = true;
1525 indent = false;
1526 }
1527 }
1528 }
1529
1530 if (children == null || children.getLength() == 0)
1531 {
1532 sb.append("/>");
1533
1534 if (indent)
1535 {
1536 sb.append("\n");
1537 }
1538 }
1539 else
1540 {
1541 sb.append(">");
1542 if (hasElements && indent)
1543 {
1544 sb.append("\n");
1545 }
1546
1547 int len = children.getLength();
1548 for (int i = 0; i < len; i++)
1549 {
1550 xmlNodeToString(sb, children.item(i), indent, indentString, depth + 1);
1551 }
1552
1553 if (indent)
1554 {
1555 for (int i = 0; i < depth; i++)
1556 {
1557 sb.append(indentString);
1558 }
1559 }
1560
1561 sb.append("</" + e.getNodeName() + ">");
1562
1563 if ((hasElements && indent) || indentSwapped)
1564 {
1565 sb.append("\n");
1566 }
1567 }
1568 */
1569 }
1570
1571 public static void printXMLNode(Node e, int depth, boolean printText)
1572 { //recursive method call using DOM API...
1573
1574 if (e == null)
1575 {
1576 return;
1577 }
1578
1579 for (int i = 0; i < depth; i++)
1580 System.out.print(' ');
1581
1582 if (e.getNodeType() == Node.TEXT_NODE)
1583 {
1584 if (printText)
1585 {
1586 System.out.println(e.getNodeValue());
1587 }
1588 else
1589 {
1590 System.out.println("text");
1591 }
1592 return;
1593 }
1594
1595 System.out.print('<');
1596 System.out.print(e.getNodeName());
1597 NamedNodeMap attrs = e.getAttributes();
1598
1599 if (attrs != null)
1600 {
1601 for (int i = 0; i < attrs.getLength(); i++)
1602 {
1603 Node attr = attrs.item(i);
1604 System.out.print(' ');
1605 System.out.print(attr.getNodeName());
1606 System.out.print("=\"");
1607 System.out.print(attr.getNodeValue());
1608 System.out.print('"');
1609 }
1610 }
1611
1612 NodeList children = e.getChildNodes();
1613
1614 if (children == null || children.getLength() == 0)
1615 System.out.println("/>");
1616 else
1617 {
1618
1619 System.out.println('>');
1620
1621 int len = children.getLength();
1622 for (int i = 0; i < len; i++)
1623 {
1624 printXMLNode(children.item(i), depth + 1, printText);
1625 }
1626
1627 for (int i = 0; i < depth; i++)
1628 System.out.print(' ');
1629
1630 System.out.println("</" + e.getNodeName() + ">");
1631 }
1632 }
1633
1634 private static void elementToLogAsString(String prefix, Element e, boolean indent, boolean debugEncoding)
1635 {
1636 String str = prefix + "\n" + elementToString(e, indent, debugEncoding);
1637 System.err.println(str);
1638 logger.info(str);
1639 }
1640
1641 // hex/unicode codepoint used only for those chars that are beyond printable/basic ASCII
1642 public static void elementToLogAsUnicodeDebugString(String prefix, Element e, boolean indent)
1643 {
1644 elementToLogAsString(prefix, e, indent, true);
1645 }
1646
1647 public static void elementToLogAsString(String prefix, Element e, boolean indent)
1648 {
1649 elementToLogAsString(prefix, e, indent, false);
1650 }
1651
1652 // pass in debugEncoding=true to investigate encoding issues. This function will then return non-basic ASCII characters in hex
1653 private static String elementToString(Element e, boolean indent, boolean debugEncoding)
1654 {
1655 String str = "";
1656 try
1657 {
1658 TransformerFactory tf = TransformerFactory.newInstance();
1659 Transformer trans = tf.newTransformer();
1660 StringWriter sw = new StringWriter();
1661 if (indent)
1662 {
1663 trans.setOutputProperty(OutputKeys.INDENT, "yes");
1664 }
1665 else
1666 {
1667 trans.setOutputProperty(OutputKeys.INDENT, "no");
1668 }
1669 trans.transform(new DOMSource(e), new StreamResult(sw));
1670 str += sw.toString();
1671
1672 // if debugging encoding issues, then encode unicode code pts as hex for all but non-alphanumeric and space/tab/newline chars
1673 if(debugEncoding) str = Misc.debugUnicodeString(str);
1674 }
1675 catch (Exception ex)
1676 {
1677 str += "Exception: couldn't write " + e + " to log";
1678 }
1679 finally
1680 {
1681 return str;
1682 }
1683 }
1684
1685 public static String elementToString(Element e, boolean indent)
1686 {
1687 return elementToString(e, indent, false);
1688 }
1689
1690 // hex/unicode codepoint used only for those chars that are beyond printable/basic ASCII
1691 public static String elementToUnicodeDebugString(Element e, boolean indent)
1692 {
1693 return elementToString(e, indent, true);
1694 }
1695
1696 public static ArrayList<String> getGroupsFromSecurityResponse(Element securityResponse)
1697 {
1698 ArrayList<String> groups = new ArrayList<String>();
1699
1700 Element groupList = (Element) getChildByTagName(securityResponse, GROUP_ELEM + LIST_MODIFIER);
1701 if (groupList == null)
1702 {
1703 return groups;
1704 }
1705
1706 NodeList groupElems = getChildrenByTagName(groupList, GROUP_ELEM);
1707
1708 for (int i = 0; i < groupElems.getLength(); i++)
1709 {
1710 Element groupElem = (Element) groupElems.item(i);
1711 // an empty attribute will return "". some code depends on having "" for groups, so leave it in for now.
1712 groups.add(groupElem.getAttribute(NAME_ATT));
1713 }
1714
1715 return groups;
1716 }
1717
1718}
Note: See TracBrowser for help on using the repository browser.