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
.hibernate
.HHH_9751_Util
;
47 import eu
.etaxonomy
.cdm
.hibernate
.HibernateProxyHelper
;
48 import eu
.etaxonomy
.cdm
.model
.common
.CdmBase
;
49 import eu
.etaxonomy
.cdm
.model
.common
.DefinedTermBase
;
50 import eu
.etaxonomy
.cdm
.model
.common
.ITreeNode
;
51 import eu
.etaxonomy
.cdm
.model
.common
.MarkerType
;
52 import eu
.etaxonomy
.cdm
.model
.common
.TreeIndex
;
53 import eu
.etaxonomy
.cdm
.model
.description
.DescriptionElementBase
;
54 import eu
.etaxonomy
.cdm
.model
.description
.TaxonDescription
;
55 import eu
.etaxonomy
.cdm
.model
.media
.Media
;
56 import eu
.etaxonomy
.cdm
.model
.media
.MediaRepresentation
;
57 import eu
.etaxonomy
.cdm
.model
.media
.MediaUtils
;
58 import eu
.etaxonomy
.cdm
.model
.name
.INonViralName
;
59 import eu
.etaxonomy
.cdm
.model
.name
.Rank
;
60 import eu
.etaxonomy
.cdm
.model
.name
.TaxonName
;
61 import eu
.etaxonomy
.cdm
.model
.reference
.Reference
;
62 import eu
.etaxonomy
.cdm
.model
.taxon
.Classification
;
63 import eu
.etaxonomy
.cdm
.model
.taxon
.ITaxonNodeComparator
;
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
.taxon
.TaxonRelationshipType
;
70 import eu
.etaxonomy
.cdm
.persistence
.dao
.common
.IDefinedTermDao
;
71 import eu
.etaxonomy
.cdm
.persistence
.dao
.initializer
.IBeanInitializer
;
72 import eu
.etaxonomy
.cdm
.persistence
.dao
.taxon
.IClassificationDao
;
73 import eu
.etaxonomy
.cdm
.persistence
.dao
.taxon
.ITaxonDao
;
74 import eu
.etaxonomy
.cdm
.persistence
.dao
.taxon
.ITaxonNodeDao
;
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
{
92 private static final Logger logger
= Logger
.getLogger(ClassificationServiceImpl
.class);
95 private ITaxonNodeDao taxonNodeDao
;
98 private ITaxonDao taxonDao
;
101 private ITaxonNodeService taxonNodeService
;
104 private IDefinedTermDao termDao
;
107 private IBeanInitializer defaultBeanInitializer
;
111 protected void setDao(IClassificationDao dao
) {
115 private Comparator
<?
super TaxonNode
> taxonNodeComparator
;
118 public void setTaxonNodeComparator(ITaxonNodeComparator
<?
super TaxonNode
> taxonNodeComparator
){
119 this.taxonNodeComparator
= (Comparator
<?
super TaxonNode
>) taxonNodeComparator
;
123 public TaxonNode
loadTaxonNodeByTaxon(Taxon taxon
, UUID classificationUuid
, List
<String
> propertyPaths
){
124 Classification tree
= dao
.load(classificationUuid
);
125 TaxonNode node
= tree
.getNode(taxon
);
127 return loadTaxonNode(node
.getUuid(), propertyPaths
);
131 @Deprecated // use loadTaxonNode(UUID, List<String>) instead
132 public TaxonNode
loadTaxonNode(TaxonNode taxonNode
, List
<String
> propertyPaths
){
133 return taxonNodeDao
.load(taxonNode
.getUuid(), propertyPaths
);
136 public TaxonNode
loadTaxonNode(UUID taxonNodeUuid
, List
<String
> propertyPaths
){
137 return taxonNodeDao
.load(taxonNodeUuid
, propertyPaths
);
141 @Transactional(readOnly
= false)
142 public UpdateResult
cloneClassification(UUID classificationUuid
,
143 String name
, Reference sec
, TaxonRelationshipType relationshipType
) {
144 UpdateResult result
= new UpdateResult();
145 Classification classification
= load(classificationUuid
);
146 Classification clone
= Classification
.NewInstance(name
);
147 clone
.setReference(sec
);
149 //clone taxa and taxon nodes
150 List
<TaxonNode
> childNodes
= classification
.getRootNode().getChildNodes();
151 for (TaxonNode taxonNode
: childNodes
) {
152 addChildTaxa(taxonNode
, null, clone
, relationshipType
);
154 dao
.saveOrUpdate(clone
);
155 result
.setCdmEntity(clone
);
159 private void addChildTaxa(TaxonNode originalParentNode
, TaxonNode cloneParentNode
, Classification classification
, TaxonRelationshipType relationshipType
){
160 Reference reference
= classification
.getReference();
161 Taxon cloneTaxon
= (Taxon
) HibernateProxyHelper
.deproxy(originalParentNode
.getTaxon(), Taxon
.class).clone();
162 cloneTaxon
.setSec(reference
);
163 String microReference
= null;
164 List
<TaxonNode
> originalChildNodes
= originalParentNode
.getChildNodes();
165 HHH_9751_Util
.removeAllNull(originalChildNodes
);
167 //add relation between taxa
168 if (relationshipType
!= null){
169 cloneTaxon
.addTaxonRelation(originalParentNode
.getTaxon(), relationshipType
, reference
, microReference
);
172 TaxonNode cloneChildNode
= null;
173 //add taxon node to either parent node or classification (no parent node)
174 if(cloneParentNode
==null){
175 cloneChildNode
= classification
.addChildTaxon(cloneTaxon
, reference
, microReference
);
178 cloneChildNode
= cloneParentNode
.addChildTaxon(cloneTaxon
, reference
, microReference
);
180 taxonNodeDao
.saveOrUpdate(cloneChildNode
);
182 for (TaxonNode originalChildNode
: originalChildNodes
) {
183 addChildTaxa(originalChildNode
, cloneChildNode
, classification
, relationshipType
);
191 public List
<TaxonNode
> listRankSpecificRootNodes(Classification classification
, Rank rank
,
192 boolean includeUnpublished
, Integer pageSize
, Integer pageIndex
, List
<String
> propertyPaths
) {
193 return pageRankSpecificRootNodes(classification
, rank
, includeUnpublished
, pageSize
, pageIndex
, propertyPaths
).getRecords();
197 public Pager
<TaxonNode
> pageRankSpecificRootNodes(Classification classification
, Rank rank
,
198 boolean includeUnpublished
, Integer pageSize
, Integer pageIndex
, List
<String
> propertyPaths
) {
199 long[] numberOfResults
= dao
.countRankSpecificRootNodes(classification
, includeUnpublished
, rank
);
200 long totalNumberOfResults
= numberOfResults
[0] + (numberOfResults
.length
> 1 ? numberOfResults
[1] : 0);
202 List
<TaxonNode
> results
= new ArrayList
<>();
204 if (AbstractPagerImpl
.hasResultsInRange(totalNumberOfResults
, pageIndex
, pageSize
)) { // no point checking again
205 Integer limit
= PagerUtils
.limitFor(pageSize
);
206 Integer start
= PagerUtils
.startFor(pageSize
, pageIndex
);
208 Integer remainingLimit
= limit
;
209 int[] queryIndexes
= rank
== null ?
new int[]{0} : new int[]{0,1};
211 for(int queryIndex
: queryIndexes
) {
212 if(start
!= null && start
> numberOfResults
[queryIndex
]) {
213 // start in next query with new start value
214 start
= start
- (int)numberOfResults
[queryIndex
];
218 List
<TaxonNode
> perQueryResults
= dao
.listRankSpecificRootNodes(classification
,
219 rank
, includeUnpublished
, remainingLimit
, start
, propertyPaths
, queryIndex
);
220 results
.addAll(perQueryResults
);
221 if(remainingLimit
!= null ){
222 remainingLimit
= remainingLimit
- results
.size();
223 if(remainingLimit
<= 0) {
224 // no need to run further queries if first query returned enough items!
227 // start at with fist item of next query to fetch the remaining items
232 // long start_t = System.currentTimeMillis();
233 Collections
.sort(results
, taxonNodeComparator
); // TODO is ordering during the hibernate query in the dao possible?
234 // System.err.println("service.pageRankSpecificRootNodes() - Collections.sort(results, taxonNodeComparator) " + (System.currentTimeMillis() - start_t));
235 return new DefaultPagerImpl
<TaxonNode
>(pageIndex
, totalNumberOfResults
, pageSize
, results
);
240 * @implements {@link IClassificationService#loadTreeBranch(TaxonNode, Rank, List)
241 * @see eu.etaxonomy.cdm.api.service.ITaxonService#loadTreeBranchTo(eu.etaxonomy.cdm.model.taxon.TaxonNode, eu.etaxonomy.cdm.model.name.Rank, java.util.List)
242 * FIXME Candidate for harmonization
243 * move to classification service
246 public List
<TaxonNode
> loadTreeBranch(TaxonNode taxonNode
, Rank baseRank
, List
<String
> propertyPaths
){
248 TaxonNode thisNode
= taxonNodeDao
.load(taxonNode
.getUuid(), propertyPaths
);
249 if(baseRank
!= null){
250 baseRank
= (Rank
) termDao
.load(baseRank
.getUuid());
252 List
<TaxonNode
> pathToRoot
= new ArrayList
<TaxonNode
>();
253 pathToRoot
.add(thisNode
);
255 while(!thisNode
.isTopmostNode()){
256 //TODO why do we need to deproxy here?
257 // without this thisNode.getParent() will return NULL in
258 // some cases (environment dependend?) even if the parent exits
259 TaxonNode parentNode
= CdmBase
.deproxy(thisNode
, TaxonNode
.class).getParent();
261 if(parentNode
== null){
262 throw new NullPointerException("taxonNode " + thisNode
+ " must have a parent since it is not top most");
264 if(parentNode
.getTaxon() == null){
265 throw new NullPointerException("The taxon associated with taxonNode " + parentNode
+ " is NULL");
267 if(parentNode
.getTaxon().getName() == null){
268 throw new NullPointerException("The name of the taxon associated with taxonNode " + parentNode
+ " is NULL");
271 Rank parentNodeRank
= parentNode
.getTaxon().getName() == null ?
null : parentNode
.getTaxon().getName().getRank();
272 // stop if the next parent is higher than the baseRank
273 if(baseRank
!= null && parentNodeRank
!= null && baseRank
.isLower(parentNodeRank
)){
277 pathToRoot
.add(parentNode
);
278 thisNode
= parentNode
;
281 // initialize and invert order of nodes in list
282 defaultBeanInitializer
.initializeAll(pathToRoot
, propertyPaths
);
283 Collections
.reverse(pathToRoot
);
289 public List
<TaxonNode
> loadTreeBranchToTaxon(Taxon taxon
, Classification classification
, Rank baseRank
, List
<String
> propertyPaths
){
290 Classification tree
= dao
.load(classification
.getUuid());
291 taxon
= (Taxon
) taxonDao
.load(taxon
.getUuid());
292 TaxonNode node
= tree
.getNode(taxon
);
294 logger
.warn("The specified taxon is not found in the given tree.");
297 return loadTreeBranch(node
, baseRank
, propertyPaths
);
302 public List
<TaxonNode
> loadChildNodesOfTaxonNode(TaxonNode taxonNode
,
303 List
<String
> propertyPaths
) {
304 taxonNode
= taxonNodeDao
.load(taxonNode
.getUuid());
305 List
<TaxonNode
> childNodes
= new ArrayList
<TaxonNode
>(taxonNode
.getChildNodes());
306 defaultBeanInitializer
.initializeAll(childNodes
, propertyPaths
);
307 Collections
.sort(childNodes
, taxonNodeComparator
);
312 public List
<TaxonNode
> listChildNodesOfTaxon(UUID taxonUuid
, UUID classificationUuid
,
313 boolean includeUnpublished
, Integer pageSize
, Integer pageIndex
, List
<String
> propertyPaths
){
315 Classification classification
= dao
.load(classificationUuid
);
316 Taxon taxon
= (Taxon
) taxonDao
.load(taxonUuid
);
318 List
<TaxonNode
> results
= dao
.listChildrenOf(
319 taxon
, classification
, includeUnpublished
, pageSize
, pageIndex
, propertyPaths
);
320 Collections
.sort(results
, taxonNodeComparator
); // FIXME this is only a HACK, order during the hibernate query in the dao
325 public Pager
<TaxonNode
> pageSiblingsOfTaxon(UUID taxonUuid
, UUID classificationUuid
, boolean includeUnpublished
,
326 Integer pageSize
, Integer pageIndex
, List
<String
> propertyPaths
){
328 Classification classification
= dao
.load(classificationUuid
);
329 Taxon taxon
= (Taxon
) taxonDao
.load(taxonUuid
);
331 long numberOfResults
= dao
.countSiblingsOf(taxon
, classification
, includeUnpublished
);
333 List
<TaxonNode
> results
;
334 if(PagerUtils
.hasResultsInRange(numberOfResults
, pageIndex
, pageSize
)) {
335 results
= dao
.listSiblingsOf(taxon
, classification
, includeUnpublished
, pageSize
, pageIndex
, propertyPaths
);
336 Collections
.sort(results
, taxonNodeComparator
); // FIXME this is only a HACK, order during the hibernate query in the dao
338 results
= new ArrayList
<>();
341 return new DefaultPagerImpl
<TaxonNode
>(pageIndex
, numberOfResults
, pageSize
, results
);
345 public List
<TaxonNode
> listSiblingsOfTaxon(UUID taxonUuid
, UUID classificationUuid
, boolean includeUnpublished
,
346 Integer pageSize
, Integer pageIndex
, List
<String
> propertyPaths
){
348 Pager
<TaxonNode
> pager
= pageSiblingsOfTaxon(taxonUuid
, classificationUuid
, includeUnpublished
, pageSize
, pageIndex
, propertyPaths
);
349 return pager
.getRecords();
353 public ITaxonTreeNode
getTreeNodeByUuid(UUID uuid
){
354 ITaxonTreeNode treeNode
= taxonNodeDao
.findByUuid(uuid
);
355 if(treeNode
== null){
356 treeNode
= dao
.findByUuid(uuid
);
363 public TaxonNode
getRootNode(UUID classificationUuid
){
364 return dao
.getRootNode(classificationUuid
);
368 public List
<Classification
> listClassifications(Integer limit
, Integer start
, List
<OrderHint
> orderHints
, List
<String
> propertyPaths
) {
369 return dao
.list(limit
, start
, orderHints
, propertyPaths
);
373 public UUID
removeTaxonNode(TaxonNode taxonNode
) {
374 return taxonNodeDao
.delete(taxonNode
);
377 public UUID
removeTreeNode(ITaxonTreeNode treeNode
) {
378 if(treeNode
instanceof Classification
){
379 return dao
.delete((Classification
) treeNode
);
380 }else if(treeNode
instanceof TaxonNode
){
381 return taxonNodeDao
.delete((TaxonNode
)treeNode
);
386 public UUID
saveTaxonNode(TaxonNode taxonNode
) {
387 return taxonNodeDao
.save(taxonNode
).getUuid();
391 public Map
<UUID
, TaxonNode
> saveTaxonNodeAll(
392 Collection
<TaxonNode
> taxonNodeCollection
) {
393 return taxonNodeDao
.saveAll(taxonNodeCollection
);
397 public UUID
saveClassification(Classification classification
) {
399 taxonNodeDao
.saveOrUpdateAll(classification
.getAllNodes());
400 UUID result
=dao
.saveOrUpdate(classification
);
405 public UUID
saveTreeNode(ITaxonTreeNode treeNode
) {
406 if(treeNode
instanceof Classification
){
407 return dao
.save((Classification
) treeNode
).getUuid();
408 }else if(treeNode
instanceof TaxonNode
){
409 return taxonNodeDao
.save((TaxonNode
)treeNode
).getUuid();
415 public List
<TaxonNode
> getAllNodes(){
416 return taxonNodeDao
.list(null,null);
420 public List
<UuidAndTitleCache
<TaxonNode
>> getTaxonNodeUuidAndTitleCacheOfAcceptedTaxaByClassification(UUID classificationUuid
, Integer limit
, String pattern
, boolean searchForClassifications
) {
421 return taxonNodeDao
.getTaxonNodeUuidAndTitleCacheOfAcceptedTaxaByClassification(dao
.load(classificationUuid
), limit
, pattern
, searchForClassifications
);
425 public List
<UuidAndTitleCache
<TaxonNode
>> getTaxonNodeUuidAndTitleCacheOfAcceptedTaxaByClassification(Classification classification
, Integer limit
, String pattern
, boolean searchForClassifications
) {
426 return taxonNodeDao
.getTaxonNodeUuidAndTitleCacheOfAcceptedTaxaByClassification(classification
, limit
, pattern
, searchForClassifications
);
430 public List
<UuidAndTitleCache
<TaxonNode
>> getTaxonNodeUuidAndTitleCacheOfAcceptedTaxaByClassification(UUID classificationUuid
, boolean searchForClassifications
) {
431 return taxonNodeDao
.getTaxonNodeUuidAndTitleCacheOfAcceptedTaxaByClassification(dao
.load(classificationUuid
), null, null, searchForClassifications
);
435 public List
<UuidAndTitleCache
<TaxonNode
>> getTaxonNodeUuidAndTitleCacheOfAcceptedTaxaByClassification(Classification classification
, boolean searchForClassifications
) {
436 return taxonNodeDao
.getTaxonNodeUuidAndTitleCacheOfAcceptedTaxaByClassification(classification
, null, null, searchForClassifications
);
440 public List
<UuidAndTitleCache
<Classification
>> getUuidAndTitleCache(Integer limit
, String pattern
) {
441 return dao
.getUuidAndTitleCache(limit
, pattern
);
445 public Map
<UUID
, List
<MediaRepresentation
>> getAllMediaForChildNodes(
446 TaxonNode taxonNode
, List
<String
> propertyPaths
, int size
,
447 int height
, int widthOrDuration
, String
[] mimeTypes
) {
449 TreeMap
<UUID
, List
<MediaRepresentation
>> result
= new TreeMap
<UUID
, List
<MediaRepresentation
>>();
450 List
<Media
> taxonMedia
= new ArrayList
<Media
>();
451 List
<MediaRepresentation
> mediaRepresentations
= new ArrayList
<MediaRepresentation
>();
453 //add all media of the children to the result map
454 if (taxonNode
!= null){
456 List
<TaxonNode
> nodes
= new ArrayList
<TaxonNode
>();
458 nodes
.add(loadTaxonNode(taxonNode
, propertyPaths
));
459 nodes
.addAll(loadChildNodesOfTaxonNode(taxonNode
, propertyPaths
));
462 for(TaxonNode node
: nodes
){
463 Taxon taxon
= node
.getTaxon();
464 for (TaxonDescription taxonDescription
: taxon
.getDescriptions()){
465 for (DescriptionElementBase descriptionElement
: taxonDescription
.getElements()){
466 for(Media media
: descriptionElement
.getMedia()){
467 taxonMedia
.add(media
);
469 //find the best matching representation
470 mediaRepresentations
.add(MediaUtils
.findBestMatchingRepresentation(media
,null, size
, height
, widthOrDuration
, mimeTypes
));
475 result
.put(taxon
.getUuid(), mediaRepresentations
);
488 @Transactional(readOnly
= false)
489 public void updateTitleCache(Class
<?
extends Classification
> clazz
, Integer stepSize
, IIdentifiableEntityCacheStrategy
<Classification
> cacheStrategy
, IProgressMonitor monitor
) {
491 clazz
= Classification
.class;
493 super.updateTitleCacheImpl(clazz
, stepSize
, cacheStrategy
, monitor
);
498 * @param allNodesOfClassification
499 * @return null - if allNodesOfClassification is empty <br>
502 private Map
<String
, List
<TaxonNode
>> getSortedGenusList(Collection
<TaxonNode
> allNodesOfClassification
){
504 if(allNodesOfClassification
== null || allNodesOfClassification
.isEmpty()){
507 Map
<String
, List
<TaxonNode
>> sortedGenusMap
= new HashMap
<>();
508 for(TaxonNode node
:allNodesOfClassification
){
509 final TaxonNode tn
= node
;
510 Taxon taxon
= node
.getTaxon();
511 INonViralName name
= taxon
.getName();
512 String genusOrUninomial
= name
.getGenusOrUninomial();
513 //if rank unknown split string and take first word
514 if(genusOrUninomial
== null){
515 String titleCache
= taxon
.getTitleCache();
516 String
[] split
= titleCache
.split("\\s+");
518 genusOrUninomial
= s
;
522 //if node has children
524 //retrieve list from map if not create List
525 if(sortedGenusMap
.containsKey(genusOrUninomial
)){
526 List
<TaxonNode
> list
= sortedGenusMap
.get(genusOrUninomial
);
528 sortedGenusMap
.put(genusOrUninomial
, list
);
530 //create List for genus
531 List
<TaxonNode
> list
= new ArrayList
<TaxonNode
>();
533 sortedGenusMap
.put(genusOrUninomial
, list
);
536 return sortedGenusMap
;
541 * creates new Classification and parent TaxonNodes at genus level
544 * @param map GenusMap which holds a name (Genus) and all the same Taxa as a list
545 * @param classification you want to improve the hierarchy (will not be modified)
546 * @param configurator to change certain settings, if null then standard settings will be taken
547 * @return new classification with parentNodes for each entry in the map
549 @SuppressWarnings({ "unchecked" })
550 @Transactional(readOnly
= false)
552 public UpdateResult
createHierarchyInClassification(Classification classification
, CreateHierarchyForClassificationConfigurator configurator
){
553 UpdateResult result
= new UpdateResult();
554 classification
= dao
.findByUuid(classification
.getUuid());
555 Map
<String
, List
<TaxonNode
>> map
= getSortedGenusList(classification
.getAllNodes());
557 final String APPENDIX
= "repaired";
558 String titleCache
= StringUtils
.isBlank(classification
.getTitleCache()) ?
" " : classification
.getTitleCache() ;
559 //TODO classification clone???
560 Classification newClassification
= Classification
.NewInstance(titleCache
+" "+ APPENDIX
);
561 newClassification
.setReference(classification
.getReference());
563 for(Map
.Entry
<String
, List
<TaxonNode
>> entry
:map
.entrySet()){
564 String genus
= entry
.getKey();
565 List
<TaxonNode
> listOfTaxonNodes
= entry
.getValue();
566 TaxonNode parentNode
= null;
567 //Search for genus in list
568 for(TaxonNode tNode
:listOfTaxonNodes
){
569 //take that taxonNode as parent and remove from list with all it possible children
571 TaxonName name
= tNode
.getTaxon().getName();
572 if(name
.getNameCache().equalsIgnoreCase(genus
)){
573 TaxonNode clone
= (TaxonNode
) tNode
.clone();
574 if(!tNode
.hasChildNodes()){
575 //FIXME remove classification
576 // parentNode = newClassification.addChildNode(clone, 0, classification.getCitation(), classification.getMicroReference());
577 parentNode
= newClassification
.addChildNode(clone
, 0, clone
.getReference(), clone
.getMicroReference());
578 //remove taxonNode from list because just added to classification
579 result
.addUpdatedObject(tNode
);
580 listOfTaxonNodes
.remove(tNode
);
583 //save prior Hierarchy and remove them from the list
584 List
<TaxonNode
> copyAllChildrenToTaxonNode
= copyAllChildrenToTaxonNode(tNode
, clone
, result
);
585 // parentNode = newClassification.addChildNode(clone, 0, classification.getCitation(), classification.getMicroReference());
586 //FIXME remove classification
587 parentNode
= newClassification
.addChildNode(clone
, 0, clone
.getReference(), clone
.getMicroReference());
588 //remove taxonNode from list because just added to classification
589 result
.addUpdatedObject(tNode
);
590 listOfTaxonNodes
.remove(tNode
);
591 if(copyAllChildrenToTaxonNode
!= null){
592 listOfTaxonNodes
= (List
<TaxonNode
>) CollectionUtils
.removeAll(listOfTaxonNodes
, copyAllChildrenToTaxonNode
);
598 if(parentNode
== null){
599 //if no match found in list, create parentNode
600 NonViralNameParserImpl parser
= NonViralNameParserImpl
.NewInstance();
601 TaxonName TaxonName
= (TaxonName
)parser
.parseFullName(genus
);
602 //TODO Sec via configurator
603 Taxon taxon
= Taxon
.NewInstance(TaxonName
, null);
604 parentNode
= newClassification
.addChildTaxon(taxon
, 0, null, null);
605 result
.addUpdatedObject(parentNode
);
607 //iterate over the rest of the list
608 for(TaxonNode tn
: listOfTaxonNodes
){
609 //if TaxonNode has a parent and this is not the classification then skip it
610 //and add to new classification via the parentNode as children of it
611 //this should assures to keep the already existing hierarchy
612 //FIXME: Assert is not rootnode --> entrypoint is not classification in future but rather rootNode
614 if(!tn
.isTopmostNode()){
615 continue; //skip to next taxonNode
618 TaxonNode clone
= (TaxonNode
) tn
.clone();
619 //FIXME: citation from node
620 //TODO: addchildNode without citation and references
621 // TaxonNode taxonNode = parentNode.addChildNode(clone, classification.getCitation(), classification.getMicroReference());
622 TaxonNode taxonNode
= parentNode
.addChildNode(clone
, clone
.getReference(), clone
.getMicroReference());
623 result
.addUnChangedObject(clone
);
624 if(tn
.hasChildNodes()){
625 //save hierarchy in new classification
626 List
<TaxonNode
> copyAllChildrenToTaxonNode
= copyAllChildrenToTaxonNode(tn
, taxonNode
, result
);
627 if(copyAllChildrenToTaxonNode
!= null){
628 listOfTaxonNodes
= (List
<TaxonNode
>) CollectionUtils
.removeAll(listOfTaxonNodes
, copyAllChildrenToTaxonNode
);
633 dao
.saveOrUpdate(newClassification
);
634 result
.setCdmEntity(newClassification
);
640 * recursive method to get all childnodes of taxonNode in classification.
642 * @param classification just for References and Citation, can be null
643 * @param copyFromNode TaxonNode with Children
644 * @param copyToNode TaxonNode which will receive the children
645 * @return List of ChildNode which has been added. If node has no children returns null
647 private List
<TaxonNode
> copyAllChildrenToTaxonNode(TaxonNode copyFromNode
, TaxonNode copyToNode
, UpdateResult result
) {
648 List
<TaxonNode
> childNodes
;
649 if(!copyFromNode
.hasChildNodes()){
652 childNodes
= copyFromNode
.getChildNodes();
654 for(TaxonNode childNode
:childNodes
){
655 TaxonNode clone
= (TaxonNode
) childNode
.clone();
656 result
.addUnChangedObject(clone
);
657 if(childNode
.hasChildNodes()){
658 copyAllChildrenToTaxonNode(childNode
, clone
, result
);
660 //FIXME: citation from node instead of classification
661 // copyToNode.addChildNode(clone,classification.getCitation(), classification.getMicroReference());
662 copyToNode
.addChildNode(clone
, clone
.getReference(), clone
.getMicroReference());
671 public ClassificationLookupDTO
classificationLookup(Classification classification
) {
672 return dao
.classificationLookup(classification
);
678 public DeleteResult
delete(UUID classificationUuid
, TaxonDeletionConfigurator config
){
679 DeleteResult result
= new DeleteResult();
680 Classification classification
= dao
.findByUuid(classificationUuid
);
681 if (classification
== null){
682 result
.addException(new IllegalArgumentException("The classification does not exist in database."));
686 if (!classification
.hasChildNodes()){
687 dao
.delete(classification
);
688 result
.addDeletedObject(classification
);
691 if (config
.getTaxonNodeConfig().getChildHandling().equals(ChildHandling
.DELETE
)){
692 // TaxonNode root = classification.getRootNode();
693 // result.includeResult(taxonNodeService.deleteTaxonNode(HibernateProxyHelper.deproxy(root), config));
694 // result.addDeletedObject(classification);
695 dao
.delete(classification
);
696 result
.addDeletedObject(classification
);
705 public List
<GroupedTaxonDTO
> groupTaxaByHigherTaxon(List
<UUID
> originalTaxonUuids
, UUID classificationUuid
, Rank minRank
, Rank maxRank
){
706 List
<GroupedTaxonDTO
> result
= new ArrayList
<>();
708 //get treeindex for each taxonUUID
709 Map
<UUID
, TreeIndex
> taxonIdTreeIndexMap
= dao
.treeIndexForTaxonUuids(classificationUuid
, originalTaxonUuids
);
711 //build treeindex list (or tree)
712 //TODO make it work with TreeIndex or move there
713 List
<String
> treeIndexClosureStr
= new ArrayList
<>();
714 for (TreeIndex treeIndex
: taxonIdTreeIndexMap
.values()){
715 String
[] splits
= treeIndex
.toString().substring(1).split(ITreeNode
.separator
);
716 String currentIndex
= ITreeNode
.separator
;
717 for (String split
: splits
){
718 if (split
.equals("")){
721 currentIndex
+= split
+ ITreeNode
.separator
;
722 if (!treeIndexClosureStr
.contains(currentIndex
) && !split
.startsWith(ITreeNode
.treePrefix
)){
723 treeIndexClosureStr
.add(currentIndex
);
728 //get rank sortindex for all parent taxa with sortindex <= minRank and sortIndex >= maxRank (if available)
729 Integer minRankOrderIndex
= minRank
== null ?
null : minRank
.getOrderIndex();
730 Integer maxRankOrderIndex
= maxRank
== null ?
null : maxRank
.getOrderIndex();
731 List
<TreeIndex
> treeIndexClosure
= TreeIndex
.NewListInstance(treeIndexClosureStr
);
733 Map
<TreeIndex
, Integer
> treeIndexSortIndexMapTmp
= taxonNodeDao
.rankOrderIndexForTreeIndex(treeIndexClosure
, minRankOrderIndex
, maxRankOrderIndex
);
735 //remove all treeindex with "exists child in above map(and child.sortindex > xxx)
736 List
<TreeIndex
> treeIndexList
= TreeIndex
.sort(treeIndexSortIndexMapTmp
.keySet());
738 Map
<TreeIndex
, Integer
> treeIndexSortIndexMap
= new HashMap
<>();
739 TreeIndex lastTreeIndex
= null;
740 for (TreeIndex treeIndex
: treeIndexList
){
741 if (lastTreeIndex
!= null && lastTreeIndex
.hasChild(treeIndex
)){
742 treeIndexSortIndexMap
.remove(lastTreeIndex
);
744 treeIndexSortIndexMap
.put(treeIndex
, treeIndexSortIndexMapTmp
.get(treeIndex
));
745 lastTreeIndex
= treeIndex
;
748 //get taxonID for treeIndexes
749 Map
<TreeIndex
, UuidAndTitleCache
<?
>> treeIndexTaxonIdMap
= taxonNodeDao
.taxonUuidsForTreeIndexes(treeIndexSortIndexMap
.keySet());
752 for (UUID originalTaxonUuid
: originalTaxonUuids
){
753 GroupedTaxonDTO item
= new GroupedTaxonDTO();
755 item
.setTaxonUuid(originalTaxonUuid
);
756 TreeIndex groupTreeIndex
= taxonIdTreeIndexMap
.get(originalTaxonUuid
);
757 String groupIndexX
= TreeIndex
.toString(groupTreeIndex
);
758 while (groupTreeIndex
!= null){
759 if (treeIndexTaxonIdMap
.get(groupTreeIndex
) != null){
760 UuidAndTitleCache
<?
> uuidAndLabel
= treeIndexTaxonIdMap
.get(groupTreeIndex
);
761 item
.setGroupTaxonUuid(uuidAndLabel
.getUuid());
762 item
.setGroupTaxonName(uuidAndLabel
.getTitleCache());
765 groupTreeIndex
= groupTreeIndex
.parent();
766 // int index = groupIndex.substring(0, groupIndex.length()-1).lastIndexOf(ITreeNode.separator);
767 // groupIndex = index < 0 ? null : groupIndex.substring(0, index+1);
779 public List
<GroupedTaxonDTO
> groupTaxaByMarkedParents(List
<UUID
> originalTaxonUuids
, UUID classificationUuid
,
780 MarkerType markerType
, Boolean flag
) {
782 List
<GroupedTaxonDTO
> result
= new ArrayList
<>();
784 //get treeindex for each taxonUUID
785 Map
<UUID
, TreeIndex
> taxonIdTreeIndexMap
= dao
.treeIndexForTaxonUuids(classificationUuid
, originalTaxonUuids
);
787 //get all marked tree indexes
788 Set
<TreeIndex
> markedTreeIndexes
= dao
.getMarkedTreeIndexes(markerType
, flag
);
791 Map
<TreeIndex
, TreeIndex
> groupedMap
= TreeIndex
.group(markedTreeIndexes
, taxonIdTreeIndexMap
.values());
792 Set
<TreeIndex
> notNullGroups
= new HashSet
<>(groupedMap
.values());
793 notNullGroups
.remove(null);
795 //get taxonInfo for treeIndexes
796 Map
<TreeIndex
, UuidAndTitleCache
<?
>> treeIndexTaxonIdMap
= taxonNodeDao
.taxonUuidsForTreeIndexes(notNullGroups
);
799 for (UUID originalTaxonUuid
: originalTaxonUuids
){
800 GroupedTaxonDTO item
= new GroupedTaxonDTO();
802 item
.setTaxonUuid(originalTaxonUuid
);
804 TreeIndex toBeGroupedTreeIndex
= taxonIdTreeIndexMap
.get(originalTaxonUuid
);
805 TreeIndex groupTreeIndex
= groupedMap
.get(toBeGroupedTreeIndex
);
806 UuidAndTitleCache
<?
> uuidAndLabel
= treeIndexTaxonIdMap
.get(groupTreeIndex
);
807 if (uuidAndLabel
!= null){
808 item
.setGroupTaxonUuid(uuidAndLabel
.getUuid());
809 item
.setGroupTaxonName(uuidAndLabel
.getTitleCache());
820 public UUID
getTaxonNodeUuidByTaxonUuid(UUID classificationUuid
, UUID taxonUuid
) {
821 Map
<UUID
, UUID
> map
= dao
.getTaxonNodeUuidByTaxonUuid(classificationUuid
, Arrays
.asList(taxonUuid
));
822 UUID taxonNodeUuid
= map
.get(taxonUuid
);
823 return taxonNodeUuid
;
830 public TaxonInContextDTO
getTaxonInContext(UUID classificationUuid
, UUID taxonBaseUuid
,
831 Boolean doChildren
, Boolean doSynonyms
, boolean includeUnpublished
, List
<UUID
> ancestorMarkers
,
832 NodeSortMode sortMode
) {
833 TaxonInContextDTO result
= new TaxonInContextDTO();
835 TaxonBase
<?
> taxonBase
= taxonDao
.load(taxonBaseUuid
);
836 if (taxonBase
== null){
837 throw new EntityNotFoundException("Taxon with uuid " + taxonBaseUuid
+ " not found in datasource");
839 boolean isSynonym
= false;
841 if (taxonBase
.isInstanceOf(Synonym
.class)){
843 Synonym synonym
= CdmBase
.deproxy(taxonBase
, Synonym
.class);
844 acceptedTaxon
= synonym
.getAcceptedTaxon();
845 if (acceptedTaxon
== null) {
846 throw new EntityNotFoundException("Accepted taxon not found for synonym" );
848 TaxonStatus taxonStatus
= TaxonStatus
.Synonym
;
849 if (synonym
.getName()!= null && acceptedTaxon
.getName() != null
850 && synonym
.getName().getHomotypicalGroup().equals(acceptedTaxon
.getName().getHomotypicalGroup())){
851 taxonStatus
= TaxonStatus
.SynonymObjective
;
853 result
.setTaxonStatus(taxonStatus
);
856 acceptedTaxon
= CdmBase
.deproxy(taxonBase
, Taxon
.class);
857 result
.setTaxonStatus(TaxonStatus
.Accepted
);
859 UUID acceptedTaxonUuid
= acceptedTaxon
.getUuid();
861 UUID taxonNodeUuid
= getTaxonNodeUuidByTaxonUuid(classificationUuid
, acceptedTaxonUuid
);
862 if (taxonNodeUuid
== null) {
863 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
);
865 result
.setTaxonNodeUuid(taxonNodeUuid
);
867 //TODO make it a dao call
868 Taxon parentTaxon
= getParentTaxon(classificationUuid
, acceptedTaxon
);
869 if (parentTaxon
!= null){
870 result
.setParentTaxonUuid(parentTaxon
.getUuid());
871 result
.setParentTaxonLabel(parentTaxon
.getTitleCache());
872 if (parentTaxon
.getName() != null){
873 result
.setParentNameLabel(parentTaxon
.getName().getTitleCache());
877 result
.setTaxonUuid(taxonBaseUuid
);
878 result
.setClassificationUuid(classificationUuid
);
879 if (taxonBase
.getSec() != null){
880 result
.setSecundumUuid(taxonBase
.getSec().getUuid());
881 result
.setSecundumLabel(taxonBase
.getSec().getTitleCache());
883 result
.setTaxonLabel(taxonBase
.getTitleCache());
885 TaxonName name
= taxonBase
.getName();
886 result
.setNameUuid(name
.getUuid());
887 result
.setNameLabel(name
.getTitleCache());
888 result
.setNameWithoutAuthor(name
.getNameCache());
889 result
.setGenusOrUninomial(name
.getGenusOrUninomial());
890 result
.setInfraGenericEpithet(name
.getInfraGenericEpithet());
891 result
.setSpeciesEpithet(name
.getSpecificEpithet());
892 result
.setInfraSpecificEpithet(name
.getInfraSpecificEpithet());
894 result
.setAuthorship(name
.getAuthorshipCache());
896 Rank rank
= name
.getRank();
898 result
.setRankUuid(rank
.getUuid());
899 String rankLabel
= rank
.getAbbreviation();
900 if (StringUtils
.isBlank(rankLabel
)){
901 rankLabel
= rank
.getLabel();
903 result
.setRankLabel(rankLabel
);
906 boolean recursive
= false;
907 Integer pageSize
= null;
908 Integer pageIndex
= null;
909 Pager
<TaxonNodeDto
> children
= taxonNodeService
.pageChildNodesDTOs(taxonNodeUuid
, recursive
, includeUnpublished
, doSynonyms
,
910 sortMode
, pageSize
, pageIndex
);
914 for (TaxonNodeDto childDto
: children
.getRecords()){
915 if (doChildren
&& childDto
.getStatus().equals(TaxonStatus
.Accepted
)){
916 EntityDTO
<Taxon
> child
= new EntityDTO
<Taxon
>(childDto
.getTaxonUuid(), childDto
.getTitleCache());
917 result
.addChild(child
);
918 }else if (doSynonyms
&& childDto
.getStatus().isSynonym()){
919 EntityDTO
<Synonym
> child
= new EntityDTO
<Synonym
>(childDto
.getTaxonUuid(), childDto
.getTitleCache());
920 result
.addSynonym(child
);
924 result
.setAcceptedTaxonUuid(acceptedTaxonUuid
);
925 String nameTitel
= acceptedTaxon
.getName() == null ?
null : acceptedTaxon
.getName().getTitleCache();
926 result
.setAcceptedTaxonLabel(acceptedTaxon
.getTitleCache());
927 result
.setAcceptedNameLabel(nameTitel
);
931 if (ancestorMarkers
!= null && !ancestorMarkers
.isEmpty()){
932 List
<DefinedTermBase
> markerTypesTerms
= termDao
.list(ancestorMarkers
, pageSize
, null, null, null);
933 List
<MarkerType
> markerTypes
= new ArrayList
<>();
934 for (DefinedTermBase
<?
> term
: markerTypesTerms
){
935 if (term
.isInstanceOf(MarkerType
.class)){
936 markerTypes
.add(CdmBase
.deproxy(term
, MarkerType
.class));
939 if (! markerTypes
.isEmpty()){
940 TaxonNode node
= taxonNodeDao
.findByUuid(taxonNodeUuid
);
941 handleAncestorsForMarkersRecursive(result
, markerTypes
, node
);
949 * @param classificationUuid
950 * @param acceptedTaxon
953 private Taxon
getParentTaxon(UUID classificationUuid
, Taxon acceptedTaxon
) {
954 if (classificationUuid
== null){
957 TaxonNode parent
= null;
958 for (TaxonNode node
: acceptedTaxon
.getTaxonNodes()){
959 if (classificationUuid
.equals(node
.getClassification().getUuid())){
960 parent
= node
.getParent();
964 return parent
.getTaxon();
974 private void handleAncestorsForMarkersRecursive(TaxonInContextDTO result
, List
<MarkerType
> markerTypes
, TaxonNode node
) {
975 for (MarkerType type
: markerTypes
){
976 Taxon taxon
= node
.getTaxon();
977 if (taxon
!= null && taxon
.hasMarker(type
, true)){
978 String label
= taxon
.getName() == null? taxon
.getTitleCache() : taxon
.getName().getTitleCache();
979 MarkedEntityDTO
<Taxon
> dto
= new MarkedEntityDTO
<>(type
, true, taxon
.getUuid(), label
);
980 result
.addMarkedAncestor(dto
);
983 TaxonNode parentNode
= node
.getParent();
984 if (parentNode
!= null){
985 handleAncestorsForMarkersRecursive(result
, markerTypes
, parentNode
);
993 public List
<UuidAndTitleCache
<TaxonNode
>> getTaxonNodeUuidAndTitleCacheOfAcceptedTaxaByClassification(
994 Classification classification
) {
995 return getTaxonNodeUuidAndTitleCacheOfAcceptedTaxaByClassification(classification
, false);
1002 public List
<UuidAndTitleCache
<TaxonNode
>> getTaxonNodeUuidAndTitleCacheOfAcceptedTaxaByClassification(
1003 UUID classificationUuid
) {
1004 return getTaxonNodeUuidAndTitleCacheOfAcceptedTaxaByClassification(classificationUuid
, false);
1011 public List
<UuidAndTitleCache
<TaxonNode
>> getTaxonNodeUuidAndTitleCacheOfAcceptedTaxaByClassification(
1012 UUID classificationUuid
, Integer limit
, String pattern
) {
1013 return getTaxonNodeUuidAndTitleCacheOfAcceptedTaxaByClassification(classificationUuid
, limit
, pattern
, false);
1020 public List
<UuidAndTitleCache
<TaxonNode
>> getTaxonNodeUuidAndTitleCacheOfAcceptedTaxaByClassification(
1021 Classification classification
, Integer limit
, String pattern
) {
1022 return getTaxonNodeUuidAndTitleCacheOfAcceptedTaxaByClassification(classification
, limit
, pattern
, false);