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

Last change on this file since 16875 was 16875, checked in by kjdon, 16 years ago

added SERVICE_TYPE_OAI

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