2 * Copyright (C) 2007 EDIT
3 * European Distributed Institute of Taxonomy
4 * http://www.e-taxonomy.eu
6 * The contents of this file are subject to the Mozilla Public License Version 1.1
7 * See LICENSE.TXT at the top of this package for the full license terms.
10 package eu
.etaxonomy
.cdm
.api
.service
;
12 import java
.util
.ArrayList
;
13 import java
.util
.Arrays
;
14 import java
.util
.Collection
;
15 import java
.util
.Collections
;
16 import java
.util
.Comparator
;
17 import java
.util
.HashMap
;
18 import java
.util
.HashSet
;
19 import java
.util
.List
;
22 import java
.util
.TreeMap
;
23 import java
.util
.UUID
;
24 import java
.util
.stream
.Collectors
;
26 import javax
.persistence
.EntityNotFoundException
;
28 import org
.apache
.commons
.collections
.CollectionUtils
;
29 import org
.apache
.commons
.lang
.StringUtils
;
30 import org
.apache
.log4j
.Logger
;
31 import org
.springframework
.beans
.factory
.annotation
.Autowired
;
32 import org
.springframework
.stereotype
.Service
;
33 import org
.springframework
.transaction
.annotation
.Transactional
;
35 import eu
.etaxonomy
.cdm
.api
.service
.config
.CreateHierarchyForClassificationConfigurator
;
36 import eu
.etaxonomy
.cdm
.api
.service
.config
.NodeDeletionConfigurator
.ChildHandling
;
37 import eu
.etaxonomy
.cdm
.api
.service
.config
.TaxonDeletionConfigurator
;
38 import eu
.etaxonomy
.cdm
.api
.service
.dto
.EntityDTO
;
39 import eu
.etaxonomy
.cdm
.api
.service
.dto
.GroupedTaxonDTO
;
40 import eu
.etaxonomy
.cdm
.api
.service
.dto
.MarkedEntityDTO
;
41 import eu
.etaxonomy
.cdm
.api
.service
.dto
.TaxonInContextDTO
;
42 import eu
.etaxonomy
.cdm
.api
.service
.pager
.Pager
;
43 import eu
.etaxonomy
.cdm
.api
.service
.pager
.PagerUtils
;
44 import eu
.etaxonomy
.cdm
.api
.service
.pager
.impl
.AbstractPagerImpl
;
45 import eu
.etaxonomy
.cdm
.api
.service
.pager
.impl
.DefaultPagerImpl
;
46 import eu
.etaxonomy
.cdm
.common
.monitor
.IProgressMonitor
;
47 import eu
.etaxonomy
.cdm
.compare
.taxon
.ITaxonNodeComparator
;
48 import eu
.etaxonomy
.cdm
.compare
.taxon
.TaxonNodeSortMode
;
49 import eu
.etaxonomy
.cdm
.exception
.FilterException
;
50 import eu
.etaxonomy
.cdm
.exception
.UnpublishedException
;
51 import eu
.etaxonomy
.cdm
.model
.common
.CdmBase
;
52 import eu
.etaxonomy
.cdm
.model
.common
.ITreeNode
;
53 import eu
.etaxonomy
.cdm
.model
.common
.MarkerType
;
54 import eu
.etaxonomy
.cdm
.model
.common
.TreeIndex
;
55 import eu
.etaxonomy
.cdm
.model
.description
.DescriptionElementBase
;
56 import eu
.etaxonomy
.cdm
.model
.description
.TaxonDescription
;
57 import eu
.etaxonomy
.cdm
.model
.media
.Media
;
58 import eu
.etaxonomy
.cdm
.model
.media
.MediaRepresentation
;
59 import eu
.etaxonomy
.cdm
.model
.media
.MediaUtils
;
60 import eu
.etaxonomy
.cdm
.model
.name
.INonViralName
;
61 import eu
.etaxonomy
.cdm
.model
.name
.Rank
;
62 import eu
.etaxonomy
.cdm
.model
.name
.TaxonName
;
63 import eu
.etaxonomy
.cdm
.model
.taxon
.Classification
;
64 import eu
.etaxonomy
.cdm
.model
.taxon
.ITaxonTreeNode
;
65 import eu
.etaxonomy
.cdm
.model
.taxon
.Synonym
;
66 import eu
.etaxonomy
.cdm
.model
.taxon
.Taxon
;
67 import eu
.etaxonomy
.cdm
.model
.taxon
.TaxonBase
;
68 import eu
.etaxonomy
.cdm
.model
.taxon
.TaxonNode
;
69 import eu
.etaxonomy
.cdm
.model
.term
.DefinedTermBase
;
70 import eu
.etaxonomy
.cdm
.persistence
.dao
.initializer
.IBeanInitializer
;
71 import eu
.etaxonomy
.cdm
.persistence
.dao
.taxon
.IClassificationDao
;
72 import eu
.etaxonomy
.cdm
.persistence
.dao
.taxon
.ITaxonDao
;
73 import eu
.etaxonomy
.cdm
.persistence
.dao
.taxon
.ITaxonNodeDao
;
74 import eu
.etaxonomy
.cdm
.persistence
.dao
.term
.IDefinedTermDao
;
75 import eu
.etaxonomy
.cdm
.persistence
.dto
.ClassificationLookupDTO
;
76 import eu
.etaxonomy
.cdm
.persistence
.dto
.TaxonNodeDto
;
77 import eu
.etaxonomy
.cdm
.persistence
.dto
.TaxonStatus
;
78 import eu
.etaxonomy
.cdm
.persistence
.dto
.UuidAndTitleCache
;
79 import eu
.etaxonomy
.cdm
.persistence
.query
.OrderHint
;
80 import eu
.etaxonomy
.cdm
.strategy
.cache
.common
.IIdentifiableEntityCacheStrategy
;
81 import eu
.etaxonomy
.cdm
.strategy
.parser
.NonViralNameParserImpl
;
88 @Transactional(readOnly
= true)
89 public class ClassificationServiceImpl
90 extends IdentifiableServiceBase
<Classification
, IClassificationDao
>
91 implements IClassificationService
{
93 private static final Logger logger
= Logger
.getLogger(ClassificationServiceImpl
.class);
96 private ITaxonNodeDao taxonNodeDao
;
99 private ITaxonDao taxonDao
;
102 private ITaxonNodeService taxonNodeService
;
105 private IDefinedTermDao termDao
;
108 private IBeanInitializer defaultBeanInitializer
;
112 protected void setDao(IClassificationDao dao
) {
116 private Comparator
<?
super TaxonNode
> taxonNodeComparator
;
119 public void setTaxonNodeComparator(ITaxonNodeComparator
<?
super TaxonNode
> taxonNodeComparator
){
120 this.taxonNodeComparator
= (Comparator
<?
super TaxonNode
>) taxonNodeComparator
;
124 public TaxonNode
loadTaxonNodeByTaxon(Taxon taxon
, UUID classificationUuid
, List
<String
> propertyPaths
){
125 Classification tree
= dao
.load(classificationUuid
);
126 TaxonNode node
= tree
.getNode(taxon
);
128 return loadTaxonNode(node
.getUuid(), propertyPaths
);
131 public TaxonNode
loadTaxonNode(UUID taxonNodeUuid
, List
<String
> propertyPaths
){
132 return taxonNodeDao
.load(taxonNodeUuid
, propertyPaths
);
136 public List
<TaxonNode
> listRankSpecificRootNodes(Classification classification
,
137 TaxonNode subtree
, Rank rank
,
138 boolean includeUnpublished
, Integer pageSize
, Integer pageIndex
, List
<String
> propertyPaths
) {
139 return pageRankSpecificRootNodes(classification
, subtree
, rank
, includeUnpublished
, pageSize
, pageIndex
, propertyPaths
).getRecords();
143 public List
<TaxonNodeDto
> listRankSpecificRootNodeDtos(Classification classification
, TaxonNode subtree
,
144 Rank rank
, boolean includeUnpublished
, Integer pageSize
, Integer pageIndex
, TaxonNodeDtoSortMode sortMode
,
145 List
<String
> propertyPaths
) {
146 List
<TaxonNode
> list
= listRankSpecificRootNodes(classification
, subtree
, rank
, includeUnpublished
, pageSize
, pageIndex
, propertyPaths
);
147 return list
.stream().filter(e
-> e
!= null).map(e
-> new TaxonNodeDto(e
)).sorted(sortMode
.newComparator()).collect(Collectors
.toList());
151 public Pager
<TaxonNode
> pageRankSpecificRootNodes(Classification classification
, Rank rank
,
152 boolean includeUnpublished
, Integer pageSize
, Integer pageIndex
, List
<String
> propertyPaths
) {
153 return pageRankSpecificRootNodes(classification
, null, rank
, includeUnpublished
, pageSize
, pageIndex
, propertyPaths
);
157 public Pager
<TaxonNode
> pageRankSpecificRootNodes(Classification classification
, TaxonNode subtree
, Rank rank
,
158 boolean includeUnpublished
, Integer pageSize
, Integer pageIndex
, List
<String
> propertyPaths
) {
159 long[] numberOfResults
= dao
.countRankSpecificRootNodes(classification
, subtree
, includeUnpublished
, rank
);
160 long totalNumberOfResults
= numberOfResults
[0] + (numberOfResults
.length
> 1 ? numberOfResults
[1] : 0);
162 List
<TaxonNode
> results
= new ArrayList
<>();
164 if (AbstractPagerImpl
.hasResultsInRange(totalNumberOfResults
, pageIndex
, pageSize
)) { // no point checking again
165 Integer limit
= PagerUtils
.limitFor(pageSize
);
166 Integer start
= PagerUtils
.startFor(pageSize
, pageIndex
);
168 Integer remainingLimit
= limit
;
169 int[] queryIndexes
= rank
== null ?
new int[]{0} : new int[]{0,1};
171 for(int queryIndex
: queryIndexes
) {
172 if(start
!= null && start
> numberOfResults
[queryIndex
]) {
173 // start in next query with new start value
174 start
= start
- (int)numberOfResults
[queryIndex
];
178 List
<TaxonNode
> perQueryResults
= dao
.listRankSpecificRootNodes(classification
,
179 subtree
, rank
, includeUnpublished
, remainingLimit
,
180 start
, propertyPaths
, queryIndex
);
181 results
.addAll(perQueryResults
);
182 if(remainingLimit
!= null ){
183 remainingLimit
= remainingLimit
- results
.size();
184 if(remainingLimit
<= 0) {
185 // no need to run further queries if first query returned enough items!
188 // start at with fist item of next query to fetch the remaining items
193 // long start_t = System.currentTimeMillis();
194 Collections
.sort(results
, taxonNodeComparator
); // TODO is ordering during the hibernate query in the dao possible?
195 // System.err.println("service.pageRankSpecificRootNodes() - Collections.sort(results, taxonNodeComparator) " + (System.currentTimeMillis() - start_t));
196 return new DefaultPagerImpl
<>(pageIndex
, totalNumberOfResults
, pageSize
, results
);
201 public List
<TaxonNode
> loadTreeBranch(TaxonNode taxonNode
, Rank baseRank
,
202 boolean includeUnpublished
, List
<String
> propertyPaths
) throws UnpublishedException
{
203 return loadTreeBranch(taxonNode
, null, baseRank
, includeUnpublished
, propertyPaths
);
207 public List
<TaxonNode
> loadTreeBranch(TaxonNode taxonNode
, TaxonNode subtree
, Rank baseRank
,
208 boolean includeUnpublished
, List
<String
> propertyPaths
) throws UnpublishedException
{
210 TaxonNode thisNode
= taxonNodeDao
.load(taxonNode
.getUuid(), propertyPaths
);
211 if(baseRank
!= null){
212 baseRank
= (Rank
) termDao
.load(baseRank
.getUuid());
214 if (!includeUnpublished
&& thisNode
.getTaxon() != null && !thisNode
.getTaxon().isPublish()){
215 throw new UnpublishedException("Final taxon in tree branch is unpublished.");
218 List
<TaxonNode
> pathToRoot
= new ArrayList
<>();
219 pathToRoot
.add(thisNode
);
221 while(!thisNode
.isTopmostNode()){
222 //TODO why do we need to deproxy here?
223 // without this thisNode.getParent() will return NULL in
224 // some cases (environment dependend?) even if the parent exits
225 TaxonNode parentNode
= CdmBase
.deproxy(thisNode
).getParent();
227 if(parentNode
== null){
228 throw new NullPointerException("Taxon node " + thisNode
+ " must have a parent since it is not top most");
230 if(parentNode
.getTaxon() == null){
231 throw new NullPointerException("The taxon associated with taxon node " + parentNode
+ " is NULL");
233 if(!includeUnpublished
&& !parentNode
.getTaxon().isPublish()){
234 throw new UnpublishedException("Some taxon in tree branch is unpublished.");
236 if(parentNode
.getTaxon().getName() == null){
237 throw new NullPointerException("The name of the taxon associated with taxonNode " + parentNode
+ " is NULL");
240 Rank parentNodeRank
= (parentNode
.getTaxon().getName() == null) ?
null : parentNode
.getTaxon().getName().getRank();
241 // stop if the next parent is higher than the baseRank
242 if(baseRank
!= null && parentNodeRank
!= null && baseRank
.isLower(parentNodeRank
)){
245 if((subtree
!= null && !subtree
.isAncestor(parentNode
) )){
249 pathToRoot
.add(parentNode
);
250 thisNode
= parentNode
;
253 // initialize and invert order of nodes in list
254 defaultBeanInitializer
.initializeAll(pathToRoot
, propertyPaths
);
255 Collections
.reverse(pathToRoot
);
261 public List
<TaxonNode
> loadTreeBranchToTaxon(Taxon taxon
, Classification classification
, Rank baseRank
,
262 boolean includeUnpublished
, List
<String
> propertyPaths
) throws UnpublishedException
{
263 return loadTreeBranchToTaxon(taxon
, classification
, null, baseRank
, includeUnpublished
, propertyPaths
);
267 public List
<TaxonNodeDto
> loadTreeBranchDTOsToTaxon(Taxon taxon
, Classification classification
,
268 TaxonNode subtree
, Rank baseRank
,
269 boolean includeUnpublished
, List
<String
> propertyPaths
) throws UnpublishedException
{
270 List
<TaxonNode
> list
= loadTreeBranchToTaxon(taxon
, classification
, subtree
, baseRank
, includeUnpublished
, propertyPaths
);
271 return list
.stream().map(e
-> new TaxonNodeDto(e
)).collect(Collectors
.toList());
275 public List
<TaxonNode
> loadTreeBranchToTaxon(Taxon taxon
, Classification classification
,
276 TaxonNode subtree
, Rank baseRank
,
277 boolean includeUnpublished
, List
<String
> propertyPaths
) throws UnpublishedException
{
279 UUID nodeUuid
= getTaxonNodeUuidByTaxonUuid(classification
.getUuid(), taxon
.getUuid());
280 TaxonNode node
= taxonNodeService
.find(nodeUuid
);
282 logger
.warn("The specified taxon is not found in the given tree.");
284 }else if (subtree
!= null && !node
.isDescendant(subtree
)){
285 //TODO handle as exception? E.g. FilterException, AccessDeniedException?
286 logger
.warn("The specified taxon is not found for the given subtree.");
290 return loadTreeBranch(node
, subtree
, baseRank
, includeUnpublished
, propertyPaths
);
295 public List
<TaxonNode
> loadChildNodesOfTaxonNode(TaxonNode taxonNode
,
296 List
<String
> propertyPaths
) {
297 taxonNode
= taxonNodeDao
.load(taxonNode
.getUuid());
298 List
<TaxonNode
> childNodes
= new ArrayList
<TaxonNode
>(taxonNode
.getChildNodes());
299 defaultBeanInitializer
.initializeAll(childNodes
, propertyPaths
);
300 Collections
.sort(childNodes
, taxonNodeComparator
);
305 public List
<TaxonNode
> listChildNodesOfTaxon(UUID taxonUuid
, UUID classificationUuid
,
306 boolean includeUnpublished
, Integer pageSize
, Integer pageIndex
, List
<String
> propertyPaths
){
308 return listChildNodesOfTaxon(taxonUuid
, classificationUuid
, null, includeUnpublished
, pageSize
, pageIndex
, propertyPaths
);
309 } catch (FilterException e
) {
310 throw new RuntimeException(e
); //this should not happen as filter is null
315 public List
<TaxonNode
> listChildNodesOfTaxon(UUID taxonUuid
, UUID classificationUuid
, UUID subtreeUuid
,
316 boolean includeUnpublished
, Integer pageSize
, Integer pageIndex
, List
<String
> propertyPaths
) throws FilterException
{
318 Classification classification
= dao
.load(classificationUuid
);
319 Taxon taxon
= (Taxon
) taxonDao
.load(taxonUuid
);
320 TaxonNode subtree
= taxonNodeDao
.load(subtreeUuid
);
321 if (subtreeUuid
!= null && subtree
== null){
322 throw new FilterException("Taxon node for subtree filter can not be found in database", true);
325 List
<TaxonNode
> results
= dao
.listChildrenOf(
326 taxon
, classification
, subtree
, includeUnpublished
, pageSize
, pageIndex
, propertyPaths
);
327 Collections
.sort(results
, taxonNodeComparator
); // FIXME this is only a HACK, order during the hibernate query in the dao
332 public List
<TaxonNodeDto
> listChildNodeDtosOfTaxon(UUID taxonUuid
, UUID classificationUuid
, UUID subtreeUuid
, boolean includeUnpublished
,
333 Integer pageSize
, Integer pageIndex
, TaxonNodeDtoSortMode sortMode
, List
<String
> propertyPaths
) throws FilterException
{
334 Classification classification
= dao
.load(classificationUuid
);
335 Taxon taxon
= (Taxon
) taxonDao
.load(taxonUuid
);
336 TaxonNode subtree
= taxonNodeDao
.load(subtreeUuid
);
337 if (subtreeUuid
!= null && subtree
== null){
338 throw new FilterException("Taxon node for subtree filter can not be found in database", true);
341 List
<TaxonNode
> results
= dao
.listChildrenOf(
342 taxon
, classification
, subtree
, includeUnpublished
, pageSize
, pageIndex
, propertyPaths
);
343 Comparator
<TaxonNodeDto
> comparator
= sortMode
.newComparator();
344 // TODO order during the hibernate query in the dao?
345 List
<TaxonNodeDto
> dtos
= results
.stream().map(e
-> new TaxonNodeDto(e
)).sorted(comparator
).collect(Collectors
.toList());
350 public Pager
<TaxonNode
> pageSiblingsOfTaxon(UUID taxonUuid
, UUID classificationUuid
, boolean includeUnpublished
,
351 Integer pageSize
, Integer pageIndex
, List
<String
> propertyPaths
){
353 Classification classification
= dao
.load(classificationUuid
);
354 Taxon taxon
= (Taxon
) taxonDao
.load(taxonUuid
);
356 long numberOfResults
= dao
.countSiblingsOf(taxon
, classification
, includeUnpublished
);
358 List
<TaxonNode
> results
;
359 if(PagerUtils
.hasResultsInRange(numberOfResults
, pageIndex
, pageSize
)) {
360 results
= dao
.listSiblingsOf(taxon
, classification
, includeUnpublished
, pageSize
, pageIndex
, propertyPaths
);
361 Collections
.sort(results
, taxonNodeComparator
); // FIXME this is only a HACK, order during the hibernate query in the dao
363 results
= new ArrayList
<>();
366 return new DefaultPagerImpl
<>(pageIndex
, numberOfResults
, pageSize
, results
);
370 public List
<TaxonNode
> listSiblingsOfTaxon(UUID taxonUuid
, UUID classificationUuid
, boolean includeUnpublished
,
371 Integer pageSize
, Integer pageIndex
, List
<String
> propertyPaths
){
373 Pager
<TaxonNode
> pager
= pageSiblingsOfTaxon(taxonUuid
, classificationUuid
, includeUnpublished
, pageSize
, pageIndex
, propertyPaths
);
374 return pager
.getRecords();
378 public ITaxonTreeNode
getTreeNodeByUuid(UUID uuid
){
379 ITaxonTreeNode treeNode
= taxonNodeDao
.findByUuid(uuid
);
380 if(treeNode
== null){
381 treeNode
= dao
.findByUuid(uuid
);
388 public TaxonNode
getRootNode(UUID classificationUuid
){
389 return dao
.getRootNode(classificationUuid
);
393 public List
<Classification
> listClassifications(Integer limit
, Integer start
, List
<OrderHint
> orderHints
, List
<String
> propertyPaths
) {
394 return dao
.list(limit
, start
, orderHints
, propertyPaths
);
398 public UUID
removeTreeNode(ITaxonTreeNode treeNode
) {
399 if(treeNode
instanceof Classification
){
400 return dao
.delete((Classification
) treeNode
);
401 }else if(treeNode
instanceof TaxonNode
){
402 return taxonNodeDao
.delete((TaxonNode
)treeNode
);
408 public Map
<UUID
, TaxonNode
> saveTaxonNodeAll(
409 Collection
<TaxonNode
> taxonNodeCollection
) {
410 return taxonNodeDao
.saveAll(taxonNodeCollection
);
414 public UUID
saveClassification(Classification classification
) {
416 taxonNodeDao
.saveOrUpdateAll(classification
.getAllNodes());
417 UUID result
=dao
.saveOrUpdate(classification
);
422 public UUID
saveTreeNode(ITaxonTreeNode treeNode
) {
423 if(treeNode
instanceof Classification
){
424 return dao
.save((Classification
) treeNode
).getUuid();
425 }else if(treeNode
instanceof TaxonNode
){
426 return taxonNodeDao
.save((TaxonNode
)treeNode
).getUuid();
432 public List
<TaxonNode
> getAllNodes(){
433 return taxonNodeDao
.list(null,null);
437 public List
<UuidAndTitleCache
<TaxonNode
>> getTaxonNodeUuidAndTitleCacheOfAcceptedTaxaByClassification(UUID classificationUuid
, Integer limit
, String pattern
, boolean searchForClassifications
, boolean includeDoubtful
) {
438 return taxonNodeDao
.getTaxonNodeUuidAndTitleCacheOfAcceptedTaxaByClassification(dao
.load(classificationUuid
), limit
, pattern
, searchForClassifications
, includeDoubtful
);
442 public List
<UuidAndTitleCache
<TaxonNode
>> getTaxonNodeUuidAndTitleCacheOfAcceptedTaxaByClassification(Classification classification
, Integer limit
, String pattern
, boolean searchForClassifications
) {
443 return taxonNodeDao
.getTaxonNodeUuidAndTitleCacheOfAcceptedTaxaByClassification(classification
, limit
, pattern
, searchForClassifications
);
447 public List
<UuidAndTitleCache
<TaxonNode
>> getTaxonNodeUuidAndTitleCacheOfAcceptedTaxaByClassification(UUID classificationUuid
, boolean searchForClassifications
) {
448 return taxonNodeDao
.getTaxonNodeUuidAndTitleCacheOfAcceptedTaxaByClassification(dao
.load(classificationUuid
), null, null, searchForClassifications
);
452 public List
<UuidAndTitleCache
<TaxonNode
>> getTaxonNodeUuidAndTitleCacheOfAcceptedTaxaByClassification(Classification classification
, boolean searchForClassifications
) {
453 return taxonNodeDao
.getTaxonNodeUuidAndTitleCacheOfAcceptedTaxaByClassification(classification
, null, null, searchForClassifications
);
457 public List
<UuidAndTitleCache
<Classification
>> getUuidAndTitleCache(Integer limit
, String pattern
) {
458 return dao
.getUuidAndTitleCache(limit
, pattern
);
462 public Map
<UUID
, List
<MediaRepresentation
>> getAllMediaForChildNodes(
463 TaxonNode taxonNode
, List
<String
> propertyPaths
, int size
,
464 int height
, int widthOrDuration
, String
[] mimeTypes
) {
466 TreeMap
<UUID
, List
<MediaRepresentation
>> result
= new TreeMap
<>();
467 List
<MediaRepresentation
> mediaRepresentations
= new ArrayList
<>();
469 //add all media of the children to the result map
470 if (taxonNode
!= null){
472 List
<TaxonNode
> nodes
= new ArrayList
<>();
474 nodes
.add(loadTaxonNode(taxonNode
.getUuid(), propertyPaths
));
475 nodes
.addAll(loadChildNodesOfTaxonNode(taxonNode
, propertyPaths
));
477 for(TaxonNode node
: nodes
){
478 Taxon taxon
= node
.getTaxon();
479 for (TaxonDescription taxonDescription
: taxon
.getDescriptions()){
480 for (DescriptionElementBase descriptionElement
: taxonDescription
.getElements()){
481 for(Media media
: descriptionElement
.getMedia()){
482 //find the best matching representation
483 mediaRepresentations
.add(MediaUtils
.findBestMatchingRepresentation(media
,null, size
, height
, widthOrDuration
, mimeTypes
, MediaUtils
.MissingValueStrategy
.MAX
));
487 result
.put(taxon
.getUuid(), mediaRepresentations
);
495 @Transactional(readOnly
= false)
496 public UpdateResult
updateCaches(Class
<?
extends Classification
> clazz
, Integer stepSize
, IIdentifiableEntityCacheStrategy
<Classification
> cacheStrategy
, IProgressMonitor monitor
) {
498 clazz
= Classification
.class;
500 return super.updateCachesImpl(clazz
, stepSize
, cacheStrategy
, monitor
);
505 * @param allNodesOfClassification
506 * @return null - if allNodesOfClassification is empty <br>
509 private Map
<String
, List
<TaxonNode
>> getSortedGenusList(Collection
<TaxonNode
> allNodesOfClassification
){
511 if(allNodesOfClassification
== null || allNodesOfClassification
.isEmpty()){
514 Map
<String
, List
<TaxonNode
>> sortedGenusMap
= new HashMap
<>();
515 for(TaxonNode node
:allNodesOfClassification
){
516 Taxon taxon
= node
.getTaxon();
517 INonViralName name
= taxon
.getName();
518 String genusOrUninomial
= name
.getGenusOrUninomial();
519 //if rank unknown split string and take first word
520 if(genusOrUninomial
== null){
521 String titleCache
= taxon
.getTitleCache();
522 String
[] split
= titleCache
.split("\\s+");
524 genusOrUninomial
= s
;
528 //if node has children
530 //retrieve list from map if not create List
531 if(sortedGenusMap
.containsKey(genusOrUninomial
)){
532 List
<TaxonNode
> list
= sortedGenusMap
.get(genusOrUninomial
);
534 sortedGenusMap
.put(genusOrUninomial
, list
);
536 //create List for genus
537 List
<TaxonNode
> list
= new ArrayList
<>();
539 sortedGenusMap
.put(genusOrUninomial
, list
);
542 return sortedGenusMap
;
547 * creates new Classification and parent TaxonNodes at genus level
550 * @param map GenusMap which holds a name (Genus) and all the same Taxa as a list
551 * @param classification you want to improve the hierarchy (will not be modified)
552 * @param configurator to change certain settings, if null then standard settings will be taken
553 * @return new classification with parentNodes for each entry in the map
555 @SuppressWarnings({ "unchecked" })
556 @Transactional(readOnly
= false)
558 public UpdateResult
createHierarchyInClassification(Classification classification
, CreateHierarchyForClassificationConfigurator configurator
){
559 UpdateResult result
= new UpdateResult();
560 classification
= dao
.findByUuid(classification
.getUuid());
561 Map
<String
, List
<TaxonNode
>> map
= getSortedGenusList(classification
.getAllNodes());
563 final String APPENDIX
= "repaired";
564 String titleCache
= StringUtils
.isBlank(classification
.getTitleCache()) ?
" " : classification
.getTitleCache() ;
565 //TODO classification clone???
566 Classification newClassification
= Classification
.NewInstance(titleCache
+" "+ APPENDIX
);
567 newClassification
.setReference(classification
.getReference());
569 for(Map
.Entry
<String
, List
<TaxonNode
>> entry
:map
.entrySet()){
570 String genus
= entry
.getKey();
571 List
<TaxonNode
> listOfTaxonNodes
= entry
.getValue();
572 TaxonNode parentNode
= null;
573 //Search for genus in list
574 for(TaxonNode tNode
:listOfTaxonNodes
){
575 //take that taxonNode as parent and remove from list with all it possible children
577 TaxonName name
= tNode
.getTaxon().getName();
578 if(name
.getNameCache().equalsIgnoreCase(genus
)){
579 TaxonNode clone
= tNode
.clone();
580 if(!tNode
.hasChildNodes()){
581 //FIXME remove classification
582 // parentNode = newClassification.addChildNode(clone, 0, classification.getCitation(), classification.getMicroReference());
583 parentNode
= newClassification
.addChildNode(clone
, 0, clone
.getReference(), clone
.getMicroReference());
584 //remove taxonNode from list because just added to classification
585 result
.addUpdatedObject(tNode
);
586 listOfTaxonNodes
.remove(tNode
);
589 //save prior Hierarchy and remove them from the list
590 List
<TaxonNode
> copyAllChildrenToTaxonNode
= copyAllChildrenToTaxonNode(tNode
, clone
, result
);
591 // parentNode = newClassification.addChildNode(clone, 0, classification.getCitation(), classification.getMicroReference());
592 //FIXME remove classification
593 parentNode
= newClassification
.addChildNode(clone
, 0, clone
.getReference(), clone
.getMicroReference());
594 //remove taxonNode from list because just added to classification
595 result
.addUpdatedObject(tNode
);
596 listOfTaxonNodes
.remove(tNode
);
597 if(copyAllChildrenToTaxonNode
!= null){
598 listOfTaxonNodes
= (List
<TaxonNode
>) CollectionUtils
.removeAll(listOfTaxonNodes
, copyAllChildrenToTaxonNode
);
604 if(parentNode
== null){
605 //if no match found in list, create parentNode
606 NonViralNameParserImpl parser
= NonViralNameParserImpl
.NewInstance();
607 TaxonName TaxonName
= (TaxonName
)parser
.parseFullName(genus
);
608 //TODO Sec via configurator
609 Taxon taxon
= Taxon
.NewInstance(TaxonName
, null);
610 parentNode
= newClassification
.addChildTaxon(taxon
, 0, null, null);
611 result
.addUpdatedObject(parentNode
);
613 //iterate over the rest of the list
614 for(TaxonNode tn
: listOfTaxonNodes
){
615 //if TaxonNode has a parent and this is not the classification then skip it
616 //and add to new classification via the parentNode as children of it
617 //this should assures to keep the already existing hierarchy
618 //FIXME: Assert is not rootnode --> entrypoint is not classification in future but rather rootNode
620 if(!tn
.isTopmostNode()){
621 continue; //skip to next taxonNode
624 TaxonNode clone
= tn
.clone();
625 //FIXME: citation from node
626 //TODO: addchildNode without citation and references
627 // TaxonNode taxonNode = parentNode.addChildNode(clone, classification.getCitation(), classification.getMicroReference());
628 TaxonNode taxonNode
= parentNode
.addChildNode(clone
, clone
.getReference(), clone
.getMicroReference());
629 result
.addUnChangedObject(clone
);
630 if(tn
.hasChildNodes()){
631 //save hierarchy in new classification
632 List
<TaxonNode
> copyAllChildrenToTaxonNode
= copyAllChildrenToTaxonNode(tn
, taxonNode
, result
);
633 if(copyAllChildrenToTaxonNode
!= null){
634 listOfTaxonNodes
= (List
<TaxonNode
>) CollectionUtils
.removeAll(listOfTaxonNodes
, copyAllChildrenToTaxonNode
);
639 dao
.saveOrUpdate(newClassification
);
640 result
.setCdmEntity(newClassification
);
646 * recursive method to get all childnodes of taxonNode in classification.
648 * @param classification just for References and Citation, can be null
649 * @param copyFromNode TaxonNode with Children
650 * @param copyToNode TaxonNode which will receive the children
651 * @return List of ChildNode which has been added. If node has no children returns null
653 private List
<TaxonNode
> copyAllChildrenToTaxonNode(TaxonNode copyFromNode
, TaxonNode copyToNode
, UpdateResult result
) {
654 List
<TaxonNode
> childNodes
;
655 if(!copyFromNode
.hasChildNodes()){
658 childNodes
= copyFromNode
.getChildNodes();
660 for(TaxonNode childNode
:childNodes
){
661 TaxonNode clone
= childNode
.clone();
662 result
.addUnChangedObject(clone
);
663 if(childNode
.hasChildNodes()){
664 copyAllChildrenToTaxonNode(childNode
, clone
, result
);
666 //FIXME: citation from node instead of classification
667 // copyToNode.addChildNode(clone,classification.getCitation(), classification.getMicroReference());
668 copyToNode
.addChildNode(clone
, clone
.getReference(), clone
.getMicroReference());
674 public ClassificationLookupDTO
classificationLookup(Classification classification
) {
675 return dao
.classificationLookup(classification
);
680 public DeleteResult
delete(UUID classificationUuid
, TaxonDeletionConfigurator config
){
681 DeleteResult result
= new DeleteResult();
682 Classification classification
= dao
.findByUuid(classificationUuid
);
683 if (classification
== null){
684 result
.addException(new IllegalArgumentException("The classification does not exist in database."));
688 if (!classification
.hasChildNodes()){
689 dao
.delete(classification
);
690 result
.addDeletedObject(classification
);
693 if (config
.getTaxonNodeConfig().getChildHandling().equals(ChildHandling
.DELETE
)){
694 // TaxonNode root = classification.getRootNode();
695 // result.includeResult(taxonNodeService.deleteTaxonNode(HibernateProxyHelper.deproxy(root), config));
696 // result.addDeletedObject(classification);
697 dao
.delete(classification
);
698 result
.addDeletedObject(classification
);
707 public List
<GroupedTaxonDTO
> groupTaxaByHigherTaxon(List
<UUID
> originalTaxonUuids
, UUID classificationUuid
, Rank minRank
, Rank maxRank
){
708 List
<GroupedTaxonDTO
> result
= new ArrayList
<>();
710 //get treeindex for each taxonUUID
711 Map
<UUID
, TreeIndex
> taxonIdTreeIndexMap
= dao
.treeIndexForTaxonUuids(classificationUuid
, originalTaxonUuids
);
713 //build treeindex list (or tree)
714 //TODO make it work with TreeIndex or move there
715 List
<String
> treeIndexClosureStr
= new ArrayList
<>();
716 for (TreeIndex treeIndex
: taxonIdTreeIndexMap
.values()){
717 String
[] splits
= treeIndex
.toString().substring(1).split(ITreeNode
.separator
);
718 String currentIndex
= ITreeNode
.separator
;
719 for (String split
: splits
){
720 if (split
.equals("")){
723 currentIndex
+= split
+ ITreeNode
.separator
;
724 if (!treeIndexClosureStr
.contains(currentIndex
) && !split
.startsWith(ITreeNode
.treePrefix
)){
725 treeIndexClosureStr
.add(currentIndex
);
730 //get rank sortindex for all parent taxa with sortindex <= minRank and sortIndex >= maxRank (if available)
731 Integer minRankOrderIndex
= minRank
== null ?
null : minRank
.getOrderIndex();
732 Integer maxRankOrderIndex
= maxRank
== null ?
null : maxRank
.getOrderIndex();
733 List
<TreeIndex
> treeIndexClosure
= TreeIndex
.NewListInstance(treeIndexClosureStr
);
735 Map
<TreeIndex
, Integer
> treeIndexSortIndexMapTmp
= taxonNodeDao
.rankOrderIndexForTreeIndex(treeIndexClosure
, minRankOrderIndex
, maxRankOrderIndex
);
737 //remove all treeindex with "exists child in above map(and child.sortindex > xxx)
738 List
<TreeIndex
> treeIndexList
= TreeIndex
.sort(treeIndexSortIndexMapTmp
.keySet());
740 Map
<TreeIndex
, Integer
> treeIndexSortIndexMap
= new HashMap
<>();
741 TreeIndex lastTreeIndex
= null;
742 for (TreeIndex treeIndex
: treeIndexList
){
743 if (lastTreeIndex
!= null && lastTreeIndex
.hasChild(treeIndex
)){
744 treeIndexSortIndexMap
.remove(lastTreeIndex
);
746 treeIndexSortIndexMap
.put(treeIndex
, treeIndexSortIndexMapTmp
.get(treeIndex
));
747 lastTreeIndex
= treeIndex
;
750 //get taxonID for treeIndexes
751 Map
<TreeIndex
, UuidAndTitleCache
<?
>> treeIndexTaxonIdMap
= taxonNodeDao
.taxonUuidsForTreeIndexes(treeIndexSortIndexMap
.keySet());
754 for (UUID originalTaxonUuid
: originalTaxonUuids
){
755 GroupedTaxonDTO item
= new GroupedTaxonDTO();
757 item
.setTaxonUuid(originalTaxonUuid
);
758 TreeIndex groupTreeIndex
= taxonIdTreeIndexMap
.get(originalTaxonUuid
);
759 String groupIndexX
= TreeIndex
.toString(groupTreeIndex
);
760 while (groupTreeIndex
!= null){
761 if (treeIndexTaxonIdMap
.get(groupTreeIndex
) != null){
762 UuidAndTitleCache
<?
> uuidAndLabel
= treeIndexTaxonIdMap
.get(groupTreeIndex
);
763 item
.setGroupTaxonUuid(uuidAndLabel
.getUuid());
764 item
.setGroupTaxonName(uuidAndLabel
.getTitleCache());
767 groupTreeIndex
= groupTreeIndex
.parent();
768 // int index = groupIndex.substring(0, groupIndex.length()-1).lastIndexOf(ITreeNode.separator);
769 // groupIndex = index < 0 ? null : groupIndex.substring(0, index+1);
778 public List
<GroupedTaxonDTO
> groupTaxaByMarkedParents(List
<UUID
> originalTaxonUuids
, UUID classificationUuid
,
779 MarkerType markerType
, Boolean flag
) {
781 List
<GroupedTaxonDTO
> result
= new ArrayList
<>();
783 //get treeindex for each taxonUUID
784 Map
<UUID
, TreeIndex
> taxonIdTreeIndexMap
= dao
.treeIndexForTaxonUuids(classificationUuid
, originalTaxonUuids
);
786 //get all marked tree indexes
787 Set
<TreeIndex
> markedTreeIndexes
= dao
.getMarkedTreeIndexes(markerType
, flag
);
789 Map
<TreeIndex
, TreeIndex
> groupedMap
= TreeIndex
.group(markedTreeIndexes
, taxonIdTreeIndexMap
.values());
790 Set
<TreeIndex
> notNullGroups
= new HashSet
<>(groupedMap
.values());
791 notNullGroups
.remove(null);
793 //get taxonInfo for treeIndexes
794 Map
<TreeIndex
, UuidAndTitleCache
<?
>> treeIndexTaxonIdMap
= taxonNodeDao
.taxonUuidsForTreeIndexes(notNullGroups
);
797 for (UUID originalTaxonUuid
: originalTaxonUuids
){
798 GroupedTaxonDTO item
= new GroupedTaxonDTO();
800 item
.setTaxonUuid(originalTaxonUuid
);
802 TreeIndex toBeGroupedTreeIndex
= taxonIdTreeIndexMap
.get(originalTaxonUuid
);
803 TreeIndex groupTreeIndex
= groupedMap
.get(toBeGroupedTreeIndex
);
804 UuidAndTitleCache
<?
> uuidAndLabel
= treeIndexTaxonIdMap
.get(groupTreeIndex
);
805 if (uuidAndLabel
!= null){
806 item
.setGroupTaxonUuid(uuidAndLabel
.getUuid());
807 item
.setGroupTaxonName(uuidAndLabel
.getTitleCache());
815 public UUID
getTaxonNodeUuidByTaxonUuid(UUID classificationUuid
, UUID taxonUuid
) {
816 Map
<UUID
, UUID
> map
= dao
.getTaxonNodeUuidByTaxonUuid(classificationUuid
, Arrays
.asList(taxonUuid
));
817 UUID taxonNodeUuid
= map
.get(taxonUuid
);
818 return taxonNodeUuid
;
822 public TaxonInContextDTO
getTaxonInContext(UUID classificationUuid
, UUID taxonBaseUuid
,
823 Boolean doChildren
, Boolean doSynonyms
, boolean includeUnpublished
, List
<UUID
> ancestorMarkers
,
824 TaxonNodeSortMode sortMode
) {
826 TaxonInContextDTO result
= new TaxonInContextDTO();
828 TaxonBase
<?
> taxonBase
= taxonDao
.load(taxonBaseUuid
);
829 if (taxonBase
== null){
830 throw new EntityNotFoundException("Taxon with uuid " + taxonBaseUuid
+ " not found in datasource");
832 boolean isSynonym
= false;
834 if (taxonBase
.isInstanceOf(Synonym
.class)){
836 Synonym synonym
= CdmBase
.deproxy(taxonBase
, Synonym
.class);
837 acceptedTaxon
= synonym
.getAcceptedTaxon();
838 if (acceptedTaxon
== null) {
839 throw new EntityNotFoundException("Accepted taxon not found for synonym" );
841 TaxonStatus taxonStatus
= TaxonStatus
.Synonym
;
842 if (synonym
.getName()!= null && acceptedTaxon
.getName() != null
843 && synonym
.getName().getHomotypicalGroup().equals(acceptedTaxon
.getName().getHomotypicalGroup())){
844 taxonStatus
= TaxonStatus
.SynonymObjective
;
846 result
.setTaxonStatus(taxonStatus
);
849 acceptedTaxon
= CdmBase
.deproxy(taxonBase
, Taxon
.class);
850 result
.setTaxonStatus(TaxonStatus
.Accepted
);
852 UUID acceptedTaxonUuid
= acceptedTaxon
.getUuid();
854 UUID taxonNodeUuid
= getTaxonNodeUuidByTaxonUuid(classificationUuid
, acceptedTaxonUuid
);
855 if (taxonNodeUuid
== null) {
856 throw new EntityNotFoundException("Taxon not found in classficiation with uuid " + classificationUuid
+ ". Either classification does not exist or does not contain taxon/synonym with uuid " + taxonBaseUuid
);
858 result
.setTaxonNodeUuid(taxonNodeUuid
);
860 //TODO make it a dao call
861 Taxon parentTaxon
= getParentTaxon(classificationUuid
, acceptedTaxon
);
862 if (parentTaxon
!= null){
863 result
.setParentTaxonUuid(parentTaxon
.getUuid());
864 result
.setParentTaxonLabel(parentTaxon
.getTitleCache());
865 if (parentTaxon
.getName() != null){
866 result
.setParentNameLabel(parentTaxon
.getName().getTitleCache());
870 result
.setTaxonUuid(taxonBaseUuid
);
871 result
.setClassificationUuid(classificationUuid
);
872 if (taxonBase
.getSec() != null){
873 result
.setSecundumUuid(taxonBase
.getSec().getUuid());
874 result
.setSecundumLabel(taxonBase
.getSec().getTitleCache());
876 result
.setTaxonLabel(taxonBase
.getTitleCache());
878 TaxonName name
= taxonBase
.getName();
879 result
.setNameUuid(name
.getUuid());
880 result
.setNameLabel(name
.getTitleCache());
881 result
.setNameWithoutAuthor(name
.getNameCache());
882 result
.setGenusOrUninomial(name
.getGenusOrUninomial());
883 result
.setInfraGenericEpithet(name
.getInfraGenericEpithet());
884 result
.setSpeciesEpithet(name
.getSpecificEpithet());
885 result
.setInfraSpecificEpithet(name
.getInfraSpecificEpithet());
887 result
.setAuthorship(name
.getAuthorshipCache());
889 Rank rank
= name
.getRank();
891 result
.setRankUuid(rank
.getUuid());
892 String rankLabel
= rank
.getAbbreviation();
893 if (StringUtils
.isBlank(rankLabel
)){
894 rankLabel
= rank
.getLabel();
896 result
.setRankLabel(rankLabel
);
899 boolean recursive
= false;
900 Integer pageSize
= null;
901 Integer pageIndex
= null;
902 Pager
<TaxonNodeDto
> children
= taxonNodeService
.pageChildNodesDTOs(taxonNodeUuid
, recursive
, includeUnpublished
, doSynonyms
,
903 sortMode
, pageSize
, pageIndex
);
907 for (TaxonNodeDto childDto
: children
.getRecords()){
908 if (doChildren
&& childDto
.getTaxonStatus().equals(TaxonStatus
.Accepted
)){
909 EntityDTO
<Taxon
> child
= new EntityDTO
<Taxon
>(childDto
.getTaxonUuid(), childDto
.getTitleCache());
910 result
.addChild(child
);
911 }else if (doSynonyms
&& childDto
.getTaxonStatus().isSynonym()){
912 EntityDTO
<Synonym
> child
= new EntityDTO
<>(childDto
.getTaxonUuid(), childDto
.getTitleCache());
913 result
.addSynonym(child
);
917 result
.setAcceptedTaxonUuid(acceptedTaxonUuid
);
918 String nameTitel
= acceptedTaxon
.getName() == null ?
null : acceptedTaxon
.getName().getTitleCache();
919 result
.setAcceptedTaxonLabel(acceptedTaxon
.getTitleCache());
920 result
.setAcceptedNameLabel(nameTitel
);
924 if (ancestorMarkers
!= null && !ancestorMarkers
.isEmpty()){
925 @SuppressWarnings("rawtypes")
926 List
<DefinedTermBase
> markerTypesTerms
= termDao
.list(ancestorMarkers
, pageSize
, null, null, null);
927 List
<MarkerType
> markerTypes
= new ArrayList
<>();
928 for (DefinedTermBase
<?
> term
: markerTypesTerms
){
929 if (term
.isInstanceOf(MarkerType
.class)){
930 markerTypes
.add(CdmBase
.deproxy(term
, MarkerType
.class));
933 if (! markerTypes
.isEmpty()){
934 TaxonNode node
= taxonNodeDao
.findByUuid(taxonNodeUuid
);
935 handleAncestorsForMarkersRecursive(result
, markerTypes
, node
);
942 private Taxon
getParentTaxon(UUID classificationUuid
, Taxon acceptedTaxon
) {
943 if (classificationUuid
== null){
946 TaxonNode parent
= null;
947 for (TaxonNode node
: acceptedTaxon
.getTaxonNodes()){
948 if (classificationUuid
.equals(node
.getClassification().getUuid())){
949 parent
= node
.getParent();
953 return parent
.getTaxon();
958 private void handleAncestorsForMarkersRecursive(TaxonInContextDTO result
, List
<MarkerType
> markerTypes
, TaxonNode node
) {
959 for (MarkerType type
: markerTypes
){
960 Taxon taxon
= node
.getTaxon();
961 if (taxon
!= null && taxon
.hasMarker(type
, true)){
962 String label
= taxon
.getName() == null? taxon
.getTitleCache() : taxon
.getName().getTitleCache();
963 MarkedEntityDTO
<Taxon
> dto
= new MarkedEntityDTO
<>(type
, true, taxon
.getUuid(), label
);
964 result
.addMarkedAncestor(dto
);
967 TaxonNode parentNode
= node
.getParent();
968 if (parentNode
!= null){
969 handleAncestorsForMarkersRecursive(result
, markerTypes
, parentNode
);
974 public List
<UuidAndTitleCache
<TaxonNode
>> getTaxonNodeUuidAndTitleCacheOfAcceptedTaxaByClassification(
975 Classification classification
) {
976 return getTaxonNodeUuidAndTitleCacheOfAcceptedTaxaByClassification(classification
, false);
980 public List
<UuidAndTitleCache
<TaxonNode
>> getTaxonNodeUuidAndTitleCacheOfAcceptedTaxaByClassification(
981 UUID classificationUuid
) {
982 return getTaxonNodeUuidAndTitleCacheOfAcceptedTaxaByClassification(classificationUuid
, false);
986 public List
<UuidAndTitleCache
<TaxonNode
>> getTaxonNodeUuidAndTitleCacheOfAcceptedTaxaByClassification(
987 UUID classificationUuid
, Integer limit
, String pattern
) {
988 return getTaxonNodeUuidAndTitleCacheOfAcceptedTaxaByClassification(classificationUuid
, limit
, pattern
, false);
992 public List
<UuidAndTitleCache
<TaxonNode
>> getTaxonNodeUuidAndTitleCacheOfAcceptedTaxaByClassification(
993 Classification classification
, Integer limit
, String pattern
) {
994 return getTaxonNodeUuidAndTitleCacheOfAcceptedTaxaByClassification(classification
, limit
, pattern
, false);
998 public List
<UuidAndTitleCache
<TaxonNode
>> getTaxonNodeUuidAndTitleCacheOfAcceptedTaxaByClassification(
999 UUID classificationUuid
, Integer limit
, String pattern
, boolean searchForClassifications
) {
1000 return getTaxonNodeUuidAndTitleCacheOfAcceptedTaxaByClassification(
1001 classificationUuid
, limit
, pattern
, searchForClassifications
, false);