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

Last change on this file since 24254 was 24254, checked in by ak19, 13 years ago

Commits for ticket 770 concerning the display of multiple values for a metadata (like dc.Title) when classified by that metadata. So when the user browses by dc.Title, they no longer merely see a doc listed once for each dc.Title assigned but under the same (first retrieved) dc.Title, but they should now see the doc listed once for each dc.Title assigned to it with a different dc.Title value each time.

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