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

Last change on this file since 23360 was 23360, checked in by sjb48, 13 years ago

Starting working on new format statement save architecture. This involves a new action, FormatAction, which will be responsible for the XSL transform and will pass the format string to the Collection object via the Message Router,

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