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

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

added editEnabled att string

  • Property svn:keywords set to Author Date Id Revision
File size: 52.9 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) { // 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 // for parameters where value is an attribute
1008 public static Element createParameter(Document owner, String name, String value)
1009 {
1010 Element param = owner.createElement(PARAM_ELEM);
1011 param.setAttribute(NAME_ATT, name);
1012 param.setAttribute(VALUE_ATT, value);
1013 return param;
1014 }
1015
1016 // for parameters where value is a text node
1017 public static Element createParameter2(Document owner, String name, String value) {
1018 Element param = owner.createElement(PARAM_ELEM);
1019 param.setAttribute(NAME_ATT, name);
1020 param.appendChild(owner.createTextNode(value));
1021 return param;
1022 }
1023
1024 public static void addParameterToList(Element param_list, String name, String value) {
1025 Element p = createParameter(param_list.getOwnerDocument(), name, value);
1026 param_list.appendChild(p);
1027 }
1028 public static void addParameter2ToList(Element param_list, String name, String value) {
1029 Element p = createParameter2(param_list.getOwnerDocument(), name, value);
1030 param_list.appendChild(p);
1031 }
1032 public static void addParametersToList(Element param_list, HashMap params)
1033 {
1034 if (params == null)
1035 {
1036 return;
1037 }
1038
1039 Set items = params.entrySet();
1040 Iterator i = items.iterator();
1041 Document owner = param_list.getOwnerDocument();
1042 while (i.hasNext())
1043 {
1044 Map.Entry m = (Map.Entry) i.next();
1045 param_list.appendChild(createParameter(owner, (String) m.getKey(), (String) m.getValue()));
1046 }
1047
1048 }
1049
1050 public static Element createParameterDescription(Document owner, String id, String display_name, String type, String default_value, String[] option_ids, String[] option_names)
1051 {
1052
1053 Element p = owner.createElement(PARAM_ELEM);
1054 p.setAttribute(NAME_ATT, id);
1055 p.setAttribute(TYPE_ATT, type);
1056 p.appendChild(createDisplayTextElement(owner, DISPLAY_TEXT_NAME, display_name));
1057
1058 if (default_value != null)
1059 {
1060 p.setAttribute(DEFAULT_ATT, default_value);
1061 }
1062 if (option_ids != null && option_names != null)
1063 {
1064 for (int i = 0; i < option_ids.length; i++)
1065 {
1066 Element e = owner.createElement(PARAM_OPTION_ELEM);
1067 e.setAttribute(NAME_ATT, option_ids[i]);
1068 e.appendChild(createDisplayTextElement(owner, DISPLAY_TEXT_NAME, option_names[i]));
1069 p.appendChild(e);
1070 }
1071 }
1072 return p;
1073 }
1074
1075 public static Element createParameterDescription2(Document owner, String id, String display_name, String type, String default_value, ArrayList<String> option_ids, ArrayList<String> option_names)
1076 {
1077
1078 Element p = owner.createElement(PARAM_ELEM);
1079 p.setAttribute(NAME_ATT, id);
1080 p.setAttribute(TYPE_ATT, type);
1081 p.appendChild(createDisplayTextElement(owner, DISPLAY_TEXT_NAME, display_name));
1082 if (default_value != null)
1083 {
1084 p.setAttribute(DEFAULT_ATT, default_value);
1085 }
1086 if (option_ids != null && option_names != null)
1087 {
1088 for (int i = 0; i < option_ids.size(); i++)
1089 {
1090 Element e = owner.createElement(PARAM_OPTION_ELEM);
1091 e.setAttribute(NAME_ATT, option_ids.get(i));
1092 e.appendChild(createDisplayTextElement(owner, DISPLAY_TEXT_NAME, option_names.get(i)));
1093 p.appendChild(e);
1094 }
1095 }
1096 return p;
1097 }
1098
1099 /** returns the element parent/node_name[@attribute_name='attribute_value']
1100 if attribute_value is null, just returns the first one with that attribute */
1101 public static Element getNamedElement(Element parent, String node_name, String attribute_name, String attribute_value)
1102 {
1103
1104 NodeList children = parent.getChildNodes();
1105 for (int i = 0; i < children.getLength(); i++)
1106 {
1107 Node child = children.item(i);
1108 if (child.getNodeName().equals(node_name))
1109 {
1110 String att_val = ((Element) child).getAttribute(attribute_name);
1111 if (!att_val.equals("") ) {
1112 if (attribute_value == null || att_val.equals(attribute_value)) {
1113 return (Element) child;
1114 }
1115 }
1116 }
1117 } // for each child
1118 // not found
1119 return null;
1120 }
1121
1122 public static Element getNamedElementNS(Element parent, String namespace_uri, String node_local_name, String attribute_name, String attribute_value)
1123 {
1124 NodeList children = parent.getChildNodes();
1125 for (int i = 0; i < children.getLength(); i++)
1126 {
1127 Node child = children.item(i);
1128 if (child.getNodeType() == Node.ELEMENT_NODE && child.getNamespaceURI() != null && child.getNamespaceURI().equals(namespace_uri) && child.getLocalName().equals(node_local_name))
1129 {
1130 if (((Element) child).getAttribute(attribute_name).equals(attribute_value))
1131 return (Element) child;
1132 }
1133 }
1134 // not found
1135 return null;
1136 }
1137
1138 public static NodeList getNamedElementsNS(Element parent, String namespace_uri, String node_local_name, String attribute_name, String attribute_value)
1139 {
1140 MyNodeList result = new MyNodeList();
1141 NodeList children = parent.getChildNodes();
1142 for (int i = 0; i < children.getLength(); i++)
1143 {
1144 Node child = children.item(i);
1145 if (child.getNodeType() == Node.ELEMENT_NODE && child.getNamespaceURI() != null && child.getNamespaceURI().equals(namespace_uri) && child.getLocalName().equals(node_local_name))
1146 {
1147 if (((Element) child).getAttribute(attribute_name).equals(attribute_value))
1148 result.addNode(child);
1149 }
1150 }
1151 return result;
1152 }
1153
1154 public static NodeList getElementsWithAttributesNS(Element parent, String namespace_uri, String node_local_name, String[] attribute_names, String[] attribute_values)
1155 {
1156 if (attribute_names.length == 0 || attribute_names.length != attribute_values.length)
1157 {
1158 return new MyNodeList();
1159 }
1160
1161 MyNodeList result = new MyNodeList();
1162
1163 NodeList matchingNodes = getNamedElementsNS(parent, namespace_uri, node_local_name, attribute_names[0], attribute_values[0]);
1164 for (int i = 0; i < matchingNodes.getLength(); i++)
1165 {
1166 Element current = (Element) matchingNodes.item(i);
1167 boolean nodeMatches = true;
1168 for (int j = 1; j < attribute_names.length; j++)
1169 {
1170 String currentName = attribute_names[j];
1171 String currentValue = attribute_values[j];
1172 if (!current.getAttribute(currentName).equals(currentValue))
1173 {
1174 nodeMatches = false;
1175 break;
1176 }
1177 }
1178
1179 if (nodeMatches)
1180 {
1181 result.addNode(current);
1182 }
1183 }
1184
1185 return result;
1186 }
1187
1188 public static void removeElementsWithAttributesNS(Element parent, String namespace_uri, String node_local_name, String[] attribute_names, String[] attribute_values)
1189 {
1190 NodeList matchingNodes = getElementsWithAttributesNS(parent, namespace_uri, node_local_name, attribute_names, attribute_values);
1191 for (int i = 0; i < matchingNodes.getLength(); i++)
1192 {
1193 parent.removeChild(matchingNodes.item(i));
1194 }
1195 }
1196
1197 // In element main, tries to find any previous occurrence of elements with xsl-template-name=templateName,
1198 // and whose named attribute (attributeName) has the same value as the same attribute in node.
1199 // If this is the case, such a previous occurrence is removed from element main, since
1200 // the new node will contain a more specific redefinition of this element.
1201 public static void removeNamedElementNS(Element parent, String namespace_uri, String node_local_name, String attribute_name, String attribute_value)
1202 {
1203 if (attribute_value.equals(""))
1204 {
1205 // it has no identifying attribute, so we can't find any matches
1206 return;
1207 }
1208
1209 Element old_elem = getNamedElementNS(parent, namespace_uri, node_local_name, attribute_name, attribute_value);
1210 if (old_elem != null)
1211 {
1212 parent.removeChild(old_elem);
1213 }
1214 }
1215
1216 public static void removeNamedElementsNS(Element parent, String namespace, String node_local_name, String attribute_name, String attribute_value)
1217 {
1218 if (attribute_value.equals(""))
1219 {
1220 // it has no identifying attribute, so we can't find any matches
1221 return;
1222 }
1223
1224 NodeList children = parent.getChildNodes();
1225 for (int i = children.getLength() - 1; i >= 0; i--)
1226 {
1227 Node child = children.item(i);
1228 if (child.getNodeType() == Node.ELEMENT_NODE && child.getNamespaceURI() != null && child.getNamespaceURI().equals(namespace) && child.getLocalName() != null && child.getLocalName().equals(node_local_name))
1229 {
1230 if (((Element) child).getAttribute(attribute_name).equals(attribute_value))
1231 parent.removeChild(child);
1232 }
1233 }
1234 }
1235
1236 /**
1237 * returns a NodeList of elements:
1238 * ancestor/node_name[@attribute_name='attribute_value']
1239 */
1240 public static NodeList getNamedElements(Element ancestor, String node_name, String attribute_name, String attribute_value)
1241 {
1242 MyNodeList node_list = new MyNodeList();
1243 NodeList children = ancestor.getElementsByTagName(node_name);
1244
1245 if (children != null && children.getLength() > 0)
1246 {
1247
1248 for (int i = 0; i < children.getLength(); i++)
1249 {
1250 Node child = children.item(i);
1251 if (child.getNodeName().equals(node_name))
1252 {
1253 if (((Element) child).getAttribute(attribute_name).equals(attribute_value))
1254 node_list.addNode(child);
1255 }
1256 }
1257 }
1258 return node_list;
1259 }
1260
1261 public static Element getLastElementByTagNameNS(Element main, String namespace, String node_name)
1262 {
1263 NodeList nodes = main.getElementsByTagNameNS(namespace, node_name);
1264 int len = nodes.getLength();
1265 if (len == 0)
1266 {
1267 return null;
1268 }
1269 return (Element) nodes.item(len - 1);
1270 }
1271
1272 public static int SORT_TYPE_STRING = 0;
1273 public static int SORT_TYPE_INT = 1;
1274 public static int SORT_TYPE_FLOAT = 2;
1275
1276 // sort type:
1277 public static Element insertIntoOrderedList(Element parent_node, String node_name, Element start_from_elem, Element new_elem, String sort_att, boolean descending)
1278 {
1279 if (new_elem == null)
1280 return null;
1281 Element cloned_elem = (Element) parent_node.getOwnerDocument().importNode(new_elem, true);
1282 if (start_from_elem == null)
1283 {
1284 parent_node.appendChild(cloned_elem);
1285 return cloned_elem;
1286 }
1287
1288 Node current_node = start_from_elem;
1289 String insert_att = cloned_elem.getAttribute(sort_att);
1290 String list_att = start_from_elem.getAttribute(sort_att);
1291 while ((!descending && list_att.compareTo(insert_att) < 0) || (descending && list_att.compareTo(insert_att) > 0))
1292 {
1293 current_node = current_node.getNextSibling();
1294 if (current_node == null)
1295 break; // end of the list
1296 if (!current_node.getNodeName().equals(node_name))
1297 {
1298 continue; // not a valid node
1299 }
1300 list_att = ((Element) current_node).getAttribute(sort_att);
1301 }
1302
1303 parent_node.insertBefore(cloned_elem, current_node);
1304 return cloned_elem;
1305 }
1306
1307 public static String getMetadataValue(Element metadata_list, String name) {
1308 Element meta = getNamedElement(metadata_list, METADATA_ELEM, NAME_ATT, name);
1309 if (meta == null) {
1310 return "";
1311 }
1312 String att_value = meta.getAttribute(VALUE_ATT);
1313 if (att_value.equals("")) {
1314 // try the text
1315 att_value = getNodeText(meta);
1316 }
1317 return att_value;
1318 }
1319
1320 // replaces < > " ' & in the original with their entities
1321 public static String xmlSafe(String original)
1322 {
1323
1324 StringBuffer filtered = new StringBuffer(original.length());
1325 char c;
1326 for (int i = 0; i < original.length(); i++)
1327 {
1328 c = original.charAt(i);
1329 if (c == '>')
1330 {
1331 filtered.append("&gt;");
1332 }
1333 else if (c == '<')
1334 {
1335 filtered.append("&lt;");
1336 }
1337 else if (c == '"')
1338 {
1339 filtered.append("&quot;");
1340 }
1341 else if (c == '&')
1342 {
1343 filtered.append("&amp;");
1344 }
1345 else if (c == '\'')
1346 {
1347 filtered.append("&apos;");
1348 }
1349 else
1350 {
1351 filtered.append(c);
1352 }
1353 }
1354 return filtered.toString();
1355 }
1356
1357 // replaces < > " ' & entities with their originals
1358 public static String unXmlSafe(String original)
1359 {
1360
1361 StringBuffer filtered = new StringBuffer(original.length());
1362 char c;
1363 for (int i = 0; i < original.length(); i++)
1364 {
1365 c = original.charAt(i);
1366 if (c == '&')
1367 {
1368 int pos = original.indexOf(";", i);
1369 String entity = original.substring(i + 1, pos);
1370 if (entity.equals("gt"))
1371 {
1372 filtered.append(">");
1373 }
1374 else if (entity.equals("lt"))
1375 {
1376 filtered.append("<");
1377 }
1378 else if (entity.equals("apos"))
1379 {
1380 filtered.append("'");
1381 }
1382 else if (entity.equals("amp"))
1383 {
1384 filtered.append("&");
1385 }
1386 else if (entity.equals("quot"))
1387 {
1388 filtered.append("\"");
1389 }
1390 else
1391 {
1392 filtered.append("&" + entity + ";");
1393 }
1394 i = pos;
1395 }
1396 else
1397 {
1398 filtered.append(c);
1399 }
1400 }
1401 return filtered.toString();
1402 }
1403
1404 public static void printXMLNode(Node e, boolean printText)
1405 {
1406 printXMLNode(e, 0, printText);
1407 }
1408
1409 public static String xmlNodeToString(Node e)
1410 {
1411 StringBuffer sb = new StringBuffer("");
1412 xmlNodeToString(sb, e, true, "\t", 0);
1413 return sb.toString();
1414 }
1415
1416 public static void xmlNodeToString(StringBuffer sb, Node e, boolean indent, String indentString, int depth)
1417 {
1418 if (e.getNodeType() == Node.TEXT_NODE)
1419 {
1420 if (e.getNodeValue() != "")
1421 {
1422 String text = e.getNodeValue();
1423 if (text != null)
1424 {
1425 text = text.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("^[\\n\\r\\t\\s]*", "").replaceAll("[\\n\\r\\t\\s]*$", "");
1426 sb.append(text);
1427 }
1428 }
1429 return;
1430 }
1431
1432 if (e.getNodeType() == Node.COMMENT_NODE)
1433 {
1434 if (e.getNodeValue() != "")
1435 {
1436 sb.append("<!--" + e.getNodeValue() + "-->");
1437 }
1438 return;
1439 }
1440
1441 if (indent)
1442 {
1443 for (int i = 0; i < depth; i++)
1444 {
1445 sb.append(indentString);
1446 }
1447 }
1448
1449 sb.append('<');
1450 sb.append(e.getNodeName());
1451 NamedNodeMap attrs = e.getAttributes();
1452 if (attrs != null)
1453 {
1454 for (int i = 0; i < attrs.getLength(); i++)
1455 {
1456 Node attr = attrs.item(i);
1457 sb.append(' ');
1458 sb.append(attr.getNodeName());
1459 sb.append("=\"");
1460 sb.append(attr.getNodeValue().replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;"));
1461 sb.append('"');
1462 }
1463 }
1464
1465 if (e.hasChildNodes())
1466 {
1467 boolean hasElements = false;
1468 boolean indentSwapped = false;
1469
1470 Node child = e.getFirstChild();
1471 do
1472 {
1473 if (child.getNodeType() == Node.ELEMENT_NODE)
1474 {
1475 hasElements = true;
1476 }
1477 if (child.getNodeType() == Node.TEXT_NODE && indent)
1478 {
1479 if (child.getNodeValue() != null && child.getNodeValue().trim().length() > 0)
1480 {
1481 indentSwapped = true;
1482 indent = false;
1483 }
1484 }
1485 } while ((child = child.getNextSibling()) != null);
1486
1487 sb.append(">");
1488 if (hasElements && indent)
1489 {
1490 sb.append("\n");
1491 }
1492
1493 child = e.getFirstChild();
1494 do
1495 {
1496 xmlNodeToString(sb, child, indent, indentString, depth + 1);
1497 } while ((child = child.getNextSibling()) != null);
1498
1499 if (indent)
1500 {
1501 for (int i = 0; i < depth; i++)
1502 {
1503 sb.append(indentString);
1504 }
1505 }
1506
1507 sb.append("</" + e.getNodeName() + ">");
1508
1509 if ((hasElements && indent) || indentSwapped)
1510 {
1511 sb.append("\n");
1512 }
1513 }
1514 else
1515 {
1516 sb.append("/>");
1517
1518 if (indent)
1519 {
1520 sb.append("\n");
1521 }
1522 }
1523
1524 /*
1525 boolean hasElements = false;
1526 boolean indentSwapped = false;
1527 for (int i = 0; i < children.getLength(); i++)
1528 {
1529 if (children.item(i).getNodeType() == Node.ELEMENT_NODE)
1530 {
1531 hasElements = true;
1532 }
1533 if (children.item(i).getNodeType() == Node.TEXT_NODE && indent)
1534 {
1535 if (children.item(i).getNodeValue() != null && children.item(i).getNodeValue().trim().length() > 0)
1536 {
1537 indentSwapped = true;
1538 indent = false;
1539 }
1540 }
1541 }
1542
1543 if (children == null || children.getLength() == 0)
1544 {
1545 sb.append("/>");
1546
1547 if (indent)
1548 {
1549 sb.append("\n");
1550 }
1551 }
1552 else
1553 {
1554 sb.append(">");
1555 if (hasElements && indent)
1556 {
1557 sb.append("\n");
1558 }
1559
1560 int len = children.getLength();
1561 for (int i = 0; i < len; i++)
1562 {
1563 xmlNodeToString(sb, children.item(i), indent, indentString, depth + 1);
1564 }
1565
1566 if (indent)
1567 {
1568 for (int i = 0; i < depth; i++)
1569 {
1570 sb.append(indentString);
1571 }
1572 }
1573
1574 sb.append("</" + e.getNodeName() + ">");
1575
1576 if ((hasElements && indent) || indentSwapped)
1577 {
1578 sb.append("\n");
1579 }
1580 }
1581 */
1582 }
1583
1584 public static void printXMLNode(Node e, int depth, boolean printText)
1585 { //recursive method call using DOM API...
1586
1587 if (e == null)
1588 {
1589 return;
1590 }
1591
1592 for (int i = 0; i < depth; i++)
1593 System.out.print(' ');
1594
1595 if (e.getNodeType() == Node.TEXT_NODE)
1596 {
1597 if (printText)
1598 {
1599 System.out.println(e.getNodeValue());
1600 }
1601 else
1602 {
1603 System.out.println("text");
1604 }
1605 return;
1606 }
1607
1608 System.out.print('<');
1609 System.out.print(e.getNodeName());
1610 NamedNodeMap attrs = e.getAttributes();
1611
1612 if (attrs != null)
1613 {
1614 for (int i = 0; i < attrs.getLength(); i++)
1615 {
1616 Node attr = attrs.item(i);
1617 System.out.print(' ');
1618 System.out.print(attr.getNodeName());
1619 System.out.print("=\"");
1620 System.out.print(attr.getNodeValue());
1621 System.out.print('"');
1622 }
1623 }
1624
1625 NodeList children = e.getChildNodes();
1626
1627 if (children == null || children.getLength() == 0)
1628 System.out.println("/>");
1629 else
1630 {
1631
1632 System.out.println('>');
1633
1634 int len = children.getLength();
1635 for (int i = 0; i < len; i++)
1636 {
1637 printXMLNode(children.item(i), depth + 1, printText);
1638 }
1639
1640 for (int i = 0; i < depth; i++)
1641 System.out.print(' ');
1642
1643 System.out.println("</" + e.getNodeName() + ">");
1644 }
1645 }
1646
1647 private static void elementToLogAsString(String prefix, Element e, boolean indent, boolean debugEncoding)
1648 {
1649 String str = prefix + "\n" + elementToString(e, indent, debugEncoding);
1650 System.err.println(str);
1651 logger.info(str);
1652 }
1653
1654 // hex/unicode codepoint used only for those chars that are beyond printable/basic ASCII
1655 public static void elementToLogAsUnicodeDebugString(String prefix, Element e, boolean indent)
1656 {
1657 elementToLogAsString(prefix, e, indent, true);
1658 }
1659
1660 public static void elementToLogAsString(String prefix, Element e, boolean indent)
1661 {
1662 elementToLogAsString(prefix, e, indent, false);
1663 }
1664
1665 // pass in debugEncoding=true to investigate encoding issues. This function will then return non-basic ASCII characters in hex
1666 private static String elementToString(Element e, boolean indent, boolean debugEncoding)
1667 {
1668 String str = "";
1669 try
1670 {
1671 TransformerFactory tf = TransformerFactory.newInstance();
1672 Transformer trans = tf.newTransformer();
1673 StringWriter sw = new StringWriter();
1674 if (indent)
1675 {
1676 trans.setOutputProperty(OutputKeys.INDENT, "yes");
1677 }
1678 else
1679 {
1680 trans.setOutputProperty(OutputKeys.INDENT, "no");
1681 }
1682 trans.transform(new DOMSource(e), new StreamResult(sw));
1683 str += sw.toString();
1684
1685 // if debugging encoding issues, then encode unicode code pts as hex for all but non-alphanumeric and space/tab/newline chars
1686 if(debugEncoding) str = Misc.debugUnicodeString(str);
1687 }
1688 catch (Exception ex)
1689 {
1690 str += "Exception: couldn't write " + e + " to log";
1691 }
1692 finally
1693 {
1694 return str;
1695 }
1696 }
1697
1698 public static String elementToString(Element e, boolean indent)
1699 {
1700 return elementToString(e, indent, false);
1701 }
1702
1703 // hex/unicode codepoint used only for those chars that are beyond printable/basic ASCII
1704 public static String elementToUnicodeDebugString(Element e, boolean indent)
1705 {
1706 return elementToString(e, indent, true);
1707 }
1708
1709 public static ArrayList<String> getGroupsFromSecurityResponse(Element securityResponse)
1710 {
1711 ArrayList<String> groups = new ArrayList<String>();
1712
1713 Element groupList = (Element) getChildByTagName(securityResponse, GROUP_ELEM + LIST_MODIFIER);
1714 if (groupList == null)
1715 {
1716 return groups;
1717 }
1718
1719 NodeList groupElems = getChildrenByTagName(groupList, GROUP_ELEM);
1720
1721 for (int i = 0; i < groupElems.getLength(); i++)
1722 {
1723 Element groupElem = (Element) groupElems.item(i);
1724 // an empty attribute will return "". some code depends on having "" for groups, so leave it in for now.
1725 groups.add(groupElem.getAttribute(NAME_ATT));
1726 }
1727
1728 return groups;
1729 }
1730
1731}
Note: See TracBrowser for help on using the repository browser.