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

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

some tidy up stuff, for code and output

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