source: main/branches/64_bit_Greenstone/greenstone3/src/java/org/greenstone/gsdl3/util/GSXML.java@ 24007

Last change on this file since 24007 was 24007, checked in by sjm84, 13 years ago

Updating this branch to match the latest Greenstone3 changes

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