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
;
25 import javax
.persistence
.EntityNotFoundException
;
27 import org
.apache
.commons
.collections
.CollectionUtils
;
28 import org
.apache
.commons
.lang
.StringUtils
;
29 import org
.apache
.log4j
.Logger
;
30 import org
.springframework
.beans
.factory
.annotation
.Autowired
;
31 import org
.springframework
.stereotype
.Service
;
32 import org
.springframework
.transaction
.annotation
.Transactional
;
34 import eu
.etaxonomy
.cdm
.api
.service
.config
.CreateHierarchyForClassificationConfigurator
;
35 import eu
.etaxonomy
.cdm
.api
.service
.config
.NodeDeletionConfigurator
.ChildHandling
;
36 import eu
.etaxonomy
.cdm
.api
.service
.config
.TaxonDeletionConfigurator
;
37 import eu
.etaxonomy
.cdm
.api
.service
.dto
.EntityDTO
;
38 import eu
.etaxonomy
.cdm
.api
.service
.dto
.GroupedTaxonDTO
;
39 import eu
.etaxonomy
.cdm
.api
.service
.dto
.MarkedEntityDTO
;
40 import eu
.etaxonomy
.cdm
.api
.service
.dto
.TaxonInContextDTO
;
41 import eu
.etaxonomy
.cdm
.api
.service
.pager
.Pager
;
42 import eu
.etaxonomy
.cdm
.api
.service
.pager
.PagerUtils
;
43 import eu
.etaxonomy
.cdm
.api
.service
.pager
.impl
.AbstractPagerImpl
;
44 import eu
.etaxonomy
.cdm
.api
.service
.pager
.impl
.DefaultPagerImpl
;
45 import eu
.etaxonomy
.cdm
.common
.monitor
.IProgressMonitor
;
46 import eu
.etaxonomy
.cdm
.exception
.FilterException
;
47 import eu
.etaxonomy
.cdm
.exception
.UnpublishedException
;
48 import eu
.etaxonomy
.cdm
.hibernate
.HHH_9751_Util
;
49 import eu
.etaxonomy
.cdm
.hibernate
.HibernateProxyHelper
;
50 import eu
.etaxonomy
.cdm
.model
.common
.CdmBase
;
51 import eu
.etaxonomy
.cdm
.model
.common
.DefinedTermBase
;
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
.reference
.Reference
;
64 import eu
.etaxonomy
.cdm
.model
.taxon
.Classification
;
65 import eu
.etaxonomy
.cdm
.model
.taxon
.ITaxonNodeComparator
;
66 import eu
.etaxonomy
.cdm
.model
.taxon
.ITaxonTreeNode
;
67 import eu
.etaxonomy
.cdm
.model
.taxon
.Synonym
;
68 import eu
.etaxonomy
.cdm
.model
.taxon
.Taxon
;
69 import eu
.etaxonomy
.cdm
.model
.taxon
.TaxonBase
;
70 import eu
.etaxonomy
.cdm
.model
.taxon
.TaxonNode
;
71 import eu
.etaxonomy
.cdm
.model
.taxon
.TaxonRelationshipType
;
72 import eu
.etaxonomy
.cdm
.persistence
.dao
.common
.IDefinedTermDao
;
73 import eu
.etaxonomy
.cdm
.persistence
.dao
.initializer
.IBeanInitializer
;
74 import eu
.etaxonomy
.cdm
.persistence
.dao
.taxon
.IClassificationDao
;
75 import eu
.etaxonomy
.cdm
.persistence
.dao
.taxon
.ITaxonDao
;
76 import eu
.etaxonomy
.cdm
.persistence
.dao
.taxon
.ITaxonNodeDao
;
77 import eu
.etaxonomy
.cdm
.persistence
.dto
.ClassificationLookupDTO
;
78 import eu
.etaxonomy
.cdm
.persistence
.dto
.TaxonNodeDto
;
79 import eu
.etaxonomy
.cdm
.persistence
.dto
.TaxonStatus
;
80 import eu
.etaxonomy
.cdm
.persistence
.dto
.UuidAndTitleCache
;
81 import eu
.etaxonomy
.cdm
.persistence
.query
.OrderHint
;
82 import eu
.etaxonomy
.cdm
.strategy
.cache
.common
.IIdentifiableEntityCacheStrategy
;
83 import eu
.etaxonomy
.cdm
.strategy
.parser
.NonViralNameParserImpl
;
90 @Transactional(readOnly
= true)
91 public class ClassificationServiceImpl
92 extends IdentifiableServiceBase
<Classification
, IClassificationDao
>
93 implements IClassificationService
{
94 private static final Logger logger
= Logger
.getLogger(ClassificationServiceImpl
.class);
97 private ITaxonNodeDao taxonNodeDao
;
100 private ITaxonDao taxonDao
;
103 private ITaxonNodeService taxonNodeService
;
106 private IDefinedTermDao termDao
;
109 private IBeanInitializer defaultBeanInitializer
;
113 protected void setDao(IClassificationDao dao
) {
117 private Comparator
<?
super TaxonNode
> taxonNodeComparator
;
120 public void setTaxonNodeComparator(ITaxonNodeComparator
<?
super TaxonNode
> taxonNodeComparator
){
121 this.taxonNodeComparator
= (Comparator
<?
super TaxonNode
>) taxonNodeComparator
;
125 public TaxonNode
loadTaxonNodeByTaxon(Taxon taxon
, UUID classificationUuid
, List
<String
> propertyPaths
){
126 Classification tree
= dao
.load(classificationUuid
);
127 TaxonNode node
= tree
.getNode(taxon
);
129 return loadTaxonNode(node
.getUuid(), propertyPaths
);
132 public TaxonNode
loadTaxonNode(UUID taxonNodeUuid
, List
<String
> propertyPaths
){
133 return taxonNodeDao
.load(taxonNodeUuid
, propertyPaths
);
137 @Transactional(readOnly
= false)
138 public UpdateResult
cloneClassification(UUID classificationUuid
,
139 String name
, Reference sec
, TaxonRelationshipType relationshipType
) {
140 UpdateResult result
= new UpdateResult();
141 Classification classification
= load(classificationUuid
);
142 Classification clone
= Classification
.NewInstance(name
);
143 clone
.setReference(sec
);
145 //clone taxa and taxon nodes
146 List
<TaxonNode
> childNodes
= classification
.getRootNode().getChildNodes();
147 for (TaxonNode taxonNode
: childNodes
) {
148 addChildTaxa(taxonNode
, null, clone
, relationshipType
);
150 dao
.saveOrUpdate(clone
);
151 result
.setCdmEntity(clone
);
155 private void addChildTaxa(TaxonNode originalParentNode
, TaxonNode cloneParentNode
, Classification classification
, TaxonRelationshipType relationshipType
){
156 Reference reference
= classification
.getReference();
157 Taxon cloneTaxon
= (Taxon
) HibernateProxyHelper
.deproxy(originalParentNode
.getTaxon(), Taxon
.class).clone();
158 cloneTaxon
.setSec(reference
);
159 String microReference
= null;
160 List
<TaxonNode
> originalChildNodes
= originalParentNode
.getChildNodes();
161 HHH_9751_Util
.removeAllNull(originalChildNodes
);
163 //add relation between taxa
164 if (relationshipType
!= null){
165 cloneTaxon
.addTaxonRelation(originalParentNode
.getTaxon(), relationshipType
, reference
, microReference
);
168 TaxonNode cloneChildNode
= null;
169 //add taxon node to either parent node or classification (no parent node)
170 if(cloneParentNode
==null){
171 cloneChildNode
= classification
.addChildTaxon(cloneTaxon
, reference
, microReference
);
174 cloneChildNode
= cloneParentNode
.addChildTaxon(cloneTaxon
, reference
, microReference
);
176 taxonNodeDao
.saveOrUpdate(cloneChildNode
);
178 for (TaxonNode originalChildNode
: originalChildNodes
) {
179 addChildTaxa(originalChildNode
, cloneChildNode
, classification
, relationshipType
);
184 public List
<TaxonNode
> listRankSpecificRootNodes(Classification classification
, Rank rank
,
185 boolean includeUnpublished
, Integer pageSize
, Integer pageIndex
, List
<String
> propertyPaths
) {
186 return listRankSpecificRootNodes(classification
, null, rank
, includeUnpublished
, pageSize
, pageIndex
, propertyPaths
);
193 public List
<TaxonNode
> listRankSpecificRootNodes(Classification classification
,
194 TaxonNode subtree
, Rank rank
,
195 boolean includeUnpublished
, Integer pageSize
, Integer pageIndex
, List
<String
> propertyPaths
) {
196 return pageRankSpecificRootNodes(classification
, subtree
, rank
, includeUnpublished
, pageSize
, pageIndex
, propertyPaths
).getRecords();
200 public Pager
<TaxonNode
> pageRankSpecificRootNodes(Classification classification
, Rank rank
,
201 boolean includeUnpublished
, Integer pageSize
, Integer pageIndex
, List
<String
> propertyPaths
) {
202 return pageRankSpecificRootNodes(classification
, null, rank
, includeUnpublished
, pageSize
, pageIndex
, propertyPaths
);
206 public Pager
<TaxonNode
> pageRankSpecificRootNodes(Classification classification
, TaxonNode subtree
, Rank rank
,
207 boolean includeUnpublished
, Integer pageSize
, Integer pageIndex
, List
<String
> propertyPaths
) {
208 long[] numberOfResults
= dao
.countRankSpecificRootNodes(classification
, subtree
, includeUnpublished
, rank
);
209 long totalNumberOfResults
= numberOfResults
[0] + (numberOfResults
.length
> 1 ? numberOfResults
[1] : 0);
211 List
<TaxonNode
> results
= new ArrayList
<>();
213 if (AbstractPagerImpl
.hasResultsInRange(totalNumberOfResults
, pageIndex
, pageSize
)) { // no point checking again
214 Integer limit
= PagerUtils
.limitFor(pageSize
);
215 Integer start
= PagerUtils
.startFor(pageSize
, pageIndex
);
217 Integer remainingLimit
= limit
;
218 int[] queryIndexes
= rank
== null ?
new int[]{0} : new int[]{0,1};
220 for(int queryIndex
: queryIndexes
) {
221 if(start
!= null && start
> numberOfResults
[queryIndex
]) {
222 // start in next query with new start value
223 start
= start
- (int)numberOfResults
[queryIndex
];
227 List
<TaxonNode
> perQueryResults
= dao
.listRankSpecificRootNodes(classification
,
228 subtree
, rank
, includeUnpublished
, remainingLimit
,
229 start
, propertyPaths
, queryIndex
);
230 results
.addAll(perQueryResults
);
231 if(remainingLimit
!= null ){
232 remainingLimit
= remainingLimit
- results
.size();
233 if(remainingLimit
<= 0) {
234 // no need to run further queries if first query returned enough items!
237 // start at with fist item of next query to fetch the remaining items
242 // long start_t = System.currentTimeMillis();
243 Collections
.sort(results
, taxonNodeComparator
); // TODO is ordering during the hibernate query in the dao possible?
244 // System.err.println("service.pageRankSpecificRootNodes() - Collections.sort(results, taxonNodeComparator) " + (System.currentTimeMillis() - start_t));
245 return new DefaultPagerImpl
<>(pageIndex
, totalNumberOfResults
, pageSize
, results
);
250 public List
<TaxonNode
> loadTreeBranch(TaxonNode taxonNode
, Rank baseRank
,
251 boolean includeUnpublished
, List
<String
> propertyPaths
) throws UnpublishedException
{
252 return loadTreeBranch(taxonNode
, null, baseRank
, includeUnpublished
, propertyPaths
);
259 public List
<TaxonNode
> loadTreeBranch(TaxonNode taxonNode
, TaxonNode subtree
, Rank baseRank
,
260 boolean includeUnpublished
, List
<String
> propertyPaths
) throws UnpublishedException
{
262 TaxonNode thisNode
= taxonNodeDao
.load(taxonNode
.getUuid(), propertyPaths
);
263 if(baseRank
!= null){
264 baseRank
= (Rank
) termDao
.load(baseRank
.getUuid());
266 if (!includeUnpublished
&& thisNode
.getTaxon() != null && !thisNode
.getTaxon().isPublish()){
267 throw new UnpublishedException("Final taxon in tree branch is unpublished.");
270 List
<TaxonNode
> pathToRoot
= new ArrayList
<>();
271 pathToRoot
.add(thisNode
);
273 while(!thisNode
.isTopmostNode()){
274 //TODO why do we need to deproxy here?
275 // without this thisNode.getParent() will return NULL in
276 // some cases (environment dependend?) even if the parent exits
277 TaxonNode parentNode
= CdmBase
.deproxy(thisNode
).getParent();
279 if(parentNode
== null){
280 throw new NullPointerException("Taxon node " + thisNode
+ " must have a parent since it is not top most");
282 if(parentNode
.getTaxon() == null){
283 throw new NullPointerException("The taxon associated with taxon node " + parentNode
+ " is NULL");
285 if(!includeUnpublished
&& !parentNode
.getTaxon().isPublish()){
286 throw new UnpublishedException("Some taxon in tree branch is unpublished.");
288 if(parentNode
.getTaxon().getName() == null){
289 throw new NullPointerException("The name of the taxon associated with taxonNode " + parentNode
+ " is NULL");
292 Rank parentNodeRank
= (parentNode
.getTaxon().getName() == null) ?
null : parentNode
.getTaxon().getName().getRank();
293 // stop if the next parent is higher than the baseRank
294 if(baseRank
!= null && parentNodeRank
!= null && baseRank
.isLower(parentNodeRank
)){
297 if((subtree
!= null && !subtree
.isAncestor(parentNode
) )){
301 pathToRoot
.add(parentNode
);
302 thisNode
= parentNode
;
305 // initialize and invert order of nodes in list
306 defaultBeanInitializer
.initializeAll(pathToRoot
, propertyPaths
);
307 Collections
.reverse(pathToRoot
);
313 public List
<TaxonNode
> loadTreeBranchToTaxon(Taxon taxon
, Classification classification
, Rank baseRank
,
314 boolean includeUnpublished
, List
<String
> propertyPaths
) throws UnpublishedException
{
315 return loadTreeBranchToTaxon(taxon
, classification
, null, baseRank
, includeUnpublished
, propertyPaths
);
319 public List
<TaxonNode
> loadTreeBranchToTaxon(Taxon taxon
, Classification classification
,
320 TaxonNode subtree
, Rank baseRank
,
321 boolean includeUnpublished
, List
<String
> propertyPaths
) throws UnpublishedException
{
323 UUID nodeUuid
= getTaxonNodeUuidByTaxonUuid(classification
.getUuid(), taxon
.getUuid());
324 TaxonNode node
= taxonNodeService
.find(nodeUuid
);
326 logger
.warn("The specified taxon is not found in the given tree.");
328 }else if (subtree
!= null && !node
.isDescendant(subtree
)){
329 //TODO handle as exception? E.g. FilterException, AccessDeniedException?
330 logger
.warn("The specified taxon is not found for the given subtree.");
334 return loadTreeBranch(node
, subtree
, baseRank
, includeUnpublished
, propertyPaths
);
339 public List
<TaxonNode
> loadChildNodesOfTaxonNode(TaxonNode taxonNode
,
340 List
<String
> propertyPaths
) {
341 taxonNode
= taxonNodeDao
.load(taxonNode
.getUuid());
342 List
<TaxonNode
> childNodes
= new ArrayList
<TaxonNode
>(taxonNode
.getChildNodes());
343 defaultBeanInitializer
.initializeAll(childNodes
, propertyPaths
);
344 Collections
.sort(childNodes
, taxonNodeComparator
);
349 public List
<TaxonNode
> listChildNodesOfTaxon(UUID taxonUuid
, UUID classificationUuid
,
350 boolean includeUnpublished
, Integer pageSize
, Integer pageIndex
, List
<String
> propertyPaths
){
352 return listChildNodesOfTaxon(taxonUuid
, classificationUuid
, null, includeUnpublished
, pageSize
, pageIndex
, propertyPaths
);
353 } catch (FilterException e
) {
354 throw new RuntimeException(e
); //this should not happen as filter is null
359 public List
<TaxonNode
> listChildNodesOfTaxon(UUID taxonUuid
, UUID classificationUuid
, UUID subtreeUuid
,
360 boolean includeUnpublished
, Integer pageSize
, Integer pageIndex
, List
<String
> propertyPaths
) throws FilterException
{
362 Classification classification
= dao
.load(classificationUuid
);
363 Taxon taxon
= (Taxon
) taxonDao
.load(taxonUuid
);
364 TaxonNode subtree
= taxonNodeDao
.load(subtreeUuid
);
365 if (subtreeUuid
!= null && subtree
== null){
366 throw new FilterException("Taxon node for subtree filter can not be found in database", true);
369 List
<TaxonNode
> results
= dao
.listChildrenOf(
370 taxon
, classification
, subtree
, includeUnpublished
, pageSize
, pageIndex
, propertyPaths
);
371 Collections
.sort(results
, taxonNodeComparator
); // FIXME this is only a HACK, order during the hibernate query in the dao
376 public Pager
<TaxonNode
> pageSiblingsOfTaxon(UUID taxonUuid
, UUID classificationUuid
, boolean includeUnpublished
,
377 Integer pageSize
, Integer pageIndex
, List
<String
> propertyPaths
){
379 Classification classification
= dao
.load(classificationUuid
);
380 Taxon taxon
= (Taxon
) taxonDao
.load(taxonUuid
);
382 long numberOfResults
= dao
.countSiblingsOf(taxon
, classification
, includeUnpublished
);
384 List
<TaxonNode
> results
;
385 if(PagerUtils
.hasResultsInRange(numberOfResults
, pageIndex
, pageSize
)) {
386 results
= dao
.listSiblingsOf(taxon
, classification
, includeUnpublished
, pageSize
, pageIndex
, propertyPaths
);
387 Collections
.sort(results
, taxonNodeComparator
); // FIXME this is only a HACK, order during the hibernate query in the dao
389 results
= new ArrayList
<>();
392 return new DefaultPagerImpl
<>(pageIndex
, numberOfResults
, pageSize
, results
);
396 public List
<TaxonNode
> listSiblingsOfTaxon(UUID taxonUuid
, UUID classificationUuid
, boolean includeUnpublished
,
397 Integer pageSize
, Integer pageIndex
, List
<String
> propertyPaths
){
399 Pager
<TaxonNode
> pager
= pageSiblingsOfTaxon(taxonUuid
, classificationUuid
, includeUnpublished
, pageSize
, pageIndex
, propertyPaths
);
400 return pager
.getRecords();
404 public ITaxonTreeNode
getTreeNodeByUuid(UUID uuid
){
405 ITaxonTreeNode treeNode
= taxonNodeDao
.findByUuid(uuid
);
406 if(treeNode
== null){
407 treeNode
= dao
.findByUuid(uuid
);
414 public TaxonNode
getRootNode(UUID classificationUuid
){
415 return dao
.getRootNode(classificationUuid
);
419 public List
<Classification
> listClassifications(Integer limit
, Integer start
, List
<OrderHint
> orderHints
, List
<String
> propertyPaths
) {
420 return dao
.list(limit
, start
, orderHints
, propertyPaths
);
424 public UUID
removeTaxonNode(TaxonNode taxonNode
) {
425 return taxonNodeDao
.delete(taxonNode
);
428 public UUID
removeTreeNode(ITaxonTreeNode treeNode
) {
429 if(treeNode
instanceof Classification
){
430 return dao
.delete((Classification
) treeNode
);
431 }else if(treeNode
instanceof TaxonNode
){
432 return taxonNodeDao
.delete((TaxonNode
)treeNode
);
437 public UUID
saveTaxonNode(TaxonNode taxonNode
) {
438 return taxonNodeDao
.save(taxonNode
).getUuid();
442 public Map
<UUID
, TaxonNode
> saveTaxonNodeAll(
443 Collection
<TaxonNode
> taxonNodeCollection
) {
444 return taxonNodeDao
.saveAll(taxonNodeCollection
);
448 public UUID
saveClassification(Classification classification
) {
450 taxonNodeDao
.saveOrUpdateAll(classification
.getAllNodes());
451 UUID result
=dao
.saveOrUpdate(classification
);
456 public UUID
saveTreeNode(ITaxonTreeNode treeNode
) {
457 if(treeNode
instanceof Classification
){
458 return dao
.save((Classification
) treeNode
).getUuid();
459 }else if(treeNode
instanceof TaxonNode
){
460 return taxonNodeDao
.save((TaxonNode
)treeNode
).getUuid();
466 public List
<TaxonNode
> getAllNodes(){
467 return taxonNodeDao
.list(null,null);
471 public List
<UuidAndTitleCache
<TaxonNode
>> getTaxonNodeUuidAndTitleCacheOfAcceptedTaxaByClassification(UUID classificationUuid
, Integer limit
, String pattern
, boolean searchForClassifications
) {
472 return taxonNodeDao
.getTaxonNodeUuidAndTitleCacheOfAcceptedTaxaByClassification(dao
.load(classificationUuid
), limit
, pattern
, searchForClassifications
);
476 public List
<UuidAndTitleCache
<TaxonNode
>> getTaxonNodeUuidAndTitleCacheOfAcceptedTaxaByClassification(Classification classification
, Integer limit
, String pattern
, boolean searchForClassifications
) {
477 return taxonNodeDao
.getTaxonNodeUuidAndTitleCacheOfAcceptedTaxaByClassification(classification
, limit
, pattern
, searchForClassifications
);
481 public List
<UuidAndTitleCache
<TaxonNode
>> getTaxonNodeUuidAndTitleCacheOfAcceptedTaxaByClassification(UUID classificationUuid
, boolean searchForClassifications
) {
482 return taxonNodeDao
.getTaxonNodeUuidAndTitleCacheOfAcceptedTaxaByClassification(dao
.load(classificationUuid
), null, null, searchForClassifications
);
486 public List
<UuidAndTitleCache
<TaxonNode
>> getTaxonNodeUuidAndTitleCacheOfAcceptedTaxaByClassification(Classification classification
, boolean searchForClassifications
) {
487 return taxonNodeDao
.getTaxonNodeUuidAndTitleCacheOfAcceptedTaxaByClassification(classification
, null, null, searchForClassifications
);
491 public List
<UuidAndTitleCache
<Classification
>> getUuidAndTitleCache(Integer limit
, String pattern
) {
492 return dao
.getUuidAndTitleCache(limit
, pattern
);
496 public Map
<UUID
, List
<MediaRepresentation
>> getAllMediaForChildNodes(
497 TaxonNode taxonNode
, List
<String
> propertyPaths
, int size
,
498 int height
, int widthOrDuration
, String
[] mimeTypes
) {
500 TreeMap
<UUID
, List
<MediaRepresentation
>> result
= new TreeMap
<>();
501 List
<MediaRepresentation
> mediaRepresentations
= new ArrayList
<>();
503 //add all media of the children to the result map
504 if (taxonNode
!= null){
506 List
<TaxonNode
> nodes
= new ArrayList
<>();
508 nodes
.add(loadTaxonNode(taxonNode
.getUuid(), propertyPaths
));
509 nodes
.addAll(loadChildNodesOfTaxonNode(taxonNode
, propertyPaths
));
511 for(TaxonNode node
: nodes
){
512 Taxon taxon
= node
.getTaxon();
513 for (TaxonDescription taxonDescription
: taxon
.getDescriptions()){
514 for (DescriptionElementBase descriptionElement
: taxonDescription
.getElements()){
515 for(Media media
: descriptionElement
.getMedia()){
516 //find the best matching representation
517 mediaRepresentations
.add(MediaUtils
.findBestMatchingRepresentation(media
,null, size
, height
, widthOrDuration
, mimeTypes
));
521 result
.put(taxon
.getUuid(), mediaRepresentations
);
529 @Transactional(readOnly
= false)
530 public void updateCaches(Class
<?
extends Classification
> clazz
, Integer stepSize
, IIdentifiableEntityCacheStrategy
<Classification
> cacheStrategy
, IProgressMonitor monitor
) {
532 clazz
= Classification
.class;
534 super.updateCachesImpl(clazz
, stepSize
, cacheStrategy
, monitor
);
539 * @param allNodesOfClassification
540 * @return null - if allNodesOfClassification is empty <br>
543 private Map
<String
, List
<TaxonNode
>> getSortedGenusList(Collection
<TaxonNode
> allNodesOfClassification
){
545 if(allNodesOfClassification
== null || allNodesOfClassification
.isEmpty()){
548 Map
<String
, List
<TaxonNode
>> sortedGenusMap
= new HashMap
<>();
549 for(TaxonNode node
:allNodesOfClassification
){
550 Taxon taxon
= node
.getTaxon();
551 INonViralName name
= taxon
.getName();
552 String genusOrUninomial
= name
.getGenusOrUninomial();
553 //if rank unknown split string and take first word
554 if(genusOrUninomial
== null){
555 String titleCache
= taxon
.getTitleCache();
556 String
[] split
= titleCache
.split("\\s+");
558 genusOrUninomial
= s
;
562 //if node has children
564 //retrieve list from map if not create List
565 if(sortedGenusMap
.containsKey(genusOrUninomial
)){
566 List
<TaxonNode
> list
= sortedGenusMap
.get(genusOrUninomial
);
568 sortedGenusMap
.put(genusOrUninomial
, list
);
570 //create List for genus
571 List
<TaxonNode
> list
= new ArrayList
<>();
573 sortedGenusMap
.put(genusOrUninomial
, list
);
576 return sortedGenusMap
;
581 * creates new Classification and parent TaxonNodes at genus level
584 * @param map GenusMap which holds a name (Genus) and all the same Taxa as a list
585 * @param classification you want to improve the hierarchy (will not be modified)
586 * @param configurator to change certain settings, if null then standard settings will be taken
587 * @return new classification with parentNodes for each entry in the map
589 @SuppressWarnings({ "unchecked" })
590 @Transactional(readOnly
= false)
592 public UpdateResult
createHierarchyInClassification(Classification classification
, CreateHierarchyForClassificationConfigurator configurator
){
593 UpdateResult result
= new UpdateResult();
594 classification
= dao
.findByUuid(classification
.getUuid());
595 Map
<String
, List
<TaxonNode
>> map
= getSortedGenusList(classification
.getAllNodes());
597 final String APPENDIX
= "repaired";
598 String titleCache
= StringUtils
.isBlank(classification
.getTitleCache()) ?
" " : classification
.getTitleCache() ;
599 //TODO classification clone???
600 Classification newClassification
= Classification
.NewInstance(titleCache
+" "+ APPENDIX
);
601 newClassification
.setReference(classification
.getReference());
603 for(Map
.Entry
<String
, List
<TaxonNode
>> entry
:map
.entrySet()){
604 String genus
= entry
.getKey();
605 List
<TaxonNode
> listOfTaxonNodes
= entry
.getValue();
606 TaxonNode parentNode
= null;
607 //Search for genus in list
608 for(TaxonNode tNode
:listOfTaxonNodes
){
609 //take that taxonNode as parent and remove from list with all it possible children
611 TaxonName name
= tNode
.getTaxon().getName();
612 if(name
.getNameCache().equalsIgnoreCase(genus
)){
613 TaxonNode clone
= (TaxonNode
) tNode
.clone();
614 if(!tNode
.hasChildNodes()){
615 //FIXME remove classification
616 // parentNode = newClassification.addChildNode(clone, 0, classification.getCitation(), classification.getMicroReference());
617 parentNode
= newClassification
.addChildNode(clone
, 0, clone
.getReference(), clone
.getMicroReference());
618 //remove taxonNode from list because just added to classification
619 result
.addUpdatedObject(tNode
);
620 listOfTaxonNodes
.remove(tNode
);
623 //save prior Hierarchy and remove them from the list
624 List
<TaxonNode
> copyAllChildrenToTaxonNode
= copyAllChildrenToTaxonNode(tNode
, clone
, result
);
625 // parentNode = newClassification.addChildNode(clone, 0, classification.getCitation(), classification.getMicroReference());
626 //FIXME remove classification
627 parentNode
= newClassification
.addChildNode(clone
, 0, clone
.getReference(), clone
.getMicroReference());
628 //remove taxonNode from list because just added to classification
629 result
.addUpdatedObject(tNode
);
630 listOfTaxonNodes
.remove(tNode
);
631 if(copyAllChildrenToTaxonNode
!= null){
632 listOfTaxonNodes
= (List
<TaxonNode
>) CollectionUtils
.removeAll(listOfTaxonNodes
, copyAllChildrenToTaxonNode
);
638 if(parentNode
== null){
639 //if no match found in list, create parentNode
640 NonViralNameParserImpl parser
= NonViralNameParserImpl
.NewInstance();
641 TaxonName TaxonName
= (TaxonName
)parser
.parseFullName(genus
);
642 //TODO Sec via configurator
643 Taxon taxon
= Taxon
.NewInstance(TaxonName
, null);
644 parentNode
= newClassification
.addChildTaxon(taxon
, 0, null, null);
645 result
.addUpdatedObject(parentNode
);
647 //iterate over the rest of the list
648 for(TaxonNode tn
: listOfTaxonNodes
){
649 //if TaxonNode has a parent and this is not the classification then skip it
650 //and add to new classification via the parentNode as children of it
651 //this should assures to keep the already existing hierarchy
652 //FIXME: Assert is not rootnode --> entrypoint is not classification in future but rather rootNode
654 if(!tn
.isTopmostNode()){
655 continue; //skip to next taxonNode
658 TaxonNode clone
= (TaxonNode
) tn
.clone();
659 //FIXME: citation from node
660 //TODO: addchildNode without citation and references
661 // TaxonNode taxonNode = parentNode.addChildNode(clone, classification.getCitation(), classification.getMicroReference());
662 TaxonNode taxonNode
= parentNode
.addChildNode(clone
, clone
.getReference(), clone
.getMicroReference());
663 result
.addUnChangedObject(clone
);
664 if(tn
.hasChildNodes()){
665 //save hierarchy in new classification
666 List
<TaxonNode
> copyAllChildrenToTaxonNode
= copyAllChildrenToTaxonNode(tn
, taxonNode
, result
);
667 if(copyAllChildrenToTaxonNode
!= null){
668 listOfTaxonNodes
= (List
<TaxonNode
>) CollectionUtils
.removeAll(listOfTaxonNodes
, copyAllChildrenToTaxonNode
);
673 dao
.saveOrUpdate(newClassification
);
674 result
.setCdmEntity(newClassification
);
680 * recursive method to get all childnodes of taxonNode in classification.
682 * @param classification just for References and Citation, can be null
683 * @param copyFromNode TaxonNode with Children
684 * @param copyToNode TaxonNode which will receive the children
685 * @return List of ChildNode which has been added. If node has no children returns null
687 private List
<TaxonNode
> copyAllChildrenToTaxonNode(TaxonNode copyFromNode
, TaxonNode copyToNode
, UpdateResult result
) {
688 List
<TaxonNode
> childNodes
;
689 if(!copyFromNode
.hasChildNodes()){
692 childNodes
= copyFromNode
.getChildNodes();
694 for(TaxonNode childNode
:childNodes
){
695 TaxonNode clone
= (TaxonNode
) childNode
.clone();
696 result
.addUnChangedObject(clone
);
697 if(childNode
.hasChildNodes()){
698 copyAllChildrenToTaxonNode(childNode
, clone
, result
);
700 //FIXME: citation from node instead of classification
701 // copyToNode.addChildNode(clone,classification.getCitation(), classification.getMicroReference());
702 copyToNode
.addChildNode(clone
, clone
.getReference(), clone
.getMicroReference());
711 public ClassificationLookupDTO
classificationLookup(Classification classification
) {
712 return dao
.classificationLookup(classification
);
718 public DeleteResult
delete(UUID classificationUuid
, TaxonDeletionConfigurator config
){
719 DeleteResult result
= new DeleteResult();
720 Classification classification
= dao
.findByUuid(classificationUuid
);
721 if (classification
== null){
722 result
.addException(new IllegalArgumentException("The classification does not exist in database."));
726 if (!classification
.hasChildNodes()){
727 dao
.delete(classification
);
728 result
.addDeletedObject(classification
);
731 if (config
.getTaxonNodeConfig().getChildHandling().equals(ChildHandling
.DELETE
)){
732 // TaxonNode root = classification.getRootNode();
733 // result.includeResult(taxonNodeService.deleteTaxonNode(HibernateProxyHelper.deproxy(root), config));
734 // result.addDeletedObject(classification);
735 dao
.delete(classification
);
736 result
.addDeletedObject(classification
);
745 public List
<GroupedTaxonDTO
> groupTaxaByHigherTaxon(List
<UUID
> originalTaxonUuids
, UUID classificationUuid
, Rank minRank
, Rank maxRank
){
746 List
<GroupedTaxonDTO
> result
= new ArrayList
<>();
748 //get treeindex for each taxonUUID
749 Map
<UUID
, TreeIndex
> taxonIdTreeIndexMap
= dao
.treeIndexForTaxonUuids(classificationUuid
, originalTaxonUuids
);
751 //build treeindex list (or tree)
752 //TODO make it work with TreeIndex or move there
753 List
<String
> treeIndexClosureStr
= new ArrayList
<>();
754 for (TreeIndex treeIndex
: taxonIdTreeIndexMap
.values()){
755 String
[] splits
= treeIndex
.toString().substring(1).split(ITreeNode
.separator
);
756 String currentIndex
= ITreeNode
.separator
;
757 for (String split
: splits
){
758 if (split
.equals("")){
761 currentIndex
+= split
+ ITreeNode
.separator
;
762 if (!treeIndexClosureStr
.contains(currentIndex
) && !split
.startsWith(ITreeNode
.treePrefix
)){
763 treeIndexClosureStr
.add(currentIndex
);
768 //get rank sortindex for all parent taxa with sortindex <= minRank and sortIndex >= maxRank (if available)
769 Integer minRankOrderIndex
= minRank
== null ?
null : minRank
.getOrderIndex();
770 Integer maxRankOrderIndex
= maxRank
== null ?
null : maxRank
.getOrderIndex();
771 List
<TreeIndex
> treeIndexClosure
= TreeIndex
.NewListInstance(treeIndexClosureStr
);
773 Map
<TreeIndex
, Integer
> treeIndexSortIndexMapTmp
= taxonNodeDao
.rankOrderIndexForTreeIndex(treeIndexClosure
, minRankOrderIndex
, maxRankOrderIndex
);
775 //remove all treeindex with "exists child in above map(and child.sortindex > xxx)
776 List
<TreeIndex
> treeIndexList
= TreeIndex
.sort(treeIndexSortIndexMapTmp
.keySet());
778 Map
<TreeIndex
, Integer
> treeIndexSortIndexMap
= new HashMap
<>();
779 TreeIndex lastTreeIndex
= null;
780 for (TreeIndex treeIndex
: treeIndexList
){
781 if (lastTreeIndex
!= null && lastTreeIndex
.hasChild(treeIndex
)){
782 treeIndexSortIndexMap
.remove(lastTreeIndex
);
784 treeIndexSortIndexMap
.put(treeIndex
, treeIndexSortIndexMapTmp
.get(treeIndex
));
785 lastTreeIndex
= treeIndex
;
788 //get taxonID for treeIndexes
789 Map
<TreeIndex
, UuidAndTitleCache
<?
>> treeIndexTaxonIdMap
= taxonNodeDao
.taxonUuidsForTreeIndexes(treeIndexSortIndexMap
.keySet());
792 for (UUID originalTaxonUuid
: originalTaxonUuids
){
793 GroupedTaxonDTO item
= new GroupedTaxonDTO();
795 item
.setTaxonUuid(originalTaxonUuid
);
796 TreeIndex groupTreeIndex
= taxonIdTreeIndexMap
.get(originalTaxonUuid
);
797 String groupIndexX
= TreeIndex
.toString(groupTreeIndex
);
798 while (groupTreeIndex
!= null){
799 if (treeIndexTaxonIdMap
.get(groupTreeIndex
) != null){
800 UuidAndTitleCache
<?
> uuidAndLabel
= treeIndexTaxonIdMap
.get(groupTreeIndex
);
801 item
.setGroupTaxonUuid(uuidAndLabel
.getUuid());
802 item
.setGroupTaxonName(uuidAndLabel
.getTitleCache());
805 groupTreeIndex
= groupTreeIndex
.parent();
806 // int index = groupIndex.substring(0, groupIndex.length()-1).lastIndexOf(ITreeNode.separator);
807 // groupIndex = index < 0 ? null : groupIndex.substring(0, index+1);
819 public List
<GroupedTaxonDTO
> groupTaxaByMarkedParents(List
<UUID
> originalTaxonUuids
, UUID classificationUuid
,
820 MarkerType markerType
, Boolean flag
) {
822 List
<GroupedTaxonDTO
> result
= new ArrayList
<>();
824 //get treeindex for each taxonUUID
825 Map
<UUID
, TreeIndex
> taxonIdTreeIndexMap
= dao
.treeIndexForTaxonUuids(classificationUuid
, originalTaxonUuids
);
827 //get all marked tree indexes
828 Set
<TreeIndex
> markedTreeIndexes
= dao
.getMarkedTreeIndexes(markerType
, flag
);
831 Map
<TreeIndex
, TreeIndex
> groupedMap
= TreeIndex
.group(markedTreeIndexes
, taxonIdTreeIndexMap
.values());
832 Set
<TreeIndex
> notNullGroups
= new HashSet
<>(groupedMap
.values());
833 notNullGroups
.remove(null);
835 //get taxonInfo for treeIndexes
836 Map
<TreeIndex
, UuidAndTitleCache
<?
>> treeIndexTaxonIdMap
= taxonNodeDao
.taxonUuidsForTreeIndexes(notNullGroups
);
839 for (UUID originalTaxonUuid
: originalTaxonUuids
){
840 GroupedTaxonDTO item
= new GroupedTaxonDTO();
842 item
.setTaxonUuid(originalTaxonUuid
);
844 TreeIndex toBeGroupedTreeIndex
= taxonIdTreeIndexMap
.get(originalTaxonUuid
);
845 TreeIndex groupTreeIndex
= groupedMap
.get(toBeGroupedTreeIndex
);
846 UuidAndTitleCache
<?
> uuidAndLabel
= treeIndexTaxonIdMap
.get(groupTreeIndex
);
847 if (uuidAndLabel
!= null){
848 item
.setGroupTaxonUuid(uuidAndLabel
.getUuid());
849 item
.setGroupTaxonName(uuidAndLabel
.getTitleCache());
860 public UUID
getTaxonNodeUuidByTaxonUuid(UUID classificationUuid
, UUID taxonUuid
) {
861 Map
<UUID
, UUID
> map
= dao
.getTaxonNodeUuidByTaxonUuid(classificationUuid
, Arrays
.asList(taxonUuid
));
862 UUID taxonNodeUuid
= map
.get(taxonUuid
);
863 return taxonNodeUuid
;
870 public TaxonInContextDTO
getTaxonInContext(UUID classificationUuid
, UUID taxonBaseUuid
,
871 Boolean doChildren
, Boolean doSynonyms
, boolean includeUnpublished
, List
<UUID
> ancestorMarkers
,
872 NodeSortMode sortMode
) {
873 TaxonInContextDTO result
= new TaxonInContextDTO();
875 TaxonBase
<?
> taxonBase
= taxonDao
.load(taxonBaseUuid
);
876 if (taxonBase
== null){
877 throw new EntityNotFoundException("Taxon with uuid " + taxonBaseUuid
+ " not found in datasource");
879 boolean isSynonym
= false;
881 if (taxonBase
.isInstanceOf(Synonym
.class)){
883 Synonym synonym
= CdmBase
.deproxy(taxonBase
, Synonym
.class);
884 acceptedTaxon
= synonym
.getAcceptedTaxon();
885 if (acceptedTaxon
== null) {
886 throw new EntityNotFoundException("Accepted taxon not found for synonym" );
888 TaxonStatus taxonStatus
= TaxonStatus
.Synonym
;
889 if (synonym
.getName()!= null && acceptedTaxon
.getName() != null
890 && synonym
.getName().getHomotypicalGroup().equals(acceptedTaxon
.getName().getHomotypicalGroup())){
891 taxonStatus
= TaxonStatus
.SynonymObjective
;
893 result
.setTaxonStatus(taxonStatus
);
896 acceptedTaxon
= CdmBase
.deproxy(taxonBase
, Taxon
.class);
897 result
.setTaxonStatus(TaxonStatus
.Accepted
);
899 UUID acceptedTaxonUuid
= acceptedTaxon
.getUuid();
901 UUID taxonNodeUuid
= getTaxonNodeUuidByTaxonUuid(classificationUuid
, acceptedTaxonUuid
);
902 if (taxonNodeUuid
== null) {
903 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
);
905 result
.setTaxonNodeUuid(taxonNodeUuid
);
907 //TODO make it a dao call
908 Taxon parentTaxon
= getParentTaxon(classificationUuid
, acceptedTaxon
);
909 if (parentTaxon
!= null){
910 result
.setParentTaxonUuid(parentTaxon
.getUuid());
911 result
.setParentTaxonLabel(parentTaxon
.getTitleCache());
912 if (parentTaxon
.getName() != null){
913 result
.setParentNameLabel(parentTaxon
.getName().getTitleCache());
917 result
.setTaxonUuid(taxonBaseUuid
);
918 result
.setClassificationUuid(classificationUuid
);
919 if (taxonBase
.getSec() != null){
920 result
.setSecundumUuid(taxonBase
.getSec().getUuid());
921 result
.setSecundumLabel(taxonBase
.getSec().getTitleCache());
923 result
.setTaxonLabel(taxonBase
.getTitleCache());
925 TaxonName name
= taxonBase
.getName();
926 result
.setNameUuid(name
.getUuid());
927 result
.setNameLabel(name
.getTitleCache());
928 result
.setNameWithoutAuthor(name
.getNameCache());
929 result
.setGenusOrUninomial(name
.getGenusOrUninomial());
930 result
.setInfraGenericEpithet(name
.getInfraGenericEpithet());
931 result
.setSpeciesEpithet(name
.getSpecificEpithet());
932 result
.setInfraSpecificEpithet(name
.getInfraSpecificEpithet());
934 result
.setAuthorship(name
.getAuthorshipCache());
936 Rank rank
= name
.getRank();
938 result
.setRankUuid(rank
.getUuid());
939 String rankLabel
= rank
.getAbbreviation();
940 if (StringUtils
.isBlank(rankLabel
)){
941 rankLabel
= rank
.getLabel();
943 result
.setRankLabel(rankLabel
);
946 boolean recursive
= false;
947 Integer pageSize
= null;
948 Integer pageIndex
= null;
949 Pager
<TaxonNodeDto
> children
= taxonNodeService
.pageChildNodesDTOs(taxonNodeUuid
, recursive
, includeUnpublished
, doSynonyms
,
950 sortMode
, pageSize
, pageIndex
);
954 for (TaxonNodeDto childDto
: children
.getRecords()){
955 if (doChildren
&& childDto
.getStatus().equals(TaxonStatus
.Accepted
)){
956 EntityDTO
<Taxon
> child
= new EntityDTO
<Taxon
>(childDto
.getTaxonUuid(), childDto
.getTitleCache());
957 result
.addChild(child
);
958 }else if (doSynonyms
&& childDto
.getStatus().isSynonym()){
959 EntityDTO
<Synonym
> child
= new EntityDTO
<>(childDto
.getTaxonUuid(), childDto
.getTitleCache());
960 result
.addSynonym(child
);
964 result
.setAcceptedTaxonUuid(acceptedTaxonUuid
);
965 String nameTitel
= acceptedTaxon
.getName() == null ?
null : acceptedTaxon
.getName().getTitleCache();
966 result
.setAcceptedTaxonLabel(acceptedTaxon
.getTitleCache());
967 result
.setAcceptedNameLabel(nameTitel
);
971 if (ancestorMarkers
!= null && !ancestorMarkers
.isEmpty()){
972 @SuppressWarnings("rawtypes")
973 List
<DefinedTermBase
> markerTypesTerms
= termDao
.list(ancestorMarkers
, pageSize
, null, null, null);
974 List
<MarkerType
> markerTypes
= new ArrayList
<>();
975 for (DefinedTermBase
<?
> term
: markerTypesTerms
){
976 if (term
.isInstanceOf(MarkerType
.class)){
977 markerTypes
.add(CdmBase
.deproxy(term
, MarkerType
.class));
980 if (! markerTypes
.isEmpty()){
981 TaxonNode node
= taxonNodeDao
.findByUuid(taxonNodeUuid
);
982 handleAncestorsForMarkersRecursive(result
, markerTypes
, node
);
990 * @param classificationUuid
991 * @param acceptedTaxon
994 private Taxon
getParentTaxon(UUID classificationUuid
, Taxon acceptedTaxon
) {
995 if (classificationUuid
== null){
998 TaxonNode parent
= null;
999 for (TaxonNode node
: acceptedTaxon
.getTaxonNodes()){
1000 if (classificationUuid
.equals(node
.getClassification().getUuid())){
1001 parent
= node
.getParent();
1004 if (parent
!= null){
1005 return parent
.getTaxon();
1012 * @param markerTypes
1015 private void handleAncestorsForMarkersRecursive(TaxonInContextDTO result
, List
<MarkerType
> markerTypes
, TaxonNode node
) {
1016 for (MarkerType type
: markerTypes
){
1017 Taxon taxon
= node
.getTaxon();
1018 if (taxon
!= null && taxon
.hasMarker(type
, true)){
1019 String label
= taxon
.getName() == null? taxon
.getTitleCache() : taxon
.getName().getTitleCache();
1020 MarkedEntityDTO
<Taxon
> dto
= new MarkedEntityDTO
<>(type
, true, taxon
.getUuid(), label
);
1021 result
.addMarkedAncestor(dto
);
1024 TaxonNode parentNode
= node
.getParent();
1025 if (parentNode
!= null){
1026 handleAncestorsForMarkersRecursive(result
, markerTypes
, parentNode
);
1034 public List
<UuidAndTitleCache
<TaxonNode
>> getTaxonNodeUuidAndTitleCacheOfAcceptedTaxaByClassification(
1035 Classification classification
) {
1036 return getTaxonNodeUuidAndTitleCacheOfAcceptedTaxaByClassification(classification
, false);
1043 public List
<UuidAndTitleCache
<TaxonNode
>> getTaxonNodeUuidAndTitleCacheOfAcceptedTaxaByClassification(
1044 UUID classificationUuid
) {
1045 return getTaxonNodeUuidAndTitleCacheOfAcceptedTaxaByClassification(classificationUuid
, false);
1052 public List
<UuidAndTitleCache
<TaxonNode
>> getTaxonNodeUuidAndTitleCacheOfAcceptedTaxaByClassification(
1053 UUID classificationUuid
, Integer limit
, String pattern
) {
1054 return getTaxonNodeUuidAndTitleCacheOfAcceptedTaxaByClassification(classificationUuid
, limit
, pattern
, false);
1061 public List
<UuidAndTitleCache
<TaxonNode
>> getTaxonNodeUuidAndTitleCacheOfAcceptedTaxaByClassification(
1062 Classification classification
, Integer limit
, String pattern
) {
1063 return getTaxonNodeUuidAndTitleCacheOfAcceptedTaxaByClassification(classification
, limit
, pattern
, false);