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

Last change on this file since 32475 was 32475, checked in by kjdon, 6 years ago

set a no_archives att to the collection element if archives are not present - then we know not to show document editing. for now, this is just a basic test whether the folder exists or not. not doing any test on the contents of it.

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