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
.UnpublishedException
;
47 import eu
.etaxonomy
.cdm
.hibernate
.HHH_9751_Util
;
48 import eu
.etaxonomy
.cdm
.hibernate
.HibernateProxyHelper
;
49 import eu
.etaxonomy
.cdm
.model
.common
.CdmBase
;
50 import eu
.etaxonomy
.cdm
.model
.common
.DefinedTermBase
;
51 import eu
.etaxonomy
.cdm
.model
.common
.ITreeNode
;
52 import eu
.etaxonomy
.cdm
.model
.common
.MarkerType
;
53 import eu
.etaxonomy
.cdm
.model
.common
.TreeIndex
;
54 import eu
.etaxonomy
.cdm
.model
.description
.DescriptionElementBase
;
55 import eu
.etaxonomy
.cdm
.model
.description
.TaxonDescription
;
56 import eu
.etaxonomy
.cdm
.model
.media
.Media
;
57 import eu
.etaxonomy
.cdm
.model
.media
.MediaRepresentation
;
58 import eu
.etaxonomy
.cdm
.model
.media
.MediaUtils
;
59 import eu
.etaxonomy
.cdm
.model
.name
.INonViralName
;
60 import eu
.etaxonomy
.cdm
.model
.name
.Rank
;
61 import eu
.etaxonomy
.cdm
.model
.name
.TaxonName
;
62 import eu
.etaxonomy
.cdm
.model
.reference
.Reference
;
63 import eu
.etaxonomy
.cdm
.model
.taxon
.Classification
;
64 import eu
.etaxonomy
.cdm
.model
.taxon
.ITaxonNodeComparator
;
65 import eu
.etaxonomy
.cdm
.model
.taxon
.ITaxonTreeNode
;
66 import eu
.etaxonomy
.cdm
.model
.taxon
.Synonym
;
67 import eu
.etaxonomy
.cdm
.model
.taxon
.Taxon
;
68 import eu
.etaxonomy
.cdm
.model
.taxon
.TaxonBase
;
69 import eu
.etaxonomy
.cdm
.model
.taxon
.TaxonNode
;
70 import eu
.etaxonomy
.cdm
.model
.taxon
.TaxonRelationshipType
;
71 import eu
.etaxonomy
.cdm
.persistence
.dao
.common
.IDefinedTermDao
;
72 import eu
.etaxonomy
.cdm
.persistence
.dao
.initializer
.IBeanInitializer
;
73 import eu
.etaxonomy
.cdm
.persistence
.dao
.taxon
.IClassificationDao
;
74 import eu
.etaxonomy
.cdm
.persistence
.dao
.taxon
.ITaxonDao
;
75 import eu
.etaxonomy
.cdm
.persistence
.dao
.taxon
.ITaxonNodeDao
;
76 import eu
.etaxonomy
.cdm
.persistence
.dto
.ClassificationLookupDTO
;
77 import eu
.etaxonomy
.cdm
.persistence
.dto
.TaxonNodeDto
;
78 import eu
.etaxonomy
.cdm
.persistence
.dto
.TaxonStatus
;
79 import eu
.etaxonomy
.cdm
.persistence
.dto
.UuidAndTitleCache
;
80 import eu
.etaxonomy
.cdm
.persistence
.query
.OrderHint
;
81 import eu
.etaxonomy
.cdm
.strategy
.cache
.common
.IIdentifiableEntityCacheStrategy
;
82 import eu
.etaxonomy
.cdm
.strategy
.parser
.NonViralNameParserImpl
;
89 @Transactional(readOnly
= true)
90 public class ClassificationServiceImpl
91 extends IdentifiableServiceBase
<Classification
, IClassificationDao
>
92 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
);
132 @Deprecated // use loadTaxonNode(UUID, List<String>) instead
133 public TaxonNode
loadTaxonNode(TaxonNode taxonNode
, List
<String
> propertyPaths
){
134 return taxonNodeDao
.load(taxonNode
.getUuid(), propertyPaths
);
137 public TaxonNode
loadTaxonNode(UUID taxonNodeUuid
, List
<String
> propertyPaths
){
138 return taxonNodeDao
.load(taxonNodeUuid
, propertyPaths
);
142 @Transactional(readOnly
= false)
143 public UpdateResult
cloneClassification(UUID classificationUuid
,
144 String name
, Reference sec
, TaxonRelationshipType relationshipType
) {
145 UpdateResult result
= new UpdateResult();
146 Classification classification
= load(classificationUuid
);
147 Classification clone
= Classification
.NewInstance(name
);
148 clone
.setReference(sec
);
150 //clone taxa and taxon nodes
151 List
<TaxonNode
> childNodes
= classification
.getRootNode().getChildNodes();
152 for (TaxonNode taxonNode
: childNodes
) {
153 addChildTaxa(taxonNode
, null, clone
, relationshipType
);
155 dao
.saveOrUpdate(clone
);
156 result
.setCdmEntity(clone
);
160 private void addChildTaxa(TaxonNode originalParentNode
, TaxonNode cloneParentNode
, Classification classification
, TaxonRelationshipType relationshipType
){
161 Reference reference
= classification
.getReference();
162 Taxon cloneTaxon
= (Taxon
) HibernateProxyHelper
.deproxy(originalParentNode
.getTaxon(), Taxon
.class).clone();
163 cloneTaxon
.setSec(reference
);
164 String microReference
= null;
165 List
<TaxonNode
> originalChildNodes
= originalParentNode
.getChildNodes();
166 HHH_9751_Util
.removeAllNull(originalChildNodes
);
168 //add relation between taxa
169 if (relationshipType
!= null){
170 cloneTaxon
.addTaxonRelation(originalParentNode
.getTaxon(), relationshipType
, reference
, microReference
);
173 TaxonNode cloneChildNode
= null;
174 //add taxon node to either parent node or classification (no parent node)
175 if(cloneParentNode
==null){
176 cloneChildNode
= classification
.addChildTaxon(cloneTaxon
, reference
, microReference
);
179 cloneChildNode
= cloneParentNode
.addChildTaxon(cloneTaxon
, reference
, microReference
);
181 taxonNodeDao
.saveOrUpdate(cloneChildNode
);
183 for (TaxonNode originalChildNode
: originalChildNodes
) {
184 addChildTaxa(originalChildNode
, cloneChildNode
, classification
, relationshipType
);
192 public List
<TaxonNode
> listRankSpecificRootNodes(Classification classification
, Rank rank
,
193 boolean includeUnpublished
, Integer pageSize
, Integer pageIndex
, List
<String
> propertyPaths
) {
194 return pageRankSpecificRootNodes(classification
, rank
, includeUnpublished
, pageSize
, pageIndex
, propertyPaths
).getRecords();
198 public Pager
<TaxonNode
> pageRankSpecificRootNodes(Classification classification
, Rank rank
,
199 boolean includeUnpublished
, Integer pageSize
, Integer pageIndex
, List
<String
> propertyPaths
) {
200 long[] numberOfResults
= dao
.countRankSpecificRootNodes(classification
, includeUnpublished
, rank
);
201 long totalNumberOfResults
= numberOfResults
[0] + (numberOfResults
.length
> 1 ? numberOfResults
[1] : 0);
203 List
<TaxonNode
> results
= new ArrayList
<>();
205 if (AbstractPagerImpl
.hasResultsInRange(totalNumberOfResults
, pageIndex
, pageSize
)) { // no point checking again
206 Integer limit
= PagerUtils
.limitFor(pageSize
);
207 Integer start
= PagerUtils
.startFor(pageSize
, pageIndex
);
209 Integer remainingLimit
= limit
;
210 int[] queryIndexes
= rank
== null ?
new int[]{0} : new int[]{0,1};
212 for(int queryIndex
: queryIndexes
) {
213 if(start
!= null && start
> numberOfResults
[queryIndex
]) {
214 // start in next query with new start value
215 start
= start
- (int)numberOfResults
[queryIndex
];
219 List
<TaxonNode
> perQueryResults
= dao
.listRankSpecificRootNodes(classification
,
220 rank
, includeUnpublished
, remainingLimit
, start
, propertyPaths
, queryIndex
);
221 results
.addAll(perQueryResults
);
222 if(remainingLimit
!= null ){
223 remainingLimit
= remainingLimit
- results
.size();
224 if(remainingLimit
<= 0) {
225 // no need to run further queries if first query returned enough items!
228 // start at with fist item of next query to fetch the remaining items
233 // long start_t = System.currentTimeMillis();
234 Collections
.sort(results
, taxonNodeComparator
); // TODO is ordering during the hibernate query in the dao possible?
235 // System.err.println("service.pageRankSpecificRootNodes() - Collections.sort(results, taxonNodeComparator) " + (System.currentTimeMillis() - start_t));
236 return new DefaultPagerImpl
<TaxonNode
>(pageIndex
, totalNumberOfResults
, pageSize
, results
);
245 public List
<TaxonNode
> loadTreeBranch(TaxonNode taxonNode
, Rank baseRank
,
246 boolean includeUnpublished
, List
<String
> propertyPaths
) throws UnpublishedException
{
248 TaxonNode thisNode
= taxonNodeDao
.load(taxonNode
.getUuid(), propertyPaths
);
249 if(baseRank
!= null){
250 baseRank
= (Rank
) termDao
.load(baseRank
.getUuid());
252 if (!includeUnpublished
&& thisNode
.getTaxon() != null && !thisNode
.getTaxon().isPublish()){
253 throw new UnpublishedException("Final taxon in tree branch is unpublished.");
256 List
<TaxonNode
> pathToRoot
= new ArrayList
<>();
257 pathToRoot
.add(thisNode
);
259 while(!thisNode
.isTopmostNode()){
260 //TODO why do we need to deproxy here?
261 // without this thisNode.getParent() will return NULL in
262 // some cases (environment dependend?) even if the parent exits
263 TaxonNode parentNode
= CdmBase
.deproxy(thisNode
).getParent();
265 if(parentNode
== null){
266 throw new NullPointerException("Taxon node " + thisNode
+ " must have a parent since it is not top most");
268 if(parentNode
.getTaxon() == null){
269 throw new NullPointerException("The taxon associated with taxon node " + parentNode
+ " is NULL");
271 if(!includeUnpublished
&& !parentNode
.getTaxon().isPublish()){
272 throw new UnpublishedException("Some taxon in tree branch is unpublished.");
274 if(parentNode
.getTaxon().getName() == null){
275 throw new NullPointerException("The name of the taxon associated with taxonNode " + parentNode
+ " is NULL");
278 Rank parentNodeRank
= (parentNode
.getTaxon().getName() == null) ?
null : parentNode
.getTaxon().getName().getRank();
279 // stop if the next parent is higher than the baseRank
280 if(baseRank
!= null && parentNodeRank
!= null && baseRank
.isLower(parentNodeRank
)){
284 pathToRoot
.add(parentNode
);
285 thisNode
= parentNode
;
288 // initialize and invert order of nodes in list
289 defaultBeanInitializer
.initializeAll(pathToRoot
, propertyPaths
);
290 Collections
.reverse(pathToRoot
);
296 public List
<TaxonNode
> loadTreeBranchToTaxon(Taxon taxon
, Classification classification
, Rank baseRank
,
297 boolean includeUnpublished
, List
<String
> propertyPaths
) throws UnpublishedException
{
299 UUID nodeUuid
= getTaxonNodeUuidByTaxonUuid(classification
.getUuid(), taxon
.getUuid());
300 TaxonNode node
= taxonNodeService
.find(nodeUuid
);
302 logger
.warn("The specified taxon is not found in the given tree.");
305 return loadTreeBranch(node
, baseRank
, includeUnpublished
, propertyPaths
);
310 public List
<TaxonNode
> loadChildNodesOfTaxonNode(TaxonNode taxonNode
,
311 List
<String
> propertyPaths
) {
312 taxonNode
= taxonNodeDao
.load(taxonNode
.getUuid());
313 List
<TaxonNode
> childNodes
= new ArrayList
<TaxonNode
>(taxonNode
.getChildNodes());
314 defaultBeanInitializer
.initializeAll(childNodes
, propertyPaths
);
315 Collections
.sort(childNodes
, taxonNodeComparator
);
320 public List
<TaxonNode
> listChildNodesOfTaxon(UUID taxonUuid
, UUID classificationUuid
,
321 boolean includeUnpublished
, Integer pageSize
, Integer pageIndex
, List
<String
> propertyPaths
){
323 Classification classification
= dao
.load(classificationUuid
);
324 Taxon taxon
= (Taxon
) taxonDao
.load(taxonUuid
);
326 List
<TaxonNode
> results
= dao
.listChildrenOf(
327 taxon
, classification
, includeUnpublished
, pageSize
, pageIndex
, propertyPaths
);
328 Collections
.sort(results
, taxonNodeComparator
); // FIXME this is only a HACK, order during the hibernate query in the dao
333 public Pager
<TaxonNode
> pageSiblingsOfTaxon(UUID taxonUuid
, UUID classificationUuid
, boolean includeUnpublished
,
334 Integer pageSize
, Integer pageIndex
, List
<String
> propertyPaths
){
336 Classification classification
= dao
.load(classificationUuid
);
337 Taxon taxon
= (Taxon
) taxonDao
.load(taxonUuid
);
339 long numberOfResults
= dao
.countSiblingsOf(taxon
, classification
, includeUnpublished
);
341 List
<TaxonNode
> results
;
342 if(PagerUtils
.hasResultsInRange(numberOfResults
, pageIndex
, pageSize
)) {
343 results
= dao
.listSiblingsOf(taxon
, classification
, includeUnpublished
, pageSize
, pageIndex
, propertyPaths
);
344 Collections
.sort(results
, taxonNodeComparator
); // FIXME this is only a HACK, order during the hibernate query in the dao
346 results
= new ArrayList
<>();
349 return new DefaultPagerImpl
<TaxonNode
>(pageIndex
, numberOfResults
, pageSize
, results
);
353 public List
<TaxonNode
> listSiblingsOfTaxon(UUID taxonUuid
, UUID classificationUuid
, boolean includeUnpublished
,
354 Integer pageSize
, Integer pageIndex
, List
<String
> propertyPaths
){
356 Pager
<TaxonNode
> pager
= pageSiblingsOfTaxon(taxonUuid
, classificationUuid
, includeUnpublished
, pageSize
, pageIndex
, propertyPaths
);
357 return pager
.getRecords();
361 public ITaxonTreeNode
getTreeNodeByUuid(UUID uuid
){
362 ITaxonTreeNode treeNode
= taxonNodeDao
.findByUuid(uuid
);
363 if(treeNode
== null){
364 treeNode
= dao
.findByUuid(uuid
);
371 public TaxonNode
getRootNode(UUID classificationUuid
){
372 return dao
.getRootNode(classificationUuid
);
376 public List
<Classification
> listClassifications(Integer limit
, Integer start
, List
<OrderHint
> orderHints
, List
<String
> propertyPaths
) {
377 return dao
.list(limit
, start
, orderHints
, propertyPaths
);
381 public UUID
removeTaxonNode(TaxonNode taxonNode
) {
382 return taxonNodeDao
.delete(taxonNode
);
385 public UUID
removeTreeNode(ITaxonTreeNode treeNode
) {
386 if(treeNode
instanceof Classification
){
387 return dao
.delete((Classification
) treeNode
);
388 }else if(treeNode
instanceof TaxonNode
){
389 return taxonNodeDao
.delete((TaxonNode
)treeNode
);
394 public UUID
saveTaxonNode(TaxonNode taxonNode
) {
395 return taxonNodeDao
.save(taxonNode
).getUuid();
399 public Map
<UUID
, TaxonNode
> saveTaxonNodeAll(
400 Collection
<TaxonNode
> taxonNodeCollection
) {
401 return taxonNodeDao
.saveAll(taxonNodeCollection
);
405 public UUID
saveClassification(Classification classification
) {
407 taxonNodeDao
.saveOrUpdateAll(classification
.getAllNodes());
408 UUID result
=dao
.saveOrUpdate(classification
);
413 public UUID
saveTreeNode(ITaxonTreeNode treeNode
) {
414 if(treeNode
instanceof Classification
){
415 return dao
.save((Classification
) treeNode
).getUuid();
416 }else if(treeNode
instanceof TaxonNode
){
417 return taxonNodeDao
.save((TaxonNode
)treeNode
).getUuid();
423 public List
<TaxonNode
> getAllNodes(){
424 return taxonNodeDao
.list(null,null);
428 public List
<UuidAndTitleCache
<TaxonNode
>> getTaxonNodeUuidAndTitleCacheOfAcceptedTaxaByClassification(UUID classificationUuid
, Integer limit
, String pattern
, boolean searchForClassifications
) {
429 return taxonNodeDao
.getTaxonNodeUuidAndTitleCacheOfAcceptedTaxaByClassification(dao
.load(classificationUuid
), limit
, pattern
, searchForClassifications
);
433 public List
<UuidAndTitleCache
<TaxonNode
>> getTaxonNodeUuidAndTitleCacheOfAcceptedTaxaByClassification(Classification classification
, Integer limit
, String pattern
, boolean searchForClassifications
) {
434 return taxonNodeDao
.getTaxonNodeUuidAndTitleCacheOfAcceptedTaxaByClassification(classification
, limit
, pattern
, searchForClassifications
);
438 public List
<UuidAndTitleCache
<TaxonNode
>> getTaxonNodeUuidAndTitleCacheOfAcceptedTaxaByClassification(UUID classificationUuid
, boolean searchForClassifications
) {
439 return taxonNodeDao
.getTaxonNodeUuidAndTitleCacheOfAcceptedTaxaByClassification(dao
.load(classificationUuid
), null, null, searchForClassifications
);
443 public List
<UuidAndTitleCache
<TaxonNode
>> getTaxonNodeUuidAndTitleCacheOfAcceptedTaxaByClassification(Classification classification
, boolean searchForClassifications
) {
444 return taxonNodeDao
.getTaxonNodeUuidAndTitleCacheOfAcceptedTaxaByClassification(classification
, null, null, searchForClassifications
);
448 public List
<UuidAndTitleCache
<Classification
>> getUuidAndTitleCache(Integer limit
, String pattern
) {
449 return dao
.getUuidAndTitleCache(limit
, pattern
);
453 public Map
<UUID
, List
<MediaRepresentation
>> getAllMediaForChildNodes(
454 TaxonNode taxonNode
, List
<String
> propertyPaths
, int size
,
455 int height
, int widthOrDuration
, String
[] mimeTypes
) {
457 TreeMap
<UUID
, List
<MediaRepresentation
>> result
= new TreeMap
<UUID
, List
<MediaRepresentation
>>();
458 List
<Media
> taxonMedia
= new ArrayList
<Media
>();
459 List
<MediaRepresentation
> mediaRepresentations
= new ArrayList
<MediaRepresentation
>();
461 //add all media of the children to the result map
462 if (taxonNode
!= null){
464 List
<TaxonNode
> nodes
= new ArrayList
<TaxonNode
>();
466 nodes
.add(loadTaxonNode(taxonNode
, propertyPaths
));
467 nodes
.addAll(loadChildNodesOfTaxonNode(taxonNode
, propertyPaths
));
470 for(TaxonNode node
: nodes
){
471 Taxon taxon
= node
.getTaxon();
472 for (TaxonDescription taxonDescription
: taxon
.getDescriptions()){
473 for (DescriptionElementBase descriptionElement
: taxonDescription
.getElements()){
474 for(Media media
: descriptionElement
.getMedia()){
475 taxonMedia
.add(media
);
477 //find the best matching representation
478 mediaRepresentations
.add(MediaUtils
.findBestMatchingRepresentation(media
,null, size
, height
, widthOrDuration
, mimeTypes
));
483 result
.put(taxon
.getUuid(), mediaRepresentations
);
496 @Transactional(readOnly
= false)
497 public void updateTitleCache(Class
<?
extends Classification
> clazz
, Integer stepSize
, IIdentifiableEntityCacheStrategy
<Classification
> cacheStrategy
, IProgressMonitor monitor
) {
499 clazz
= Classification
.class;
501 super.updateTitleCacheImpl(clazz
, stepSize
, cacheStrategy
, monitor
);
506 * @param allNodesOfClassification
507 * @return null - if allNodesOfClassification is empty <br>
510 private Map
<String
, List
<TaxonNode
>> getSortedGenusList(Collection
<TaxonNode
> allNodesOfClassification
){
512 if(allNodesOfClassification
== null || allNodesOfClassification
.isEmpty()){
515 Map
<String
, List
<TaxonNode
>> sortedGenusMap
= new HashMap
<>();
516 for(TaxonNode node
:allNodesOfClassification
){
517 final TaxonNode tn
= node
;
518 Taxon taxon
= node
.getTaxon();
519 INonViralName name
= taxon
.getName();
520 String genusOrUninomial
= name
.getGenusOrUninomial();
521 //if rank unknown split string and take first word
522 if(genusOrUninomial
== null){
523 String titleCache
= taxon
.getTitleCache();
524 String
[] split
= titleCache
.split("\\s+");
526 genusOrUninomial
= s
;
530 //if node has children
532 //retrieve list from map if not create List
533 if(sortedGenusMap
.containsKey(genusOrUninomial
)){
534 List
<TaxonNode
> list
= sortedGenusMap
.get(genusOrUninomial
);
536 sortedGenusMap
.put(genusOrUninomial
, list
);
538 //create List for genus
539 List
<TaxonNode
> list
= new ArrayList
<TaxonNode
>();
541 sortedGenusMap
.put(genusOrUninomial
, list
);
544 return sortedGenusMap
;
549 * creates new Classification and parent TaxonNodes at genus level
552 * @param map GenusMap which holds a name (Genus) and all the same Taxa as a list
553 * @param classification you want to improve the hierarchy (will not be modified)
554 * @param configurator to change certain settings, if null then standard settings will be taken
555 * @return new classification with parentNodes for each entry in the map
557 @SuppressWarnings({ "unchecked" })
558 @Transactional(readOnly
= false)
560 public UpdateResult
createHierarchyInClassification(Classification classification
, CreateHierarchyForClassificationConfigurator configurator
){
561 UpdateResult result
= new UpdateResult();
562 classification
= dao
.findByUuid(classification
.getUuid());
563 Map
<String
, List
<TaxonNode
>> map
= getSortedGenusList(classification
.getAllNodes());
565 final String APPENDIX
= "repaired";
566 String titleCache
= StringUtils
.isBlank(classification
.getTitleCache()) ?
" " : classification
.getTitleCache() ;
567 //TODO classification clone???
568 Classification newClassification
= Classification
.NewInstance(titleCache
+" "+ APPENDIX
);
569 newClassification
.setReference(classification
.getReference());
571 for(Map
.Entry
<String
, List
<TaxonNode
>> entry
:map
.entrySet()){
572 String genus
= entry
.getKey();
573 List
<TaxonNode
> listOfTaxonNodes
= entry
.getValue();
574 TaxonNode parentNode
= null;
575 //Search for genus in list
576 for(TaxonNode tNode
:listOfTaxonNodes
){
577 //take that taxonNode as parent and remove from list with all it possible children
579 TaxonName name
= tNode
.getTaxon().getName();
580 if(name
.getNameCache().equalsIgnoreCase(genus
)){
581 TaxonNode clone
= (TaxonNode
) tNode
.clone();
582 if(!tNode
.hasChildNodes()){
583 //FIXME remove classification
584 // parentNode = newClassification.addChildNode(clone, 0, classification.getCitation(), classification.getMicroReference());
585 parentNode
= newClassification
.addChildNode(clone
, 0, clone
.getReference(), clone
.getMicroReference());
586 //remove taxonNode from list because just added to classification
587 result
.addUpdatedObject(tNode
);
588 listOfTaxonNodes
.remove(tNode
);
591 //save prior Hierarchy and remove them from the list
592 List
<TaxonNode
> copyAllChildrenToTaxonNode
= copyAllChildrenToTaxonNode(tNode
, clone
, result
);
593 // parentNode = newClassification.addChildNode(clone, 0, classification.getCitation(), classification.getMicroReference());
594 //FIXME remove classification
595 parentNode
= newClassification
.addChildNode(clone
, 0, clone
.getReference(), clone
.getMicroReference());
596 //remove taxonNode from list because just added to classification
597 result
.addUpdatedObject(tNode
);
598 listOfTaxonNodes
.remove(tNode
);
599 if(copyAllChildrenToTaxonNode
!= null){
600 listOfTaxonNodes
= (List
<TaxonNode
>) CollectionUtils
.removeAll(listOfTaxonNodes
, copyAllChildrenToTaxonNode
);
606 if(parentNode
== null){
607 //if no match found in list, create parentNode
608 NonViralNameParserImpl parser
= NonViralNameParserImpl
.NewInstance();
609 TaxonName TaxonName
= (TaxonName
)parser
.parseFullName(genus
);
610 //TODO Sec via configurator
611 Taxon taxon
= Taxon
.NewInstance(TaxonName
, null);
612 parentNode
= newClassification
.addChildTaxon(taxon
, 0, null, null);
613 result
.addUpdatedObject(parentNode
);
615 //iterate over the rest of the list
616 for(TaxonNode tn
: listOfTaxonNodes
){
617 //if TaxonNode has a parent and this is not the classification then skip it
618 //and add to new classification via the parentNode as children of it
619 //this should assures to keep the already existing hierarchy
620 //FIXME: Assert is not rootnode --> entrypoint is not classification in future but rather rootNode
622 if(!tn
.isTopmostNode()){
623 continue; //skip to next taxonNode
626 TaxonNode clone
= (TaxonNode
) tn
.clone();
627 //FIXME: citation from node
628 //TODO: addchildNode without citation and references
629 // TaxonNode taxonNode = parentNode.addChildNode(clone, classification.getCitation(), classification.getMicroReference());
630 TaxonNode taxonNode
= parentNode
.addChildNode(clone
, clone
.getReference(), clone
.getMicroReference());
631 result
.addUnChangedObject(clone
);
632 if(tn
.hasChildNodes()){
633 //save hierarchy in new classification
634 List
<TaxonNode
> copyAllChildrenToTaxonNode
= copyAllChildrenToTaxonNode(tn
, taxonNode
, result
);
635 if(copyAllChildrenToTaxonNode
!= null){
636 listOfTaxonNodes
= (List
<TaxonNode
>) CollectionUtils
.removeAll(listOfTaxonNodes
, copyAllChildrenToTaxonNode
);
641 dao
.saveOrUpdate(newClassification
);
642 result
.setCdmEntity(newClassification
);
648 * recursive method to get all childnodes of taxonNode in classification.
650 * @param classification just for References and Citation, can be null
651 * @param copyFromNode TaxonNode with Children
652 * @param copyToNode TaxonNode which will receive the children
653 * @return List of ChildNode which has been added. If node has no children returns null
655 private List
<TaxonNode
> copyAllChildrenToTaxonNode(TaxonNode copyFromNode
, TaxonNode copyToNode
, UpdateResult result
) {
656 List
<TaxonNode
> childNodes
;
657 if(!copyFromNode
.hasChildNodes()){
660 childNodes
= copyFromNode
.getChildNodes();
662 for(TaxonNode childNode
:childNodes
){
663 TaxonNode clone
= (TaxonNode
) childNode
.clone();
664 result
.addUnChangedObject(clone
);
665 if(childNode
.hasChildNodes()){
666 copyAllChildrenToTaxonNode(childNode
, clone
, result
);
668 //FIXME: citation from node instead of classification
669 // copyToNode.addChildNode(clone,classification.getCitation(), classification.getMicroReference());
670 copyToNode
.addChildNode(clone
, clone
.getReference(), clone
.getMicroReference());
679 public ClassificationLookupDTO
classificationLookup(Classification classification
) {
680 return dao
.classificationLookup(classification
);
686 public DeleteResult
delete(UUID classificationUuid
, TaxonDeletionConfigurator config
){
687 DeleteResult result
= new DeleteResult();
688 Classification classification
= dao
.findByUuid(classificationUuid
);
689 if (classification
== null){
690 result
.addException(new IllegalArgumentException("The classification does not exist in database."));
694 if (!classification
.hasChildNodes()){
695 dao
.delete(classification
);
696 result
.addDeletedObject(classification
);
699 if (config
.getTaxonNodeConfig().getChildHandling().equals(ChildHandling
.DELETE
)){
700 // TaxonNode root = classification.getRootNode();
701 // result.includeResult(taxonNodeService.deleteTaxonNode(HibernateProxyHelper.deproxy(root), config));
702 // result.addDeletedObject(classification);
703 dao
.delete(classification
);
704 result
.addDeletedObject(classification
);
713 public List
<GroupedTaxonDTO
> groupTaxaByHigherTaxon(List
<UUID
> originalTaxonUuids
, UUID classificationUuid
, Rank minRank
, Rank maxRank
){
714 List
<GroupedTaxonDTO
> result
= new ArrayList
<>();
716 //get treeindex for each taxonUUID
717 Map
<UUID
, TreeIndex
> taxonIdTreeIndexMap
= dao
.treeIndexForTaxonUuids(classificationUuid
, originalTaxonUuids
);
719 //build treeindex list (or tree)
720 //TODO make it work with TreeIndex or move there
721 List
<String
> treeIndexClosureStr
= new ArrayList
<>();
722 for (TreeIndex treeIndex
: taxonIdTreeIndexMap
.values()){
723 String
[] splits
= treeIndex
.toString().substring(1).split(ITreeNode
.separator
);
724 String currentIndex
= ITreeNode
.separator
;
725 for (String split
: splits
){
726 if (split
.equals("")){
729 currentIndex
+= split
+ ITreeNode
.separator
;
730 if (!treeIndexClosureStr
.contains(currentIndex
) && !split
.startsWith(ITreeNode
.treePrefix
)){
731 treeIndexClosureStr
.add(currentIndex
);
736 //get rank sortindex for all parent taxa with sortindex <= minRank and sortIndex >= maxRank (if available)
737 Integer minRankOrderIndex
= minRank
== null ?
null : minRank
.getOrderIndex();
738 Integer maxRankOrderIndex
= maxRank
== null ?
null : maxRank
.getOrderIndex();
739 List
<TreeIndex
> treeIndexClosure
= TreeIndex
.NewListInstance(treeIndexClosureStr
);
741 Map
<TreeIndex
, Integer
> treeIndexSortIndexMapTmp
= taxonNodeDao
.rankOrderIndexForTreeIndex(treeIndexClosure
, minRankOrderIndex
, maxRankOrderIndex
);
743 //remove all treeindex with "exists child in above map(and child.sortindex > xxx)
744 List
<TreeIndex
> treeIndexList
= TreeIndex
.sort(treeIndexSortIndexMapTmp
.keySet());
746 Map
<TreeIndex
, Integer
> treeIndexSortIndexMap
= new HashMap
<>();
747 TreeIndex lastTreeIndex
= null;
748 for (TreeIndex treeIndex
: treeIndexList
){
749 if (lastTreeIndex
!= null && lastTreeIndex
.hasChild(treeIndex
)){
750 treeIndexSortIndexMap
.remove(lastTreeIndex
);
752 treeIndexSortIndexMap
.put(treeIndex
, treeIndexSortIndexMapTmp
.get(treeIndex
));
753 lastTreeIndex
= treeIndex
;
756 //get taxonID for treeIndexes
757 Map
<TreeIndex
, UuidAndTitleCache
<?
>> treeIndexTaxonIdMap
= taxonNodeDao
.taxonUuidsForTreeIndexes(treeIndexSortIndexMap
.keySet());
760 for (UUID originalTaxonUuid
: originalTaxonUuids
){
761 GroupedTaxonDTO item
= new GroupedTaxonDTO();
763 item
.setTaxonUuid(originalTaxonUuid
);
764 TreeIndex groupTreeIndex
= taxonIdTreeIndexMap
.get(originalTaxonUuid
);
765 String groupIndexX
= TreeIndex
.toString(groupTreeIndex
);
766 while (groupTreeIndex
!= null){
767 if (treeIndexTaxonIdMap
.get(groupTreeIndex
) != null){
768 UuidAndTitleCache
<?
> uuidAndLabel
= treeIndexTaxonIdMap
.get(groupTreeIndex
);
769 item
.setGroupTaxonUuid(uuidAndLabel
.getUuid());
770 item
.setGroupTaxonName(uuidAndLabel
.getTitleCache());
773 groupTreeIndex
= groupTreeIndex
.parent();
774 // int index = groupIndex.substring(0, groupIndex.length()-1).lastIndexOf(ITreeNode.separator);
775 // groupIndex = index < 0 ? null : groupIndex.substring(0, index+1);
787 public List
<GroupedTaxonDTO
> groupTaxaByMarkedParents(List
<UUID
> originalTaxonUuids
, UUID classificationUuid
,
788 MarkerType markerType
, Boolean flag
) {
790 List
<GroupedTaxonDTO
> result
= new ArrayList
<>();
792 //get treeindex for each taxonUUID
793 Map
<UUID
, TreeIndex
> taxonIdTreeIndexMap
= dao
.treeIndexForTaxonUuids(classificationUuid
, originalTaxonUuids
);
795 //get all marked tree indexes
796 Set
<TreeIndex
> markedTreeIndexes
= dao
.getMarkedTreeIndexes(markerType
, flag
);
799 Map
<TreeIndex
, TreeIndex
> groupedMap
= TreeIndex
.group(markedTreeIndexes
, taxonIdTreeIndexMap
.values());
800 Set
<TreeIndex
> notNullGroups
= new HashSet
<>(groupedMap
.values());
801 notNullGroups
.remove(null);
803 //get taxonInfo for treeIndexes
804 Map
<TreeIndex
, UuidAndTitleCache
<?
>> treeIndexTaxonIdMap
= taxonNodeDao
.taxonUuidsForTreeIndexes(notNullGroups
);
807 for (UUID originalTaxonUuid
: originalTaxonUuids
){
808 GroupedTaxonDTO item
= new GroupedTaxonDTO();
810 item
.setTaxonUuid(originalTaxonUuid
);
812 TreeIndex toBeGroupedTreeIndex
= taxonIdTreeIndexMap
.get(originalTaxonUuid
);
813 TreeIndex groupTreeIndex
= groupedMap
.get(toBeGroupedTreeIndex
);
814 UuidAndTitleCache
<?
> uuidAndLabel
= treeIndexTaxonIdMap
.get(groupTreeIndex
);
815 if (uuidAndLabel
!= null){
816 item
.setGroupTaxonUuid(uuidAndLabel
.getUuid());
817 item
.setGroupTaxonName(uuidAndLabel
.getTitleCache());
828 public UUID
getTaxonNodeUuidByTaxonUuid(UUID classificationUuid
, UUID taxonUuid
) {
829 Map
<UUID
, UUID
> map
= dao
.getTaxonNodeUuidByTaxonUuid(classificationUuid
, Arrays
.asList(taxonUuid
));
830 UUID taxonNodeUuid
= map
.get(taxonUuid
);
831 return taxonNodeUuid
;
838 public TaxonInContextDTO
getTaxonInContext(UUID classificationUuid
, UUID taxonBaseUuid
,
839 Boolean doChildren
, Boolean doSynonyms
, boolean includeUnpublished
, List
<UUID
> ancestorMarkers
,
840 NodeSortMode sortMode
) {
841 TaxonInContextDTO result
= new TaxonInContextDTO();
843 TaxonBase
<?
> taxonBase
= taxonDao
.load(taxonBaseUuid
);
844 if (taxonBase
== null){
845 throw new EntityNotFoundException("Taxon with uuid " + taxonBaseUuid
+ " not found in datasource");
847 boolean isSynonym
= false;
849 if (taxonBase
.isInstanceOf(Synonym
.class)){
851 Synonym synonym
= CdmBase
.deproxy(taxonBase
, Synonym
.class);
852 acceptedTaxon
= synonym
.getAcceptedTaxon();
853 if (acceptedTaxon
== null) {
854 throw new EntityNotFoundException("Accepted taxon not found for synonym" );
856 TaxonStatus taxonStatus
= TaxonStatus
.Synonym
;
857 if (synonym
.getName()!= null && acceptedTaxon
.getName() != null
858 && synonym
.getName().getHomotypicalGroup().equals(acceptedTaxon
.getName().getHomotypicalGroup())){
859 taxonStatus
= TaxonStatus
.SynonymObjective
;
861 result
.setTaxonStatus(taxonStatus
);
864 acceptedTaxon
= CdmBase
.deproxy(taxonBase
, Taxon
.class);
865 result
.setTaxonStatus(TaxonStatus
.Accepted
);
867 UUID acceptedTaxonUuid
= acceptedTaxon
.getUuid();
869 UUID taxonNodeUuid
= getTaxonNodeUuidByTaxonUuid(classificationUuid
, acceptedTaxonUuid
);
870 if (taxonNodeUuid
== null) {
871 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
);
873 result
.setTaxonNodeUuid(taxonNodeUuid
);
875 //TODO make it a dao call
876 Taxon parentTaxon
= getParentTaxon(classificationUuid
, acceptedTaxon
);
877 if (parentTaxon
!= null){
878 result
.setParentTaxonUuid(parentTaxon
.getUuid());
879 result
.setParentTaxonLabel(parentTaxon
.getTitleCache());
880 if (parentTaxon
.getName() != null){
881 result
.setParentNameLabel(parentTaxon
.getName().getTitleCache());
885 result
.setTaxonUuid(taxonBaseUuid
);
886 result
.setClassificationUuid(classificationUuid
);
887 if (taxonBase
.getSec() != null){
888 result
.setSecundumUuid(taxonBase
.getSec().getUuid());
889 result
.setSecundumLabel(taxonBase
.getSec().getTitleCache());
891 result
.setTaxonLabel(taxonBase
.getTitleCache());
893 TaxonName name
= taxonBase
.getName();
894 result
.setNameUuid(name
.getUuid());
895 result
.setNameLabel(name
.getTitleCache());
896 result
.setNameWithoutAuthor(name
.getNameCache());
897 result
.setGenusOrUninomial(name
.getGenusOrUninomial());
898 result
.setInfraGenericEpithet(name
.getInfraGenericEpithet());
899 result
.setSpeciesEpithet(name
.getSpecificEpithet());
900 result
.setInfraSpecificEpithet(name
.getInfraSpecificEpithet());
902 result
.setAuthorship(name
.getAuthorshipCache());
904 Rank rank
= name
.getRank();
906 result
.setRankUuid(rank
.getUuid());
907 String rankLabel
= rank
.getAbbreviation();
908 if (StringUtils
.isBlank(rankLabel
)){
909 rankLabel
= rank
.getLabel();
911 result
.setRankLabel(rankLabel
);
914 boolean recursive
= false;
915 Integer pageSize
= null;
916 Integer pageIndex
= null;
917 Pager
<TaxonNodeDto
> children
= taxonNodeService
.pageChildNodesDTOs(taxonNodeUuid
, recursive
, includeUnpublished
, doSynonyms
,
918 sortMode
, pageSize
, pageIndex
);
922 for (TaxonNodeDto childDto
: children
.getRecords()){
923 if (doChildren
&& childDto
.getStatus().equals(TaxonStatus
.Accepted
)){
924 EntityDTO
<Taxon
> child
= new EntityDTO
<Taxon
>(childDto
.getTaxonUuid(), childDto
.getTitleCache());
925 result
.addChild(child
);
926 }else if (doSynonyms
&& childDto
.getStatus().isSynonym()){
927 EntityDTO
<Synonym
> child
= new EntityDTO
<Synonym
>(childDto
.getTaxonUuid(), childDto
.getTitleCache());
928 result
.addSynonym(child
);
932 result
.setAcceptedTaxonUuid(acceptedTaxonUuid
);
933 String nameTitel
= acceptedTaxon
.getName() == null ?
null : acceptedTaxon
.getName().getTitleCache();
934 result
.setAcceptedTaxonLabel(acceptedTaxon
.getTitleCache());
935 result
.setAcceptedNameLabel(nameTitel
);
939 if (ancestorMarkers
!= null && !ancestorMarkers
.isEmpty()){
940 List
<DefinedTermBase
> markerTypesTerms
= termDao
.list(ancestorMarkers
, pageSize
, null, null, null);
941 List
<MarkerType
> markerTypes
= new ArrayList
<>();
942 for (DefinedTermBase
<?
> term
: markerTypesTerms
){
943 if (term
.isInstanceOf(MarkerType
.class)){
944 markerTypes
.add(CdmBase
.deproxy(term
, MarkerType
.class));
947 if (! markerTypes
.isEmpty()){
948 TaxonNode node
= taxonNodeDao
.findByUuid(taxonNodeUuid
);
949 handleAncestorsForMarkersRecursive(result
, markerTypes
, node
);
957 * @param classificationUuid
958 * @param acceptedTaxon
961 private Taxon
getParentTaxon(UUID classificationUuid
, Taxon acceptedTaxon
) {
962 if (classificationUuid
== null){
965 TaxonNode parent
= null;
966 for (TaxonNode node
: acceptedTaxon
.getTaxonNodes()){
967 if (classificationUuid
.equals(node
.getClassification().getUuid())){
968 parent
= node
.getParent();
972 return parent
.getTaxon();
982 private void handleAncestorsForMarkersRecursive(TaxonInContextDTO result
, List
<MarkerType
> markerTypes
, TaxonNode node
) {
983 for (MarkerType type
: markerTypes
){
984 Taxon taxon
= node
.getTaxon();
985 if (taxon
!= null && taxon
.hasMarker(type
, true)){
986 String label
= taxon
.getName() == null? taxon
.getTitleCache() : taxon
.getName().getTitleCache();
987 MarkedEntityDTO
<Taxon
> dto
= new MarkedEntityDTO
<>(type
, true, taxon
.getUuid(), label
);
988 result
.addMarkedAncestor(dto
);
991 TaxonNode parentNode
= node
.getParent();
992 if (parentNode
!= null){
993 handleAncestorsForMarkersRecursive(result
, markerTypes
, parentNode
);
1001 public List
<UuidAndTitleCache
<TaxonNode
>> getTaxonNodeUuidAndTitleCacheOfAcceptedTaxaByClassification(
1002 Classification classification
) {
1003 return getTaxonNodeUuidAndTitleCacheOfAcceptedTaxaByClassification(classification
, false);
1010 public List
<UuidAndTitleCache
<TaxonNode
>> getTaxonNodeUuidAndTitleCacheOfAcceptedTaxaByClassification(
1011 UUID classificationUuid
) {
1012 return getTaxonNodeUuidAndTitleCacheOfAcceptedTaxaByClassification(classificationUuid
, false);
1019 public List
<UuidAndTitleCache
<TaxonNode
>> getTaxonNodeUuidAndTitleCacheOfAcceptedTaxaByClassification(
1020 UUID classificationUuid
, Integer limit
, String pattern
) {
1021 return getTaxonNodeUuidAndTitleCacheOfAcceptedTaxaByClassification(classificationUuid
, limit
, pattern
, false);
1028 public List
<UuidAndTitleCache
<TaxonNode
>> getTaxonNodeUuidAndTitleCacheOfAcceptedTaxaByClassification(
1029 Classification classification
, Integer limit
, String pattern
) {
1030 return getTaxonNodeUuidAndTitleCacheOfAcceptedTaxaByClassification(classification
, limit
, pattern
, false);