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

Last change on this file since 31166 was 31166, checked in by Georgiy Litvinov, 7 years ago

Java code for groups breadcrumbs

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