Project

General

Profile

Download (21.3 KB) Statistics
| Branch: | Tag: | Revision:
1
package eu.etaxonomy.cdm.remote.controller;
2

    
3
import java.util.ArrayList;
4
import java.util.HashSet;
5
import java.util.List;
6

    
7
import javax.servlet.http.HttpServletRequest;
8

    
9
import org.hibernate.envers.query.AuditEntity;
10
import org.hibernate.envers.query.criteria.AuditCriterion;
11
import org.joda.time.DateTime;
12
import org.springframework.beans.TypeMismatchException;
13
import org.springframework.beans.factory.annotation.Autowired;
14
import org.springframework.http.HttpStatus;
15
import org.springframework.web.bind.MissingServletRequestParameterException;
16
import org.springframework.web.bind.WebDataBinder;
17
import org.springframework.web.bind.annotation.ExceptionHandler;
18
import org.springframework.web.bind.annotation.InitBinder;
19
import org.springframework.web.bind.annotation.RequestMapping;
20
import org.springframework.web.bind.annotation.RequestMethod;
21
import org.springframework.web.bind.annotation.RequestParam;
22
import org.springframework.web.bind.annotation.ResponseStatus;
23
import org.springframework.web.servlet.ModelAndView;
24
import org.springmodules.cache.CachingModel;
25
import org.springmodules.cache.provider.CacheProviderFacade;
26

    
27
import eu.etaxonomy.cdm.api.service.IAuditEventService;
28
import eu.etaxonomy.cdm.api.service.IIdentifiableEntityService;
29
import eu.etaxonomy.cdm.api.service.pager.Pager;
30
import eu.etaxonomy.cdm.model.common.IdentifiableEntity;
31
import eu.etaxonomy.cdm.model.common.LSID;
32
import eu.etaxonomy.cdm.model.view.AuditEvent;
33
import eu.etaxonomy.cdm.model.view.AuditEventRecord;
34
import eu.etaxonomy.cdm.persistence.dao.common.AuditEventSort;
35
import eu.etaxonomy.cdm.remote.dto.oaipmh.DeletedRecord;
36
import eu.etaxonomy.cdm.remote.dto.oaipmh.ErrorCode;
37
import eu.etaxonomy.cdm.remote.dto.oaipmh.Granularity;
38
import eu.etaxonomy.cdm.remote.dto.oaipmh.MetadataPrefix;
39
import eu.etaxonomy.cdm.remote.dto.oaipmh.ResumptionToken;
40
import eu.etaxonomy.cdm.remote.dto.oaipmh.SetSpec;
41
import eu.etaxonomy.cdm.remote.dto.oaipmh.Verb;
42
import eu.etaxonomy.cdm.remote.editor.IsoDateTimeEditor;
43
import eu.etaxonomy.cdm.remote.editor.LSIDPropertyEditor;
44
import eu.etaxonomy.cdm.remote.editor.MetadataPrefixEditor;
45
import eu.etaxonomy.cdm.remote.editor.SetSpecEditor;
46
import eu.etaxonomy.cdm.remote.exception.CannotDisseminateFormatException;
47
import eu.etaxonomy.cdm.remote.exception.NoRecordsMatchException;
48

    
49
public abstract class AbstractOaiPmhController<T extends IdentifiableEntity, SERVICE extends IIdentifiableEntityService<T>> {
50

    
51
    protected SERVICE service;
52

    
53
    protected IAuditEventService auditEventService;
54

    
55
	private String repositoryName;
56

    
57
	private String baseURL;
58

    
59
	private String protocolVersion;
60

    
61
	private String adminEmail;
62

    
63
	private String description;
64

    
65
	private Integer pageSize;
66

    
67
    public abstract void setService(SERVICE service);
68
    
69
    private CacheProviderFacade cacheProviderFacade;
70
    
71
    private CachingModel cachingModel;
72

    
73
    /**
74
     * sets cache name to be used
75
     */
76
    @Autowired
77
	public void setCacheProviderFacade(CacheProviderFacade cacheProviderFacade) {
78
		this.cacheProviderFacade = cacheProviderFacade;
79
	}
80
    
81
    @Autowired
82
	public void setCachingModel(CachingModel cachingModel) {
83
		this.cachingModel = cachingModel;
84
	}
85
    
86
    /**
87
     * Subclasses should override this method to return a list of property
88
     * paths that should be initialized for the getRecord, listRecords methods
89
     * @return
90
     */
91
    protected List<String> getPropertyPaths() {
92
    	return new ArrayList<String>();
93
    }
94
    
95
    /**
96
     * Subclasses should override this method and add a collection of 
97
     * eu.etaxonomy.cdm.remote.dto.oaipmh.Set objects  called "sets" that
98
     * will be returned in the response
99
     * @param modelAndView
100
     */
101
    protected void addSets(ModelAndView modelAndView) {
102
    	modelAndView.addObject("sets",new HashSet<SetSpec>());
103
    }
104

    
105
    @Autowired
106
    public void setAuditEventService(IAuditEventService auditEventService) {
107
        this.auditEventService = auditEventService;
108
    }    
109

    
110
    public void setRepositoryName(String repositoryName) {
111
		this.repositoryName = repositoryName;
112
	}
113

    
114
	public void setBaseURL(String baseURL) {
115
		this.baseURL = baseURL;
116
	}
117

    
118
	public void setProtocolVersion(String protocolVersion) {
119
		this.protocolVersion = protocolVersion;
120
	}
121

    
122
	public void setAdminEmail(String adminEmail) {
123
		this.adminEmail = adminEmail;
124
	}
125

    
126
	public void setDescription(String description) {
127
		this.description = description;
128
	}
129

    
130
	public void setPageSize(Integer pageSize) {
131
		this.pageSize = pageSize;
132
	}
133
	
134
	@InitBinder
135
    public void initBinder(WebDataBinder binder) {
136
        binder.registerCustomEditor(DateTime.class, new IsoDateTimeEditor());
137
        binder.registerCustomEditor(LSID.class, new LSIDPropertyEditor());
138
        binder.registerCustomEditor(MetadataPrefix.class, new MetadataPrefixEditor());
139
        binder.registerCustomEditor(SetSpec.class, new SetSpecEditor());
140
    }
141

    
142

    
143
	/**
144
	 * CannotDisseminateFormatException thrown by MetadataPrefixEditor
145
	 * 
146
	 * @throws IdDoesNotExistException
147
	 */
148
	@RequestMapping(method = RequestMethod.GET, params = "verb=GetRecord")
149
	public ModelAndView getRecord(
150
			@RequestParam(value = "identifier", required = true) LSID identifier,
151
			@RequestParam(value = "metadataPrefix", required = true) MetadataPrefix metadataPrefix)
152
			throws IdDoesNotExistException {
153

    
154
		ModelAndView modelAndView = new ModelAndView();
155
		modelAndView.addObject("metadataPrefix", metadataPrefix);
156

    
157
		finishModelAndView(identifier, metadataPrefix, modelAndView);
158

    
159
		return modelAndView;
160
	}
161

    
162
	/**
163
	 * @param identifier
164
	 * @param metadataPrefix
165
	 * @param modelAndView
166
	 * @throws IdDoesNotExistException
167
	 */
168
	protected void finishModelAndView(LSID identifier,
169
			MetadataPrefix metadataPrefix, ModelAndView modelAndView)
170
			throws IdDoesNotExistException {
171
		
172
		switch (metadataPrefix) {
173
			case RDF:
174
				modelAndView.addObject("object", obtainCdmEntity(identifier));
175
				modelAndView.setViewName("oai/getRecord.rdf");
176
				break;
177
			case OAI_DC:
178
			default:
179
				modelAndView.addObject("object", obtainCdmEntity(identifier));
180
				modelAndView.setViewName("oai/getRecord.dc");
181
		}
182
	}
183

    
184
	/**
185
	 * @param identifier
186
	 * @return
187
	 * @throws IdDoesNotExistException
188
	 */
189
	protected AuditEventRecord<T> obtainCdmEntity(LSID identifier)
190
			throws IdDoesNotExistException {
191
		T object = service.find(identifier);
192
		Pager<AuditEventRecord<T>> results = service.pageAuditEvents(object, 1,
193
				0, AuditEventSort.BACKWARDS, getPropertyPaths());
194

    
195
		if (results.getCount() == 0) {
196
			throw new IdDoesNotExistException(identifier);
197
		}
198
		return results.getRecords().get(0);
199
	}
200
	
201

    
202
    /**
203
     *  CannotDisseminateFormatException thrown by MetadataPrefixEditor
204
     * @throws IdDoesNotExistException 
205
     */
206
    @RequestMapping(method = RequestMethod.GET,params = "verb=ListMetadataFormats")
207
    public ModelAndView listMetadataFormats(@RequestParam(value = "identifier", required = false) LSID identifier) throws IdDoesNotExistException {
208
 
209
        ModelAndView modelAndView = new ModelAndView("oai/listMetadataFormats");
210
        
211
        if(identifier != null) {
212
        	T  object = service.find(identifier);
213
	        if(object == null) {
214
		        throw new IdDoesNotExistException(identifier);
215
	        }
216
    	}
217

    
218
        return modelAndView;
219
    }
220
    
221
    /**
222
     *  CannotDisseminateFormatException thrown by MetadataPrefixEditor
223
     */
224
    @RequestMapping(method = RequestMethod.GET,params = "verb=ListSets")
225
    public ModelAndView listSets() {
226
 
227
        ModelAndView modelAndView = new ModelAndView("oai/listSets");
228
        
229
        addSets(modelAndView);
230

    
231
        return modelAndView;
232
    }
233

    
234
	@RequestMapping(method = RequestMethod.GET,params = "verb=Identify")
235
    public ModelAndView identify() {
236
        ModelAndView modelAndView = new ModelAndView("oai/identify");
237
        modelAndView.addObject("repositoryName", repositoryName);
238
        modelAndView.addObject("baseURL",baseURL);
239
        modelAndView.addObject("protocolVersion",protocolVersion);
240
        modelAndView.addObject("deletedRecord",DeletedRecord.PERSISTENT);
241
        modelAndView.addObject("granularity",Granularity.YYYY_MM_DD_THH_MM_SS_Z);
242

    
243
        Pager<AuditEvent> auditEvents = auditEventService.list(0,1,AuditEventSort.FORWARDS);
244
        modelAndView.addObject("earliestDatestamp",auditEvents.getRecords().get(0).getDate());
245
        modelAndView.addObject("adminEmail",adminEmail);
246
        modelAndView.addObject("description",description);
247

    
248
        return modelAndView;
249
    }
250
 
251
    @RequestMapping(method = RequestMethod.GET, params = {"verb=ListIdentifiers", "!resumptionToken"})
252
    public ModelAndView listIdentifiers(
253
    		@RequestParam(value = "from", required = false) DateTime from, 
254
    		@RequestParam(value = "until", required = false) DateTime until,
255
    		@RequestParam(value = "metadataPrefix",required = true) MetadataPrefix metadataPrefix, 
256
    		@RequestParam(value = "set", required = false) SetSpec set) {
257
 
258
        ModelAndView modelAndView = new ModelAndView("oai/listIdentifiers");
259
        modelAndView.addObject("metadataPrefix",metadataPrefix);
260
        
261
        AuditEvent fromAuditEvent = null;
262
        if(from != null) { // if from is specified, use the event at that date
263
            modelAndView.addObject("from",from);
264
            fromAuditEvent = auditEventService.find(from);
265
        } 
266
    
267
        AuditEvent untilAuditEvent = null;
268
        if(until != null) {
269
            modelAndView.addObject("until",until);
270
            untilAuditEvent = auditEventService.find(until);
271
        } 
272

    
273
        Class clazz = null;
274
        if(set != null) {
275
        	modelAndView.addObject("set",set);
276
        	clazz = (Class)set.getSetClass();
277
        }
278
        
279
        List<AuditCriterion> criteria = new ArrayList<AuditCriterion>();
280
        //criteria.add(AuditEntity.property("lsid_lsid").isNotNull()); 
281
        //TODO this isNotNull criterion did not work with mysql, so using a like statement as interim solution
282
        criteria.add(AuditEntity.property("lsid_lsid").like("urn:lsid:%"));
283
        Pager<AuditEventRecord<T>> results = service.pageAuditEvents(clazz, fromAuditEvent, untilAuditEvent, criteria, pageSize, 0, AuditEventSort.FORWARDS, null); 
284
        
285
        if(results.getCount() == 0) {
286
        	throw new NoRecordsMatchException("No records match");
287
        }
288
        
289
        modelAndView.addObject("pager",results);
290

    
291
        if(results.getCount() > results.getRecords().size() && cacheProviderFacade != null) {
292
	        ResumptionToken resumptionToken = new ResumptionToken(results, from, until, metadataPrefix, set);
293
            modelAndView.addObject("resumptionToken",resumptionToken);
294
            cacheProviderFacade.putInCache(resumptionToken.getValue(), cachingModel, resumptionToken);
295
        }
296

    
297
        return modelAndView;
298
    }
299

    
300
    @RequestMapping(method = RequestMethod.GET, params = {"verb=ListIdentifiers", "resumptionToken"})
301
    public ModelAndView listIdentifiers(@RequestParam(value = "resumptionToken",required = true) String rToken) {
302
    	ResumptionToken resumptionToken;
303
    	if(cacheProviderFacade != null && cacheProviderFacade.getFromCache(rToken, cachingModel) != null) {
304
    	    resumptionToken = (ResumptionToken) cacheProviderFacade.getFromCache(rToken, cachingModel);
305
            ModelAndView modelAndView = new ModelAndView("oai/listIdentifiers");
306
            modelAndView.addObject("metadataPrefix",resumptionToken.getMetadataPrefix());
307

    
308
            AuditEvent fromAuditEvent = null;
309
            if(resumptionToken.getFrom() != null) { // if from is specified, use the event at that date
310
                modelAndView.addObject("from",resumptionToken.getFrom());
311
                fromAuditEvent = auditEventService.find(resumptionToken.getFrom());
312
            } 
313
    
314
            AuditEvent untilAuditEvent = null;
315
            if(resumptionToken.getUntil() != null) {
316
                modelAndView.addObject("until",resumptionToken.getUntil());
317
                untilAuditEvent = auditEventService.find(resumptionToken.getUntil());
318
            }
319

    
320
            Class clazz = null;
321
            if(resumptionToken.getSet() != null) {
322
            	modelAndView.addObject("set",resumptionToken.getSet());
323
            	clazz = (Class)resumptionToken.getSet().getSetClass();
324
            }
325
            
326
            List<AuditCriterion> criteria = new ArrayList<AuditCriterion>();
327
            //criteria.add(AuditEntity.property("lsid_lsid").isNotNull()); 
328
            //TODO this isNotNull criterion did not work with mysql, so using a like statement as interim solution
329
            criteria.add(AuditEntity.property("lsid_lsid").like("urn:lsid:%"));
330
            Pager<AuditEventRecord<T>> results = service.pageAuditEvents(clazz,fromAuditEvent,untilAuditEvent,criteria, pageSize, (resumptionToken.getCursor().intValue() / pageSize) + 1, AuditEventSort.FORWARDS,null); 
331
        
332
            if(results.getCount() == 0) {
333
            	throw new NoRecordsMatchException("No records match");
334
            }
335
            
336
            modelAndView.addObject("pager",results);
337

    
338
            if(results.getCount() > ((results.getPageSize() * results.getCurrentIndex()) + results.getRecords().size())) {
339
	            resumptionToken.updateResults(results);
340
                modelAndView.addObject("resumptionToken",resumptionToken);
341
                cacheProviderFacade.putInCache(resumptionToken.getValue(),cachingModel, resumptionToken);
342
            } else {
343
                resumptionToken = ResumptionToken.emptyResumptionToken();
344
                modelAndView.addObject("resumptionToken",resumptionToken);
345
                cacheProviderFacade.removeFromCache(rToken,cachingModel);
346
            }
347

    
348
            return modelAndView;
349
    	} else {
350
    		throw new BadResumptionTokenException();
351
    	}
352
    }
353

    
354
    @RequestMapping(method = RequestMethod.GET, params = {"verb=ListRecords", "!resumptionToken"})
355
    public ModelAndView listRecords(@RequestParam(value = "from", required = false) DateTime from, 
356
    		@RequestParam(value = "until", required = false) DateTime until,
357
    		@RequestParam(value = "metadataPrefix", required = true) MetadataPrefix metadataPrefix, 
358
    		@RequestParam(value = "set", required = false) SetSpec set) {
359
 
360
        ModelAndView modelAndView = new ModelAndView();
361
        modelAndView.addObject("metadataPrefix",metadataPrefix);
362
 
363
        switch(metadataPrefix) {
364
        case RDF:
365
            modelAndView.setViewName("oai/listRecords.rdf");
366
            break; 
367
	    case OAI_DC:
368
            default:
369
		    modelAndView.setViewName("oai/listRecords.dc");        
370
        }
371

    
372
        AuditEvent fromAuditEvent = null;
373
        if(from != null) { // if from is specified, use the event at that date
374
            modelAndView.addObject("from",from);
375
            fromAuditEvent = auditEventService.find(from);
376
        } 
377
    
378
        AuditEvent untilAuditEvent = null;
379
        if(until != null) {
380
            modelAndView.addObject("until",until);
381
            untilAuditEvent = auditEventService.find(until);
382
        } 
383

    
384
        Class clazz = null;
385
        if(set != null) {
386
            modelAndView.addObject("set",set);
387
            clazz = (Class)set.getSetClass();
388
        }
389
        
390
        List<AuditCriterion> criteria = new ArrayList<AuditCriterion>();
391
        //criteria.add(AuditEntity.property("lsid_lsid").isNotNull()); 
392
        //TODO this isNotNull criterion did not work with mysql, so using a like statement as interim solution
393
        criteria.add(AuditEntity.property("lsid_lsid").like("urn:lsid:%"));
394
        Pager<AuditEventRecord<T>> results = service.pageAuditEvents(clazz, fromAuditEvent, untilAuditEvent, criteria, pageSize, 0, AuditEventSort.FORWARDS, getPropertyPaths()); 
395
        
396
        if(results.getCount() == 0) {
397
        	throw new NoRecordsMatchException("No records match");
398
        }
399
        
400
        modelAndView.addObject("pager",results);
401

    
402
        if(results.getCount() > results.getRecords().size() && cacheProviderFacade != null) {
403
	        ResumptionToken resumptionToken = new ResumptionToken(results, from, until, metadataPrefix, set);
404
            modelAndView.addObject("resumptionToken",resumptionToken);
405
            cacheProviderFacade.putInCache(resumptionToken.getValue(), cachingModel, resumptionToken);
406
        }
407

    
408
        return modelAndView;
409
    }
410

    
411
	@RequestMapping(method = RequestMethod.GET, params = {"verb=ListRecords", "resumptionToken"})
412
    public ModelAndView listRecords(@RequestParam("resumptionToken") String rToken) {
413
 
414
	   ResumptionToken resumptionToken;
415
	   if(cacheProviderFacade != null && cacheProviderFacade.getFromCache(rToken,cachingModel) != null) {
416
   	        resumptionToken = (ResumptionToken) cacheProviderFacade.getFromCache(rToken,cachingModel);
417
            ModelAndView modelAndView = new ModelAndView();
418
            modelAndView.addObject("metadataPrefix",resumptionToken.getMetadataPrefix());
419
 
420
            switch (resumptionToken.getMetadataPrefix()) {
421
            case RDF:
422
                modelAndView.setViewName("oai/listRecords.rdf");
423
                break; 
424
	        case OAI_DC:
425
                default:
426
		        modelAndView.setViewName("oai/listRecords.dc");        
427
            }
428

    
429
            AuditEvent fromAuditEvent = null;
430
            if(resumptionToken.getFrom() != null) { // if from is specified, use the event at that date
431
                modelAndView.addObject("from",resumptionToken.getFrom());
432
                fromAuditEvent = auditEventService.find(resumptionToken.getFrom());
433
            }
434
    
435
            AuditEvent untilAuditEvent = null;
436
            if(resumptionToken.getUntil() != null) {
437
                modelAndView.addObject("until",resumptionToken.getUntil());
438
                untilAuditEvent = auditEventService.find(resumptionToken.getUntil());
439
            }
440
        
441
            Class clazz = null;
442
            if(resumptionToken.getSet() != null) {
443
              modelAndView.addObject("set",resumptionToken.getSet());
444
              clazz = (Class)resumptionToken.getSet().getSetClass();
445
            }
446
            List<AuditCriterion> criteria = new ArrayList<AuditCriterion>();
447
            //criteria.add(AuditEntity.property("lsid_lsid").isNotNull()); 
448
            //TODO this isNotNull criterion did not work with mysql, so using a like statement as interim solution
449
            criteria.add(AuditEntity.property("lsid_lsid").like("urn:lsid:%"));
450
            Pager<AuditEventRecord<T>> results = service.pageAuditEvents(clazz,fromAuditEvent,untilAuditEvent,criteria, pageSize, (resumptionToken.getCursor().intValue()  / pageSize) + 1, AuditEventSort.FORWARDS,getPropertyPaths()); 
451
        
452
            if(results.getCount() == 0) {
453
            	throw new NoRecordsMatchException("No records match");
454
            }
455
            
456
            modelAndView.addObject("pager",results);
457

    
458
            if(results.getCount() > ((results.getPageSize() * results.getCurrentIndex()) + results.getRecords().size())) {
459
	            resumptionToken.updateResults(results);
460
                modelAndView.addObject("resumptionToken",resumptionToken);
461
                cacheProviderFacade.putInCache(resumptionToken.getValue(),cachingModel,resumptionToken);
462
            } else {
463
                resumptionToken = ResumptionToken.emptyResumptionToken();
464
                modelAndView.addObject("resumptionToken",resumptionToken);
465
                cacheProviderFacade.removeFromCache(rToken,cachingModel);
466
            }
467

    
468
            return modelAndView;
469
	   } else {
470
		   throw new BadResumptionTokenException();
471
	   }
472
    }
473
	
474
	private ModelAndView doException(Exception ex, HttpServletRequest request, ErrorCode code) {
475
		ModelAndView modelAndView = new ModelAndView("oai/exception");
476
    	modelAndView.addObject("message", ex.getMessage());
477
    	if(request.getParameter("verb") != null) {
478
    		try {
479
    		  modelAndView.addObject("verb", Verb.fromValue(request.getParameter("verb")));
480
    		} catch(Exception e) {// prevent endless recursion
481
    			
482
    		}
483
    	}
484
    	modelAndView.addObject("code",code);
485
    	return modelAndView;    	
486
	}
487

    
488
	@ResponseStatus(HttpStatus.BAD_REQUEST)
489
	@ExceptionHandler({IllegalArgumentException.class,TypeMismatchException.class,MissingServletRequestParameterException.class})
490
    public ModelAndView handleBadArgument(Exception ex, HttpServletRequest request) {
491
		return doException(ex,request,ErrorCode.BAD_ARGUMENT);  	
492
    }
493
	
494
	@ResponseStatus(HttpStatus.BAD_REQUEST)
495
	@ExceptionHandler(CannotDisseminateFormatException.class)
496
    public ModelAndView handleCannotDisseminateFormat(Exception ex, HttpServletRequest request) {
497
		return doException(ex,request,ErrorCode.CANNOT_DISSEMINATE_FORMAT);  	
498
    }
499
	
500
	@ResponseStatus(HttpStatus.BAD_REQUEST)
501
	@ExceptionHandler(BadResumptionTokenException.class)
502
    public ModelAndView handleBadResumptionToken(Exception ex, HttpServletRequest request) {
503
		return doException(ex,request,ErrorCode.BAD_RESUMPTION_TOKEN);  	   	
504
    }
505
	
506
	@ExceptionHandler(NoRecordsMatchException.class)
507
    public ModelAndView handleNoRecordsMatch(Exception ex, HttpServletRequest request) {
508
		return doException(ex,request,ErrorCode.NO_RECORDS_MATCH);  	   	
509
    }
510
	
511
	@ResponseStatus(HttpStatus.NOT_FOUND)
512
	@ExceptionHandler(IdDoesNotExistException.class)
513
    public ModelAndView handleIdDoesNotExist(Exception ex, HttpServletRequest request) {
514
		return doException(ex,request,ErrorCode.ID_DOES_NOT_EXIST);
515
    }
516
	
517
	
518
}
(3-3/43)