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

Last change on this file since 16882 was 16882, checked in by xiao, 16 years ago

just add few constant strings

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