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

Last change on this file since 36067 was 35295, checked in by kjdon, 3 years ago

if we want to add new namespaces into collection's xsl files, we need to make sure they are added into the main xsl, and then also into expand_gslib xsl, otherwise they will be ignored and left off the page

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