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

Last change on this file since 37613 was 37613, checked in by kjdon, 14 months ago

added a couple of element/attribute name constants. Also added removeAllAttributes method, but didn't end up using it.

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