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

Last change on this file since 25571 was 25571, checked in by ak19, 12 years ago

Added a ping SystemAction to mirror GS2's updated ability to ping the server as is needed for activate.pl. (GS2 also allows pinging a collection, but that's not been ported to GS3 yet).

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