source: main/trunk/greenstone3/src/java/org/greenstone/gsdl3/util/OAIXML.java@ 23862

Last change on this file since 23862 was 23862, checked in by ak19, 13 years ago

Minor error in specifying schemaLocation discovered when validating: need a trailing slash after OAI 2.0 part of schemaLocation URL

File size: 28.5 KB
Line 
1/*
2 * OAIXML.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.greenstone.util.GlobalProperties;
22
23import org.w3c.dom.*;
24import java.io.*;
25import java.net.*;
26import java.util.*;
27import java.text.DateFormat;
28import java.text.SimpleDateFormat;
29import org.apache.xerces.parsers.*;
30import org.apache.xml.serialize.*;
31
32// SAX
33import org.xml.sax.XMLReader;
34import org.xml.sax.SAXException;
35import org.xml.sax.SAXParseException;
36import org.xml.sax.helpers.DefaultHandler;
37import org.xml.sax.InputSource;
38
39// JAXP
40import javax.xml.parsers.FactoryConfigurationError;
41import javax.xml.parsers.ParserConfigurationException;
42import javax.xml.parsers.SAXParser;
43import javax.xml.parsers.SAXParserFactory;
44
45// import file Logger.java
46import org.apache.log4j.*;
47
48/** these constants are used for the OAI service */
49public class OAIXML {
50
51 static Logger logger = Logger.getLogger(org.greenstone.gsdl3.util.GSXML.class.getName());
52
53 // the leading keyword of oai protocol
54 public static final String VERB = "verb";
55
56 // six valid oai verbs
57 public static final String GET_RECORD = "GetRecord";
58 public static final String LIST_RECORDS = "ListRecords";
59 public static final String LIST_IDENTIFIERS = "ListIdentifiers";
60 public static final String LIST_SETS = "ListSets";
61 public static final String LIST_METADATA_FORMATS = "ListMetadataFormats";
62 public static final String IDENTIFY = "Identify";
63
64 // other valid oai parameters
65 public static final String OAI_METADATAFORMAT = "OAIMetadataFormat";
66 public static final String METADATA_NAMESPACE = "metadataNamespace";
67 public static final String OAI_DC = "oai_dc";
68 public static final String DC = "dc";
69 public static final String METADATA_PREFIX = "metadataPrefix";
70 public static final String FROM = "from";
71 public static final String UNTIL = "until";
72 public static final String SET = "set";
73 public static final String RESUMPTION_TOKEN = "resumptionToken";
74 public static final String RESUMPTION_TOKEN_EXPIRATION = "resumptionTokenExpiration";
75 public static final String IDENTIFIER = "identifier";
76
77 public static final String USE_STYLESHEET = "useOAIStylesheet";
78 public static final String STYLESHEET = "OAIStylesheet";
79 // words used to compose oai responses
80 public static final String ADMIN_EMAIL = "adminEmail";
81 public static final String BAD_ARGUMENT = "badArgument";
82 public static final String BAD_RESUMPTION_TOKEN = "badResumptionToken";
83 public static final String BAD_VERB = "badVerb";
84 public static final String BASE_URL = "baseURL";
85 public static final String CANNOT_DISSEMINATE_FORMAT = "cannotDisseminateFormat";
86 public static final String CODE = "code";
87 public static final String COLLECTION = "collection";
88 public static final String COLLECTION_LIST = "collectionList";
89 public static final String COMPLETE_LIST_SIZE = "completeListSize";
90 public static final String COMPRESSION = "compression";
91 public static final String CURSOR = "cursor";
92 public static final String DATESTAMP = "datestamp";
93 public static final String DELETED_RECORD = "deletedRecord";
94 public static final String DESCRIPTION = "description";
95 public static final String EARLIEST_DATESTAMP = "earliestDatestamp";
96 public static final String ERROR = "error";
97 public static final String EXPIRATION_DATE = "expirationDate";
98 public static final String GRANULARITY = "granularity";
99 public static final String GS3OAI = "GS3OAI";
100 public static final String HAS_OAI = "hasOAI";
101 public static final String HEADER = "header";
102 public static final String ILLEGAL_OAI_VERB = "Illegal OAI verb";
103 public static final String INDEX_STEM = "indexStem";
104 public static final String LASTMODIFIED = "lastmodified";
105 public static final String MAPPING = "mapping";
106 public static final String MAPPING_LIST = "mappingList";
107 public static final String MESSAGE = "message";
108 public static final String METADATA = "metadata";
109 public static final String METADATA_FORMAT = "metadataFormat";
110 public static final String NAME = "name";
111 public static final String NO_RECORDS_MATCH = "noRecordsMatch";
112 public static final String OAI = "OAI";
113 public static final String OAI_DASH_PMH = "OAI-PMH";
114 public static final String OAIPMH = "OAIPMH";
115 public static final String OAI_RESUMPTION_TOKENS = "OAIResumptionTokens";
116 public static final String OAI_SERVICE = "oaiService";
117 public static final String OAI_SET_LIST = "oaiSetList";
118 public static final String OAI_SERVICE_UNAVAILABLE = "OAI service unavailable";
119 public static final String OID = "OID";
120 public static final String PARAM = "param";
121 public static final String PARAM_LIST = "paramList";
122 public static final String PROTOCOL_VERSION = "protocolVersion";
123 public static final String RECORD = "record";
124 public static final String REQUEST = "request";
125 public static final String REPOSITORY_NAME = "repositoryName";
126 public static final String RESPONSE = "response";
127 public static final String RESPONSE_DATE = "responseDate";
128 public static final String RESUME_AFTER = "resumeAfter";
129 public static final String SCHEMA = "schema";
130 public static final String SERVICE = "service";
131 public static final String SERVICE_UNAVAILABLE = "service unavailable";
132 public static final String SET_SPEC = "setSpec";
133 public static final String SET_NAME = "setName";
134 public static final String SET_DESCRIPTION = "setDescription";
135 public static final String SITE = "site";
136 public static final String TO = "to";
137 public static final String TYPE = "type";
138 public static final String VALUE = "value";
139
140 //Two error and exception conditions for the verb 'ListMetadataFormats'
141 public static final String ID_DOES_NOT_EXIST = "idDoesNotExist";
142 public static final String NO_METADATA_FORMATS = "noMetadataFormats";
143
144 // The node id in the collection database, which contains all the OIDs in the database
145 public static final String BROWSELIST = "browselist";
146
147 //system-dependent file separator, maybe '/' or '\'
148 public static final String FILE_SEPARATOR = File.separator;
149 public static final String OAI_VERSION1 = "1.0";
150 public static final String OAI_VERSION2 = "2.0";
151 /*************************above are final values****************************/
152
153 public static Element resumption_token_elem = null;
154 //used when saving the token file
155 public static File resumption_token_file = null;
156 //public static ArrayList token_list = new ArrayList();
157
158 //initialized in getOAIConfigXML()
159 public static Element oai_config_elem = null;
160
161 //stores the date format "yyyy-MM-ddTHH:mm:ssZ"
162 public static String granularity = "";
163 //this value is overriden in getOAIConfigXML()
164 public static long token_expiration = 7200;
165
166 /** which version of oai that this oaiserver supports; default is 2.0
167 * initialized in getOAIConfigXML()
168 */
169 public static String oai_version = "2.0";
170
171 /**response owner document */
172 public static Document response_doc = new XMLConverter().newDOM();
173
174 public static String[] special_char = {"/", "?", "#", "=", "&", ":", ";", " ", "%", "+"};
175 public static String[] escape_sequence = {"%2F", "%3F", "%23", "%3D", "%26", "%3A", "%3B", "%20", "%25", "%2B"};
176// /** key=special character; value=escaped sequence */
177// public static HashMap encode_map = new HashMap();
178// /** key=escaped sequence; value=special character */
179// public static HashMap decode_map = new HashMap();
180
181 public static void init() {
182 resumption_token_elem = getOAIResumptionTokenXML();
183 }
184 public static String getOAIVersion() {
185 return oai_version;
186 }
187 public static Element createElement(String tag_name) {
188 return response_doc.createElement(tag_name);
189 }
190 /**Compose a response element used when OAIPMH service sending responses thru
191 * ServiceCluster and MessageRouter, as they automatically wrap a message element
192 * on this response element
193 */
194 public static Element getResponse(Element core_msg) {
195 Element res = createElement(RESPONSE);
196 res.appendChild(response_doc.importNode(core_msg, true));
197 return res;
198 }
199 /** Read in OAIResumptionToken.xml (residing web/WEB-INF/classes/) */
200 public static Element getOAIResumptionTokenXML() {
201
202 // The system environment variable $GSDL3HOME(ends ../web) does not contain the file separator
203 resumption_token_file = new File(GlobalProperties.getGSDL3Home() + FILE_SEPARATOR +
204 "WEB-INF" + FILE_SEPARATOR + "classes" +FILE_SEPARATOR + "OAIResumptionToken.xml");
205 if (resumption_token_file.exists()) {
206 Document token_doc = parseXMLFile(resumption_token_file);
207 if (token_doc != null) {
208 resumption_token_elem = token_doc.getDocumentElement();
209 } else {
210 logger.error("Fail to parse resumption token file OAIReceptionToken.xml.");
211 return null;
212 }
213 //remove all expired tokens
214 clearExpiredTokens();
215 return resumption_token_elem;
216 }
217 //if resumption_token_file does not exist
218 logger.info("resumption token file: "+ resumption_token_file.getPath()+" not found! create an empty one.");
219 resumption_token_elem = createElement(OAI_RESUMPTION_TOKENS);
220 saveOAIResumptionTokenXML(resumption_token_elem);
221 return resumption_token_elem;
222 }
223 public static void saveOAIResumptionTokenXML(Element token_elem) {
224 if(writeXMLFile(resumption_token_file, token_elem.getOwnerDocument()) == false) {
225 logger.error("Fail to save the resumption token file");
226 }
227 }
228 public static void clearExpiredTokens() {
229 boolean token_deleted = false;
230 NodeList tokens = GSXML.getChildrenByTagName(resumption_token_elem, RESUMPTION_TOKEN);
231 for (int i=0; i<tokens.getLength(); i++) {
232 Element token_elem = (Element)tokens.item(i);
233 String expire_str = token_elem.getAttribute(EXPIRATION_DATE);
234 long datestamp = getTime(expire_str);
235 if(datestamp < System.currentTimeMillis()) {
236 resumption_token_elem.removeChild(token_elem);
237 token_elem = null;
238 token_deleted = true;
239 }
240 }
241
242 if(token_deleted) {
243 saveOAIResumptionTokenXML(resumption_token_elem);
244 }
245 }
246 public static boolean containsToken(String token) {
247 NodeList tokens = GSXML.getChildrenByTagName(resumption_token_elem, OAIXML.RESUMPTION_TOKEN);
248 for (int i=0; i<tokens.getLength(); i++) {
249 if(token.equals(GSXML.getNodeText((Element)tokens.item(i)).trim() ))
250 return true;
251 }
252 return false;
253 }
254 public static void addToken(Element token) {
255 Document doc = resumption_token_elem.getOwnerDocument();
256 resumption_token_elem.appendChild(duplicateElement(doc, token, true));
257 saveOAIResumptionTokenXML(resumption_token_elem);
258 }
259 public static void addToken(String token) {
260 Element te = resumption_token_elem.getOwnerDocument().createElement(OAIXML.RESUMPTION_TOKEN);
261 //add expiration att
262 resumption_token_elem.appendChild(te);
263 saveOAIResumptionTokenXML(resumption_token_elem);
264 }
265 public static boolean removeToken(String token) {
266 NodeList tokens = GSXML.getChildrenByTagName(resumption_token_elem, OAIXML.RESUMPTION_TOKEN);
267 int num_tokens = tokens.getLength();
268 for (int i=0; i<num_tokens; i++) {
269 Element e = (Element)(tokens.item(i));
270 if(token.equals(GSXML.getNodeText(e))) {
271 resumption_token_elem.removeChild(e);
272 saveOAIResumptionTokenXML(resumption_token_elem);
273 return true;
274 }
275 }
276 return false;
277 }
278 /** Read in OAIConfig.xml (residing web/WEB-INF/classes/) and use it to configure the receptionist etc.
279 * the oai_version variable is also set in here.
280 * The init() method is also called in here. */
281 public static Element getOAIConfigXML() {
282 init();
283
284 // The system environment variable $GSDL3HOME(ends ../web) does not contain the file separator
285 File oai_config_file = new File(GlobalProperties.getGSDL3Home() + FILE_SEPARATOR +
286 "WEB-INF" + FILE_SEPARATOR + "classes" +FILE_SEPARATOR + "OAIConfig.xml");
287 if (!oai_config_file.exists()) {
288 logger.error(" oai config file: "+oai_config_file.getPath()+" not found!");
289 return null;
290 }
291 Document oai_config_doc = parseXMLFile(oai_config_file);
292 if (oai_config_doc != null) {
293 oai_config_elem = oai_config_doc.getDocumentElement();
294 } else {
295 logger.error("Fail to parse oai config file OAIConfig.xml.");
296 return null;
297 }
298
299 //initialize oai_version
300 Element protocol_version = (Element)GSXML.getChildByTagName(oai_config_elem, PROTOCOL_VERSION);
301 oai_version = GSXML.getNodeText(protocol_version).trim();
302
303 //initialize token_expiration
304 Element expiration = (Element)GSXML.getChildByTagName(oai_config_elem, RESUMPTION_TOKEN_EXPIRATION);
305 String expire_str = GSXML.getNodeText(expiration).trim();
306 if (expiration != null && !expire_str.equals("")) {
307 token_expiration = Long.parseLong(expire_str);
308 }
309
310 // read granularity from the config file
311 Element granu_elem = (Element)GSXML.getChildByTagName(oai_config_elem, GRANULARITY);
312 //initialize the granu_str which might be used by other methods (eg, getDate())
313 granularity = GSXML.getNodeText(granu_elem).trim();
314 //change "yyyy-MM-ddTHH:mm:ssZ" to "yyyy-MM-dd'T'HH:mm:ss'Z'"
315 granularity = granularity.replaceAll("T", "'T'");
316 granularity = granularity.replaceAll("Z", "'Z'");
317 granularity = granularity.replaceAll("YYYY", "yyyy").replaceAll("DD", "dd").replaceAll("hh", "HH");
318 return oai_config_elem;
319 }
320
321 public static String[] getMetadataMapping(Element metadata_format) {
322
323 if (metadata_format == null) {
324 return null;
325 }
326 NodeList mappings = metadata_format.getElementsByTagName(MAPPING);
327 int size = mappings.getLength();
328 if (size == 0) {
329 logger.info("No metadata mappings are provided in OAIConfig.xml.");
330 return null;
331 }
332 String[] names = new String[size];
333 for (int i=0; i<size; i++) {
334 names[i] = GSXML.getNodeText((Element)mappings.item(i)).trim();
335 }
336 return names;
337
338 }
339
340 public static String[] getGlobalMetadataMapping(String prefix) {
341 Element list_meta_formats = (Element)GSXML.getChildByTagName(oai_config_elem, LIST_METADATA_FORMATS);
342 if(list_meta_formats == null) {
343 return null;
344 }
345 Element metadata_format = GSXML.getNamedElement(list_meta_formats, METADATA_FORMAT, METADATA_PREFIX, prefix);
346 if(metadata_format == null) {
347 return null;
348 }
349 return getMetadataMapping(metadata_format);
350 }
351
352
353 public static long getTokenExpiration() {
354 return token_expiration*1000;
355 }
356
357 /** TODO: returns a basic response for appropriate oai version
358 *
359 */
360 public static Element createBasicResponse(String verb, String[] pairs) {
361
362 Element response = createResponseHeader(verb);
363
364 //set the responseDate and request elements accordingly
365 Element request_elem = (Element)GSXML.getChildByTagName(response, REQUEST);
366 if (verb.equals("")) {
367 request_elem.setAttribute(VERB, verb);
368 }
369 int num_pairs = (pairs==null)? 0 : pairs.length;
370 for (int i=num_pairs - 1; i>=0; i--) {
371 int index = pairs[i].indexOf("=");
372 if (index != -1) {
373 String[] strs = pairs[i].split("=");
374 if(strs != null && strs.length == 2) {
375 request_elem.setAttribute(strs[0], oaiDecode(strs[1]));
376 }
377 }
378 }//end of for()
379 Element base_url_elem = (Element)GSXML.getChildByTagName(oai_config_elem, BASE_URL);
380 String base_url = GSXML.getNodeText(base_url_elem);
381 GSXML.setNodeText(request_elem, base_url);
382
383 Node resp_date = GSXML.getChildByTagName(response, RESPONSE_DATE);
384 if (resp_date != null) {
385 GSXML.setNodeText((Element)resp_date, getCurrentUTCTime());
386 }
387
388 return response;
389 }
390 /** @param error_code the value of the code attribute
391 * @param error_text the node text of the error element
392 * @return an oai error element
393 * Used by receptionist
394 */
395 public static Element createErrorElement(String error_code, String error_text) {
396 Element error = createElement(ERROR);
397 error.setAttribute(CODE, error_code);
398 GSXML.setNodeText(error, error_text);
399 return error;
400 }
401
402 /** convert the escaped sequences (eg, '%3A') of those special characters back to their
403 * original form (eg, ':').
404 */
405 public static String oaiDecode(String escaped_str) {
406 logger.info("oaiDecode() " +escaped_str);
407 for (int i=0; i<special_char.length; i++) {
408 if (escaped_str.indexOf(escape_sequence[i]) != -1) {
409 escaped_str = escaped_str.replaceAll(escape_sequence[i], special_char[i]);
410 }
411 }
412 //escaped_str = escaped_str.replaceAll("%3A", ":");
413 return escaped_str;
414 }
415 /** convert those special characters (eg, ':') to their
416 * escaped sequences (eg, '%3A').
417 */
418 public static String oaiEncode(String original_str) {
419 logger.info("oaiEncode() " + original_str);
420 for (int i=0; i<special_char.length; i++) {
421 if (original_str.indexOf(special_char[i]) != -1) {
422 original_str = original_str.replaceAll(special_char[i], escape_sequence[i]);
423 }
424 }
425 //original_str = original_str.replaceAll(":", "%3A");
426 return original_str;
427 }
428 /** convert YYYY-MM_DDThh:mm:ssZ to yyyy-MM-ddTHH:mm:ssZ
429 */
430 public static String convertToJava(String oai_format) {
431 oai_format = oai_format.replaceAll("YYYY", "yyyy").replaceAll("DD", "dd").replaceAll("hh", "HH");
432 return oai_format;
433 }
434 /** convert yyyy-MM-ddTHH:mm:ssZ to YYYY-MM_DDThh:mm:ssZ
435 */
436 public static String convertToOAI(String java_format) {
437 java_format = java_format.replaceAll("yyyy", "YYYY").replaceAll("dd", "DD").replaceAll("HH", "hh");
438 return java_format;
439 }
440 public static String getCurrentUTCTime() {
441 Date current_utc = new Date(System.currentTimeMillis());
442 //granularity is in the form: yyyy-MM-dd'T'HH:mm:ss'Z '
443 DateFormat formatter = new SimpleDateFormat(granularity);
444 return formatter.format(current_utc);
445 }
446 /** get a Date object from a Date format pattern string
447 *
448 * @param pattern - in the form: 2007-06-14T16:48:25Z, for example.
449 * @return a Date object - null if the pattern is not in the specified form
450 */
451
452 public static Date getDate(String pattern) {
453 if (pattern == null || pattern.equals("")) {
454 return null;
455 }
456 Date date = null;
457// String str = pattern.replaceAll("T", " ");
458// str = str.replaceAll("Z", "");
459 SimpleDateFormat sdf = null;
460 try {
461 sdf = new SimpleDateFormat(granularity);
462 date = sdf.parse(pattern);
463 } catch(Exception e) {
464 logger.error("invalid date format: " + pattern);
465 return null;
466 }
467 return date;
468 }
469 /** get the million second value from a string representing time in a pattern
470 * (eg, 2007-06-14T16:48:25Z)
471 */
472 public static long getTime(String pattern) {
473 if (pattern == null || pattern.equals("")) {
474 return -1;
475 }
476 Date date = null;
477 SimpleDateFormat sdf = null;
478 try {
479 //granularity is a global variable in the form: yyyy-MM-ddTHH:mm:ssZ
480 sdf = new SimpleDateFormat(granularity);
481 date = sdf.parse(pattern);
482 } catch(Exception e) {
483 logger.error("invalid date format: " + pattern);
484 return -1;
485 }
486 return date.getTime();
487 }
488 /** get the string representation of a time from a long value(long type)
489 */
490 public static String getTime(long seconds) {
491 Date date = new Date(seconds);
492 SimpleDateFormat sdf = new SimpleDateFormat(granularity);
493 return sdf.format(date);
494 }
495 public static Element createResponseHeader(String verb) {
496 String tag_name = (oai_version.equals(OAI_VERSION2))? OAI_DASH_PMH : verb;
497 Element oai = response_doc.createElement(tag_name);
498 Element resp_date = response_doc.createElement(RESPONSE_DATE);
499 Element req = response_doc.createElement(REQUEST);
500 oai.appendChild(resp_date);
501 oai.appendChild(req);
502
503 if(oai_version.equals(OAI_VERSION2)) {
504 oai.setAttribute("xmlns", "http://www.openarchives.org/OAI/2.0/");
505 oai.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
506 oai.setAttribute("xsi:schemaLocation", "http://www.openarchives.org/OAI/2.0/ \n http://www.openarchives.org/OAI/2.0/OAI-PMH.xsd");
507 } else {
508 oai.setAttribute("xmlns", "http://www.openarchives.com/OAI/1.1/OAI_" + verb);
509 oai.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
510 oai.setAttribute("xsi:schemaLocation", "http://www.openarchives.org/OAI/1.1/OAI_" + verb + "\n http://www.openarchives.org/OAI/1.1/OAI_" + verb + ".xsd");
511 }
512 return oai;
513 }
514 public static Element getMetadataPrefixElement(String tag_name, String version) {
515 //examples of tag_name: dc, oai_dc:dc, etc.
516 Element oai = response_doc.createElement(tag_name);
517 if (version.equals(OAI_VERSION2)) {
518 oai.setAttribute("xmlns:oai_dc", "http://www.openarchives.org/OAI/2.0/oai_dc/");
519 oai.setAttribute("xmlns:dc", "http://purl.org/dc/elements/1.1/");
520 oai.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
521 oai.setAttribute("xsi:schemaLocation", "http://www.openarchives.org/OAI/2.0/oai_dc/ \n http://www.openarchives.org/OAI/2.0/oai_dc.xsd");
522 } else {
523 oai.setAttribute("xmlns", "ttp://www.openarchives.com/OAI/1.1/");
524 oai.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
525 oai.setAttribute("xsi:schemaLocation", "http://www.openarchives.org/OAI/1.1/" + tag_name + ".xsd");
526 }
527
528 return oai;
529 }
530 public static HashMap getChildrenMapByTagName(Node n, String tag_name) {
531
532 HashMap map= new HashMap();
533 Node child = n.getFirstChild();
534 while (child!=null) {
535 String name = child.getNodeName();
536 if(name.equals(tag_name)) {
537 map.put(name, child);
538 }
539 child = child.getNextSibling();
540 }
541 return map;
542 }
543
544 /** Duplicates an element */
545 public static Element duplicateElement (Document owner, Element element, boolean with_attributes) {
546 return duplicateElementNS (owner, element, null, with_attributes);
547 }
548
549 /** Duplicates an element */
550 public static Element duplicateElementNS (Document owner,
551 Element element,
552 String namespace_uri,
553 boolean with_attributes) {
554 Element duplicate;
555 if (namespace_uri == null) {
556 duplicate = owner.createElement (element.getTagName ());
557 } else {
558 duplicate = owner.createElementNS (namespace_uri, element.getTagName ());
559 }
560 // Copy element attributes
561 if (with_attributes) {
562 NamedNodeMap attributes = element.getAttributes ();
563 for (int i = 0; i < attributes.getLength (); i++) {
564 Node attribute = attributes.item (i);
565 duplicate.setAttribute (attribute.getNodeName (), attribute.getNodeValue ());
566 }
567 }
568
569 // Copy element children
570 NodeList children = element.getChildNodes ();
571 for (int i = 0; i < children.getLength (); i++) {
572 Node child = children.item (i);
573 duplicate.appendChild (owner.importNode (child, true));
574 }
575
576 return duplicate;
577 }
578
579 public static void copyElement(Element to, Element from, String elem_name) {
580
581 Document to_doc = to.getOwnerDocument();
582 Node child = from.getFirstChild();
583 while (child != null) {
584 if (child.getNodeName().equals(elem_name)) {
585 to.appendChild(to_doc.importNode(child, true));
586 return;
587 }
588 child = child.getNextSibling();
589 }
590 }
591 public static HashMap getParamMap(NodeList params) {
592 HashMap map = new HashMap();
593 for(int i=0; i<params.getLength(); i++) {
594 Element param = (Element)params.item(i);
595 String param_name = param.getAttribute(OAIXML.NAME);
596 String param_value = param.getAttribute(OAIXML.VALUE);
597 map.put(param_name, param_value);
598 }
599 return map;
600 }
601 /** Parse an XML document from a given file */
602 static public Document parseXMLFile (File xml_file) {
603 // No file? No point trying!
604 if (xml_file.exists () == false) {
605 return null;
606 }
607 Document doc = null;
608 try {
609 doc = parseXML (new FileInputStream (xml_file));
610 }
611 catch (Exception exception) {
612 logger.error(exception.toString());
613 return null;
614 }
615 return doc;
616 }
617
618
619 /** Parse an XML document from a given input stream */
620 static public Document parseXML (InputStream xml_input_stream) {
621 Document document = null;
622
623 try {
624 InputStreamReader isr = new InputStreamReader (xml_input_stream, "UTF-8");
625 Reader xml_reader = new BufferedReader (isr);
626 document = parseXML (xml_reader);
627 isr.close ();
628 xml_input_stream.close ();
629 }
630 catch (Exception exception) {
631 logger.error(exception.toString());
632 }
633
634 return document;
635 }
636
637 /** Parse an XML document from a given reader */
638 static public Document parseXML (Reader xml_reader) {
639 Document document = null;
640
641 try {
642 InputSource isc = new InputSource (xml_reader);
643 DOMParser parser = new DOMParser ();
644 parser.setFeature ("http://xml.org/sax/features/validation", false);
645 parser.setFeature ("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
646 // May or may not be ignored, the documentation for Xerces is contradictory. If it works then parsing -should- be faster.
647 parser.setFeature ("http://apache.org/xml/features/dom/defer-node-expansion", true);
648 parser.setFeature ("http://apache.org/xml/features/dom/include-ignorable-whitespace", false);
649 parser.parse (isc);
650 document = parser.getDocument ();
651 }
652 catch (SAXException exception) {
653 System.err.println ("SAX exception: " + exception.getMessage ());
654 logger.error(exception.toString());
655 }
656 catch (Exception exception) {
657 logger.error(exception.toString());
658 }
659
660 return document;
661 }
662 /** Write an XML document to a given file */
663 static public boolean writeXMLFile (File xml_file, Document document) {
664 try {
665 OutputStream os = new FileOutputStream (xml_file);
666 // Create an output format for our document.
667 OutputFormat f = new OutputFormat (document);
668 f.setEncoding ("UTF-8");
669 f.setIndenting (true);
670 f.setLineWidth (0); // Why isn't this working!
671 f.setPreserveSpace (false);
672 // Create the necessary writer stream for serialization.
673 OutputStreamWriter osw = new OutputStreamWriter (os, "UTF-8");
674 Writer w = new BufferedWriter (osw);
675 // Generate a new serializer from the above.
676 XMLSerializer s = new XMLSerializer (w, f);
677 s.asDOMSerializer ();
678 // Finally serialize the document to file.
679 s.serialize (document);
680 // And close.
681 os.close ();
682 return true;
683 }
684 catch (Exception exception) {
685 logger.error(exception.toString());
686 return false;
687 }
688 }
689
690
691}
692
693
694
695
696
697
Note: See TracBrowser for help on using the repository browser.