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

Last change on this file since 20005 was 20005, checked in by xiao, 15 years ago

remove two static strings about flax

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