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

Last change on this file since 32869 was 32869, checked in by ak19, 5 years ago
  1. Other possible return value from getCollectionListForSet() is now also a clone rather than the member variable because we don't want our destructive remove() operations affecting member variable data structures. 2. Cleaning up debugging.
File size: 50.4 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 /** the configure file of this receptionist passed from the oai servlet. */
51 protected Element oai_config = null;
52
53 /** contained in the OAIConfig.xml deciding whether the resumptionToken should be in use */
54 protected int resume_after = -1 ;
55
56 /** the message router that the Receptionist and Actions will talk to */
57 protected ModuleInterface mr = null;
58
59 // Some of the data/responses will not change while the servlet is running, so
60 // we can cache them
61
62 /** A list of all the collections available to this OAI server */
63 protected Element collection_list = null;
64 /** a vector of the names, for convenience */
65 protected Vector<String> collection_name_list = null;
66 /** a vector to be maintained in parallel to Vector collection_name_list in terms of adds/removes.
67 * This is a list of Integers that denote whether the associated collection in collection_name_list is currently ACTIVE or DEACTIVATED.
68 * The state for any collection can be changed when the building folder is moved to index during rebuilding, before and after which
69 * activateOrDeactivateCollection() here is called to deactivate a collection and then activate it again, respectively.
70 * Can't make collection_name_list a HashMap, since a map's keys are unique (i.e. a Set) whereas collection_name_list is a Vector.
71 * I've confirmed that collection_name_list is specifically a list of OAI collection names, not non-OAI collections.
72 */
73 protected Vector<Integer> collection_state_list = null;
74 /** Possible states for a collection */
75 protected static final Integer DEACTIVATED = new Integer(0);
76 protected static final Integer ACTIVE = new Integer(1);
77
78 /** If this is true, then there are no OAI enabled collections, so can always return noRecordsMatch (after validating the request params) */
79 protected boolean noRecordsMatch = false;
80
81 /** A set of all known 'sets' */
82 protected HashSet<String> set_set = null;
83
84 protected boolean has_super_colls = false;
85 /** a hash of super set-> collection list */
86 protected HashMap<String, Vector<String>> super_coll_map = null;
87 /** store the super coll elements for convenience */
88 HashMap<String, Element> super_coll_data = null;
89 /** store the metadata formats ??????*/
90 /** The identify response */
91 protected Element identify_response = null;
92 /** The list set response */
93 protected Element listsets_response = null;
94 /** the list metadata formats response */
95 protected Element listmetadataformats_response = null;
96
97 public OAIReceptionist() {
98
99 }
100
101 public void cleanUp() {
102 if (this.mr != null) {
103
104 this.mr.cleanUp();
105 }
106 OAIResumptionToken.saveTokensToFile();
107 }
108
109 public void setSiteName(String site_name) {
110 this.site_name = site_name;
111 }
112 /** sets the message router - it should already be created and
113 * configured in the init() of a servlet (OAIServer, for example) before being passed to the receptionist*/
114 public void setMessageRouter(ModuleInterface mr) {
115 this.mr = mr;
116 }
117
118 /** configures the receptionist */
119 public boolean configure(Element config) {
120
121 if (this.mr==null) {
122 logger.error(" message routers must be set before calling oai configure");
123 return false;
124 }
125 if (config == null) {
126 logger.error(" oai configure file is null");
127 return false;
128 }
129 oai_config = config;
130 resume_after = getResumeAfter();
131
132 repository_id = getRepositoryIdentifier();
133 configureSuperSetInfo();
134 if (!configureSetInfo()) {
135 // there are no sets
136 logger.error("No sets (collections) available for OAI");
137 return false;
138 }
139
140 // load in tokens from OAIResumptionToken.xml, and then clear out any
141 // expired ones.
142 OAIResumptionToken.init();
143 OAIResumptionToken.clearExpiredTokens();
144
145 return true;
146 }
147
148 // assuming that sets are static. If collections change then the servlet
149 // should be restarted.
150 private boolean configureSuperSetInfo() {
151 // do we have any super colls listed in web/WEB-INF/classes/OAIConfig.xml?
152 // Will be like
153 // <oaiSuperSet>
154 // <SetSpec>xxx</SetSpec>
155 // <setName>xxx</SetName>
156 // <SetDescription>xxx</setDescription>
157 // </oaiSuperSet>
158 // The super set is listed in OAIConfig, and collections themselves state
159 // whether they are part of the super set or not.
160 NodeList super_coll_list = this.oai_config.getElementsByTagName(OAIXML.OAI_SUPER_SET);
161 this.super_coll_data = new HashMap<String, Element>();
162 if (super_coll_list.getLength() > 0) {
163 this.has_super_colls = true;
164 for (int i=0; i<super_coll_list.getLength(); i++) {
165 Element super_coll = (Element)super_coll_list.item(i);
166 Element set_spec = (Element)GSXML.getChildByTagName(super_coll, OAIXML.SET_SPEC);
167 if (set_spec != null) {
168 String name = GSXML.getNodeText(set_spec);
169 if (!name.equals("")) {
170 this.super_coll_data.put(name, super_coll);
171 logger.info("adding in super coll "+name);
172 }
173 }
174 }
175
176 if (this.super_coll_data.size()==0) {
177 this.has_super_colls = false;
178 }
179 }
180 if (this.has_super_colls == true) {
181 this.super_coll_map = new HashMap<String, Vector<String>>();
182 }
183 return true;
184
185 }
186 private boolean configureSetInfo() {
187 this.set_set = new HashSet<String>();
188
189 // First, we get a list of all the OAI enabled collections
190 // We get this by sending a listSets request to the MR
191 Document doc = XMLConverter.newDOM();
192 Element message = doc.createElement(GSXML.MESSAGE_ELEM);
193
194 Element request = GSXML.createBasicRequest(doc, OAIXML.OAI_SET_LIST, "", null);
195 message.appendChild(request);
196 Node msg_node = mr.process(message);
197
198 if (msg_node == null) {
199 logger.error("returned msg_node from mr is null");
200 return false;
201 }
202 Element resp = (Element)GSXML.getChildByTagName(msg_node, GSXML.RESPONSE_ELEM);
203 Element coll_list = (Element)GSXML.getChildByTagName(resp, GSXML.COLLECTION_ELEM + GSXML.LIST_MODIFIER);
204 if (coll_list == null) {
205 logger.error("coll_list is null");
206 return false;
207 }
208
209 this.collection_list = (Element)doc.importNode(coll_list, true);
210
211 // go through and store a list of collection names for convenience
212 // also create a 'to' attribute for the next request to the MR, which
213 // is a ListSets request to each collection
214 Node child = this.collection_list.getFirstChild();
215 if (child == null) {
216 logger.error("collection list has no children");
217 noRecordsMatch = true;
218 return false;
219 }
220
221 this.collection_name_list = new Vector<String>();
222 this.collection_state_list = new Vector<Integer>();
223 StringBuffer to = new StringBuffer();
224 boolean first = true;
225 while (child != null) {
226 if (child.getNodeName().equals(GSXML.COLLECTION_ELEM)) {
227 String coll_id =((Element) child).getAttribute(GSXML.NAME_ATT);
228 this.collection_name_list.add(coll_id);
229 this.collection_state_list.add(ACTIVE); // collections start out active (they get activated during configuring) until deactivation takes place
230 if (!first) {
231 to.append(',');
232 }
233 first = false;
234 to.append(coll_id+"/"+OAIXML.LIST_SETS);
235 }
236 child = child.getNextSibling();
237 }
238 if (first) {
239 // we haven't found any collections
240 logger.error("found no collection elements in collectionList");
241 noRecordsMatch = true;
242 return false;
243 }
244 Document listsets_doc = XMLConverter.newDOM();
245 Element listsets_element = listsets_doc.createElement(OAIXML.LIST_SETS);
246 this.listsets_response = getMessage(listsets_doc, listsets_element);
247
248 // Now, for each collection, get a list of all its sets
249 // might include subsets (classifiers) or super colls
250 // We'll reuse the first message, changing its type and to atts
251 request.setAttribute(GSXML.TYPE_ATT, "");
252 request.setAttribute(GSXML.TO_ATT, to.toString());
253 // send to MR
254 msg_node = mr.process(message);
255 //logger.info("*** " + XMLConverter.getPrettyString(msg_node));
256 NodeList response_list = ((Element)msg_node).getElementsByTagName(GSXML.RESPONSE_ELEM);
257 for (int c=0; c<response_list.getLength(); c++) {
258 // for each collection's response
259 Element response = (Element)response_list.item(c);
260 String coll_name = GSPath.getFirstLink(response.getAttribute(GSXML.FROM_ATT));
261 logger.info("*** coll from response "+coll_name);
262 NodeList set_list = response.getElementsByTagName(OAIXML.SET);
263 for (int j=0; j<set_list.getLength(); j++) {
264 // now check if it a super collection
265 Element set = (Element)set_list.item(j);
266 String set_spec = GSXML.getNodeText((Element)GSXML.getChildByTagName(set, OAIXML.SET_SPEC));
267 logger.info("*** set spec = "+set_spec);
268 // this may change if we add site name back in
269 // setSpecs will be collname or collname:subset or supercollname
270 if (set_spec.indexOf(":")==-1 && ! set_spec.equals(coll_name)) {
271 // it must be a super coll spec
272 logger.info("*** found super coll, "+set_spec);
273 // check that it is a valid one from config
274 if (this.has_super_colls == true && this.super_coll_data.containsKey(set_spec)) {
275 Vector <String> subcolls = this.super_coll_map.get(set_spec);
276 if (subcolls == null) {
277 logger.info("*** it's new!!");
278 // not in there yet
279 subcolls = new Vector<String>();
280 this.set_set.add(set_spec);
281 this.super_coll_map.put(set_spec, subcolls);
282 // the first time a supercoll is mentioned, add into the set list
283 logger.info("*** finding the set info "+XMLConverter.getPrettyString(this.super_coll_data.get(set_spec)));
284 listsets_element.appendChild(GSXML.duplicateWithNewName(listsets_doc, this.super_coll_data.get(set_spec), OAIXML.SET, true));
285 }
286 // add this collection to the list for the super coll
287 subcolls.add(coll_name);
288 }
289 } else { // its either the coll itself or a subcoll
290 // add in the set
291 listsets_element.appendChild(listsets_doc.importNode(set, true));
292 this.set_set.add(set_spec);
293 }
294 } // for each set in the collection
295 } // for each OAI enabled collection
296
297 return true;
298 }
299
300 protected void resetMessageRouter() {
301 // we just need to send a configure request to MR
302 Document doc = XMLConverter.newDOM();
303 Element mr_request_message = doc.createElement(GSXML.MESSAGE_ELEM);
304 Element mr_request = GSXML.createBasicRequest(doc, GSXML.REQUEST_TYPE_SYSTEM, "", null);
305 mr_request_message.appendChild(mr_request);
306
307 Element system = doc.createElement(GSXML.SYSTEM_ELEM);
308 mr_request.appendChild(system);
309 system.setAttribute(GSXML.TYPE_ATT, GSXML.SYSTEM_TYPE_CONFIGURE);
310
311 Element response = (Element) this.mr.process(mr_request_message);
312 logger.info("*** configure response = "+XMLConverter.getPrettyString(response));
313 }
314
315 protected boolean activateOrDeactivateCollection(String collName, int activationState) {
316 // Send a request like: a=s&sa=<a|d>&st=collection&sn=<collName>
317 Document doc = XMLConverter.newDOM();
318 Element mr_request_message = doc.createElement(GSXML.MESSAGE_ELEM);
319 Element mr_request = GSXML.createBasicRequest(doc, GSXML.REQUEST_TYPE_SYSTEM, "", null);
320 mr_request_message.appendChild(mr_request);
321
322 Element system = doc.createElement(GSXML.SYSTEM_ELEM);
323 mr_request.appendChild(system);
324 if(activationState == OAIXML.ACTIVATION) {
325 system.setAttribute(GSXML.TYPE_ATT, GSXML.SYSTEM_TYPE_ACTIVATE);
326 } else {
327 system.setAttribute(GSXML.TYPE_ATT, GSXML.SYSTEM_TYPE_DEACTIVATE);
328 }
329 system.setAttribute(GSXML.SYSTEM_MODULE_TYPE_ATT, GSXML.COLLECTION_ELEM);
330 system.setAttribute(GSXML.SYSTEM_MODULE_NAME_ATT, collName);
331
332 Element response = (Element) this.mr.process(mr_request_message);
333 logger.info("*** (de)activate response = "+XMLConverter.getPrettyString(response));
334
335 boolean success = false;
336 NodeList elements = response.getElementsByTagName(GSXML.STATUS_ELEM);
337 if(elements.getLength() <= 0) {
338 logger.error("***** No result status");
339 return false;
340 }
341
342 String result = GSXML.getNodeText((Element)elements.item(0));
343 if(result.contains("could not be")) { // could not be (de)activated
344 return false;
345 } else {
346 // the collection's state has successfully been set to the requested activationState (be it ACTIVE or DEACTIVATED)
347 Integer changedState = (activationState == OAIXML.ACTIVATION) ? ACTIVE : DEACTIVATED;
348 int index = this.collection_name_list.indexOf(collName); // TODO: Check that whatever collname passed in by servercontrol.pm is fully qualified, to account for super/sub collections.
349 if(index != -1) { // shouldn't be? since startup never calls this method. This method is only called when building an existing collection?
350 this.collection_state_list.set(index, changedState);
351 } else {
352 logger.error("@@@@ index == -1, could not find collection " + collName + " in collection_name_list");
353 }
354 return true;
355 }
356 }
357
358 /** process using strings - just calls process using Elements */
359 public String process(String xml_in) {
360
361 Node message_node = XMLConverter.getDOM(xml_in);
362 Node page = process(message_node);
363 return XMLConverter.getString(page);
364 }
365
366 //Compose a message/response element used to send back to the OAIServer servlet.
367 //This method is only used within OAIReceptionist
368 private Element getMessage(Document doc, Element e) {
369 Element msg = doc.createElement(GSXML.MESSAGE_ELEM);
370 Element response = doc.createElement(GSXML.RESPONSE_ELEM);
371 msg.appendChild(response);
372 response.appendChild(e);
373 return msg;
374 }
375
376 /** process - produce xml data in response to a request
377 * if something goes wrong, it returns null -
378 */
379 public Node process(Node message_node) {
380 logger.info("*** OAIReceptionist received request");
381
382 Element message = GSXML.nodeToElement(message_node);
383 logger.info("*** " + XMLConverter.getString(message));
384
385 // check that its a correct message tag
386 if (!message.getTagName().equals(GSXML.MESSAGE_ELEM)) {
387 logger.error(" Invalid message. GSDL message should start with <"+GSXML.MESSAGE_ELEM+">, instead it starts with:"+message.getTagName()+".");
388 return OAIXML.createErrorMessage(OAIXML.BAD_ARGUMENT, "Internal messaging error");
389 }
390
391 // get the request out of the message - assume that there is only one
392 Element request = (Element)GSXML.getChildByTagName(message, GSXML.REQUEST_ELEM);
393 if (request == null) {
394 logger.error(" message had no request!");
395 return OAIXML.createErrorMessage(OAIXML.BAD_ARGUMENT, "Internal messaging error");
396 }
397
398 // Special cases: certain non-OAI commands/non-verbs are recognised
399 // special case, reset=true for reloading the MR and recept data
400 String reset = request.getAttribute("reset");
401 if (!reset.equals("")) {
402 resetMessageRouter();
403 configureSetInfo();
404 return OAIXML.createResetResponse(true);
405 }
406
407 // special case 2: activate=<collname> or deactivate=<collname> can be passed to oaiserver servlet too
408 if (request.hasAttribute(GSXML.SYSTEM_TYPE_ACTIVATE)) {
409 String collname = request.getAttribute(GSXML.SYSTEM_TYPE_ACTIVATE);
410 // don't bother activating if it's not an OAI collection
411 if (!this.set_set.contains(collname)) {
412 return OAIXML.createDeActivationOfNonOAICollResponse(OAIXML.ACTIVATION, collname);
413 }
414 boolean success = activateOrDeactivateCollection(collname, OAIXML.ACTIVATION);
415 return OAIXML.createActivationStateResponse(success, OAIXML.ACTIVATION, collname);
416 } else if (request.hasAttribute(GSXML.SYSTEM_TYPE_DEACTIVATE)) {
417 String collname = request.getAttribute(GSXML.SYSTEM_TYPE_DEACTIVATE);
418 // don't bother deactivating if it's not an OAI collection
419 if (!this.set_set.contains(collname)) {
420 return OAIXML.createDeActivationOfNonOAICollResponse(OAIXML.DEACTIVATION, collname);
421 }
422 boolean success = activateOrDeactivateCollection(collname, OAIXML.DEACTIVATION);
423 return OAIXML.createActivationStateResponse(success, OAIXML.DEACTIVATION, collname);
424 }
425
426 //At this stage, the value of 'to' attribute of the request must be the 'verb'
427 //The only thing that the oai receptionist can be sure is that these verbs are valid, nothing else.
428 String verb = request.getAttribute(GSXML.TO_ATT);
429 if (verb.equals(OAIXML.IDENTIFY)) {
430 return doIdentify();
431 }
432 if (verb.equals(OAIXML.LIST_METADATA_FORMATS)) {
433 return doListMetadataFormats(request);
434 }
435 if (verb.equals(OAIXML.LIST_SETS)) {
436 // we have composed the list sets response on init
437 // Note this means that list sets never uses resumption tokens
438 return this.listsets_response;
439 }
440 if (verb.equals(OAIXML.GET_RECORD)) {
441 return doGetRecord(request);
442 }
443 if (verb.equals(OAIXML.LIST_IDENTIFIERS)) {
444 return doListIdentifiersOrRecords(request,OAIXML.LIST_IDENTIFIERS , OAIXML.HEADER);
445 }
446 if (verb.equals(OAIXML.LIST_RECORDS)) {
447 return doListIdentifiersOrRecords(request, OAIXML.LIST_RECORDS, OAIXML.RECORD);
448 }
449 // should never get here as verbs were checked in OAIServer
450 return OAIXML.createErrorMessage(OAIXML.BAD_VERB, "Unexpected things happened");
451
452 }
453
454
455 private int getResumeAfter() {
456 Element resume_after = (Element)GSXML.getChildByTagName(oai_config, OAIXML.RESUME_AFTER);
457 if(resume_after != null) return Integer.parseInt(GSXML.getNodeText(resume_after));
458 return -1;
459 }
460 private String getRepositoryIdentifier() {
461 Element ri = (Element)GSXML.getChildByTagName(oai_config, OAIXML.REPOSITORY_IDENTIFIER);
462 if (ri != null) {
463 return GSXML.getNodeText(ri);
464 }
465 return "";
466 }
467
468
469 /** if the param_map contains strings other than those in valid_strs, return false;
470 * otherwise true.
471 */
472 private boolean areAllParamsValid(HashMap<String, String> param_map, HashSet<String> valid_strs) {
473 ArrayList<String> param_list = new ArrayList<String>(param_map.keySet());
474 for(int i=0; i<param_list.size(); i++) {
475 logger.info("*** param, key = "+param_list.get(i)+", value = "+param_map.get(param_list.get(i)));
476 if (valid_strs.contains(param_list.get(i)) == false) {
477 return false;
478 }
479 }
480 return true;
481 }
482
483 private Element doListIdentifiersOrRecords(Element req, String verb, String record_type) {
484 // options: from, until, set, metadataPrefix, resumptionToken
485 // exceptions: badArgument, badResumptionToken, cannotDisseminateFormat, noRecordMatch, and noSetHierarchy
486 HashSet<String> valid_strs = new HashSet<String>();
487 valid_strs.add(OAIXML.FROM);
488 valid_strs.add(OAIXML.UNTIL);
489 valid_strs.add(OAIXML.SET);
490 valid_strs.add(OAIXML.METADATA_PREFIX);
491 valid_strs.add(OAIXML.RESUMPTION_TOKEN);
492
493 Document result_doc = XMLConverter.newDOM();
494 Element result_element = result_doc.createElement(verb);
495 boolean result_token_needed = false; // does this result need to include a
496 // resumption token
497
498 NodeList params = GSXML.getChildrenByTagName(req, GSXML.PARAM_ELEM);
499
500 HashMap<String, String> param_map = GSXML.getParamMap(params);
501
502 // are all the params valid?
503 if (!areAllParamsValid(param_map, valid_strs)) {
504 logger.error("One of the params is invalid");
505 return OAIXML.createErrorMessage(OAIXML.BAD_ARGUMENT, "There was an invalid parameter");
506 // TODO, need to tell the user which one was invalid ??
507 }
508
509 // Do we have a resumption token??
510 String token = null;
511 String from = null;
512 String until = null;
513 boolean set_requested = false;
514 String set_spec_str = null;
515 String prefix_value = null;
516 int cursor = 0;
517 int current_cursor = 0;
518 String current_set = null;
519 long initial_time = 0;
520
521 int total_size = -1; // we are only going to set this in resumption
522 // token if it is easy to work out, i.e. not sending extra requests to
523 // MR just to calculate total size
524
525 if(param_map.containsKey(OAIXML.RESUMPTION_TOKEN)) {
526 // Is it an error to have other arguments? Do we need to check to make sure that resumptionToken is the only arg??
527 // validate resumptionToken
528 token = param_map.get(OAIXML.RESUMPTION_TOKEN);
529 logger.info("has resumptionToken " + token);
530 if(OAIResumptionToken.isValidToken(token) == false) {
531 logger.error("token is not valid");
532 return OAIXML.createErrorMessage(OAIXML.BAD_RESUMPTION_TOKEN, "");
533 }
534 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
535 // initialise the request params from the stored token data
536 HashMap<String, String> token_data = OAIResumptionToken.getTokenData(token);
537 from = token_data.get(OAIXML.FROM);
538 until = token_data.get(OAIXML.UNTIL);
539 set_spec_str = token_data.get(OAIXML.SET);
540 if (set_spec_str != null) {
541 set_requested = true;
542 }
543 prefix_value = token_data.get(OAIXML.METADATA_PREFIX);
544 current_set = token_data.get(OAIResumptionToken.CURRENT_SET);
545 try {
546 cursor = Integer.parseInt(token_data.get(OAIXML.CURSOR));
547 cursor = cursor + resume_after; // increment cursor
548 current_cursor = Integer.parseInt(token_data.get(OAIResumptionToken.CURRENT_CURSOR));
549 initial_time = Long.parseLong(token_data.get(OAIResumptionToken.INITIAL_TIME));
550 } catch (NumberFormatException e) {
551 logger.error("tried to parse int from cursor data and failed");
552 }
553
554 // check that the collections/sets haven't changed since the token was issued
555 if (collectionsChangedSinceTime(set_spec_str, initial_time)) {
556 logger.error("one of the collections in set "+set_spec_str+" has changed since token issued. Expiring the token");
557 OAIResumptionToken.expireToken(token);
558 return OAIXML.createErrorMessage(OAIXML.BAD_RESUMPTION_TOKEN, "Repository data has changed since this token was issued. Resend original request");
559 }
560 }
561 else {
562 // no resumption token, lets check the other params
563 // there must be a metadataPrefix
564 if (!param_map.containsKey(OAIXML.METADATA_PREFIX)) {
565 logger.error("metadataPrefix param required");
566 return OAIXML.createErrorMessage(OAIXML.BAD_ARGUMENT, "metadataPrefix param required");
567 }
568
569 //if there are any date params, check they're of the right format
570 Date from_date = null;
571 Date until_date = null;
572
573 from = param_map.get(OAIXML.FROM);
574 if(from != null) {
575 from_date = OAIXML.getDate(from);
576 if(from_date == null) {
577 logger.error("invalid date: " + from);
578 return OAIXML.createErrorMessage(OAIXML.BAD_ARGUMENT, "invalid format for "+ OAIXML.FROM);
579 }
580 }
581 until = param_map.get(OAIXML.UNTIL);
582 if(until != null) {
583 until_date = OAIXML.getDate(until);
584 if(until_date == null) {
585 logger.error("invalid date: " + until);
586 return OAIXML.createErrorMessage(OAIXML.BAD_ARGUMENT, "invalid format for "+ OAIXML.UNTIL);
587 }
588 }
589
590 if(from != null && until != null) { // check they are of the same date-time format (granularity)
591 if(from.length() != until.length()) {
592 logger.error("The request has different granularities (date-time formats) for the From and Until date parameters.");
593 return OAIXML.createErrorMessage(OAIXML.BAD_ARGUMENT, "The request has different granularities (date-time formats) for the From and Until date parameters.");
594 }
595
596 if(from_date.compareTo(until_date) > 0) { // from date can't be later than until date
597 return OAIXML.createErrorMessage(OAIXML.NO_RECORDS_MATCH, "");
598 }
599 }
600
601 if(until_date != null) {
602
603 // Also call until_date.compareTo(earliestdatestamp) as the until date can't precede the earliest timestamp
604 // Unfortunately, this test has to be done after the granularity test
605 // compareTo() returns the value 0 if the argument Date is equal to this Date; a value less than 0 if this Date is before
606 // the Date argument; and a value greater than 0 if this Date is after the Date argument.
607 long earliestDatestamp = getEarliestDateStamp(collection_list);
608 String earliestDatestamp_str = OAIXML.getTime(earliestDatestamp);
609 Date earliestDatestamp_date = OAIXML.getDate(earliestDatestamp_str);
610
611 if(until_date.compareTo(earliestDatestamp_date) < 0) {
612 return OAIXML.createErrorMessage(OAIXML.NO_RECORDS_MATCH, "");
613 }
614 }
615
616
617 // check the set arg is a set we know about
618 set_requested = param_map.containsKey(OAIXML.SET);
619 set_spec_str = null;
620 if(set_requested == true) {
621 set_spec_str = param_map.get(OAIXML.SET);
622 if (!this.set_set.contains(set_spec_str)) {
623 // the set is not one we know about
624 logger.error("requested set is not found in this repository");
625 return OAIXML.createErrorMessage(OAIXML.BAD_ARGUMENT, "invalid set parameter");
626
627 }
628 }
629 // Is the metadataPrefix arg one this repository supports?
630 prefix_value = param_map.get(OAIXML.METADATA_PREFIX);
631 if (repositorySupportsMetadataPrefix(prefix_value) == false) {
632 logger.error("requested metadataPrefix is not found in OAIConfig.xml");
633 return OAIXML.createErrorMessage(OAIXML.CANNOT_DISSEMINATE_FORMAT, "metadata format "+prefix_value+" not supported by this repository");
634 }
635
636 } // else no resumption token, check other params
637
638 // Whew. Now we have validated the params, we can work on doing the actual
639 // request
640
641
642 Document doc = XMLConverter.newDOM();
643 Element mr_msg = doc.createElement(GSXML.MESSAGE_ELEM);
644 Element mr_req = doc.createElement(GSXML.REQUEST_ELEM);
645 // TODO does this need a type???
646 mr_msg.appendChild(mr_req);
647
648 // copy in the from/until params if there
649 if (from != null) {
650 mr_req.appendChild(GSXML.createParameter(doc, OAIXML.FROM, from));
651 }
652 if (until != null) {
653 mr_req.appendChild(GSXML.createParameter(doc, OAIXML.UNTIL, until));
654 }
655 // add metadataPrefix
656 mr_req.appendChild(GSXML.createParameter(doc, OAIXML.METADATA_PREFIX, prefix_value));
657
658 // do we have a set???
659 // if no set, we send to all collections in the collection list
660 // if super set, we send to all collections in super set list
661 // if a single collection, send to it
662 // if a subset, send to the collection
663 Vector<String> current_coll_list = getCollectionListForSet(set_spec_str); // return value is now safe to modify such as with .remove() operations
664 boolean single_collection = false;
665 if (current_coll_list.size() == 1) {
666 single_collection = true;
667
668 // now handle any deactivated OAI collections. OAI collections can be deactivated briefly during build, when the building folder gets moved to index
669 String collName = current_coll_list.get(0); //set_spec_str;
670
671 int index = collection_name_list.indexOf(collName);
672 if(collection_state_list.get(index).equals(DEACTIVATED)) {
673 // forced to send this as an OAI error message, since the XML output is of OAI schema
674 // and has to match http://www.openarchives.org/OAI/2.0/OAI-PMH.xsd, which has no info message
675 //return OAIXML.createCollectionDeactivatedMessage(collName);
676 String errorCode = (record_type.equals(OAIXML.RECORD)) ? OAIXML.NO_RECORDS_MATCH : OAIXML.ID_DOES_NOT_EXIST; // GetRecords vs GetIdentifiers request
677 return OAIXML.createErrorMessage(errorCode, "OAI collection " + collName + " is temporarily inactive. Likely it's in the final stages of being rebuilt. Check back shortly.");
678 }
679 } else {
680
681 for(int i = 0; i < collection_name_list.size(); i++) {
682 if(collection_state_list.get(i).equals(DEACTIVATED)) {
683 String collName = collection_name_list.get(i);
684 // remove from the list of collections for which we're going to get identifiers/records
685 // so we won't get identifiers/records for any deactivated collections
686 current_coll_list.remove(collName);
687 }
688 }
689
690 // Have we 0 active OAI collections?
691 if (current_coll_list.size() == 0) {
692 // 0 collections are active, but (the remaining one) would have been deactivated, not other reason
693 String errorCode = (record_type.equals(OAIXML.RECORD)) ? OAIXML.NO_RECORDS_MATCH : OAIXML.ID_DOES_NOT_EXIST; // GetRecords vs GetIdentifiers request
694 return OAIXML.createErrorMessage(errorCode, "OAI collections temporarily active. Likely because of collection rebuilding. Check back shortly.");
695 }
696 }
697 if (set_spec_str != null && set_spec_str.indexOf(":") != -1) {
698 // we have a subset - add the set param back in
699 mr_req.appendChild(GSXML.createParameter(doc, OAIXML.SET, set_spec_str));
700 }
701
702 int num_collected_records = 0;
703 int start_point = current_cursor; // may not be 0 if we are using a resumption token
704 String resumption_collection = "";
705 boolean empty_result_token = false; // if we are sending the last part of a list, then the token value will be empty
706
707 // iterate through the list of collections and send the request to each
708
709 int start_coll=0;
710 if (current_set != null) {
711 // we are resuming a previous request, need to locate the first collection
712 for (int i=0; i<current_coll_list.size(); i++) {
713 if (current_set.equals(current_coll_list.get(i))) {
714 start_coll = i;
715 break;
716 }
717 }
718 }
719
720 for (int i=start_coll; i<current_coll_list.size(); i++) {
721 String current_coll = current_coll_list.get(i);
722 mr_req.setAttribute(GSXML.TO_ATT, current_coll+"/"+verb);
723
724 Element result = (Element)mr.process(mr_msg);
725 //logger.info("*** " + verb+ " result for coll "+current_coll);
726 //logger.info("*** " + XMLConverter.getPrettyString(result));
727 if (result == null) {
728 logger.info("message router returns null");
729 // do what??? carry on? fail??
730 return OAIXML.createErrorMessage("Internal service returns null", "");
731 }
732 Element res = (Element)GSXML.getChildByTagName(result, GSXML.RESPONSE_ELEM);
733 if(res == null) {
734 logger.info("response element in xml_result is null");
735 return OAIXML.createErrorMessage("Internal service returns null", "");
736 }
737 NodeList record_list = res.getElementsByTagName(record_type);
738 int num_records = record_list.getLength();
739 if(num_records == 0) {
740 logger.info("message router returns 0 records for coll "+current_coll);
741 continue; // try the next collection
742 }
743 if (single_collection) {
744 total_size = num_records;
745 }
746 int records_to_add = (resume_after > 0 ? resume_after - num_collected_records : num_records);
747 if (records_to_add > (num_records-start_point)) {
748 records_to_add = num_records-start_point;
749 }
750 addRecordsToList(result_doc, result_element, record_list, start_point, records_to_add);
751 num_collected_records += records_to_add;
752
753 // do we need to stop here, and do we need to issue a resumption token?
754 if (resume_after > 0 && num_collected_records == resume_after) {
755 // we have finished collecting records at the moment.
756 // but are we conincidentally at the end? or are there more to go?
757 if (records_to_add < (num_records - start_point)) {
758 // we have added less than this collection had
759 start_point += records_to_add;
760 resumption_collection = current_coll;
761 result_token_needed = true;
762 }
763 else {
764 // we added all this collection had to offer
765 // is there another collection in the list??
766 if (i<current_coll_list.size()-1) {
767 result_token_needed = true;
768 start_point = 0;
769 resumption_collection = current_coll_list.get(i+1);
770 }
771 else {
772 // we have finished one collection and there are no more collection
773 // if we need to send a resumption token (in this case, only because we started with one, then it will be empty
774 logger.info("*** at end of list, need empty result token");
775 empty_result_token = true;
776 }
777 }
778 break;
779 }
780 start_point = 0; // only the first one will have start non-zero, if we
781 // have a resumption token
782
783 } // for each collection
784
785 if (num_collected_records ==0) {
786 // there were no matching results
787 return OAIXML.createErrorMessage(OAIXML.NO_RECORDS_MATCH, "");
788 }
789
790 if (num_collected_records < resume_after) {
791 // we have been through all collections, and there are no more
792 // 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
793 if (result_token_needed) {
794 empty_result_token = true;
795 }
796 }
797
798 if (result_token_needed) {
799 // we need a resumption token
800 if (empty_result_token) {
801 logger.info("*** have empty result token");
802 token = "";
803 } else {
804 if (token != null) {
805 // we had a token for this request, we can just update it
806 token = OAIResumptionToken.updateToken(token, ""+cursor, resumption_collection, ""+start_point);
807 } else {
808 // we are generating a new one
809 token = OAIResumptionToken.createAndStoreResumptionToken(set_spec_str, prefix_value, from, until, ""+cursor, resumption_collection, ""+start_point );
810 }
811 }
812
813 // result token XML
814 long expiration_date = -1;
815 if (empty_result_token) {
816 // we know how many records in total as we have sent them all
817 total_size = cursor+num_collected_records;
818 } else {
819 // non-empty token, set the expiration date
820 expiration_date = OAIResumptionToken.getExpirationDate(token);
821 }
822 Element token_elem = OAIXML.createResumptionTokenElement(result_doc, token, total_size, cursor, expiration_date);
823 // OAIXML.addToken(token_elem); // store it
824 result_element.appendChild(token_elem); // add to the result
825 }
826
827
828 return getMessage(result_doc, result_element);
829 }
830
831 private Vector<String> getCollectionListForSet(String set) {
832 if (set == null) {
833 // no set requested, need the complete collection list
834
835 // Important to return a clone of the member variable, since collection names can be locally removed from the Vector by
836 // the caller for any collection that is deactivated. This is so the caller can determine which collections are active and
837 // thus have records/identifiers to display. We don't want to remove elements from the member variable collection_name_list itself.
838 return (Vector<String>)this.collection_name_list.clone();
839 }
840 if (has_super_colls && super_coll_map.containsKey(set)) {
841 Vector<String> supercoll_list = super_coll_map.get(set);
842 return (Vector<String>)supercoll_list.clone(); // see comment just above, don't want member data structure modified by caller's destructive operations
843 }
844
845 Vector<String> coll_list = new Vector<String>();
846 if (set.indexOf(":") != -1) {
847 String col_name = set.substring(0, set.indexOf(":"));
848 coll_list.add(col_name);
849 }
850 else {
851 coll_list.add(set);
852 }
853 return coll_list;
854 }
855 private void addRecordsToList(Document doc, Element result_element, NodeList
856 record_list, int start_point, int num_records) {
857 int end_point = start_point + num_records;
858 for (int i=start_point; i<end_point; i++) {
859 result_element.appendChild(doc.importNode(record_list.item(i), true));
860 }
861 }
862
863 private Element collectAll(Element result, Element msg, String verb, String elem_name) {
864 if(result == null) {
865 //in the first round, result is null
866 return msg;
867 }
868 Element res_in_result = (Element)GSXML.getChildByTagName(result, GSXML.RESPONSE_ELEM);
869 if(res_in_result == null) { // return the results of all other collections accumulated so far
870 return msg;
871 }
872 Element verb_elem = (Element)GSXML.getChildByTagName(res_in_result, verb);
873 if(msg == null) {
874 return result;
875 }
876
877 //e.g., get all <record> elements from the returned message. There may be none of
878 //such element, for example, the collection service returned an error message
879 NodeList elem_list = msg.getElementsByTagName(elem_name);
880
881 for (int i=0; i<elem_list.getLength(); i++) {
882 verb_elem.appendChild(res_in_result.getOwnerDocument().importNode(elem_list.item(i), true));
883 }
884 return result;
885 }
886
887
888 /** there are three possible exception conditions: bad argument, idDoesNotExist, and noMetadataFormat.
889 * The first one is handled here, and the last two are processed by OAIPMH.
890 */
891 private Element doListMetadataFormats(Element req) {
892 //if the verb is ListMetadataFormats, there could be only one parameter: identifier
893 //, or there is no parameter; otherwise it is an error
894 //logger.info("" + XMLConverter.getString(msg));
895
896 NodeList params = GSXML.getChildrenByTagName(req, GSXML.PARAM_ELEM);
897 Element param = null;
898 Document lmf_doc = XMLConverter.newDOM();
899 if(params.getLength() == 0) {
900 //this is requesting metadata formats for the whole repository
901 //read the oaiConfig.xml file, return the metadata formats specified there.
902 if (this.listmetadataformats_response != null) {
903 // we have already created it
904 return this.listmetadataformats_response;
905 }
906
907 Element list_metadata_formats = lmf_doc.createElement(OAIXML.LIST_METADATA_FORMATS);
908 // get all the formats out of oai_config
909 NodeList formats = oai_config.getElementsByTagName(OAIXML.METADATA_FORMAT);
910 if (formats.getLength() ==0) {
911 logger.error("OAIConfig.xml must contain the supported metadata formats");
912 // TODO this is internal error, what to do???
913 return getMessage(lmf_doc, list_metadata_formats);
914 }
915
916 for(int i=0; i<formats.getLength(); i++) {
917 Element f = OAIXML.getMetadataFormatShort(lmf_doc, (Element)formats.item(i));
918 list_metadata_formats.appendChild(f);
919 }
920 this.listmetadataformats_response = getMessage(lmf_doc, list_metadata_formats);
921 return this.listmetadataformats_response;
922
923 }
924
925 if (params.getLength() > 1) {
926 //Bad argument. Can't be more than one parameters for ListMetadataFormats verb
927 return OAIXML.createErrorMessage(OAIXML.BAD_ARGUMENT, "");
928 }
929
930 // This is a request for the metadata of a particular item with an identifier
931 /**the request xml is in the form: <request>
932 * <param name=.../>
933 * </request>
934 *And there is a param element and one element only. (No paramList element in between).
935 */
936 param = (Element)params.item(0);
937 String param_name = param.getAttribute(GSXML.NAME_ATT);
938 String identifier = "";
939 if (!param_name.equals(OAIXML.IDENTIFIER)) {
940 //Bad argument
941 return OAIXML.createErrorMessage(OAIXML.BAD_ARGUMENT, "");
942 }
943
944 identifier = param.getAttribute(GSXML.VALUE_ATT);
945 // the identifier is in the form: <coll_name>:<OID>
946 // so it must contain at least one ':' characters
947 // (the oid itself may contain : chars)
948 String[] strs = identifier.split(":", 2);
949 if(strs.length != 2) {
950 logger.error("identifier is not in the form coll:id" + identifier);
951 return OAIXML.createErrorMessage(OAIXML.ID_DOES_NOT_EXIST, "");
952 }
953
954 // send request to message router
955 // get the names
956 String coll_name = strs[0];
957 String oid = strs[1];
958
959 Document msg_doc = XMLConverter.newDOM();
960 Element message = msg_doc.createElement(GSXML.MESSAGE_ELEM);
961 String verb = req.getAttribute(GSXML.TO_ATT);
962 String new_to = coll_name + "/" + verb;
963 Element request = GSXML.createBasicRequest(msg_doc, "oai???", new_to, null);
964 message.appendChild(request);
965 // add the id param
966 GSXML.addParameterToList(request, OAIXML.OID, oid);
967
968 //Now send the request to the message router to process
969 Node result_node = mr.process(message);
970 return GSXML.nodeToElement(result_node);
971 }
972
973 private void copyNamedElementfromConfig(Element to_elem, String element_name) {
974 Element original_element = (Element)GSXML.getChildByTagName(oai_config, element_name);
975 if(original_element != null) {
976 GSXML.copyNode(to_elem, original_element);
977 }
978 }
979
980
981 private Element doIdentify() {
982 //The validation for this verb has been done in OAIServer.validate(). So no bother here.
983 logger.info("");
984 if (this.identify_response != null) {
985 // we have already created it
986 return getMessage(this.identify_response.getOwnerDocument(), this.identify_response);
987 }
988 Document doc = XMLConverter.newDOM();
989 Element identify = doc.createElement(OAIXML.IDENTIFY);
990 //do the repository name
991 copyNamedElementfromConfig(identify, OAIXML.REPOSITORY_NAME);
992 //do the baseurl
993 copyNamedElementfromConfig(identify, OAIXML.BASE_URL);
994 //do the protocol version
995 copyNamedElementfromConfig(identify, OAIXML.PROTOCOL_VERSION);
996
997 //There can be more than one admin email according to the OAI specification
998 NodeList admin_emails = GSXML.getChildrenByTagName(oai_config, OAIXML.ADMIN_EMAIL);
999 int num_admin = 0;
1000 Element from_admin_email = null;
1001 if (admin_emails != null) {
1002 num_admin = admin_emails.getLength();
1003 }
1004 for (int i=0; i<num_admin; i++) {
1005 GSXML.copyNode(identify, admin_emails.item(i));
1006 }
1007
1008 //do the earliestDatestamp
1009 //send request to mr to search through the earliest datestamp amongst all oai collections in the repository.
1010 //ask the message router for a list of oai collections
1011 //NodeList oai_coll = getOAICollectionList();
1012 long earliestDatestamp = getEarliestDateStamp(collection_list);
1013 String earliestDatestamp_str = OAIXML.getTime(earliestDatestamp);
1014 Element earliestDatestamp_elem = doc.createElement(OAIXML.EARLIEST_DATESTAMP);
1015 GSXML.setNodeText(earliestDatestamp_elem, earliestDatestamp_str);
1016 identify.appendChild(earliestDatestamp_elem);
1017
1018 //do the deletedRecord
1019 copyNamedElementfromConfig(identify, OAIXML.DELETED_RECORD);
1020 //do the granularity
1021 copyNamedElementfromConfig(identify, OAIXML.GRANULARITY);
1022
1023 // output the oai identifier
1024 Element description = doc.createElement(OAIXML.DESCRIPTION);
1025 identify.appendChild(description);
1026 // TODO, make this a valid id
1027 Element oaiIdentifier = OAIXML.createOAIIdentifierXML(doc, repository_id, "lucene-jdbm-demo", "ec159e");
1028 description.appendChild(oaiIdentifier);
1029
1030 // if there are any oaiInfo metadata, add them in too.
1031 Element info = (Element)GSXML.getChildByTagName(oai_config, OAIXML.OAI_INFO);
1032 if (info != null) {
1033 NodeList meta = GSXML.getChildrenByTagName(info, OAIXML.METADATA);
1034 if (meta != null && meta.getLength() > 0) {
1035 Element gsdl = OAIXML.createGSDLElement(doc);
1036 description.appendChild(gsdl);
1037 for (int m = 0; m<meta.getLength(); m++) {
1038 GSXML.copyNode(gsdl, meta.item(m));
1039 }
1040
1041 }
1042 }
1043 this.identify_response = identify;
1044 return getMessage(doc, identify);
1045 }
1046 /** split the identifier into <collection + OID> as an array
1047 It has already been checked that the 'identifier' contains at least one ':'
1048 */
1049
1050 /** validate if the specified metadata prefix value is supported by the repository
1051 * by checking it in the OAIConfig.xml
1052 */
1053 private boolean repositorySupportsMetadataPrefix(String prefix_value) {
1054 NodeList prefix_list = oai_config.getElementsByTagName(OAIXML.METADATA_PREFIX);
1055
1056 for(int i=0; i<prefix_list.getLength(); i++) {
1057 if(prefix_value.equals(GSXML.getNodeText((Element)prefix_list.item(i)).trim() )) {
1058 return true;
1059 }
1060 }
1061 return false;
1062 }
1063 private Element doGetRecord(Element req){
1064 logger.info("");
1065 /** arguments:
1066 identifier: required
1067 metadataPrefix: required
1068 * Exceptions: badArgument; cannotDisseminateFormat; idDoesNotExist
1069 */
1070 Document doc = XMLConverter.newDOM();
1071 Element get_record = doc.createElement(OAIXML.GET_RECORD);
1072
1073 HashSet<String> valid_strs = new HashSet<String>();
1074 valid_strs.add(OAIXML.IDENTIFIER);
1075 valid_strs.add(OAIXML.METADATA_PREFIX);
1076
1077 NodeList params = GSXML.getChildrenByTagName(req, GSXML.PARAM_ELEM);
1078 HashMap<String, String> param_map = GSXML.getParamMap(params);
1079
1080 if(!areAllParamsValid(param_map, valid_strs) ||
1081 params.getLength() == 0 ||
1082 param_map.containsKey(OAIXML.IDENTIFIER) == false ||
1083 param_map.containsKey(OAIXML.METADATA_PREFIX) == false ) {
1084 logger.error("must have the metadataPrefix/identifier parameter.");
1085 return OAIXML.createErrorMessage(OAIXML.BAD_ARGUMENT, "");
1086 }
1087
1088 String prefix = param_map.get(OAIXML.METADATA_PREFIX);
1089 String identifier = param_map.get(OAIXML.IDENTIFIER);
1090
1091 // verify the metadata prefix
1092 if (repositorySupportsMetadataPrefix(prefix) == false) {
1093 logger.error("requested prefix is not found in OAIConfig.xml");
1094 return OAIXML.createErrorMessage(OAIXML.CANNOT_DISSEMINATE_FORMAT, "");
1095 }
1096
1097 // get the names
1098 String[] strs = identifier.split(":", 2);
1099 if(strs == null || strs.length < 2) {
1100 logger.error("identifier is not in the form coll:id" + identifier);
1101 return OAIXML.createErrorMessage(OAIXML.ID_DOES_NOT_EXIST, "");
1102 }
1103 //String name_of_site = strs[0];
1104 String coll_name = strs[0];
1105 String oid = strs[1];
1106
1107 //re-organize the request element
1108 // reset the 'to' attribute
1109 String verb = req.getAttribute(GSXML.TO_ATT);
1110 req.setAttribute(GSXML.TO_ATT, coll_name + "/" + verb);
1111 // reset the identifier element
1112 Element param = GSXML.getNamedElement(req, GSXML.PARAM_ELEM, GSXML.NAME_ATT, OAIXML.IDENTIFIER);
1113 if (param != null) {
1114 param.setAttribute(GSXML.NAME_ATT, OAIXML.OID);
1115 param.setAttribute(GSXML.VALUE_ATT, oid);
1116 }
1117
1118 //Now send the request to the message router to process
1119 Element msg = doc.createElement(GSXML.MESSAGE_ELEM);
1120 msg.appendChild(doc.importNode(req, true));
1121 Node result_node = mr.process(msg);
1122 return GSXML.nodeToElement(result_node);
1123 }
1124
1125 // See OAIConfig.xml
1126 // dynamically works out what the earliestDateStamp is, since it varies by collection
1127 // returns this time in *milliseconds*.
1128 protected long getEarliestDateStamp(Element oai_coll_list) {
1129 // config earliest datstamp
1130 long config_datestamp = 0;
1131 Element config_datestamp_elem = (Element)GSXML.getChildByTagName(this.oai_config, OAIXML.EARLIEST_DATESTAMP);
1132 if (config_datestamp_elem != null) {
1133 String datest = GSXML.getNodeText(config_datestamp_elem);
1134 config_datestamp = OAIXML.getTime(datest);
1135 if (config_datestamp == -1) {
1136 config_datestamp = 0;
1137 }
1138 }
1139 //do the earliestDatestamp
1140 long current_time = System.currentTimeMillis();
1141 long earliestDatestamp = current_time;
1142 NodeList oai_coll = oai_coll_list.getElementsByTagName(GSXML.COLLECTION_ELEM);
1143 int oai_coll_size = oai_coll.getLength();
1144 if (oai_coll_size == 0) {
1145 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.");
1146 return config_datestamp;
1147 }
1148 // the earliestDatestamp is now stored as a metadata element in the collection's buildConfig.xml file
1149 // we get the earliestDatestamp among the collections
1150 for(int i=0; i<oai_coll_size; i++) {
1151 String collName = collection_name_list.get(i);
1152 long coll_earliestDatestamp = Long.parseLong(((Element)oai_coll.item(i)).getAttribute(OAIXML.EARLIEST_OAI_DATESTAMP)); // Taken from oai-inf db's OAI_EARLIEST_TIMESTAMP_OID entry, -1 if not found
1153
1154 if (coll_earliestDatestamp > 0 && earliestDatestamp > coll_earliestDatestamp) {
1155 earliestDatestamp = coll_earliestDatestamp;
1156 //logger.info("@@@ Found earlier timestamp: " + earliestDatestamp + " ms");
1157 }
1158 }
1159
1160 // we're no longer trying fallbacks for earliestDatestamp (other than the extreme fallback of
1161 // unix epoch time) because, going forward, all collections will have oai-inf db containing
1162 // an entry for earliesttimestamp. And all OAICollections will moreover have them stored and
1163 // will return them upon calling getEarliestOAIDatestamp().
1164 /*
1165 if(earliestDatestamp == current_time) {
1166 logger.info("Can't determine earliesttimestamp from oai-inf.db for any OAI collection. Trying timestamps in build config...");
1167 for(int i=0; i<oai_coll_size; i++) {
1168 String collName = collection_name_list.get(i);
1169 long coll_earliestDatestamp = Long.parseLong(((Element)oai_coll.item(i)).getAttribute(OAIXML.EARLIEST_DATESTAMP)); // Taken from the earliest datestamp field in buildcfg
1170 if (coll_earliestDatestamp == 0) {
1171 // try last modified
1172 coll_earliestDatestamp = Long.parseLong(((Element)oai_coll.item(i)).getAttribute(OAIXML.LAST_MODIFIED));
1173 //logger.info("@@@ Falling back to using collection " + collName + "'s lastmodified date as its earliest timestamp: " + coll_earliestDatestamp);
1174 }
1175 if (coll_earliestDatestamp > 0) {
1176 earliestDatestamp = (earliestDatestamp > coll_earliestDatestamp)? coll_earliestDatestamp : earliestDatestamp;
1177 }
1178 }
1179 }
1180 */
1181
1182 if (earliestDatestamp == current_time) {
1183 logger.info("no collection had a real datestamp, using value from OAIConfig");
1184 return config_datestamp;
1185 }
1186 return earliestDatestamp;
1187 }
1188
1189 private boolean collectionsChangedSinceTime(String set_spec_str, long initial_time) {
1190
1191 // we need to look though all collections in the set to see if any have last modified dates > initial_time
1192 Vector<String> set_coll_list = getCollectionListForSet(set_spec_str);
1193
1194 Node child = this.collection_list.getFirstChild();
1195 while (child != null) {
1196 if (child.getNodeName().equals(GSXML.COLLECTION_ELEM)) {
1197 String coll_id =((Element) child).getAttribute(GSXML.NAME_ATT);
1198 if (set_coll_list.contains(coll_id)) {
1199 long last_modified = Long.parseLong(((Element)child).getAttribute(OAIXML.LAST_MODIFIED));
1200 if (initial_time < last_modified) {
1201 return true;
1202 }
1203 }
1204 }
1205 child = child.getNextSibling();
1206 }
1207 return false;
1208
1209 }
1210
1211}
1212
1213
Note: See TracBrowser for help on using the repository browser.