source: main/trunk/greenstone3/src/java/org/greenstone/gsdl3/core/OAIReceptionist.java@ 28879

Last change on this file since 28879 was 28879, checked in by kjdon, 10 years ago

changed collection_list from NodeList to Element as NodeList operations are not thread safe. Tried to get a more accurate earliestdatestamp. don't use datestamps of 0 as they are not real datestamps. use value from oaiconfig.xml if haven't found a valid collection one

File size: 40.7 KB
Line 
1/*
2 * OAIReceptionist.java
3 * Copyright (C) 2012 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 */
19
20package org.greenstone.gsdl3.core;
21
22import org.greenstone.gsdl3.util.*;
23import org.greenstone.gsdl3.action.*;
24// XML classes
25import org.w3c.dom.Node;
26import org.w3c.dom.NodeList;
27import org.w3c.dom.Document;
28import org.w3c.dom.Element;
29
30// other java classes
31import java.io.File;
32import java.util.*;
33
34import org.apache.log4j.*;
35
36/** a Receptionist, used for oai metadata response xml generation.
37 * This receptionist talks to the message router directly,
38 * instead of via any action, hence no action map is needed.
39 * @see the basic Receptionist
40 */
41public class OAIReceptionist implements ModuleInterface {
42
43 static Logger logger = Logger.getLogger(org.greenstone.gsdl3.core.OAIReceptionist.class.getName());
44
45 /** Instead of a config_params object, only a site_name is needed by oai receptionist. */
46 protected String site_name = null;
47 /** The unique repository identifier */
48 protected String repository_id = null;
49
50 /** a converter class to parse XML and create Docs */
51 protected XMLConverter converter=null;
52
53 /** the configure file of this receptionist passed from the oai servlet. */
54 protected Element oai_config = null;
55
56 /** contained in the OAIConfig.xml deciding whether the resumptionToken should be in use */
57 protected int resume_after = -1 ;
58
59 /** the message router that the Receptionist and Actions will talk to */
60 protected ModuleInterface mr = null;
61
62 // Some of the data/responses will not change while the servlet is running, so
63 // we can cache them
64
65 /** A list of all the collections available to this OAI server */
66 protected Element collection_list = null;
67 /** a vector of the names, for convenience */
68 protected Vector<String> collection_name_list = null;
69 /** If this is true, then there are no OAI enabled collections, so can always return noRecordsMatch (after validating the request params) */
70 protected boolean noRecordsMatch = false;
71
72 /** A set of all known 'sets' */
73 protected HashSet<String> set_set = null;
74
75 protected boolean has_super_colls = false;
76 /** a hash of super set-> collection list */
77 protected HashMap<String, Vector<String>> super_coll_map = null;
78 /** The identify response */
79 protected Element identify_response = null;
80 /** The list set response */
81 protected Element listsets_response = null;
82 /** the list metadata formats response */
83 protected Element listmetadataformats_response = null;
84
85 public OAIReceptionist() {
86 this.converter = new XMLConverter();
87 }
88
89 public void cleanUp() {
90 if (this.mr != null) {
91
92 this.mr.cleanUp();
93 }
94 OAIResumptionToken.saveTokensToFile();
95 }
96
97 public void setSiteName(String site_name) {
98 this.site_name = site_name;
99 }
100 /** sets the message router - it should already be created and
101 * configured in the init() of a servlet (OAIServer, for example) before being passed to the receptionist*/
102 public void setMessageRouter(ModuleInterface mr) {
103 this.mr = mr;
104 }
105
106 /** configures the receptionist */
107 public boolean configure(Element config) {
108
109 if (this.mr==null) {
110 logger.error(" message routers must be set before calling oai configure");
111 return false;
112 }
113 if (config == null) {
114 logger.error(" oai configure file is null");
115 return false;
116 }
117 oai_config = config;
118 resume_after = getResumeAfter();
119
120 repository_id = getRepositoryIdentifier();
121 if (!configureSetInfo()) {
122 // there are no sets
123 logger.error("No sets (collections) available for OAI");
124 return false;
125 }
126
127 //clear out expired resumption tokens stored in OAIResumptionToken.xml
128 OAIResumptionToken.init();
129 OAIResumptionToken.clearExpiredTokens();
130
131 return true;
132 }
133
134 // assuming that sets are static. If collections change then the servlet
135 // should be restarted.
136 private boolean configureSetInfo() {
137 // do we have any super colls listed in web/WEB-INF/classes/OAIConfig.xml?
138 // Will be like
139 // <oaiSuperSet>
140 // <SetSpec>xxx</SetSpec>
141 // <setName>xxx</SetName>
142 // <SetDescription>xxx</setDescription>
143 // </oaiSuperSet>
144 // The super set is listed in OAIConfig, and collections themselves state
145 // whether they are part of the super set or not.
146 NodeList super_coll_list = this.oai_config.getElementsByTagName(OAIXML.OAI_SUPER_SET);
147 HashMap<String, Element> super_coll_data = new HashMap<String, Element>();
148 if (super_coll_list.getLength() > 0) {
149 this.has_super_colls = true;
150 for (int i=0; i<super_coll_list.getLength(); i++) {
151 Element super_coll = (Element)super_coll_list.item(i);
152 Element set_spec = (Element)GSXML.getChildByTagName(super_coll, OAIXML.SET_SPEC);
153 if (set_spec != null) {
154 String name = GSXML.getNodeText(set_spec);
155 if (!name.equals("")) {
156 super_coll_data.put(name, super_coll);
157 logger.error("adding in super coll "+name);
158 }
159 }
160 }
161
162 if (super_coll_data.size()==0) {
163 this.has_super_colls = false;
164 }
165 }
166 if (this.has_super_colls == true) {
167 this.super_coll_map = new HashMap<String, Vector<String>>();
168 }
169 this.set_set = new HashSet<String>();
170
171 // next, we get a list of all the OAI enabled collections
172 // We get this by sending a listSets request to the MR
173 Document doc = this.converter.newDOM();
174 Element message = doc.createElement(GSXML.MESSAGE_ELEM);
175
176 Element request = GSXML.createBasicRequest(doc, OAIXML.OAI_SET_LIST, "", null);
177 message.appendChild(request);
178 Node msg_node = mr.process(message);
179
180 if (msg_node == null) {
181 logger.error("returned msg_node from mr is null");
182 return false;
183 }
184 Element resp = (Element)GSXML.getChildByTagName(msg_node, GSXML.RESPONSE_ELEM);
185 Element coll_list = (Element)GSXML.getChildByTagName(resp, GSXML.COLLECTION_ELEM + GSXML.LIST_MODIFIER);
186 if (coll_list == null) {
187 logger.error("coll_list is null");
188 return false;
189 }
190
191 this.collection_list = (Element)doc.importNode(coll_list, true);
192
193 // go through and store a list of collection names for convenience
194 // also create a 'to' attribute
195 Node child = this.collection_list.getFirstChild();
196 if (child == null) {
197 logger.error("collection list has no children");
198 noRecordsMatch = true;
199 return false;
200 }
201
202 this.collection_name_list = new Vector<String>();
203 StringBuffer to = new StringBuffer();
204 boolean first = true;
205 while (child != null) {
206 if (child.getNodeName().equals(GSXML.COLLECTION_ELEM)) {
207 String coll_id =((Element) child).getAttribute(GSXML.NAME_ATT);
208 this.collection_name_list.add(coll_id);
209 if (!first) {
210 to.append(',');
211 }
212 first = false;
213 to.append(coll_id+"/"+OAIXML.LIST_SETS);
214 }
215 child = child.getNextSibling();
216 }
217 if (first) {
218 // we haven't found any collections
219 logger.error("found no collection elements in collectionList");
220 noRecordsMatch = true;
221 return false;
222 }
223 Document listsets_doc = this.converter.newDOM();
224 Element listsets_element = listsets_doc.createElement(OAIXML.LIST_SETS);
225 this.listsets_response = getMessage(listsets_doc, listsets_element);
226
227 // Now, for each collection, get a list of all its sets
228 // might include subsets (classifiers) or super colls
229 // We'll reuse the first message, changing its type and to atts
230 request.setAttribute(GSXML.TYPE_ATT, "");
231 request.setAttribute(GSXML.TO_ATT, to.toString());
232 // send to MR
233 msg_node = mr.process(message);
234 logger.error(this.converter.getPrettyString(msg_node));
235 NodeList response_list = ((Element)msg_node).getElementsByTagName(GSXML.RESPONSE_ELEM);
236 for (int c=0; c<response_list.getLength(); c++) {
237 // for each collection's response
238 Element response = (Element)response_list.item(c);
239 String coll_name = GSPath.getFirstLink(response.getAttribute(GSXML.FROM_ATT));
240 logger.error("coll from response "+coll_name);
241 NodeList set_list = response.getElementsByTagName(OAIXML.SET);
242 for (int j=0; j<set_list.getLength(); j++) {
243 // now check if it a super collection
244 Element set = (Element)set_list.item(j);
245 String set_spec = GSXML.getNodeText((Element)GSXML.getChildByTagName(set, OAIXML.SET_SPEC));
246 logger.error("set spec = "+set_spec);
247 // this may change if we add site name back in
248 // setSpecs will be collname or collname:subset or supercollname
249 if (set_spec.indexOf(":")==-1 && ! set_spec.equals(coll_name)) {
250 // it must be a super coll spec
251 logger.error("found super coll, "+set_spec);
252 // check that it is a valid one from config
253 if (this.has_super_colls == true && super_coll_data.containsKey(set_spec)) {
254 Vector <String> subcolls = this.super_coll_map.get(set_spec);
255 if (subcolls == null) {
256 logger.error("its new!!");
257 // not in there yet
258 subcolls = new Vector<String>();
259 this.set_set.add(set_spec);
260 this.super_coll_map.put(set_spec, subcolls);
261 // the first time a supercoll is mentioned, add into the set list
262 logger.error("finding the set info "+this.converter.getPrettyString(super_coll_data.get(set_spec)));
263 listsets_element.appendChild(GSXML.duplicateWithNewName(listsets_doc, super_coll_data.get(set_spec), OAIXML.SET, true));
264 }
265 // add this collection to the list for the super coll
266 subcolls.add(coll_name);
267 }
268 } else { // its either the coll itself or a subcoll
269 // add in the set
270 listsets_element.appendChild(listsets_doc.importNode(set, true));
271 this.set_set.add(set_spec);
272 }
273 } // for each set in the collection
274 } // for each OAI enabled collection
275 return true;
276 }
277
278 /** process using strings - just calls process using Elements */
279 public String process(String xml_in) {
280
281 Node message_node = this.converter.getDOM(xml_in);
282 Node page = process(message_node);
283 return this.converter.getString(page);
284 }
285
286 //Compose a message/response element used to send back to the OAIServer servlet.
287 //This method is only used within OAIReceptionist
288 private Element getMessage(Document doc, Element e) {
289 Element msg = doc.createElement(GSXML.MESSAGE_ELEM);
290 Element response = doc.createElement(GSXML.RESPONSE_ELEM);
291 msg.appendChild(response);
292 response.appendChild(e);
293 return msg;
294 }
295
296 /** process - produce xml data in response to a request
297 * if something goes wrong, it returns null -
298 */
299 public Node process(Node message_node) {
300 logger.error("OAIReceptionist received request");
301
302 Element message = this.converter.nodeToElement(message_node);
303 logger.error(this.converter.getString(message));
304
305 // check that its a correct message tag
306 if (!message.getTagName().equals(GSXML.MESSAGE_ELEM)) {
307 logger.error(" Invalid message. GSDL message should start with <"+GSXML.MESSAGE_ELEM+">, instead it starts with:"+message.getTagName()+".");
308 return OAIXML.createErrorMessage(OAIXML.BAD_ARGUMENT, "Internal messaging error");
309 }
310
311 // get the request out of the message - assume that there is only one
312 Element request = (Element)GSXML.getChildByTagName(message, GSXML.REQUEST_ELEM);
313 if (request == null) {
314 logger.error(" message had no request!");
315 return OAIXML.createErrorMessage(OAIXML.BAD_ARGUMENT, "Internal messaging error");
316 }
317 //At this stage, the value of 'to' attribute of the request must be the 'verb'
318 //The only thing that the oai receptionist can be sure is that these verbs are valid, nothing else.
319 String verb = request.getAttribute(GSXML.TO_ATT);
320 if (verb.equals(OAIXML.IDENTIFY)) {
321 return doIdentify();
322 }
323 if (verb.equals(OAIXML.LIST_METADATA_FORMATS)) {
324 return doListMetadataFormats(request);
325 }
326 if (verb.equals(OAIXML.LIST_SETS)) {
327 // we have composed the list sets response on init
328 // Note this means that list sets never uses resumption tokens
329 return this.listsets_response;
330 }
331 if (verb.equals(OAIXML.GET_RECORD)) {
332 return doGetRecord(request);
333 }
334 if (verb.equals(OAIXML.LIST_IDENTIFIERS)) {
335 return doListIdentifiersOrRecords(request,OAIXML.LIST_IDENTIFIERS , OAIXML.HEADER);
336 }
337 if (verb.equals(OAIXML.LIST_RECORDS)) {
338 return doListIdentifiersOrRecords(request, OAIXML.LIST_RECORDS, OAIXML.RECORD);
339 }
340 // should never get here as verbs were checked in OAIServer
341 return OAIXML.createErrorMessage(OAIXML.BAD_VERB, "Unexpected things happened");
342
343 }
344
345
346 private int getResumeAfter() {
347 Element resume_after = (Element)GSXML.getChildByTagName(oai_config, OAIXML.RESUME_AFTER);
348 if(resume_after != null) return Integer.parseInt(GSXML.getNodeText(resume_after));
349 return -1;
350 }
351 private String getRepositoryIdentifier() {
352 Element ri = (Element)GSXML.getChildByTagName(oai_config, OAIXML.REPOSITORY_IDENTIFIER);
353 if (ri != null) {
354 return GSXML.getNodeText(ri);
355 }
356 return "";
357 }
358
359
360 /** if the param_map contains strings other than those in valid_strs, return false;
361 * otherwise true.
362 */
363 private boolean areAllParamsValid(HashMap<String, String> param_map, HashSet<String> valid_strs) {
364 ArrayList<String> param_list = new ArrayList<String>(param_map.keySet());
365 for(int i=0; i<param_list.size(); i++) {
366 logger.error("param, key = "+param_list.get(i)+", value = "+param_map.get(param_list.get(i)));
367 if (valid_strs.contains(param_list.get(i)) == false) {
368 return false;
369 }
370 }
371 return true;
372 }
373
374 private Element doListIdentifiersOrRecords(Element req, String verb, String record_type) {
375 // options: from, until, set, metadataPrefix, resumptionToken
376 // exceptions: badArgument, badResumptionToken, cannotDisseminateFormat, noRecordMatch, and noSetHierarchy
377 HashSet<String> valid_strs = new HashSet<String>();
378 valid_strs.add(OAIXML.FROM);
379 valid_strs.add(OAIXML.UNTIL);
380 valid_strs.add(OAIXML.SET);
381 valid_strs.add(OAIXML.METADATA_PREFIX);
382 valid_strs.add(OAIXML.RESUMPTION_TOKEN);
383
384 Document result_doc = this.converter.newDOM();
385 Element result_element = result_doc.createElement(verb);
386 boolean result_token_needed = false; // does this result need to include a
387 // resumption token
388
389 NodeList params = GSXML.getChildrenByTagName(req, GSXML.PARAM_ELEM);
390
391 HashMap<String, String> param_map = GSXML.getParamMap(params);
392
393 // are all the params valid?
394 if (!areAllParamsValid(param_map, valid_strs)) {
395 logger.error("One of the params is invalid");
396 return OAIXML.createErrorMessage(OAIXML.BAD_ARGUMENT, "There was an invalid parameter");
397 // TODO, need to tell the user which one was invalid ??
398 }
399
400 // Do we have a resumption token??
401 String token = null;
402 String from = null;
403 String until = null;
404 boolean set_requested = false;
405 String set_spec_str = null;
406 String prefix_value = null;
407 int cursor = 0;
408 int current_cursor = 0;
409 String current_set = null;
410
411 int total_size = -1; // we are only going to set this in resumption
412 // token if it is easy to work out, i.e. not sending extra requests to
413 // MR just to calculate total size
414
415 if(param_map.containsKey(OAIXML.RESUMPTION_TOKEN)) {
416 // Is it an error to have other arguments? Do we need to check to make sure that resumptionToken is the only arg??
417 // validate resumptionToken
418 token = param_map.get(OAIXML.RESUMPTION_TOKEN);
419 logger.info("has resumptionToken " + token);
420 if(OAIResumptionToken.isValidToken(token) == false) {
421 logger.error("token is not valid");
422 return OAIXML.createErrorMessage(OAIXML.BAD_RESUMPTION_TOKEN, "");
423 }
424 result_token_needed = true; // we always need to send a token back if we have started with one. It may be empty if we are returning the end of the list
425 // initialise the request params from the stored token data
426 HashMap<String, String> token_data = OAIResumptionToken.getTokenData(token);
427 from = token_data.get(OAIXML.FROM);
428 until = token_data.get(OAIXML.UNTIL);
429 set_spec_str = token_data.get(OAIXML.SET);
430 if (set_spec_str != null) {
431 set_requested = true;
432 }
433 prefix_value = token_data.get(OAIXML.METADATA_PREFIX);
434 current_set = token_data.get(OAIResumptionToken.CURRENT_SET);
435 try {
436 cursor = Integer.parseInt(token_data.get(OAIXML.CURSOR));
437 cursor = cursor + resume_after; // increment cursor
438 current_cursor = Integer.parseInt(token_data.get(OAIResumptionToken.CURRENT_CURSOR));
439 } catch (NumberFormatException e) {
440 logger.error("tried to parse int from cursor data and failed");
441 }
442
443 }
444 else {
445 // no resumption token, lets check the other params
446 // there must be a metadataPrefix
447 if (!param_map.containsKey(OAIXML.METADATA_PREFIX)) {
448 logger.error("metadataPrefix param required");
449 return OAIXML.createErrorMessage(OAIXML.BAD_ARGUMENT, "metadataPrefix param required");
450 }
451
452 //if there are any date params, check they're of the right format
453 from = param_map.get(OAIXML.FROM);
454 if(from != null) {
455 Date from_date = OAIXML.getDate(from);
456 if(from_date == null) {
457 logger.error("invalid date: " + from);
458 return OAIXML.createErrorMessage(OAIXML.BAD_ARGUMENT, "invalid format for "+ OAIXML.FROM);
459 }
460 }
461 until = param_map.get(OAIXML.UNTIL);
462 if(until != null) {
463 Date until_date = OAIXML.getDate(until);
464 if(until_date == null) {
465 logger.error("invalid date: " + until);
466 return OAIXML.createErrorMessage(OAIXML.BAD_ARGUMENT, "invalid format for "+ OAIXML.UNTIL);
467 }
468 }
469 if(from != null && until != null) { // check they are of the same date-time format (granularity)
470 if(from.length() != until.length()) {
471 logger.error("The request has different granularities (date-time formats) for the From and Until date parameters.");
472 return OAIXML.createErrorMessage(OAIXML.BAD_ARGUMENT, "The request has different granularities (date-time formats) for the From and Until date parameters.");
473 }
474 }
475
476 // check the set arg is a set we know about
477 set_requested = param_map.containsKey(OAIXML.SET);
478 set_spec_str = null;
479 if(set_requested == true) {
480 set_spec_str = param_map.get(OAIXML.SET);
481 if (!this.set_set.contains(set_spec_str)) {
482 // the set is not one we know about
483 logger.error("requested set is not found in this repository");
484 return OAIXML.createErrorMessage(OAIXML.BAD_ARGUMENT, "invalid set parameter");
485
486 }
487 }
488 // Is the metadataPrefix arg one this repository supports?
489 prefix_value = param_map.get(OAIXML.METADATA_PREFIX);
490 if (repositorySupportsMetadataPrefix(prefix_value) == false) {
491 logger.error("requested metadataPrefix is not found in OAIConfig.xml");
492 return OAIXML.createErrorMessage(OAIXML.CANNOT_DISSEMINATE_FORMAT, "metadata format "+prefix_value+" not supported by this repository");
493 }
494
495 } // else no resumption token, check other params
496
497 // Whew. Now we have validated the params, we can work on doing the actual
498 // request
499
500
501 Document doc = this.converter.newDOM();
502 Element mr_msg = doc.createElement(GSXML.MESSAGE_ELEM);
503 Element mr_req = doc.createElement(GSXML.REQUEST_ELEM);
504 // TODO does this need a type???
505 mr_msg.appendChild(mr_req);
506
507 // copy in the from/until params if there
508 if (from != null) {
509 mr_req.appendChild(GSXML.createParameter(doc, OAIXML.FROM, from));
510 }
511 if (until != null) {
512 mr_req.appendChild(GSXML.createParameter(doc, OAIXML.UNTIL, until));
513 }
514 // add metadataPrefix
515 mr_req.appendChild(GSXML.createParameter(doc, OAIXML.METADATA_PREFIX, prefix_value));
516
517 // do we have a set???
518 // if no set, we send to all collections in the collection list
519 // if super set, we send to all collections in super set list
520 // if a single collection, send to it
521 // if a subset, send to the collection
522 Vector<String> current_coll_list = null;
523 boolean single_collection = false;
524 if (set_requested == false) {
525 // just do all colls
526 current_coll_list = collection_name_list;
527 }
528 else if (has_super_colls && super_coll_map.containsKey(set_spec_str)) {
529 current_coll_list = super_coll_map.get(set_spec_str);
530 }
531 else {
532 current_coll_list = new Vector<String>();
533 if (set_spec_str.indexOf(":") != -1) {
534 // we have a subset
535 //add the set param back into the request, but send the request to the collection
536 String col_name = set_spec_str.substring(0, set_spec_str.indexOf(":"));
537 current_coll_list.add(col_name);
538 mr_req.appendChild(GSXML.createParameter(doc, OAIXML.SET, set_spec_str));
539 single_collection = true;
540 }
541 else {
542 // it must be a single collection name
543 current_coll_list.add(set_spec_str);
544 single_collection = true;
545 }
546 }
547
548 int num_collected_records = 0;
549 int start_point = current_cursor; // may not be 0 if we are using a resumption token
550 String resumption_collection = "";
551 boolean empty_result_token = false; // if we are sending the last part of a list, then the token value will be empty
552
553 // iterate through the list of collections and send the request to each
554
555 int start_coll=0;
556 if (current_set != null) {
557 // we are resuming a previous request, need to locate the first collection
558 for (int i=0; i<current_coll_list.size(); i++) {
559 if (current_set.equals(current_coll_list.get(i))) {
560 start_coll = i;
561 break;
562 }
563 }
564 }
565
566 for (int i=start_coll; i<current_coll_list.size(); i++) {
567 String current_coll = current_coll_list.get(i);
568 mr_req.setAttribute(GSXML.TO_ATT, current_coll+"/"+verb);
569
570 Element result = (Element)mr.process(mr_msg);
571 logger.error(verb+ " result for coll "+current_coll);
572 logger.error(this.converter.getPrettyString(result));
573 if (result == null) {
574 logger.info("message router returns null");
575 // do what??? carry on? fail??
576 return OAIXML.createErrorMessage("Internal service returns null", "");
577 }
578 Element res = (Element)GSXML.getChildByTagName(result, GSXML.RESPONSE_ELEM);
579 if(res == null) {
580 logger.info("response element in xml_result is null");
581 return OAIXML.createErrorMessage("Internal service returns null", "");
582 }
583 NodeList record_list = res.getElementsByTagName(record_type);
584 int num_records = record_list.getLength();
585 if(num_records == 0) {
586 logger.info("message router returns 0 records for coll "+current_coll);
587 continue; // try the next collection
588 }
589 if (single_collection) {
590 total_size = num_records;
591 }
592 int records_to_add = (resume_after > 0 ? resume_after - num_collected_records : num_records);
593 if (records_to_add > (num_records-start_point)) {
594 records_to_add = num_records-start_point;
595 }
596 addRecordsToList(result_doc, result_element, record_list, start_point, records_to_add);
597 num_collected_records += records_to_add;
598
599 // do we need to stop here, and do we need to issue a resumption token?
600 if (resume_after > 0 && num_collected_records == resume_after) {
601 // we have finished collecting records at the moment.
602 // but are we conincidentally at the end? or are there more to go?
603 if (records_to_add < (num_records - start_point)) {
604 // we have added less than this collection had
605 start_point += records_to_add;
606 resumption_collection = current_coll;
607 result_token_needed = true;
608 }
609 else {
610 // we added all this collection had to offer
611 // is there another collection in the list??
612 if (i<current_coll_list.size()-1) {
613 result_token_needed = true;
614 start_point = 0;
615 resumption_collection = current_coll_list.get(i+1);
616 }
617 else {
618 // we have finished one collection and there are no more collection
619 // if we need to send a resumption token (in this case, only because we started with one, then it will be empty
620 logger.error("at end of list, need empty result token");
621 empty_result_token = true;
622 }
623 }
624 break;
625 }
626 start_point = 0; // only the first one will have start non-zero, if we
627 // have a resumption token
628
629 } // for each collection
630
631 if (num_collected_records ==0) {
632 // there were no matching results
633 return OAIXML.createErrorMessage(OAIXML.NO_RECORDS_MATCH, "");
634 }
635
636 if (num_collected_records < resume_after) {
637 // we have been through all collections, and there are no more
638 // if we need a result token - only because we started with one, so we need to send an empty one, then make sure everyone knows we are just sending an empty one
639 if (result_token_needed) {
640 empty_result_token = true;
641 }
642 }
643
644 if (result_token_needed) {
645 // we need a resumption token
646 if (empty_result_token) {
647 logger.error("have empty result token");
648 token = "";
649 } else {
650 if (token != null) {
651 // we had a token for this request, we can just update it
652 token = OAIResumptionToken.updateToken(token, ""+cursor, resumption_collection, ""+start_point);
653 } else {
654 // we are generating a new one
655 token = OAIResumptionToken.createAndStoreResumptionToken(set_spec_str, prefix_value, from, until, ""+cursor, resumption_collection, ""+start_point );
656 }
657 }
658
659 // result token XML
660 long expiration_date = -1;
661 if (empty_result_token) {
662 // we know how many records in total as we have sent them all
663 total_size = cursor+num_collected_records;
664 } else {
665 // non-empty token, set the expiration date
666 expiration_date = OAIResumptionToken.getExpirationDate(token);
667 }
668 Element token_elem = OAIXML.createResumptionTokenElement(result_doc, token, total_size, cursor, expiration_date);
669 // OAIXML.addToken(token_elem); // store it
670 result_element.appendChild(token_elem); // add to the result
671 }
672
673
674 return getMessage(result_doc, result_element);
675 }
676
677 private void addRecordsToList(Document doc, Element result_element, NodeList
678 record_list, int start_point, int num_records) {
679 int end_point = start_point + num_records;
680 for (int i=start_point; i<end_point; i++) {
681 result_element.appendChild(doc.importNode(record_list.item(i), true));
682 }
683 }
684
685
686 // method exclusively used by doListRecords/doListIdentifiers
687 private void getRecords(Element verb_elem, NodeList list, int start_point, int end_point) {
688 for (int i=start_point; i<end_point; i++) {
689 verb_elem.appendChild(verb_elem.getOwnerDocument().importNode(list.item(i), true));
690 }
691 }
692 private Element collectAll(Element result, Element msg, String verb, String elem_name) {
693 if(result == null) {
694 //in the first round, result is null
695 return msg;
696 }
697 Element res_in_result = (Element)GSXML.getChildByTagName(result, GSXML.RESPONSE_ELEM);
698 if(res_in_result == null) { // return the results of all other collections accumulated so far
699 return msg;
700 }
701 Element verb_elem = (Element)GSXML.getChildByTagName(res_in_result, verb);
702 if(msg == null) {
703 return result;
704 }
705
706 //e.g., get all <record> elements from the returned message. There may be none of
707 //such element, for example, the collection service returned an error message
708 NodeList elem_list = msg.getElementsByTagName(elem_name);
709
710 for (int i=0; i<elem_list.getLength(); i++) {
711 verb_elem.appendChild(res_in_result.getOwnerDocument().importNode(elem_list.item(i), true));
712 }
713 return result;
714 }
715
716
717 /** there are three possible exception conditions: bad argument, idDoesNotExist, and noMetadataFormat.
718 * The first one is handled here, and the last two are processed by OAIPMH.
719 */
720 private Element doListMetadataFormats(Element req) {
721 //if the verb is ListMetadataFormats, there could be only one parameter: identifier
722 //, or there is no parameter; otherwise it is an error
723 //logger.info("" + this.converter.getString(msg));
724
725 NodeList params = GSXML.getChildrenByTagName(req, GSXML.PARAM_ELEM);
726 Element param = null;
727 Document lmf_doc = this.converter.newDOM();
728 if(params.getLength() == 0) {
729 //this is requesting metadata formats for the whole repository
730 //read the oaiConfig.xml file, return the metadata formats specified there.
731 if (this.listmetadataformats_response != null) {
732 // we have already created it
733 return this.listmetadataformats_response;
734 }
735
736 Element list_metadata_formats = lmf_doc.createElement(OAIXML.LIST_METADATA_FORMATS);
737
738 Element format_list = (Element)GSXML.getChildByTagName(oai_config, OAIXML.LIST_METADATA_FORMATS);
739 if(format_list == null) {
740 logger.error("OAIConfig.xml must contain the supported metadata formats");
741 // TODO this is internal error, what to do???
742 return getMessage(lmf_doc, list_metadata_formats);
743 }
744 NodeList formats = format_list.getElementsByTagName(OAIXML.METADATA_FORMAT);
745 for(int i=0; i<formats.getLength(); i++) {
746 Element meta_fmt = lmf_doc.createElement(OAIXML.METADATA_FORMAT);
747 Element first_meta_format = (Element)formats.item(i);
748 //the element also contains mappings, but we don't want them
749 meta_fmt.appendChild(lmf_doc.importNode(GSXML.getChildByTagName(first_meta_format, OAIXML.METADATA_PREFIX), true));
750 meta_fmt.appendChild(lmf_doc.importNode(GSXML.getChildByTagName(first_meta_format, OAIXML.SCHEMA), true));
751 meta_fmt.appendChild(lmf_doc.importNode(GSXML.getChildByTagName(first_meta_format, OAIXML.METADATA_NAMESPACE), true));
752 list_metadata_formats.appendChild(meta_fmt);
753 }
754 return getMessage(lmf_doc, list_metadata_formats);
755
756
757 }
758
759 if (params.getLength() > 1) {
760 //Bad argument. Can't be more than one parameters for ListMetadataFormats verb
761 return OAIXML.createErrorMessage(OAIXML.BAD_ARGUMENT, "");
762 }
763
764 // This is a request for the metadata of a particular item with an identifier
765 /**the request xml is in the form: <request>
766 * <param name=.../>
767 * </request>
768 *And there is a param element and one element only. (No paramList element in between).
769 */
770 param = (Element)params.item(0);
771 String param_name = param.getAttribute(GSXML.NAME_ATT);
772 String identifier = "";
773 if (!param_name.equals(OAIXML.IDENTIFIER)) {
774 //Bad argument
775 return OAIXML.createErrorMessage(OAIXML.BAD_ARGUMENT, "");
776 }
777
778 identifier = param.getAttribute(GSXML.VALUE_ATT);
779 // the identifier is in the form: <coll_name>:<OID>
780 // so it must contain at least two ':' characters
781 String[] strs = identifier.split(":");
782 if(strs == null || strs.length < 2) {
783 // the OID may also contain ':'
784 logger.error("identifier is not in the form coll:id" + identifier);
785 return OAIXML.createErrorMessage(OAIXML.ID_DOES_NOT_EXIST, "");
786 }
787
788 // send request to message router
789 // get the names
790 strs = splitNames(identifier);
791 if(strs == null || strs.length < 2) {
792 logger.error("identifier is not in the form coll:id" + identifier);
793 return OAIXML.createErrorMessage(OAIXML.ID_DOES_NOT_EXIST, "");
794 }
795 //String name_of_site = strs[0];
796 String coll_name = strs[0];
797 String oid = strs[1];
798
799 //re-organize the request element
800 // reset the 'to' attribute
801 String verb = req.getAttribute(GSXML.TO_ATT);
802 req.setAttribute(GSXML.TO_ATT, coll_name + "/" + verb);
803 // reset the identifier element
804 param.setAttribute(GSXML.NAME_ATT, OAIXML.OID);
805 param.setAttribute(GSXML.VALUE_ATT, oid);
806
807 // TODO is this the best way to do this???? should we create a new request???
808 Element message = req.getOwnerDocument().createElement(GSXML.MESSAGE_ELEM);
809 message.appendChild(req);
810 //Now send the request to the message router to process
811 Node result_node = mr.process(message);
812 return converter.nodeToElement(result_node);
813 }
814
815
816
817
818 private void copyNamedElementfromConfig(Element to_elem, String element_name) {
819 Element original_element = (Element)GSXML.getChildByTagName(oai_config, element_name);
820 if(original_element != null) {
821 copyNode(to_elem, original_element);
822 }
823 }
824
825 private void copyNode(Element to_elem, Node original_element) {
826 to_elem.appendChild(to_elem.getOwnerDocument().importNode(original_element, true));
827
828 }
829
830 private Element doIdentify() {
831 //The validation for this verb has been done in OAIServer.validate(). So no bother here.
832 logger.info("");
833 if (this.identify_response != null) {
834 // we have already created it
835 return this.identify_response;
836 }
837 Document doc = this.converter.newDOM();
838 Element identify = doc.createElement(OAIXML.IDENTIFY);
839 //do the repository name
840 copyNamedElementfromConfig(identify, OAIXML.REPOSITORY_NAME);
841 //do the baseurl
842 copyNamedElementfromConfig(identify, OAIXML.BASE_URL);
843 //do the protocol version
844 copyNamedElementfromConfig(identify, OAIXML.PROTOCOL_VERSION);
845
846 //There can be more than one admin email according to the OAI specification
847 NodeList admin_emails = GSXML.getChildrenByTagName(oai_config, OAIXML.ADMIN_EMAIL);
848 int num_admin = 0;
849 Element from_admin_email = null;
850 if (admin_emails != null) {
851 num_admin = admin_emails.getLength();
852 }
853 for (int i=0; i<num_admin; i++) {
854 copyNode(identify, admin_emails.item(i));
855 }
856
857 //do the earliestDatestamp
858 //send request to mr to search through the earliest datestamp amongst all oai collections in the repository.
859 //ask the message router for a list of oai collections
860 //NodeList oai_coll = getOAICollectionList();
861 long earliestDatestamp = getEarliestDateStamp(collection_list);
862 String earliestDatestamp_str = OAIXML.getTime(earliestDatestamp);
863 Element earliestDatestamp_elem = doc.createElement(OAIXML.EARLIEST_DATESTAMP);
864 GSXML.setNodeText(earliestDatestamp_elem, earliestDatestamp_str);
865 identify.appendChild(earliestDatestamp_elem);
866
867 //do the deletedRecord
868 copyNamedElementfromConfig(identify, OAIXML.DELETED_RECORD);
869 //do the granularity
870 copyNamedElementfromConfig(identify, OAIXML.GRANULARITY);
871
872 // output the oai identifier
873 Element description = doc.createElement(OAIXML.DESCRIPTION);
874 identify.appendChild(description);
875 // TODO, make this a valid id
876 Element oaiIdentifier = OAIXML.createOAIIdentifierXML(doc, repository_id, "lucene-jdbm-demo", "ec159e");
877 description.appendChild(oaiIdentifier);
878
879 // if there are any oaiInfo metadata, add them in too.
880 Element info = (Element)GSXML.getChildByTagName(oai_config, OAIXML.OAI_INFO);
881 if (info != null) {
882 NodeList meta = GSXML.getChildrenByTagName(info, OAIXML.METADATA);
883 if (meta != null && meta.getLength() > 0) {
884 Element gsdl = OAIXML.createGSDLElement(doc);
885 description.appendChild(gsdl);
886 for (int m = 0; m<meta.getLength(); m++) {
887 copyNode(gsdl, meta.item(m));
888 }
889
890 }
891 }
892 this.identify_response = identify;
893 return getMessage(doc, identify);
894 }
895 //split setSpec (site_name:coll_name) into an array of strings
896 //It has already been checked that the set_spec contains at least one ':'
897 private String[] splitSetSpec(String set_spec) {
898 logger.info(set_spec);
899 String[] strs = new String[2];
900 int colon_index = set_spec.indexOf(":");
901 strs[0] = set_spec.substring(0, colon_index);
902 strs[1] = set_spec.substring(colon_index + 1);
903 return strs;
904 }
905 /** split the identifier into <collection + OID> as an array
906 It has already been checked that the 'identifier' contains at least one ':'
907 */
908 private String[] splitNames(String identifier) {
909 logger.info(identifier);
910 String [] strs = new String[2];
911 int first_colon = identifier.indexOf(":");
912 if(first_colon == -1) {
913 return null;
914 }
915 strs[0] = identifier.substring(0, first_colon);
916 strs[1] = identifier.substring(first_colon + 1);
917 return strs;
918 }
919 /** validate if the specified metadata prefix value is supported by the repository
920 * by checking it in the OAIConfig.xml
921 */
922 private boolean repositorySupportsMetadataPrefix(String prefix_value) {
923 NodeList prefix_list = oai_config.getElementsByTagName(OAIXML.METADATA_PREFIX);
924
925 for(int i=0; i<prefix_list.getLength(); i++) {
926 if(prefix_value.equals(GSXML.getNodeText((Element)prefix_list.item(i)).trim() )) {
927 return true;
928 }
929 }
930 return false;
931 }
932 private Element doGetRecord(Element req){
933 logger.info("");
934 /** arguments:
935 identifier: required
936 metadataPrefix: required
937 * Exceptions: badArgument; cannotDisseminateFormat; idDoesNotExist
938 */
939 Document doc = this.converter.newDOM();
940 Element get_record = doc.createElement(OAIXML.GET_RECORD);
941
942 HashSet<String> valid_strs = new HashSet<String>();
943 valid_strs.add(OAIXML.IDENTIFIER);
944 valid_strs.add(OAIXML.METADATA_PREFIX);
945
946 NodeList params = GSXML.getChildrenByTagName(req, GSXML.PARAM_ELEM);
947 HashMap<String, String> param_map = GSXML.getParamMap(params);
948
949 if(!areAllParamsValid(param_map, valid_strs) ||
950 params.getLength() == 0 ||
951 param_map.containsKey(OAIXML.IDENTIFIER) == false ||
952 param_map.containsKey(OAIXML.METADATA_PREFIX) == false ) {
953 logger.error("must have the metadataPrefix/identifier parameter.");
954 return OAIXML.createErrorMessage(OAIXML.BAD_ARGUMENT, "");
955 }
956
957 String prefix = param_map.get(OAIXML.METADATA_PREFIX);
958 String identifier = param_map.get(OAIXML.IDENTIFIER);
959
960 // verify the metadata prefix
961 if (repositorySupportsMetadataPrefix(prefix) == false) {
962 logger.error("requested prefix is not found in OAIConfig.xml");
963 return OAIXML.createErrorMessage(OAIXML.CANNOT_DISSEMINATE_FORMAT, "");
964 }
965
966 // get the names
967 String[] strs = splitNames(identifier);
968 if(strs == null || strs.length < 2) {
969 logger.error("identifier is not in the form coll:id" + identifier);
970 return OAIXML.createErrorMessage(OAIXML.ID_DOES_NOT_EXIST, "");
971 }
972 //String name_of_site = strs[0];
973 String coll_name = strs[0];
974 String oid = strs[1];
975
976 //re-organize the request element
977 // reset the 'to' attribute
978 String verb = req.getAttribute(GSXML.TO_ATT);
979 req.setAttribute(GSXML.TO_ATT, coll_name + "/" + verb);
980 // reset the identifier element
981 Element param = GSXML.getNamedElement(req, GSXML.PARAM_ELEM, GSXML.NAME_ATT, OAIXML.IDENTIFIER);
982 if (param != null) {
983 param.setAttribute(GSXML.NAME_ATT, OAIXML.OID);
984 param.setAttribute(GSXML.VALUE_ATT, oid);
985 }
986
987 //Now send the request to the message router to process
988 Element msg = doc.createElement(GSXML.MESSAGE_ELEM);
989 msg.appendChild(doc.importNode(req, true));
990 Node result_node = mr.process(msg);
991 return converter.nodeToElement(result_node);
992 }
993
994 // See OAIConfig.xml
995 // dynamically works out what the earliestDateStamp is, since it varies by collection
996 // returns this time in *milliseconds*.
997 protected long getEarliestDateStamp(Element oai_coll_list) {
998 // config earliest datstamp
999 long config_datestamp = 0;
1000 Element config_datestamp_elem = (Element)GSXML.getChildByTagName(this.oai_config, OAIXML.EARLIEST_DATESTAMP);
1001 if (config_datestamp_elem != null) {
1002 String datest = GSXML.getNodeText(config_datestamp_elem);
1003 config_datestamp = OAIXML.getTime(datest);
1004 if (config_datestamp == -1) {
1005 config_datestamp = 0;
1006 }
1007 }
1008 //do the earliestDatestamp
1009 long current_time = System.currentTimeMillis();
1010 long earliestDatestamp = current_time;
1011 NodeList oai_coll = oai_coll_list.getElementsByTagName(GSXML.COLLECTION_ELEM);
1012 int oai_coll_size = oai_coll.getLength();
1013 if (oai_coll_size == 0) {
1014 logger.info("returned oai collection list is empty. Setting repository earliestDatestamp to be the earliest datestamp from OAIConfig.xml, or 1970-01-01 if not specified.");
1015 return config_datestamp;
1016 }
1017 // the earliestDatestamp is now stored as a metadata element in the collection's buildConfig.xml file
1018 // we get the earliestDatestamp among the collections
1019 for(int i=0; i<oai_coll_size; i++) {
1020 long coll_earliestDatestamp = Long.parseLong(((Element)oai_coll.item(i)).getAttribute(OAIXML.EARLIEST_DATESTAMP));
1021 if (coll_earliestDatestamp == 0) {
1022 // try last modified
1023 coll_earliestDatestamp = Long.parseLong(((Element)oai_coll.item(i)).getAttribute(OAIXML.LAST_MODIFIED));
1024 }
1025 if (coll_earliestDatestamp > 0) {
1026 earliestDatestamp = (earliestDatestamp > coll_earliestDatestamp)? coll_earliestDatestamp : earliestDatestamp;
1027 }
1028 }
1029 if (earliestDatestamp == current_time) {
1030 logger.info("no collection had a real datestamp, using value from OAIConfig");
1031 return config_datestamp;
1032 }
1033 return earliestDatestamp;
1034 }
1035}
1036
1037
Note: See TracBrowser for help on using the repository browser.