Project

General

Profile

Download (20.1 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
import java.util.UUID;
7

    
8
import javax.servlet.http.HttpServletRequest;
9

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

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

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

    
52
    protected SERVICE service;
53

    
54
    protected IAuditEventService auditEventService;
55

    
56
	private String repositoryName;
57

    
58
	private String baseURL;
59

    
60
	private String protocolVersion;
61

    
62
	private String adminEmail;
63

    
64
	private String description;
65

    
66
	private Integer pageSize;
67

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

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

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

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

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

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

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

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

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

    
143

    
144
	/**
145
     *  CannotDisseminateFormatException thrown by MetadataPrefixEditor
146
     * @throws IdDoesNotExistException 
147
     */
148
    @RequestMapping(method = RequestMethod.GET,params = "verb=GetRecord")
149
    public ModelAndView getRecord(@RequestParam(value = "identifier", required = true) LSID identifier,@RequestParam(value = "metadataPrefix", required = true) MetadataPrefix metadataPrefix) throws IdDoesNotExistException {
150
 
151
        ModelAndView modelAndView = new ModelAndView();
152
        modelAndView.addObject("metadataPrefix", metadataPrefix);
153
        
154
        T object = service.find(identifier);
155
        Pager<AuditEventRecord<T>> results = service.pageAuditEvents(object,1,0,AuditEventSort.BACKWARDS,getPropertyPaths()); 
156

    
157
        if(results.getCount() == 0) {
158
	        throw new IdDoesNotExistException(identifier);
159
        }
160
        
161
        modelAndView.addObject("object",results.getRecords().get(0));
162

    
163
        switch(metadataPrefix) {
164
        case RDF:
165
            modelAndView.setViewName("oai/getRecord.rdf");
166
            break; 
167
	    case OAI_DC:
168
        default:
169
		    modelAndView.setViewName("oai/getRecord.dc");        
170
        }
171

    
172
        return modelAndView;
173
    }
174
    
175
    /**
176
     *  CannotDisseminateFormatException thrown by MetadataPrefixEditor
177
     * @throws IdDoesNotExistException 
178
     */
179
    @RequestMapping(method = RequestMethod.GET,params = "verb=ListMetadataFormats")
180
    public ModelAndView listMetadataFormats(@RequestParam(value = "identifier", required = false) LSID identifier) throws IdDoesNotExistException {
181
 
182
        ModelAndView modelAndView = new ModelAndView("oai/listMetadataFormats");
183
        
184
        T object = service.find(UUID.fromString("c34eb662-6bba-4ad7-b84e-dd98f2fd9788"));
185
        if(false && identifier != null) {
186
        	object = service.find(identifier);
187
	        if(object == null) {
188
		        throw new IdDoesNotExistException(identifier);
189
	        }
190
    	}
191

    
192
        return modelAndView;
193
    }
194
    
195
    /**
196
     *  CannotDisseminateFormatException thrown by MetadataPrefixEditor
197
     */
198
    @RequestMapping(method = RequestMethod.GET,params = "verb=ListSets")
199
    public ModelAndView listSets() {
200
 
201
        ModelAndView modelAndView = new ModelAndView("oai/listSets");
202
        
203
        addSets(modelAndView);
204

    
205
        return modelAndView;
206
    }
207

    
208
	@RequestMapping(method = RequestMethod.GET,params = "verb=Identify")
209
    public ModelAndView identify() {
210
        ModelAndView modelAndView = new ModelAndView("oai/identify");
211
        modelAndView.addObject("repositoryName", repositoryName);
212
        modelAndView.addObject("baseURL",baseURL);
213
        modelAndView.addObject("protocolVersion",protocolVersion);
214
        modelAndView.addObject("deletedRecord",DeletedRecord.PERSISTENT);
215
        modelAndView.addObject("granularity",Granularity.YYYY_MM_DD_THH_MM_SS_Z);
216

    
217
        Pager<AuditEvent> auditEvents = auditEventService.list(0,1,AuditEventSort.FORWARDS);
218
        modelAndView.addObject("earliestDatestamp",auditEvents.getRecords().get(0).getDate());
219
        modelAndView.addObject("adminEmail",adminEmail);
220
        modelAndView.addObject("description",description);
221

    
222
        return modelAndView;
223
    }
224
 
225
    @RequestMapping(method = RequestMethod.GET, params = {"verb=ListIdentifiers", "!resumptionToken"})
226
    public ModelAndView listIdentifiers(@RequestParam(value = "from", required = false) DateTime from, @RequestParam(value = "until", required = false) DateTime until,@RequestParam(value = "metadataPrefix",required = true) MetadataPrefix metadataPrefix, @RequestParam(value = "set", required = false) SetSpec set) {
227
 
228
        ModelAndView modelAndView = new ModelAndView("oai/listIdentifiers");
229
        modelAndView.addObject("metadataPrefix",metadataPrefix);
230
        
231
        AuditEvent fromAuditEvent = null;
232
        if(from != null) { // if from is specified, use the event at that date
233
            modelAndView.addObject("from",from);
234
            fromAuditEvent = auditEventService.find(from);
235
        } 
236
    
237
        AuditEvent untilAuditEvent = null;
238
        if(until != null) {
239
            modelAndView.addObject("until",until);
240
            untilAuditEvent = auditEventService.find(until);
241
        } 
242

    
243
        Class clazz = null;
244
        if(set != null) {
245
        	modelAndView.addObject("set",set);
246
        	clazz = (Class)set.getSetClass();
247
        }
248
        
249
        List<AuditCriterion> criteria = new ArrayList<AuditCriterion>();
250
        criteria.add(AuditEntity.property("lsid_lsid").isNotNull());
251
        Pager<AuditEventRecord<T>> results = service.pageAuditEvents(clazz,fromAuditEvent,untilAuditEvent,criteria, pageSize, 0, AuditEventSort.FORWARDS,null); 
252
        
253
        if(results.getCount() == 0) {
254
        	throw new NoRecordsMatchException("No records match");
255
        }
256
        
257
        modelAndView.addObject("pager",results);
258

    
259
        if(results.getCount() > results.getRecords().size() && cacheProviderFacade != null) {
260
	        ResumptionToken resumptionToken = new ResumptionToken(results, from, until, metadataPrefix, set);
261
            modelAndView.addObject("resumptionToken",resumptionToken);
262
            cacheProviderFacade.putInCache(resumptionToken.getValue(), cachingModel, resumptionToken);
263
        }
264

    
265
        return modelAndView;
266
    }
267

    
268
    @RequestMapping(method = RequestMethod.GET, params = {"verb=ListIdentifiers", "resumptionToken"})
269
    public ModelAndView listIdentifiers(@RequestParam(value = "resumptionToken",required = true) String rToken) {
270
    	ResumptionToken resumptionToken;
271
    	if(cacheProviderFacade != null && cacheProviderFacade.getFromCache(rToken, cachingModel) != null) {
272
    	    resumptionToken = (ResumptionToken) cacheProviderFacade.getFromCache(rToken, cachingModel);
273
            ModelAndView modelAndView = new ModelAndView("oai/listIdentifiers");
274
            modelAndView.addObject("metadataPrefix",resumptionToken.getMetadataPrefix());
275

    
276
            AuditEvent fromAuditEvent = null;
277
            if(resumptionToken.getFrom() != null) { // if from is specified, use the event at that date
278
                modelAndView.addObject("from",resumptionToken.getFrom());
279
                fromAuditEvent = auditEventService.find(resumptionToken.getFrom());
280
            } 
281
    
282
            AuditEvent untilAuditEvent = null;
283
            if(resumptionToken.getUntil() != null) {
284
                modelAndView.addObject("until",resumptionToken.getUntil());
285
                untilAuditEvent = auditEventService.find(resumptionToken.getUntil());
286
            }
287

    
288
            Class clazz = null;
289
            if(resumptionToken.getSet() != null) {
290
            	modelAndView.addObject("set",resumptionToken.getSet());
291
            	clazz = (Class)resumptionToken.getSet().getSetClass();
292
            }
293
            
294
            List<AuditCriterion> criteria = new ArrayList<AuditCriterion>();
295
            criteria.add(AuditEntity.property("lsid_lsid").isNotNull());
296
            Pager<AuditEventRecord<T>> results = service.pageAuditEvents(clazz,fromAuditEvent,untilAuditEvent,criteria, pageSize, (resumptionToken.getCursor().intValue() / pageSize) + 1, AuditEventSort.FORWARDS,null); 
297
        
298
            if(results.getCount() == 0) {
299
            	throw new NoRecordsMatchException("No records match");
300
            }
301
            
302
            modelAndView.addObject("pager",results);
303

    
304
            if(results.getCount() > ((results.getPageSize() * results.getCurrentIndex()) + results.getRecords().size())) {
305
	            resumptionToken.updateResults(results);
306
                modelAndView.addObject("resumptionToken",resumptionToken);
307
                cacheProviderFacade.putInCache(resumptionToken.getValue(),cachingModel, resumptionToken);
308
            } else {
309
                resumptionToken = ResumptionToken.emptyResumptionToken();
310
                modelAndView.addObject("resumptionToken",resumptionToken);
311
                cacheProviderFacade.removeFromCache(rToken,cachingModel);
312
            }
313

    
314
            return modelAndView;
315
    	} else {
316
    		throw new BadResumptionTokenException();
317
    	}
318
    }
319

    
320
    @RequestMapping(method = RequestMethod.GET, params = {"verb=ListRecords", "!resumptionToken"})
321
    public ModelAndView listRecords(@RequestParam(value = "from", required = false) DateTime from, @RequestParam(value = "until", required = false) DateTime until,@RequestParam(value = "metadataPrefix", required = true) MetadataPrefix metadataPrefix, @RequestParam(value = "set", required = false) SetSpec set) {
322
 
323
        ModelAndView modelAndView = new ModelAndView();
324
        modelAndView.addObject("metadataPrefix",metadataPrefix);
325
 
326
        switch(metadataPrefix) {
327
        case RDF:
328
            modelAndView.setViewName("oai/listRecords.rdf");
329
            break; 
330
	    case OAI_DC:
331
            default:
332
		    modelAndView.setViewName("oai/listRecords.dc");        
333
        }
334

    
335
        AuditEvent fromAuditEvent = null;
336
        if(from != null) { // if from is specified, use the event at that date
337
            modelAndView.addObject("from",from);
338
            fromAuditEvent = auditEventService.find(from);
339
        } 
340
    
341
        AuditEvent untilAuditEvent = null;
342
        if(until != null) {
343
            modelAndView.addObject("until",until);
344
            untilAuditEvent = auditEventService.find(until);
345
        } 
346

    
347
        Class clazz = null;
348
        if(set != null) {
349
            modelAndView.addObject("set",set);
350
            clazz = (Class)set.getSetClass();
351
        }
352
        
353
        List<AuditCriterion> criteria = new ArrayList<AuditCriterion>();
354
        criteria.add(AuditEntity.property("lsid_lsid").isNotNull());
355
        Pager<AuditEventRecord<T>> results = service.pageAuditEvents(clazz,fromAuditEvent,untilAuditEvent,criteria, pageSize, 0, AuditEventSort.FORWARDS,getPropertyPaths()); 
356
        
357
        if(results.getCount() == 0) {
358
        	throw new NoRecordsMatchException("No records match");
359
        }
360
        
361
        modelAndView.addObject("pager",results);
362

    
363
        if(results.getCount() > results.getRecords().size() && cacheProviderFacade != null) {
364
	        ResumptionToken resumptionToken = new ResumptionToken(results, from, until, metadataPrefix, set);
365
            modelAndView.addObject("resumptionToken",resumptionToken);
366
            cacheProviderFacade.putInCache(resumptionToken.getValue(),cachingModel,resumptionToken);
367
        }
368

    
369
        return modelAndView;
370
    }
371

    
372
	@RequestMapping(method = RequestMethod.GET, params = {"verb=ListRecords", "resumptionToken"})
373
    public ModelAndView listRecords(@RequestParam("resumptionToken") String rToken) {
374
 
375
	   ResumptionToken resumptionToken;
376
	   if(cacheProviderFacade != null && cacheProviderFacade.getFromCache(rToken,cachingModel) != null) {
377
   	        resumptionToken = (ResumptionToken) cacheProviderFacade.getFromCache(rToken,cachingModel);
378
            ModelAndView modelAndView = new ModelAndView();
379
            modelAndView.addObject("metadataPrefix",resumptionToken.getMetadataPrefix());
380
 
381
            switch (resumptionToken.getMetadataPrefix()) {
382
            case RDF:
383
                modelAndView.setViewName("oai/listRecords.rdf");
384
                break; 
385
	        case OAI_DC:
386
                default:
387
		        modelAndView.setViewName("oai/listRecords.dc");        
388
            }
389

    
390
            AuditEvent fromAuditEvent = null;
391
            if(resumptionToken.getFrom() != null) { // if from is specified, use the event at that date
392
                modelAndView.addObject("from",resumptionToken.getFrom());
393
                fromAuditEvent = auditEventService.find(resumptionToken.getFrom());
394
            }
395
    
396
            AuditEvent untilAuditEvent = null;
397
            if(resumptionToken.getUntil() != null) {
398
                modelAndView.addObject("until",resumptionToken.getUntil());
399
                untilAuditEvent = auditEventService.find(resumptionToken.getUntil());
400
            }
401
        
402
            Class clazz = null;
403
            if(resumptionToken.getSet() != null) {
404
              modelAndView.addObject("set",resumptionToken.getSet());
405
              clazz = (Class)resumptionToken.getSet().getSetClass();
406
            }
407
            List<AuditCriterion> criteria = new ArrayList<AuditCriterion>();
408
            criteria.add(AuditEntity.property("lsid_lsid").isNotNull());
409
            Pager<AuditEventRecord<T>> results = service.pageAuditEvents(clazz,fromAuditEvent,untilAuditEvent,criteria, pageSize, (resumptionToken.getCursor().intValue()  / pageSize) + 1, AuditEventSort.FORWARDS,getPropertyPaths()); 
410
        
411
            if(results.getCount() == 0) {
412
            	throw new NoRecordsMatchException("No records match");
413
            }
414
            
415
            modelAndView.addObject("pager",results);
416

    
417
            if(results.getCount() > ((results.getPageSize() * results.getCurrentIndex()) + results.getRecords().size())) {
418
	            resumptionToken.updateResults(results);
419
                modelAndView.addObject("resumptionToken",resumptionToken);
420
                cacheProviderFacade.putInCache(resumptionToken.getValue(),cachingModel,resumptionToken);
421
            } else {
422
                resumptionToken = ResumptionToken.emptyResumptionToken();
423
                modelAndView.addObject("resumptionToken",resumptionToken);
424
                cacheProviderFacade.removeFromCache(rToken,cachingModel);
425
            }
426

    
427
            return modelAndView;
428
	   } else {
429
		   throw new BadResumptionTokenException();
430
	   }
431
    }
432
	
433
	private ModelAndView doException(Exception ex, HttpServletRequest request, ErrorCode code) {
434
		ModelAndView modelAndView = new ModelAndView("oai/exception");
435
    	modelAndView.addObject("message", ex.getMessage());
436
    	if(request.getParameter("verb") != null) {
437
    		try {
438
    		  modelAndView.addObject("verb", Verb.fromValue(request.getParameter("verb")));
439
    		} catch(Exception e) {// prevent endless recursion
440
    			
441
    		}
442
    	}
443
    	modelAndView.addObject("code",code);
444
    	return modelAndView;    	
445
	}
446

    
447
	@ResponseStatus(HttpStatus.BAD_REQUEST)
448
	@ExceptionHandler({IllegalArgumentException.class,TypeMismatchException.class,MissingServletRequestParameterException.class})
449
    public ModelAndView handleBadArgument(Exception ex, HttpServletRequest request) {
450
		return doException(ex,request,ErrorCode.BAD_ARGUMENT);  	
451
    }
452
	
453
	@ResponseStatus(HttpStatus.BAD_REQUEST)
454
	@ExceptionHandler(CannotDisseminateFormatException.class)
455
    public ModelAndView handleCannotDisseminateFormat(Exception ex, HttpServletRequest request) {
456
		return doException(ex,request,ErrorCode.CANNOT_DISSEMINATE_FORMAT);  	
457
    }
458
	
459
	@ResponseStatus(HttpStatus.BAD_REQUEST)
460
	@ExceptionHandler(BadResumptionTokenException.class)
461
    public ModelAndView handleBadResumptionToken(Exception ex, HttpServletRequest request) {
462
		return doException(ex,request,ErrorCode.BAD_RESUMPTION_TOKEN);  	   	
463
    }
464
	
465
	@ExceptionHandler(NoRecordsMatchException.class)
466
    public ModelAndView handleNoRecordsMatch(Exception ex, HttpServletRequest request) {
467
		return doException(ex,request,ErrorCode.NO_RECORDS_MATCH);  	   	
468
    }
469
	
470
	@ResponseStatus(HttpStatus.NOT_FOUND)
471
	@ExceptionHandler(IdDoesNotExistException.class)
472
    public ModelAndView handleIdDoesNotExist(Exception ex, HttpServletRequest request) {
473
		return doException(ex,request,ErrorCode.ID_DOES_NOT_EXIST);
474
    }
475
	
476
	
477
}
(3-3/43)