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

Last change on this file since 38845 was 38845, checked in by kjdon, 3 months ago

check for null parent before getting child nodes

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