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

Last change on this file since 26248 was 26055, checked in by sjm84, 12 years ago

Adding constants for the various XML namespaces used in the code

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