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

Last change on this file was 38953, checked in by kjdon, 31 hours ago

avoid NodeList, use our own copyAllChildren method

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