new service for media/*/metadata and bugfix of #1310
[cdmlib.git] / cdmlib-remote / src / main / java / eu / etaxonomy / cdm / remote / controller / TaxonPortalController.java
1 // $Id: TaxonController.java 5473 2009-03-25 13:42:07Z a.kohlbecker $
2 /**
3 * Copyright (C) 2007 EDIT
4 * European Distributed Institute of Taxonomy
5 * http://www.e-taxonomy.eu
6 *
7 * The contents of this file are subject to the Mozilla Public License Version 1.1
8 * See LICENSE.TXT at the top of this package for the full license terms.
9 */
10
11 package eu.etaxonomy.cdm.remote.controller;
12
13 import java.io.IOException;
14 import java.util.ArrayList;
15 import java.util.Arrays;
16 import java.util.HashSet;
17 import java.util.Hashtable;
18 import java.util.List;
19 import java.util.Map;
20 import java.util.NoSuchElementException;
21 import java.util.Set;
22 import java.util.SortedMap;
23 import java.util.TreeMap;
24 import java.util.UUID;
25 import java.util.regex.Matcher;
26 import java.util.regex.Pattern;
27
28 import javax.servlet.http.HttpServletRequest;
29 import javax.servlet.http.HttpServletResponse;
30
31 import org.apache.commons.lang.ObjectUtils;
32 import org.apache.log4j.Logger;
33 import org.springframework.beans.factory.annotation.Autowired;
34 import org.springframework.stereotype.Controller;
35 import org.springframework.web.bind.WebDataBinder;
36 import org.springframework.web.bind.annotation.InitBinder;
37 import org.springframework.web.bind.annotation.RequestMapping;
38 import org.springframework.web.bind.annotation.RequestMethod;
39 import org.springframework.web.bind.annotation.RequestParam;
40 import org.springframework.web.servlet.ModelAndView;
41
42 import eu.etaxonomy.cdm.api.service.IDescriptionService;
43 import eu.etaxonomy.cdm.api.service.INameService;
44 import eu.etaxonomy.cdm.api.service.IReferenceService;
45 import eu.etaxonomy.cdm.api.service.ITaxonService;
46 import eu.etaxonomy.cdm.api.service.ITaxonTreeService;
47 import eu.etaxonomy.cdm.api.service.config.ITaxonServiceConfigurator;
48 import eu.etaxonomy.cdm.api.service.config.impl.TaxonServiceConfiguratorImpl;
49 import eu.etaxonomy.cdm.api.service.pager.Pager;
50 import eu.etaxonomy.cdm.database.UpdatableRoutingDataSource;
51 import eu.etaxonomy.cdm.model.common.IdentifiableEntity;
52 import eu.etaxonomy.cdm.model.description.DescriptionElementBase;
53 import eu.etaxonomy.cdm.model.description.TaxonDescription;
54 import eu.etaxonomy.cdm.model.description.TaxonNameDescription;
55 import eu.etaxonomy.cdm.model.location.NamedArea;
56 import eu.etaxonomy.cdm.model.media.Media;
57 import eu.etaxonomy.cdm.model.media.MediaRepresentation;
58 import eu.etaxonomy.cdm.model.name.NameRelationship;
59 import eu.etaxonomy.cdm.model.name.TaxonNameBase;
60 import eu.etaxonomy.cdm.model.name.TypeDesignationBase;
61 import eu.etaxonomy.cdm.model.taxon.Synonym;
62 import eu.etaxonomy.cdm.model.taxon.Taxon;
63 import eu.etaxonomy.cdm.model.taxon.TaxonBase;
64 import eu.etaxonomy.cdm.model.taxon.TaxonRelationship;
65 import eu.etaxonomy.cdm.model.taxon.TaxonRelationshipType;
66 import eu.etaxonomy.cdm.model.taxon.TaxonomicTree;
67 import eu.etaxonomy.cdm.persistence.query.MatchMode;
68 import eu.etaxonomy.cdm.remote.editor.NamedAreaPropertyEditor;
69 import eu.etaxonomy.cdm.remote.editor.UUIDPropertyEditor;
70
71 /**
72 * The TaxonPortalController class is a Spring MVC Controller.
73 * <p>
74 * The syntax of the mapped service URIs contains the the {datasource-name} path element.
75 * The available {datasource-name}s are defined in a configuration file which
76 * is loaded by the {@link UpdatableRoutingDataSource}. If the
77 * UpdatableRoutingDataSource is not being used in the actual application
78 * context any arbitrary {datasource-name} may be used.
79 * <p>
80 * Methods mapped at type level, inherited from super classes ({@link BaseController}):
81 * <blockquote>
82 * URI: <b>&#x002F;{datasource-name}&#x002F;portal&#x002F;taxon&#x002F;{taxon-uuid}</b>
83 *
84 * Get the {@link TaxonBase} instance identified by the <code>{taxon-uuid}</code>.
85 * The returned Taxon is initialized by
86 * the following strategy {@link #TAXON_INIT_STRATEGY}
87 * </blockquote>
88 *
89 * @author a.kohlbecker
90 * @date 20.07.2009
91 *
92 */
93 @Controller
94 @RequestMapping(value = {"/*/portal/taxon/*", "/*/portal/taxon/*/*", "/*/portal/name/*/*", "/*/portal/taxon/*/media/*/*"})
95 public class TaxonPortalController extends BaseController<TaxonBase, ITaxonService>
96 {
97 public static final Logger logger = Logger.getLogger(TaxonPortalController.class);
98
99 @Autowired
100 private INameService nameService;
101 @Autowired
102 private IDescriptionService descriptionService;
103 @Autowired
104 private IReferenceService referenceService;
105
106 @Autowired
107 private ITaxonTreeService taxonTreeService;
108
109 private static final List<String> TAXON_INIT_STRATEGY = Arrays.asList(new String []{
110 "*",
111 // taxon relations
112 "relationsToThisName.fromTaxon.name.taggedName",
113 // the name
114 "name.$",
115 "name.taggedName",
116 "name.rank.representations",
117 "name.status.type.representations",
118
119 // taxon descriptions
120 "descriptions.elements.$",
121 "descriptions.elements.area",
122 "descriptions.elements.area.$",
123 "descriptions.elements.multilanguageText",
124 "descriptions.elements.media.representations.parts",
125
126 // // typeDesignations
127 // "name.typeDesignations.$",
128 // "name.typeDesignations.citation.authorTeam",
129 // "name.typeDesignations.typeName.$",
130 // "name.typeDesignations.typeStatus.representations",
131 // "name.typeDesignations.typeSpecimen.media.representations.parts"
132
133 });
134
135 private static final List<String> SIMPLE_TAXON_INIT_STRATEGY = Arrays.asList(new String []{
136 "*",
137 // taxon relations
138 "relationsToThisName.fromTaxon.name.taggedName",
139 // the name
140 "name.$",
141 "name.taggedName",
142 "name.rank.representations",
143 "name.status.type.representations"
144 });
145
146 private static final List<String> SYNONYMY_INIT_STRATEGY = Arrays.asList(new String []{
147 // initialize homotypical and heterotypical groups; needs synonyms
148 "synonymRelations.$",
149 "synonymRelations.synonym.$",
150 "synonymRelations.synonym.name.taggedName",
151 "synonymRelations.synonym.name.nomenclaturalReference.inBook.authorTeam",
152 "synonymRelations.synonym.name.nomenclaturalReference.inJournal",
153 "synonymRelations.synonym.name.nomenclaturalReference.inProceedings",
154 "synonymRelations.synonym.name.homotypicalGroup.typifiedNames.$",
155 "synonymRelations.synonym.name.homotypicalGroup.typifiedNames.name.taggedName",
156 "synonymRelations.synonym.name.homotypicalGroup.typifiedNames.taxonBases.$",
157 "synonymRelations.synonym.name.homotypicalGroup.typifiedNames.taxonBases.name.taggedName",
158
159 "name.homotypicalGroup.$",
160 "name.homotypicalGroup.typifiedNames.$",
161 "name.homotypicalGroup.typifiedNames.name.taggedName",
162
163 "name.homotypicalGroup.typifiedNames.taxonBases.$",
164 "name.homotypicalGroup.typifiedNames.taxonBases.name.taggedName"
165
166 });
167
168 private static final List<String> TAXONRELATIONSHIP_INIT_STRATEGY = Arrays.asList(new String []{
169 "$",
170 "type.inverseRepresentations",
171 "fromTaxon.sec.authorTeam",
172 "fromTaxon.name.taggedName"
173 });
174
175 private static final List<String> NAMERELATIONSHIP_INIT_STRATEGY = Arrays.asList(new String []{
176 "$",
177 "type.inverseRepresentations",
178 "fromName.taggedName",
179 });
180
181
182 protected static final List<String> TAXONDESCRIPTION_INIT_STRATEGY = Arrays.asList(new String []{
183 "$",
184 "elements.$",
185 "elements.sources.citation.",
186 "elements.multilanguageText",
187 "elements.media.representations.parts",
188 });
189
190 private static final List<String> NAMEDESCRIPTION_INIT_STRATEGY = Arrays.asList(new String []{
191 "uuid",
192 "feature",
193 "elements.$",
194 "elements.multilanguageText",
195 "elements.media.representations.parts",
196 });
197
198 private static final List<String> TYPEDESIGNATION_INIT_STRATEGY = Arrays.asList(new String []{
199 //"$",
200 "typeSpecimen.$",
201 "typeStatus.representations",
202 "citation.authorTeam",
203 "typeName.taggedName"
204 });
205
206
207
208 private static final String featureTreeUuidPattern = "^/(?:[^/]+)/taxon(?:(?:/)([^/?#&\\.]+))+.*";
209
210 public TaxonPortalController(){
211 super();
212 setInitializationStrategy(TAXON_INIT_STRATEGY);
213 setUuidParameterPattern("^/(?:[^/]+)/portal/(?:[^/]+)/([^/?#&\\.]+).*");
214 }
215
216 /* (non-Javadoc)
217 * @see eu.etaxonomy.cdm.remote.controller.GenericController#setService(eu.etaxonomy.cdm.api.service.IService)
218 */
219 @Autowired
220 @Override
221 public void setService(ITaxonService service) {
222 this.service = service;
223 }
224
225 @InitBinder
226 public void initBinder(WebDataBinder binder) {
227 binder.registerCustomEditor(UUID.class, new UUIDPropertyEditor());
228 binder.registerCustomEditor(NamedArea.class, new NamedAreaPropertyEditor());
229 }
230
231
232 /* (non-Javadoc)
233 * @see eu.etaxonomy.cdm.remote.controller.BaseController#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
234
235 @Override
236 @RequestMapping(method = RequestMethod.GET)
237 public TaxonBase doGet(HttpServletRequest request, HttpServletResponse response)throws IOException {
238 logger.info("doGet()");
239 TaxonBase tb = getCdmBase(request, response, TAXON_INIT_STRATEGY, TaxonBase.class);
240 return tb;
241 }
242 */
243 /**
244 * Find Taxa, Synonyms, Common Names by name, either globally or in a specific geographic area.
245 * <p>
246 * URI: <b>&#x002F;{datasource-name}&#x002F;portal&#x002F;taxon&#x002F;find</b>
247 *
248 * @param query
249 * the string to query for. Since the wildcard character '*'
250 * internally always is appended to the query string, a search
251 * always compares the query string with the beginning of a name.
252 * - <i>required parameter</i>
253 * @param treeUuid
254 * the {@link UUID} of a {@link TaxonomicTree} to which the
255 * search is to be restricted. - <i>optional parameter</i>
256 * @param areas
257 * restrict the search to a set of geographic {@link NamedArea}s.
258 * The parameter currently takes a list of TDWG area labels.
259 * - <i>optional parameter</i>
260 * @param page
261 * the number of the page to be returned, the first page has the
262 * pageNumber = 1 - <i>optional parameter</i>
263 * @param pageSize
264 * the maximum number of entities returned per page (can be null
265 * to return all entities in a single page) - <i>optional parameter</i>
266 * @param doTaxa
267 * weather to search for instances of {@link Taxon} - <i>optional parameter</i>
268 * @param doSynonyms
269 * weather to search for instances of {@link Synonym} - <i>optional parameter</i>
270 * @param doTaxaByCommonNames
271 * for instances of {@link Taxon} by a common name used - <i>optional parameter</i>
272 * @return a Pager on a list of {@link IdentifiableEntity}s initialized by
273 * the following strategy {@link #SIMPLE_TAXON_INIT_STRATEGY}
274 * @throws IOException
275 */
276 @RequestMapping(method = RequestMethod.GET,
277 value = {"/*/portal/taxon/find"}) //TODO map to path /*/portal/taxon/
278 public Pager<IdentifiableEntity> doFind(
279 @RequestParam(value = "query", required = false) String query,
280 @RequestParam(value = "tree", required = false) UUID treeUuid,
281 @RequestParam(value = "area", required = false) Set<NamedArea> areas,
282 @RequestParam(value = "page", required = false) Integer page,
283 @RequestParam(value = "pageSize", required = false) Integer pageSize,
284 @RequestParam(value = "doTaxa", required = false) Boolean doTaxa,
285 @RequestParam(value = "doSynonyms", required = false) Boolean doSynonyms,
286 @RequestParam(value = "doTaxaByCommonNames", required = false) Boolean doTaxaByCommonNames)
287 throws IOException {
288
289 logger.info("doFind( " +
290 "query=\"" + ObjectUtils.toString(query) + "\", treeUuid=" + ObjectUtils.toString(treeUuid) +
291 ", area=" + ObjectUtils.toString(areas) +
292 ", pageSize=" + ObjectUtils.toString(pageSize) + ", page=" + ObjectUtils.toString(page) +
293 ", doTaxa=" + ObjectUtils.toString(doTaxa) + ", doSynonyms=" + ObjectUtils.toString(doSynonyms) +")" );
294
295 if(page == null){ page = BaseListController.DEFAULT_PAGE_NUMBER;}
296 if(pageSize == null){ pageSize = BaseListController.DEFAULT_PAGESIZE;}
297
298 ITaxonServiceConfigurator config = new TaxonServiceConfiguratorImpl();
299 config.setPageNumber(page);
300 config.setPageSize(pageSize);
301 config.setSearchString(query);
302 config.setDoTaxa(doTaxa!= null ? doTaxa : Boolean.FALSE );
303 config.setDoSynonyms(doSynonyms != null ? doSynonyms : Boolean.FALSE );
304 config.setDoTaxaByCommonNames(doTaxaByCommonNames != null ? doTaxaByCommonNames : Boolean.FALSE );
305 config.setMatchMode(MatchMode.BEGINNING);
306 config.setTaxonPropertyPath(SIMPLE_TAXON_INIT_STRATEGY);
307 config.setNamedAreas(areas);
308 if(treeUuid != null){
309 TaxonomicTree taxonomicTree = taxonTreeService.find(treeUuid);
310 config.setTaxonomicTree(taxonomicTree);
311 }
312
313 return (Pager<IdentifiableEntity>) service.findTaxaAndNames(config);
314 }
315
316 /**
317 * Get the synonymy for a taxon identified by the <code>{taxon-uuid}</code>.
318 * The synonymy consists
319 * of two parts: The group of homotypic synonyms of the taxon and the
320 * heterotypic synonymy groups of the taxon. The synonymy is ordered
321 * historically by the type designations and by the publication date of the
322 * nomenclatural reference
323 * <p>
324 * URI:
325 * <b>&#x002F;{datasource-name}&#x002F;portal&#x002F;taxon&#x002F;{taxon-uuid}&#x002F;synonymy</b>
326 *
327 *
328 * @param request
329 * @param response
330 * @return a Map with to entries which are mapped by the following keys:
331 * "homotypicSynonymsByHomotypicGroup", "heterotypicSynonymyGroups",
332 * containing lists of {@link Synonym}s which are initialized using the
333 * following initialization strategy: {@link #SYNONYMY_INIT_STRATEGY}
334 *
335 * @throws IOException
336 */
337 @RequestMapping(
338 value = {"/*/portal/taxon/*/synonymy"},
339 method = RequestMethod.GET)
340 public ModelAndView doGetSynonymy(HttpServletRequest request, HttpServletResponse response)throws IOException {
341
342 logger.info("doGetSynonymy() " + request.getServletPath());
343 ModelAndView mv = new ModelAndView();
344 TaxonBase tb = getCdmBase(request, response, null, Taxon.class);
345 Taxon taxon = (Taxon)tb;
346 Map<String, List<?>> synonymy = new Hashtable<String, List<?>>();
347 synonymy.put("homotypicSynonymsByHomotypicGroup", service.getHomotypicSynonymsByHomotypicGroup(taxon, SYNONYMY_INIT_STRATEGY));
348 synonymy.put("heterotypicSynonymyGroups", service.getHeterotypicSynonymyGroups(taxon, SYNONYMY_INIT_STRATEGY));
349 mv.addObject(synonymy);
350 return mv;
351 }
352
353 /**
354 * Get the set of accepted {@link Taxon} entities for a given
355 * {@link TaxonBase} entity identified by the <code>{taxon-uuid}</code>.
356 * <p>
357 * URI: <b>&#x002F;{datasource-name}&#x002F;portal&#x002F;taxon&#x002F;{taxon-uuid}&#x002F;accepted</b>
358 *
359 * @param request
360 * @param response
361 * @return a Set of {@link Taxon} entities which are initialized
362 * using the following initialization strategy:
363 * {@link #SYNONYMY_INIT_STRATEGY}
364 * @throws IOException
365 */
366 @RequestMapping(value = "/*/portal/taxon/*/accepted", method = RequestMethod.GET)
367 public Set<TaxonBase> getAccepted(HttpServletRequest request, HttpServletResponse response) throws IOException {
368
369 logger.info("getAccepted() " + request.getServletPath());
370
371 UUID uuid = readValueUuid(request, null);
372 TaxonBase tb = service.load(uuid, SYNONYMY_INIT_STRATEGY);
373 if(tb == null){
374 response.sendError(HttpServletResponse.SC_NOT_FOUND, "A taxon with the uuid " + uuid + " does not exist");
375 return null;
376 }
377 HashSet<TaxonBase> resultset = new HashSet<TaxonBase>();
378 if(tb instanceof Taxon){
379 //the taxon already is accepted
380 //FIXME take the current view into account once views are implemented!!!
381 resultset.add((Taxon)tb);
382 } else {
383 Synonym syn = (Synonym)tb;
384 for(TaxonBase accepted : syn.getAcceptedTaxa()){
385 accepted = service.load(accepted.getUuid(), SIMPLE_TAXON_INIT_STRATEGY);
386 resultset.add(accepted);
387 }
388 }
389 return resultset;
390 }
391
392 /**
393 * Get the list of {@link TaxonRelationship}s for the given
394 * {@link TaxonBase} instance identified by the <code>{taxon-uuid}</code>.
395 * <p>
396 * URI: <b>&#x002F;{datasource-name}&#x002F;portal&#x002F;taxon&#x002F;{taxon-uuid}&#x002F;taxonRelationships</b>
397 *
398 * @param request
399 * @param response
400 * @return a List of {@link TaxonRelationship} entities which are initialized
401 * using the following initialization strategy:
402 * {@link #TAXONRELATIONSHIP_INIT_STRATEGY}
403 * @throws IOException
404 */
405 @RequestMapping(
406 value = {"/*/portal/taxon/*/taxonRelationships"},
407 method = RequestMethod.GET)
408 public List<TaxonRelationship> doGetTaxonRelations(HttpServletRequest request, HttpServletResponse response)throws IOException {
409
410 logger.info("doGetTaxonRelations()" + request.getServletPath());
411 TaxonBase tb = getCdmBase(request, response, null, Taxon.class);
412 Taxon taxon = (Taxon)tb;
413 List<TaxonRelationship> relations = new ArrayList<TaxonRelationship>();
414 List<TaxonRelationship> results = service.listToTaxonRelationships(taxon, TaxonRelationshipType.MISAPPLIED_NAME_FOR(), null, null, null, TAXONRELATIONSHIP_INIT_STRATEGY);
415 relations.addAll(results);
416 results = service.listToTaxonRelationships(taxon, TaxonRelationshipType.INVALID_DESIGNATION_FOR(), null, null, null, TAXONRELATIONSHIP_INIT_STRATEGY);
417 relations.addAll(results);
418
419 return relations;
420 }
421
422 /**
423 * Get the list of {@link NameRelationship}s of the Name associated with the
424 * {@link TaxonBase} instance identified by the <code>{taxon-uuid}</code>.
425 * <p>
426 * URI: <b>&#x002F;{datasource-name}&#x002F;portal&#x002F;taxon&#x002F;{taxon-uuid}&#x002F;nameRelationships</b>
427 *
428 * @param request
429 * @param response
430 * @return a List of {@link NameRelationship} entities which are initialized
431 * using the following initialization strategy:
432 * {@link #NAMERELATIONSHIP_INIT_STRATEGY}
433 * @throws IOException
434 */
435 @RequestMapping(
436 value = {"/*/portal/taxon/*/nameRelationships"},
437 method = RequestMethod.GET)
438 public List<NameRelationship> doGetNameRelations(HttpServletRequest request, HttpServletResponse response)throws IOException {
439 logger.info("doGetNameRelations()" + request.getServletPath());
440 TaxonBase tb = getCdmBase(request, response, SIMPLE_TAXON_INIT_STRATEGY, Taxon.class);
441 List<NameRelationship> list = nameService.listToNameRelationships(tb.getName(), null, null, null, null, NAMERELATIONSHIP_INIT_STRATEGY);
442 return list;
443 }
444
445 /**
446 * Get the list of {@link TaxonNameDescription}s of the Name associated with the
447 * {@link TaxonNameBase} instance identified by the <code>{name-uuid}</code>.
448 * <p>
449 * URI: <b>&#x002F;{datasource-name}&#x002F;portal&#x002F;name&#x002F;{name-uuid}&#x002F;descriptions</b>
450 *
451 * @param request
452 * @param response
453 * @return a List of {@link TaxonNameDescription} entities which are initialized
454 * using the following initialization strategy:
455 * {@link #NAMEDESCRIPTION_INIT_STRATEGY}
456 * @throws IOException
457 */
458 @RequestMapping(
459 value = {"/*/portal/name/*/descriptions"},
460 method = RequestMethod.GET)
461 public List<TaxonNameDescription> doGetNameDescriptions(HttpServletRequest request, HttpServletResponse response)throws IOException {
462 logger.info("doGetNameDescriptions()" + request.getServletPath());
463 UUID nameUuuid = readValueUuid(request, null);
464 TaxonNameBase tnb = nameService.load(nameUuuid, null);
465 Pager<TaxonNameDescription> p = descriptionService.getTaxonNameDescriptions(tnb, null, null, NAMEDESCRIPTION_INIT_STRATEGY);
466 return p.getRecords();
467 }
468
469 /**
470 * Get the list of {@link TypeDesignationBase}s of the
471 * {@link TaxonBase} instance identified by the <code>{taxon-uuid}</code>.
472 * <p>
473 * URI: <b>&#x002F;{datasource-name}&#x002F;portal&#x002F;taxon&#x002F;{taxon-uuid}&#x002F;nameTypeDesignations</b>
474 *
475 * @param request
476 * @param response
477 * @return a List of {@link TypeDesignationBase} entities which are initialized
478 * using the following initialization strategy:
479 * {@link #TYPEDESIGNATION_INIT_STRATEGY}
480 * @throws IOException
481 */
482 @RequestMapping(
483 value = {"/*/portal/taxon/*/nameTypeDesignations"},
484 method = RequestMethod.GET)
485 public List<TypeDesignationBase> doGetNameTypeDesignations(HttpServletRequest request, HttpServletResponse response)throws IOException {
486 logger.info("doGetNameTypeDesignations()" + request.getServletPath());
487 TaxonBase tb = getCdmBase(request, response, SIMPLE_TAXON_INIT_STRATEGY, Taxon.class);
488 Pager<TypeDesignationBase> p = nameService.getTypeDesignations(tb.getName(), null, null, null, TYPEDESIGNATION_INIT_STRATEGY);
489 return p.getRecords();
490 }
491
492 /**
493 * Get the list of {@link TaxonDescription}s of the
494 * {@link Taxon} instance identified by the <code>{taxon-uuid}</code>.
495 * <p>
496 * URI: <b>&#x002F;{datasource-name}&#x002F;portal&#x002F;taxon&#x002F;{taxon-uuid}&#x002F;descriptions</b>
497 *
498 * @param request
499 * @param response
500 * @return a List of {@link TaxonDescription} entities which are initialized
501 * using the following initialization strategy:
502 * {@link #TAXONDESCRIPTION_INIT_STRATEGY}
503 * @throws IOException
504 */
505 @RequestMapping(
506 value = {"/*/portal/taxon/*/descriptions"},
507 method = RequestMethod.GET)
508 public List<TaxonDescription> doGetDescriptions(HttpServletRequest request, HttpServletResponse response)throws IOException {
509 logger.info("doGetDescriptions()" + request.getServletPath());
510 Taxon t = getCdmBase(request, response, null, Taxon.class);
511 Pager<TaxonDescription> p = descriptionService.getTaxonDescriptions(t, null, null, null, null,
512 TAXONDESCRIPTION_INIT_STRATEGY);
513 return p.getRecords();
514 }
515
516 /**
517 * Get the {@link Media} attached to the {@link Taxon} instance
518 * identified by the <code>{taxon-uuid}</code>.
519 *
520 * Usage &#x002F;{datasource-name}&#x002F;portal&#x002F;taxon&#x002F;{taxon-
521 * uuid}&#x002F;media&#x002F;{mime type
522 * list}&#x002F;{size}[,[widthOrDuration}][,{height}]&#x002F;
523 *
524 * Whereas
525 * <ul>
526 * <li><b>{mime type list}</b>: a comma separated list of mime types, in the
527 * order of preference. The forward slashes contained in the mime types must
528 * be replaced by a colon. Regular expressions can be used. Each media
529 * associated with this given taxon is being searched whereas the first
530 * matching mime type matching a representation always rules.</li>
531 * <li><b>{size},{widthOrDuration},{height}</b>: <i>not jet implemented</i>
532 * valid values are an integer or the asterisk '*' as a wildcard</li>
533 * </ul>
534 *
535 * @param request
536 * @param response
537 * @return a List of {@link Media} entities which are initialized
538 * using the following initialization strategy:
539 * {@link #TAXONDESCRIPTION_INIT_STRATEGY}
540 * @throws IOException
541 */
542 @RequestMapping(
543 value = {"/*/portal/taxon/*/media/*/*"},
544 method = RequestMethod.GET)
545 public List<Media> doGetMedia(HttpServletRequest request, HttpServletResponse response)throws IOException {
546 logger.info("doGetMedia()" + request.getServletPath());
547 Taxon t = getCdmBase(request, response, null, Taxon.class);
548 Pager<TaxonDescription> p =
549 descriptionService.getTaxonDescriptions(t, null, null, null, null, TAXONDESCRIPTION_INIT_STRATEGY);
550
551 // pars the media and quality parameters
552
553
554 // collect all media of the given taxon
555 boolean limitToGalleries = false;
556 List<Media> taxonMedia = new ArrayList<Media>();
557 for(TaxonDescription desc : p.getRecords()){
558 if(!limitToGalleries || desc.isImageGallery()){
559 for(DescriptionElementBase element : desc.getElements()){
560 for(Media media : element.getMedia()){
561 taxonMedia.add(media);
562 }
563 }
564 }
565 }
566
567 // move into media ...
568
569 // find best matching representations of each media
570 String path = request.getServletPath();
571 String[] pathTokens = path.split("/");
572 String[] mimeTypes = pathTokens[6].split(",");
573 String[] sizeTokens = pathTokens[7].split(",");
574 Integer widthOrDuration = null;
575 Integer height = null;
576 Integer size = null;
577
578 for(int i=0; i<mimeTypes.length; i++){
579 mimeTypes[i] = mimeTypes[i].replace(':', '/');
580 }
581
582 if(sizeTokens.length > 0){
583 try {
584 size = Integer.valueOf(sizeTokens[0]);
585 } catch (NumberFormatException nfe) {
586 /* IGNORE */
587 }
588 }
589 if(sizeTokens.length > 1){
590 try {
591 widthOrDuration = Integer.valueOf(sizeTokens[1]);
592 } catch (NumberFormatException nfe) {
593 /* IGNORE */
594 }
595 }
596 if(sizeTokens.length > 2){
597 try {
598 height = Integer.valueOf(sizeTokens[2]);
599 } catch (NumberFormatException nfe) {
600 /* IGNORE */
601 }
602 }
603
604 List<Media> returnMedia = new ArrayList<Media>(taxonMedia.size());
605 for(Media media : taxonMedia){
606 SortedMap<String, MediaRepresentation> prefRepresentations
607 = orderMediaRepresentations(media, mimeTypes, size, widthOrDuration, height);
608 try {
609 // take first one and remove all other representations
610 MediaRepresentation prefOne = prefRepresentations.get(prefRepresentations.firstKey());
611 for (MediaRepresentation representation : media.getRepresentations()) {
612 if (representation != prefOne) {
613 media.removeRepresentation(representation);
614 }
615 }
616 returnMedia.add(media);
617 } catch (NoSuchElementException nse) {
618 /* IGNORE */
619 }
620 }
621
622 return returnMedia;
623 }
624
625 /**
626 * @param media
627 * @param mimeTypeRegexes
628 * @param size
629 * @param widthOrDuration
630 * @param height
631 * @return
632 *
633 * TODO move into a media utils class
634 * TODO implement the quality filter
635 */
636 private SortedMap<String, MediaRepresentation> orderMediaRepresentations(Media media, String[] mimeTypeRegexes,
637 Integer size, Integer widthOrDuration, Integer height) {
638 SortedMap<String, MediaRepresentation> prefRepr = new TreeMap<String, MediaRepresentation>();
639 for (String mimeTypeRegex : mimeTypeRegexes) {
640 // getRepresentationByMimeType
641 Pattern mimeTypePattern = Pattern.compile(mimeTypeRegex);
642 int representationCnt = 0;
643 for (MediaRepresentation representation : media.getRepresentations()) {
644 Matcher mather = mimeTypePattern.matcher(representation.getMimeType());
645 if (mather.matches()) {
646 int dwa = 0;
647
648 /* TODO the quality filter part is being skipped
649 * // look for representation with the best matching parts
650 for (MediaRepresentationPart part : representation.getParts()) {
651 if (part instanceof ImageFile) {
652 ImageFile image = (ImageFile) part;
653 int dw = image.getWidth() * image.getHeight() - height * widthOrDuration;
654 if (dw < 0) {
655 dw *= -1;
656 }
657 dwa += dw;
658 }
659 dwa = (representation.getParts().size() > 0 ? dwa / representation.getParts().size() : 0);
660 }*/
661 prefRepr.put((dwa + representationCnt++) + '_' + representation.getMimeType(), representation);
662
663 // preferred mime type found => end loop
664 break;
665 }
666 }
667 }
668 return prefRepr;
669 }
670
671 // ---------------------- code snippet preserved for possible later use --------------------
672 // @RequestMapping(
673 // value = {"/*/portal/taxon/*/descriptions"},
674 // method = RequestMethod.GET)
675 // public List<TaxonDescription> doGetDescriptionsbyFeatureTree(HttpServletRequest request, HttpServletResponse response)throws IOException {
676 // TaxonBase tb = getCdmBase(request, response, null, Taxon.class);
677 // if(tb instanceof Taxon){
678 // //T O D O this is a quick and dirty implementation -> generalize
679 // UUID featureTreeUuid = readValueUuid(request, featureTreeUuidPattern);
680 //
681 // FeatureTree featureTree = descriptionService.getFeatureTreeByUuid(featureTreeUuid);
682 // Pager<TaxonDescription> p = descriptionService.getTaxonDescriptions((Taxon)tb, null, null, null, null, TAXONDESCRIPTION_INIT_STRATEGY);
683 // List<TaxonDescription> descriptions = p.getRecords();
684 //
685 // if(!featureTree.isDescriptionSeparated()){
686 //
687 // TaxonDescription superDescription = TaxonDescription.NewInstance();
688 // //put all descriptionElements in superDescription and make it invisible
689 // for(TaxonDescription description: descriptions){
690 // for(DescriptionElementBase element: description.getElements()){
691 // superDescription.addElement(element);
692 // }
693 // }
694 // List<TaxonDescription> separatedDescriptions = new ArrayList<TaxonDescription>(descriptions.size());
695 // separatedDescriptions.add(superDescription);
696 // return separatedDescriptions;
697 // }else{
698 // return descriptions;
699 // }
700 // } else {
701 // response.sendError(HttpServletResponse.SC_NOT_FOUND, "invalid type; Taxon expected but " + tb.getClass().getSimpleName() + " found.");
702 // return null;
703 // }
704 // }
705
706 }