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

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

Adding in security capabilities for Greenstone 3

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