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

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

added license message

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