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

Last change on this file since 21281 was 21281, checked in by kjdon, 14 years ago

added hidden attribute definition

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