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

Last change on this file since 32882 was 32882, checked in by davidb, 5 years ago

Tweak to logger class, previously a copy-and-paste error to GSXML?

File size: 28.3 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.*;
24
25import java.io.*;
26import java.net.*;
27import java.util.*;
28import java.text.DateFormat;
29import java.text.SimpleDateFormat;
30
31// import file Logger.java
32import org.apache.log4j.*;
33
34/** these constants are used for the OAI service */
35public class OAIXML {
36
37 static Logger logger = Logger.getLogger(org.greenstone.gsdl3.util.OAIXML.class.getName());
38
39 // the leading keyword of oai protocol
40 public static final String VERB = "verb";
41
42 // Possible states for non-OAI/non-verb activate/deactivate requests
43 public static final int DEACTIVATION = 0;
44 public static final int ACTIVATION = 1;
45
46 // six valid oai verbs
47 public static final String GET_RECORD = "GetRecord";
48 public static final String LIST_RECORDS = "ListRecords";
49 public static final String LIST_IDENTIFIERS = "ListIdentifiers";
50 public static final String LIST_SETS = "ListSets";
51 public static final String LIST_METADATA_FORMATS = "ListMetadataFormats";
52 public static final String IDENTIFY = "Identify";
53
54 // oai request parameters
55 public static final String METADATA_PREFIX = "metadataPrefix";
56 public static final String FROM = "from";
57 public static final String UNTIL = "until";
58 public static final String SET = "set";
59 public static final String RESUMPTION_TOKEN = "resumptionToken";
60 public static final String IDENTIFIER = "identifier";
61
62 // Error element and code att
63 public static final String ERROR = "error";
64 public static final String CODE = "code";
65
66 // OAI error codes
67 public static final String BAD_ARGUMENT = "badArgument";
68 public static final String BAD_RESUMPTION_TOKEN = "badResumptionToken";
69 public static final String BAD_VERB = "badVerb";
70 public static final String CANNOT_DISSEMINATE_FORMAT = "cannotDisseminateFormat";
71 public static final String ID_DOES_NOT_EXIST = "idDoesNotExist";
72 public static final String NO_METADATA_FORMATS = "noMetadataFormats";
73 public static final String NO_RECORDS_MATCH = "noRecordsMatch";
74 public static final String NO_SET_HIERARCHY = "noSetHierarchy";
75
76
77 // words used to compose oai responses
78 // many of these used in OAIConfig too
79
80 // General
81 public static final String OAI_PMH = "OAI-PMH";
82 public static final String RESPONSE_DATE = "responseDate";
83 public static final String REQUEST = "request";
84
85 // internal "OID" identifiers in the oai-inf db
86 /** represents the timestamp of the OAI collection (when its oai-inf db was first created) */
87 public static final String OAI_EARLIEST_TIMESTAMP_OID = "_earliesttimestamp";
88
89 // Identify data
90 public static final String ADMIN_EMAIL = "adminEmail";
91 public static final String BASE_URL = "baseURL";
92 public static final String COMPRESSION = "compression";
93 public static final String DELETED_RECORD = "deletedRecord";
94 public static final String DESCRIPTION = "description";
95 public static final String EARLIEST_DATESTAMP = "earliestDatestamp"; // taken from buildconfig used as publishing date by RSS service
96 public static final String EARLIEST_OAI_DATESTAMP = "earliestOAIDatestamp"; // earliest timestamp of an OAI collection stored in oai-inf db
97 public static final String GRANULARITY = "granularity";
98 public static final String LAST_MODIFIED = "lastmodified";
99 public static final String PROTOCOL_VERSION = "protocolVersion";
100 public static final String REPOSITORY_NAME = "repositoryName";
101 public static final String OAI_IDENTIFIER = "oai-identifier";
102 public static final String SCHEME = "scheme";
103 public static final String REPOSITORY_IDENTIFIER = "repositoryIdentifier";
104 public static final String DELIMITER = "delimiter";
105 public static final String SAMPLE_IDENTIFIER = "sampleIdentifier";
106
107 // metadata formats
108 public static final String METADATA_FORMAT = "metadataFormat";
109 public static final String SCHEMA = "schema";
110 public static final String METADATA_NAMESPACE = "metadataNamespace";
111 public static final String META_FORMAT_DC = "oai_dc";
112
113 // record response data
114 // SET_SPEC
115 public static final String RECORD = "record";
116 public static final String HEADER = "header";
117 public static final String DATESTAMP = "datestamp";
118 public static final String METADATA = "metadata";
119
120 // list sets
121 // SET,
122 public static final String SET_NAME = "setName";
123 public static final String SET_SPEC = "setSpec";
124 public static final String SET_DESCRIPTION = "setDescription";
125
126 // resumption token element
127 public static final String RESUMPTION_TOKEN_ELEM = "resumptionToken";
128 public static final String EXPIRATION_DATE = "expirationDate";
129 public static final String COMPLETE_LIST_SIZE = "completeListSize";
130 public static final String CURSOR = "cursor";
131
132 // extra elements/attributes from OAIConfig
133 public static final String OAI_INFO = "oaiInfo";
134 public static final String USE_STYLESHEET = "useOAIStylesheet";
135 public static final String STYLESHEET = "OAIStylesheet";
136 public static final String RESUME_AFTER = "resumeAfter";
137 public static final String RESUMPTION_TOKEN_EXPIRATION = "resumptionTokenExpiration";
138 public static final String OAI_SUPER_SET = "oaiSuperSet";
139 public static final String ELEMENT = "element";
140 public static final String ELEMENTS = "elements";
141 public static final String MAPPING = "mapping";
142 public static final String SELECT = "select";
143 public static final String SELECT_SINGLE_VALUE = "firstvalue";
144 public static final String SELECT_FIRST_VALID_META = "firstvalidmetadata";
145 public static final String SELECT_ALL_VALUES = "allvalues";
146 // code constants
147 public static final String GS_OAI_DATE_STAMP = "gs.OAIDateStamp";
148 public static final String GS_OAI_RESOURCE_URL = "gs.OAIResourceURL";
149 public static final String GSF_LINK_PREFIX = "gsflink.";
150 public static final String LINK_TYPE_DOCUMENT = "document";
151 public static final String LINK_TYPE_SOURCE = "source";
152 public static final String ILLEGAL_OAI_VERB = "Illegal OAI verb";
153 public static final String LASTMODIFIED = "lastmodified";
154 // // The node id in the collection database, which contains all the OIDs in the database
155 public static final String BROWSELIST = "browselist";
156 public static final String OAI_LASTMODIFIED = "oailastmodified";
157 public static final String OAIPMH = "OAIPMH";
158 public static final String OAI_SET_LIST = "oaiSetList";
159 public static final String OAI_SERVICE_UNAVAILABLE = "OAI service unavailable";
160 public static final String OID = "OID";
161
162 // The node id in the oai-inf database of the collection, which should contain all the OIDs in the db
163 public static final String OAI_INF_STATUS = "status"; // D = Deleted; E = Existing (PD = Provisionally Deleted but PD should not be present at this stage in the oai-inf database)
164 public static final String OAI_INF_TIMESTAMP = "timestamp"; // the time of deletion/last (re)indexing of doc
165 public static final String OAI_INF_DATESTAMP = "datestamp"; // date version of timestamp
166 // oai-inf db values for OAI_INF_STATUS
167 public static final String OAI_INF_DELETED = "D";
168 public static final String OAI_INF_EXISTS = "E";
169 public static final String OAI_INF_PROVISIONALLY_DELETED = "PD";
170 // header values for ListRecords/GetRecord and listIdentifiers
171 public static final String HEADER_STATUS_ATTR_DELETED = "deleted";
172
173 public static final String OAI_SERVICE_RACK = "OAIPMH";
174 //system-dependent file separator, maybe '/' or '\'
175 public static final String FILE_SEPARATOR = File.separator;
176 public static final String OAI_VERSION1 = "1.0";
177 public static final String OAI_VERSION2 = "2.0";
178 /*************************above are final values****************************/
179
180
181 //initialized in getOAIConfigXML()
182 public static Element oai_config_elem = null;
183
184 //stores the date format "yyyy-MM-ddTHH:mm:ssZ"
185 // this is the granularity for datestamps
186 public static String granularity = "";
187
188 // http://www.openarchives.org/OAI/openarchivesprotocol.html#DatestampsRequests
189 // specifies that all repositories must support YYYY-MM-DD (yyyy-MM-dd in Java)
190 // this would be in addition to the other (optional) granularity of above that
191 // a repository may additionally choose to support.
192 public static final String default_granularity = "yyyy-MM-dd";
193
194 public static long token_expiration = 7200;
195 /** which version of oai that this oaiserver supports; default is 2.0
196 * initialized in getOAIConfigXML()
197 */
198 public static String oai_version = "2.0";
199 public static String baseURL = "";
200
201 /** Converter for parsing files and creating Elements */
202 public static XMLConverter converter = new XMLConverter();
203
204 public static String[] special_char = {"/", "?", "#", "=", "&", ":", ";", " ", "%", "+"};
205 public static String[] escape_sequence = {"%2F", "%3F", "%23", "%3D", "%26", "%3A", "%3B", "%20", "%25", "%2B"};
206
207 public static String getOAIVersion() {
208 return oai_version;
209 }
210
211 public static String getBaseURL() {
212 return baseURL;
213 }
214
215 /** Read in OAIConfig.xml (residing web/WEB-INF/classes/) and use it to configure the receptionist etc.
216 * the oai_version and baseURL variables are also set in here.
217 * The init() method is also called in here. */
218 public static Element getOAIConfigXML() {
219
220 File oai_config_file = null;
221
222 try {
223 URL oai_config_url = Class.forName("org.greenstone.gsdl3.OAIServer").getClassLoader().getResource("OAIConfig.xml");
224 if (oai_config_url == null) {
225 logger.error("couldn't find OAIConfig.xml via class loader");
226 return null;
227 }
228 oai_config_file = new File(oai_config_url.toURI());
229 if (!oai_config_file.exists()) {
230 logger.error(" oai config file: "+oai_config_file.getPath()+" not found!");
231 return null;
232 }
233 } catch(Exception e) {
234 logger.error("couldn't find OAIConfig.xml "+e.getMessage());
235 return null;
236 }
237
238 Document oai_config_doc = converter.getDOM(oai_config_file, "utf-8");
239 if (oai_config_doc != null) {
240 oai_config_elem = oai_config_doc.getDocumentElement();
241 } else {
242 logger.error("Failed to parse oai config file OAIConfig.xml.");
243 return null;
244 }
245
246 //initialize oai_version
247 Element protocol_version = (Element)GSXML.getChildByTagName(oai_config_elem, PROTOCOL_VERSION);
248 oai_version = GSXML.getNodeText(protocol_version).trim();
249
250 // initialize baseURL
251 Element base_url_elem = (Element)GSXML.getChildByTagName(oai_config_elem, BASE_URL);
252 baseURL = GSXML.getNodeText(base_url_elem);
253
254 //initialize token_expiration
255 Element expiration = (Element)GSXML.getChildByTagName(oai_config_elem, RESUMPTION_TOKEN_EXPIRATION);
256 String expire_str = GSXML.getNodeText(expiration).trim();
257 if (expiration != null && !expire_str.equals("")) {
258 token_expiration = Long.parseLong(expire_str);
259 }
260
261 // read granularity from the config file
262 Element granu_elem = (Element)GSXML.getChildByTagName(oai_config_elem, GRANULARITY);
263 //initialize the granu_str which might be used by other methods (eg, getDate())
264 granularity = GSXML.getNodeText(granu_elem).trim();
265
266 //change "yyyy-MM-ddTHH:mm:ssZ" to "yyyy-MM-dd'T'HH:mm:ss'Z'"
267 granularity = granularity.replaceAll("T", "'T'");
268 granularity = granularity.replaceAll("Z", "'Z'");
269 granularity = granularity.replaceAll("YYYY", "yyyy").replaceAll("DD", "dd").replaceAll("hh", "HH");
270 return oai_config_elem;
271 }
272
273 public static String[] getMetadataMapping(Element metadata_format) {
274
275 if (metadata_format == null) {
276 return null;
277 }
278 NodeList mappings = metadata_format.getElementsByTagName(MAPPING);
279 int size = mappings.getLength();
280 if (size == 0) {
281 logger.info("No metadata mappings are provided in OAIConfig.xml.");
282 return null;
283 }
284 String[] names = new String[size];
285 for (int i=0; i<size; i++) {
286 names[i] = GSXML.getNodeText((Element)mappings.item(i)).trim();
287 }
288 return names;
289
290 }
291
292 public static String[] getGlobalMetadataMapping(String prefix) {
293 Element list_meta_formats = (Element)GSXML.getChildByTagName(oai_config_elem, LIST_METADATA_FORMATS);
294 if(list_meta_formats == null) {
295 return null;
296 }
297 Element metadata_format = GSXML.getNamedElement(list_meta_formats, METADATA_FORMAT, METADATA_PREFIX, prefix);
298 if(metadata_format == null) {
299 return null;
300 }
301 return getMetadataMapping(metadata_format);
302 }
303
304 /** Copies out the main info from a metadataFormat element, leaving behind the mapping stuff. This gets the bit needed for OAI response */
305 public static Element getMetadataFormatShort(Document doc, Element meta_format_long) {
306 Element meta_fmt = doc.createElement(OAIXML.METADATA_FORMAT);
307 // Copy in the elements that we want, and ignore the rest
308 meta_fmt.appendChild(doc.importNode(GSXML.getChildByTagName(meta_format_long, OAIXML.METADATA_PREFIX), true));
309 meta_fmt.appendChild(doc.importNode(GSXML.getChildByTagName(meta_format_long, OAIXML.SCHEMA), true));
310 meta_fmt.appendChild(doc.importNode(GSXML.getChildByTagName(meta_format_long, OAIXML.METADATA_NAMESPACE), true));
311
312 return meta_fmt;
313 }
314
315
316 public static long getTokenExpiration() {
317 return token_expiration*1000; // in milliseconds
318 }
319
320 /** TODO: returns a basic response for appropriate oai version
321 *
322 */
323 public static Element createBasicResponse(Document doc, String verb, String[] pairs) {
324
325 Element response = createResponseHeader(doc, verb);
326
327 //set the responseDate and request elements accordingly
328 Element request_elem = (Element)GSXML.getChildByTagName(response, REQUEST);
329 if (verb.equals("")) {
330 request_elem.setAttribute(VERB, verb);
331 }
332 int num_pairs = (pairs==null)? 0 : pairs.length;
333 for (int i=num_pairs - 1; i>=0; i--) {
334 int index = pairs[i].indexOf("=");
335 if (index != -1) {
336 String[] strs = pairs[i].split("=");
337 if(strs != null && strs.length == 2) {
338 request_elem.setAttribute(strs[0], oaiDecode(strs[1]));
339 }
340 }
341 }//end of for()
342
343 GSXML.setNodeText(request_elem, baseURL);
344
345 Node resp_date = GSXML.getChildByTagName(response, RESPONSE_DATE);
346 if (resp_date != null) {
347 GSXML.setNodeText((Element)resp_date, getCurrentUTCTime());
348 }
349
350 return response;
351 }
352 /** @param error_code the value of the code attribute
353 * @param error_text the node text of the error element
354 * @return an oai error <message><response><error>
355 */
356 public static Element createErrorMessage(String error_code, String error_text) {
357 Document doc = converter.newDOM();
358 Element message = doc.createElement(GSXML.MESSAGE_ELEM);
359 Element resp = doc.createElement(GSXML.RESPONSE_ELEM);
360 message.appendChild(resp);
361 Element error = createErrorElement(doc, error_code, error_text);
362 resp.appendChild(error);
363 return message;
364 }
365
366 /** @param error_code the value of the code attribute
367 * @param error_text the node text of the error element
368 * @return an oai error <response><error>
369 */
370 public static Element createErrorResponse(String error_code, String error_text) {
371 Document doc = converter.newDOM();
372 Element resp = doc.createElement(GSXML.RESPONSE_ELEM);
373 Element error = createErrorElement(doc, error_code, error_text);
374 resp.appendChild(error);
375 return resp;
376 }
377
378 /** @param error_code the value of the code attribute
379 * @param error_text the node text of the error element
380 * @return an oai error <error>
381 */
382 public static Element createErrorElement(Document doc, String error_code, String error_text) {
383 Element error = doc.createElement(ERROR);
384 error.setAttribute(CODE, error_code);
385 GSXML.setNodeText(error, error_text);
386 return error;
387 }
388
389 // This is the response message sent when there's a request to activate/deactivate a non-OAI collection
390 // A request to activate a non-existent/non-OAI collection is not invalid, it's just that we won't process it.
391 // So we still return status code OK (OK status code is needed for servercontrol.pm of activate.pl to recognise
392 // that the command had been "successful" when it runs de/activate).
393 public static Element createDeActivationOfNonOAICollResponse(int activationState, String collname) {
394 Document doc = converter.newDOM();
395 Element response = doc.createElement(GSXML.RESPONSE_ELEM);
396 response.setAttribute("status", "OK");
397 String message = "collection: " + collname + " is not enabled for OAI.";
398 if(activationState == ACTIVATION) {
399 message += " Not attempting to activate it.";
400 } else {
401 message += " Not attempting to deactivate it.";
402 }
403 GSXML.setNodeText(response, message);
404 return response;
405 }
406
407 // The response message sent when a request comes in to activate/deactivate a proper OAI collection.
408 public static Element createActivationStateResponse(boolean success, int activationState, String collname) {
409 Document doc = converter.newDOM();
410 Element response = doc.createElement(GSXML.RESPONSE_ELEM);
411 if (success) {
412 response.setAttribute("status", "OK");
413 if(activationState == ACTIVATION) {
414 GSXML.setNodeText(response, "collection: " + collname + " activated");
415 } else {
416 GSXML.setNodeText(response, "collection: " + collname + " deactivated");
417 }
418 } else {
419 response.setAttribute("status", "FAIL");
420 if(activationState == ACTIVATION) {
421 GSXML.setNodeText(response, "Failed to activate collection " + collname);
422 } else {
423 GSXML.setNodeText(response, "Failed to deactivate collection " + collname);
424 }
425 }
426 return response;
427 }
428
429 public static Element createResetResponse(boolean success) {
430 Document doc = converter.newDOM();
431 Element response = doc.createElement(GSXML.RESPONSE_ELEM);
432 if (success) {
433 response.setAttribute("status", "OK");
434 GSXML.setNodeText(response, "Reset OAIServer successfully");
435 } else {
436 response.setAttribute("status", "FAIL");
437 GSXML.setNodeText(response, "Failed to reset oaiserver");
438 }
439 return response;
440 }
441 /** convert the escaped sequences (eg, '%3A') of those special characters back to their
442 * original form (eg, ':').
443 */
444 public static String oaiDecode(String escaped_str) {
445 logger.info("oaiDecode() " +escaped_str);
446 for (int i=0; i<special_char.length; i++) {
447 if (escaped_str.indexOf(escape_sequence[i]) != -1) {
448 escaped_str = escaped_str.replaceAll(escape_sequence[i], special_char[i]);
449 }
450 }
451 return escaped_str;
452 }
453 /** convert those special characters (eg, ':') to their
454 * escaped sequences (eg, '%3A').
455 */
456 public static String oaiEncode(String original_str) {
457 logger.info("oaiEncode() " + original_str);
458 for (int i=0; i<special_char.length; i++) {
459 if (original_str.indexOf(special_char[i]) != -1) {
460 original_str = original_str.replaceAll(special_char[i], escape_sequence[i]);
461 }
462 }
463 return original_str;
464 }
465 /** convert YYYY-MM_DDThh:mm:ssZ to yyyy-MM-ddTHH:mm:ssZ
466 */
467 public static String convertToJava(String oai_format) {
468 oai_format = oai_format.replaceAll("YYYY", "yyyy").replaceAll("DD", "dd").replaceAll("hh", "HH");
469 return oai_format;
470 }
471 /** convert yyyy-MM-ddTHH:mm:ssZ to YYYY-MM_DDThh:mm:ssZ
472 */
473 public static String convertToOAI(String java_format) {
474 java_format = java_format.replaceAll("yyyy", "YYYY").replaceAll("dd", "DD").replaceAll("HH", "hh");
475 return java_format;
476 }
477 public static String getCurrentUTCTime() {
478 Date current_utc = new Date(System.currentTimeMillis());
479 //granularity is in the form: yyyy-MM-dd'T'HH:mm:ss'Z '
480 DateFormat formatter = new SimpleDateFormat(granularity);
481 return formatter.format(current_utc);
482 }
483 /** get a Date object from a Date format pattern string
484 *
485 * @param pattern - in the form: 2007-06-14T16:48:25Z, for example.
486 * @return a Date object - null if the pattern is not in the specified form
487 */
488
489 public static Date getDate(String pattern) {
490 if (pattern == null || pattern.equals("")) {
491 return null;
492 }
493 Date date = null;
494 // String str = pattern.replaceAll("T", " ");
495 // str = str.replaceAll("Z", "");
496 SimpleDateFormat sdf = null;
497 try {
498 sdf = new SimpleDateFormat(granularity);
499 date = sdf.parse(pattern);
500 } catch(Exception e) {
501 if(!default_granularity.equals(granularity)) { // try validating against default granularity
502 try {
503 date = null;
504 sdf = null;
505 sdf = new SimpleDateFormat(default_granularity);
506 date = sdf.parse(pattern);
507 } catch(Exception ex) {
508 logger.error("invalid date format: " + pattern);
509 return null;
510 }
511 } else {
512 logger.error("invalid date format: " + pattern);
513 return null;
514 }
515 }
516 return date;
517 }
518 /** get the million second value from a string representing time in a pattern
519 * (eg, 2007-06-14T16:48:25Z)
520 */
521 public static long getTime(String pattern) {
522 if (pattern == null || pattern.equals("")) {
523 return -1;
524 }
525 Date date = null;
526 SimpleDateFormat sdf = null;
527 try {
528 //granularity is a global variable in the form: yyyy-MM-ddTHH:mm:ssZ
529 sdf = new SimpleDateFormat(granularity);
530 date = sdf.parse(pattern);
531 } catch(Exception e) {
532 if(!default_granularity.equals(granularity)) { // try validating against default granularity
533 try {
534 date = null;
535 sdf = null;
536 sdf = new SimpleDateFormat(default_granularity);
537 date = sdf.parse(pattern);
538 } catch(Exception ex) {
539 logger.error("invalid date format: " + pattern);
540 return -1;
541 }
542 } else {
543 logger.error("invalid date format: " + pattern);
544 return -1;
545 }
546 }
547 return date.getTime();
548 }
549 /** get the string representation of a time from a long value(long type)
550 */
551 public static String getTime(long milliseconds) {
552 Date date = new Date(milliseconds);
553 SimpleDateFormat sdf = new SimpleDateFormat(granularity);
554 return sdf.format(date);
555 }
556 public static Element createResponseHeader(Document response_doc, String verb) {
557 String tag_name = (oai_version.equals(OAI_VERSION2))? OAI_PMH : verb;
558 Element oai = response_doc.createElement(tag_name);
559 Element resp_date = response_doc.createElement(RESPONSE_DATE);
560 Element req = response_doc.createElement(REQUEST);
561 oai.appendChild(resp_date);
562 oai.appendChild(req);
563
564 if(oai_version.equals(OAI_VERSION2)) {
565 oai.setAttribute("xmlns", "http://www.openarchives.org/OAI/2.0/");
566 oai.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
567 oai.setAttribute("xsi:schemaLocation", "http://www.openarchives.org/OAI/2.0/ \n http://www.openarchives.org/OAI/2.0/OAI-PMH.xsd");
568 } else {
569 oai.setAttribute("xmlns", "http://www.openarchives.com/OAI/1.1/OAI_" + verb);
570 oai.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
571 oai.setAttribute("xsi:schemaLocation", "http://www.openarchives.org/OAI/1.1/OAI_" + verb + "\n http://www.openarchives.org/OAI/1.1/OAI_" + verb + ".xsd");
572 }
573 return oai;
574 }
575
576 public static Element getMetadataPrefixElement(Document doc, String prefix, Element meta_format) {
577
578 Element ns_elem = (Element)GSXML.getChildByTagName(meta_format, METADATA_NAMESPACE);
579 String namespace = null;
580 if (ns_elem != null) {
581 namespace = GSXML.getNodeText(ns_elem);
582 }
583 if (namespace == null || namespace.equals("")) {
584 logger.error("No namespace URI found in metadataFormat elemnt for "+prefix);
585 logger.error(XMLConverter.getPrettyString(meta_format));
586 return null;
587 }
588
589 Element sc_elem = (Element)GSXML.getChildByTagName(meta_format, SCHEMA);
590 String schema = null;
591 if (sc_elem != null) {
592 schema = GSXML.getNodeText(sc_elem);
593 }
594 if (schema == null || schema.equals("")) {
595 logger.error("No schema found in metadataFormat element for "+prefix);
596 logger.error(XMLConverter.getPrettyString(meta_format));
597 return null;
598 }
599
600 String tag_name = getMetadataTagName(prefix, oai_version);
601 Element oai = doc.createElement(tag_name);
602 oai.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
603
604 if (oai_version.equals(OAI_VERSION2)) {
605 oai.setAttribute("xmlns:"+prefix, namespace);
606 if (prefix.equals(META_FORMAT_DC)) {
607 // there seems to be an extra one for dc
608 oai.setAttribute("xmlns:dc", "http://purl.org/dc/elements/1.1/");
609 }
610 oai.setAttribute("xsi:schemaLocation", namespace+" \n "+schema);
611 } else {
612 oai.setAttribute("xmlns", "http://www.openarchives.com/OAI/1.1/");
613 if (prefix.equals(META_FORMAT_DC)) {
614 oai.setAttribute("xsi:schemaLocation", "http://www.openarchives.org/OAI/1.1/" + tag_name + ".xsd");
615 } else {
616 oai.setAttribute("xsi:schemaLocation", schema);
617 }
618 }
619
620 return oai;
621
622 }
623
624 public static String getMetadataTagName(String prefix, String oai_version) {
625 if (prefix.equals(META_FORMAT_DC)) {
626 if (oai_version.equals(OAI_VERSION2)) {
627 return "oai_dc:dc";
628 }
629 return "dc";
630 }
631 return prefix;
632 }
633
634 public static HashMap<String, Node> getChildrenMapByTagName(Node n, String tag_name) {
635
636 HashMap<String, Node> map= new HashMap<String, Node>();
637 Node child = n.getFirstChild();
638 while (child!=null) {
639 String name = child.getNodeName();
640 if(name.equals(tag_name)) {
641 map.put(name, child);
642 }
643 child = child.getNextSibling();
644 }
645 return map;
646 }
647
648 public static Element createOAIIdentifierXML(Document doc, String repository_id, String sample_collection, String sample_doc_id) {
649 String xml = "<oai-identifier xmlns=\"http://www.openarchives.org/OAI/2.0/oai-identifier\"\n xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation=\"http://www.openarchives.org/OAI/2.0/oai-identifier\n http://www.openarchives.org/OAI/2.0/oai-identifier.xsd\">\n <scheme>oai</scheme>\n<repositoryIdentifier>" + repository_id + "</repositoryIdentifier>\n<delimiter>:</delimiter>\n<sampleIdentifier>oai:"+repository_id+":"+sample_collection+":"+sample_doc_id+"</sampleIdentifier>\n</oai-identifier>";
650
651 Document xml_doc = converter.getDOM(xml);
652 return (Element)doc.importNode(xml_doc.getDocumentElement(), true);
653
654
655 }
656
657 public static Element createGSDLElement(Document doc) {
658 String xml = "<gsdl xmlns=\"http://www.greenstone.org/namespace/gsdl_oaiinfo/1.0/gsdl_oaiinfo\"\n xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation=\"http://www.greenstone.org/namespace/gsdl_oaiinfo/1.0/gsdl_oaiinfo\n http://www.greenstone.org/namespace/gsdl_oaiinfo/1.0/gsdl_oaiinfo.xsd\"></gsdl>";
659 Document xml_doc = converter.getDOM(xml);
660 return (Element)doc.importNode(xml_doc.getDocumentElement(), true);
661
662
663 }
664
665 public static Element createSet(Document doc, String spec, String name, String description) {
666
667 Element set_elem = doc.createElement(SET);
668 Element set_spec = doc.createElement(SET_SPEC);
669 GSXML.setNodeText(set_spec, spec);
670 set_elem.appendChild(set_spec);
671 Element set_name = doc.createElement(SET_NAME);
672 GSXML.setNodeText(set_name, name);
673 set_elem.appendChild(set_name);
674 if (description != null) {
675 Element set_description = doc.createElement(SET_DESCRIPTION);
676 GSXML.setNodeText(set_description, description);
677 set_elem.appendChild(set_description);
678 }
679 return set_elem;
680
681 }
682
683 /** returns the resumptionToken element to go into an OAI response */
684 public static Element createResumptionTokenElement(Document doc, String token_name, int total_size, int cursor, long expiration_time) {
685 Element token = doc.createElement(OAIXML.RESUMPTION_TOKEN);
686 if (total_size != -1) {
687 token.setAttribute(OAIXML.COMPLETE_LIST_SIZE, "" + total_size);
688 }
689 if (cursor != -1) {
690 token.setAttribute(OAIXML.CURSOR, "" + cursor);
691 }
692 if(expiration_time !=-1) {
693 token.setAttribute(OAIXML.EXPIRATION_DATE, getTime(expiration_time));
694 }
695
696 if (token != null) {
697 GSXML.setNodeText(token, token_name);
698 }
699 return token;
700 }
701
702}
703
704
705
706
707
708
Note: See TracBrowser for help on using the repository browser.