fix #6368 rename table and class TaxonNameBase
[cdmlib.git] / cdmlib-services / src / main / java / eu / etaxonomy / cdm / api / service / ClassificationServiceImpl.java
1 /**
2 * Copyright (C) 2007 EDIT
3 * European Distributed Institute of Taxonomy
4 * http://www.e-taxonomy.eu
5 *
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.
8 */
9
10 package eu.etaxonomy.cdm.api.service;
11
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;
20 import java.util.Map;
21 import java.util.Set;
22 import java.util.TreeMap;
23 import java.util.UUID;
24
25 import javax.persistence.EntityNotFoundException;
26
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;
33
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.HibernateProxyHelper;
47 import eu.etaxonomy.cdm.model.common.CdmBase;
48 import eu.etaxonomy.cdm.model.common.DefinedTermBase;
49 import eu.etaxonomy.cdm.model.common.ITreeNode;
50 import eu.etaxonomy.cdm.model.common.MarkerType;
51 import eu.etaxonomy.cdm.model.common.TreeIndex;
52 import eu.etaxonomy.cdm.model.description.DescriptionElementBase;
53 import eu.etaxonomy.cdm.model.description.TaxonDescription;
54 import eu.etaxonomy.cdm.model.media.Media;
55 import eu.etaxonomy.cdm.model.media.MediaRepresentation;
56 import eu.etaxonomy.cdm.model.media.MediaUtils;
57 import eu.etaxonomy.cdm.model.name.INonViralName;
58 import eu.etaxonomy.cdm.model.name.Rank;
59 import eu.etaxonomy.cdm.model.name.TaxonName;
60 import eu.etaxonomy.cdm.model.reference.Reference;
61 import eu.etaxonomy.cdm.model.taxon.Classification;
62 import eu.etaxonomy.cdm.model.taxon.ITaxonNodeComparator;
63 import eu.etaxonomy.cdm.model.taxon.ITaxonTreeNode;
64 import eu.etaxonomy.cdm.model.taxon.Synonym;
65 import eu.etaxonomy.cdm.model.taxon.Taxon;
66 import eu.etaxonomy.cdm.model.taxon.TaxonBase;
67 import eu.etaxonomy.cdm.model.taxon.TaxonNode;
68 import eu.etaxonomy.cdm.model.taxon.TaxonRelationshipType;
69 import eu.etaxonomy.cdm.persistence.dao.common.IDefinedTermDao;
70 import eu.etaxonomy.cdm.persistence.dao.initializer.IBeanInitializer;
71 import eu.etaxonomy.cdm.persistence.dao.taxon.IClassificationDao;
72 import eu.etaxonomy.cdm.persistence.dao.taxon.ITaxonDao;
73 import eu.etaxonomy.cdm.persistence.dao.taxon.ITaxonNodeDao;
74 import eu.etaxonomy.cdm.persistence.dto.ClassificationLookupDTO;
75 import eu.etaxonomy.cdm.persistence.dto.TaxonNodeDto;
76 import eu.etaxonomy.cdm.persistence.dto.TaxonStatus;
77 import eu.etaxonomy.cdm.persistence.dto.UuidAndTitleCache;
78 import eu.etaxonomy.cdm.persistence.query.OrderHint;
79 import eu.etaxonomy.cdm.strategy.cache.common.IIdentifiableEntityCacheStrategy;
80 import eu.etaxonomy.cdm.strategy.parser.NonViralNameParserImpl;
81
82 /**
83 * @author n.hoffmann
84 * @created Sep 21, 2009
85 */
86 @Service
87 @Transactional(readOnly = true)
88 public class ClassificationServiceImpl extends IdentifiableServiceBase<Classification, IClassificationDao>
89 implements IClassificationService {
90 private static final Logger logger = Logger.getLogger(ClassificationServiceImpl.class);
91
92 @Autowired
93 private ITaxonNodeDao taxonNodeDao;
94
95 @Autowired
96 private ITaxonDao taxonDao;
97
98 @Autowired
99 private ITaxonNodeService taxonNodeService;
100
101 @Autowired
102 private IDefinedTermDao termDao;
103
104 @Autowired
105 private IBeanInitializer defaultBeanInitializer;
106
107 @Override
108 @Autowired
109 protected void setDao(IClassificationDao dao) {
110 this.dao = dao;
111 }
112
113 private Comparator<? super TaxonNode> taxonNodeComparator;
114
115 @Autowired
116 public void setTaxonNodeComparator(ITaxonNodeComparator<? super TaxonNode> taxonNodeComparator){
117 this.taxonNodeComparator = (Comparator<? super TaxonNode>) taxonNodeComparator;
118 }
119
120 @Override
121 public TaxonNode loadTaxonNodeByTaxon(Taxon taxon, UUID classificationUuid, List<String> propertyPaths){
122 Classification tree = dao.load(classificationUuid);
123 TaxonNode node = tree.getNode(taxon);
124
125 return loadTaxonNode(node.getUuid(), propertyPaths);
126 }
127
128 @Override
129 @Deprecated // use loadTaxonNode(UUID, List<String>) instead
130 public TaxonNode loadTaxonNode(TaxonNode taxonNode, List<String> propertyPaths){
131 return taxonNodeDao.load(taxonNode.getUuid(), propertyPaths);
132 }
133
134 public TaxonNode loadTaxonNode(UUID taxonNodeUuid, List<String> propertyPaths){
135 return taxonNodeDao.load(taxonNodeUuid, propertyPaths);
136 }
137
138 @Override
139 @Transactional(readOnly = false)
140 public UpdateResult cloneClassification(UUID classificationUuid,
141 String name, Reference sec, TaxonRelationshipType relationshipType) {
142 UpdateResult result = new UpdateResult();
143 Classification classification = load(classificationUuid);
144 Classification clone = Classification.NewInstance(name);
145 clone.setReference(sec);
146
147 //clone taxa and taxon nodes
148 List<TaxonNode> childNodes = classification.getRootNode().getChildNodes();
149 for (TaxonNode taxonNode : childNodes) {
150 addChildTaxa(taxonNode, null, clone, relationshipType);
151 }
152 dao.saveOrUpdate(clone);
153 result.setCdmEntity(clone);
154 return result;
155 }
156
157 private void addChildTaxa(TaxonNode originalParentNode, TaxonNode cloneParentNode, Classification classification, TaxonRelationshipType relationshipType){
158 Reference reference = classification.getReference();
159 Taxon cloneTaxon = (Taxon) HibernateProxyHelper.deproxy(originalParentNode.getTaxon(), Taxon.class).clone();
160 cloneTaxon.setSec(reference);
161 String microReference = null;
162 List<TaxonNode> originalChildNodes = originalParentNode.getChildNodes();
163
164 //add relation between taxa
165 if (relationshipType != null){
166 cloneTaxon.addTaxonRelation(originalParentNode.getTaxon(), relationshipType, reference, microReference);
167 }
168
169 TaxonNode cloneChildNode = null;
170 //add taxon node to either parent node or classification (no parent node)
171 if(cloneParentNode==null){
172 cloneChildNode = classification.addChildTaxon(cloneTaxon, reference, microReference);
173 }
174 else{
175 cloneChildNode = cloneParentNode.addChildTaxon(cloneTaxon, reference, microReference);
176 }
177 taxonNodeDao.saveOrUpdate(cloneChildNode);
178 //add children
179 for (TaxonNode originalChildNode : originalChildNodes) {
180 addChildTaxa(originalChildNode, cloneChildNode, classification, relationshipType);
181 }
182 }
183
184 @Override
185 public List<TaxonNode> listRankSpecificRootNodes(Classification classification, Rank rank, Integer pageSize,
186 Integer pageIndex, List<String> propertyPaths) {
187 return pageRankSpecificRootNodes(classification, rank, pageSize, pageIndex, propertyPaths).getRecords();
188 }
189
190 @Override
191 public Pager<TaxonNode> pageRankSpecificRootNodes(Classification classification, Rank rank, Integer pageSize,
192 Integer pageIndex, List<String> propertyPaths) {
193 long[] numberOfResults = dao.countRankSpecificRootNodes(classification, rank);
194 long totalNumberOfResults = numberOfResults[0] + (numberOfResults.length > 1 ? numberOfResults[1] : 0);
195
196 List<TaxonNode> results = new ArrayList<TaxonNode>();
197
198 if (AbstractPagerImpl.hasResultsInRange(totalNumberOfResults, pageIndex, pageSize)) { // no point checking again
199 Integer limit = PagerUtils.limitFor(pageSize);
200 Integer start = PagerUtils.startFor(pageSize, pageIndex);
201
202 Integer remainingLimit = limit;
203 int[] queryIndexes = rank == null ? new int[]{0} : new int[]{0,1};
204
205 for(int queryIndex: queryIndexes) {
206 if(start != null && start > numberOfResults[queryIndex]) {
207 // start in next query with new start value
208 start = start - (int)numberOfResults[queryIndex];
209 continue;
210 }
211
212 List<TaxonNode> perQueryResults = dao.listRankSpecificRootNodes(classification, rank, remainingLimit, start, propertyPaths, queryIndex);
213 results.addAll(perQueryResults);
214 if(remainingLimit != null ){
215 remainingLimit = remainingLimit - results.size();
216 if(remainingLimit <= 0) {
217 // no need to run further queries if first query returned enough items!
218 break;
219 }
220 // start at with fist item of next query to fetch the remaining items
221 start = 0;
222 }
223 }
224 }
225 // long start_t = System.currentTimeMillis();
226 Collections.sort(results, taxonNodeComparator); // TODO is ordering during the hibernate query in the dao possible?
227 // System.err.println("service.pageRankSpecificRootNodes() - Collections.sort(results, taxonNodeComparator) " + (System.currentTimeMillis() - start_t));
228 return new DefaultPagerImpl<TaxonNode>(pageIndex, (int) totalNumberOfResults, pageSize, results);
229
230 }
231
232 /**
233 * @implements {@link IClassificationService#loadTreeBranch(TaxonNode, Rank, List)
234 * @see eu.etaxonomy.cdm.api.service.ITaxonService#loadTreeBranchTo(eu.etaxonomy.cdm.model.taxon.TaxonNode, eu.etaxonomy.cdm.model.name.Rank, java.util.List)
235 * FIXME Candidate for harmonization
236 * move to classification service
237 */
238 @Override
239 public List<TaxonNode> loadTreeBranch(TaxonNode taxonNode, Rank baseRank, List<String> propertyPaths){
240
241 TaxonNode thisNode = taxonNodeDao.load(taxonNode.getUuid(), propertyPaths);
242 List<TaxonNode> pathToRoot = new ArrayList<TaxonNode>();
243 pathToRoot.add(thisNode);
244
245 while(!thisNode.isTopmostNode()){
246 //TODO why do we need to deproxy here?
247 // without this thisNode.getParent() will return NULL in
248 // some cases (environment dependend?) even if the parent exits
249 TaxonNode parentNode = CdmBase.deproxy(thisNode, TaxonNode.class).getParent();
250
251 if(parentNode == null){
252 throw new NullPointerException("taxonNode " + thisNode + " must have a parent since it is not top most");
253 }
254 if(parentNode.getTaxon() == null){
255 throw new NullPointerException("The taxon associated with taxonNode " + parentNode + " is NULL");
256 }
257 if(parentNode.getTaxon().getName() == null){
258 throw new NullPointerException("The name of the taxon associated with taxonNode " + parentNode + " is NULL");
259 }
260
261 Rank parentNodeRank = parentNode.getTaxon().getName() == null ? null : parentNode.getTaxon().getName().getRank();
262 // stop if the next parent is higher than the baseRank
263 if(baseRank != null && parentNodeRank != null && baseRank.isLower(parentNodeRank)){
264 break;
265 }
266
267 pathToRoot.add(parentNode);
268 thisNode = parentNode;
269 }
270
271 // initialize and invert order of nodes in list
272 defaultBeanInitializer.initializeAll(pathToRoot, propertyPaths);
273 Collections.reverse(pathToRoot);
274
275 return pathToRoot;
276 }
277
278 @Override
279 public List<TaxonNode> loadTreeBranchToTaxon(Taxon taxon, Classification classification, Rank baseRank, List<String> propertyPaths){
280 Classification tree = dao.load(classification.getUuid());
281 taxon = (Taxon) taxonDao.load(taxon.getUuid());
282 TaxonNode node = tree.getNode(taxon);
283 if(node == null){
284 logger.warn("The specified taxon is not found in the given tree.");
285 return null;
286 }
287 return loadTreeBranch(node, baseRank, propertyPaths);
288 }
289
290
291 @Override
292 public List<TaxonNode> loadChildNodesOfTaxonNode(TaxonNode taxonNode,
293 List<String> propertyPaths) {
294 taxonNode = taxonNodeDao.load(taxonNode.getUuid());
295 List<TaxonNode> childNodes = new ArrayList<TaxonNode>(taxonNode.getChildNodes());
296 defaultBeanInitializer.initializeAll(childNodes, propertyPaths);
297 Collections.sort(childNodes, taxonNodeComparator);
298 return childNodes;
299 }
300
301 @Override
302 public List<TaxonNode> listChildNodesOfTaxon(UUID taxonUuid, UUID classificationUuid, Integer pageSize,
303 Integer pageIndex, List<String> propertyPaths){
304
305 Classification classification = dao.load(classificationUuid);
306 Taxon taxon = (Taxon) taxonDao.load(taxonUuid);
307
308 List<TaxonNode> results = dao.listChildrenOf(taxon, classification, pageSize, pageIndex, propertyPaths);
309 Collections.sort(results, taxonNodeComparator); // FIXME this is only a HACK, order during the hibernate query in the dao
310 return results;
311 }
312
313 @Override
314 public Pager<TaxonNode> pageSiblingsOfTaxon(UUID taxonUuid, UUID classificationUuid, Integer pageSize,
315 Integer pageIndex, List<String> propertyPaths){
316
317 Classification classification = dao.load(classificationUuid);
318 Taxon taxon = (Taxon) taxonDao.load(taxonUuid);
319
320 long numberOfResults = dao.countSiblingsOf(taxon, classification);
321
322 List<TaxonNode> results;
323 if(PagerUtils.hasResultsInRange(numberOfResults, pageIndex, pageSize)) {
324 results = dao.listSiblingsOf(taxon, classification, pageSize, pageIndex, propertyPaths);
325 Collections.sort(results, taxonNodeComparator); // FIXME this is only a HACK, order during the hibernate query in the dao
326 } else {
327 results = new ArrayList<>();
328 }
329
330 return new DefaultPagerImpl<TaxonNode>(pageIndex, numberOfResults, pageSize, results);
331 }
332
333 @Override
334 public List<TaxonNode> listSiblingsOfTaxon(UUID taxonUuid, UUID classificationUuid, Integer pageSize,
335 Integer pageIndex, List<String> propertyPaths){
336
337 Pager<TaxonNode> pager = pageSiblingsOfTaxon(taxonUuid, classificationUuid, pageSize, pageIndex, propertyPaths);
338 return pager.getRecords();
339 }
340
341 @Override
342 public TaxonNode getTaxonNodeByUuid(UUID uuid) {
343 return taxonNodeDao.findByUuid(uuid);
344 }
345
346 @Override
347 public ITaxonTreeNode getTreeNodeByUuid(UUID uuid){
348 ITaxonTreeNode treeNode = taxonNodeDao.findByUuid(uuid);
349 if(treeNode == null){
350 treeNode = dao.findByUuid(uuid);
351 }
352
353 return treeNode;
354 }
355
356 @Override
357 public TaxonNode getRootNode(UUID classificationUuid){
358 return dao.getRootNode(classificationUuid);
359 }
360
361 @Override
362 public List<Classification> listClassifications(Integer limit, Integer start, List<OrderHint> orderHints, List<String> propertyPaths) {
363 return dao.list(limit, start, orderHints, propertyPaths);
364 }
365
366 @Override
367 public UUID removeTaxonNode(TaxonNode taxonNode) {
368 return taxonNodeDao.delete(taxonNode);
369 }
370 @Override
371 public UUID removeTreeNode(ITaxonTreeNode treeNode) {
372 if(treeNode instanceof Classification){
373 return dao.delete((Classification) treeNode);
374 }else if(treeNode instanceof TaxonNode){
375 return taxonNodeDao.delete((TaxonNode)treeNode);
376 }
377 return null;
378 }
379 @Override
380 public UUID saveTaxonNode(TaxonNode taxonNode) {
381 return taxonNodeDao.save(taxonNode).getUuid();
382 }
383
384 @Override
385 public Map<UUID, TaxonNode> saveTaxonNodeAll(
386 Collection<TaxonNode> taxonNodeCollection) {
387 return taxonNodeDao.saveAll(taxonNodeCollection);
388 }
389
390 @Override
391 public UUID saveClassification(Classification classification) {
392
393 taxonNodeDao.saveOrUpdateAll(classification.getAllNodes());
394 UUID result =dao.saveOrUpdate(classification);
395 return result;
396 }
397
398 @Override
399 public UUID saveTreeNode(ITaxonTreeNode treeNode) {
400 if(treeNode instanceof Classification){
401 return dao.save((Classification) treeNode).getUuid();
402 }else if(treeNode instanceof TaxonNode){
403 return taxonNodeDao.save((TaxonNode)treeNode).getUuid();
404 }
405 return null;
406 }
407
408 @Override
409 public List<TaxonNode> getAllNodes(){
410 return taxonNodeDao.list(null,null);
411 }
412
413 @Override
414 public List<UuidAndTitleCache<TaxonNode>> getTaxonNodeUuidAndTitleCacheOfAcceptedTaxaByClassification(UUID classificationUuid, Integer limit, String pattern) {
415 return taxonDao.getTaxonNodeUuidAndTitleCacheOfAcceptedTaxaByClassification(dao.load(classificationUuid), limit, pattern);
416 }
417
418 @Override
419 public List<UuidAndTitleCache<TaxonNode>> getTaxonNodeUuidAndTitleCacheOfAcceptedTaxaByClassification(Classification classification, Integer limit, String pattern) {
420 return taxonDao.getTaxonNodeUuidAndTitleCacheOfAcceptedTaxaByClassification(classification, limit, pattern);
421 }
422
423 @Override
424 public List<UuidAndTitleCache<TaxonNode>> getTaxonNodeUuidAndTitleCacheOfAcceptedTaxaByClassification(UUID classificationUuid ) {
425 return taxonDao.getTaxonNodeUuidAndTitleCacheOfAcceptedTaxaByClassification(dao.load(classificationUuid), null, null);
426 }
427
428 @Override
429 public List<UuidAndTitleCache<TaxonNode>> getTaxonNodeUuidAndTitleCacheOfAcceptedTaxaByClassification(Classification classification ) {
430 return taxonDao.getTaxonNodeUuidAndTitleCacheOfAcceptedTaxaByClassification(classification, null, null);
431 }
432
433 @Override
434 public List<UuidAndTitleCache<Classification>> getUuidAndTitleCache(Integer limit, String pattern) {
435 return dao.getUuidAndTitleCache(limit, pattern);
436 }
437
438 @Override
439 public Map<UUID, List<MediaRepresentation>> getAllMediaForChildNodes(
440 TaxonNode taxonNode, List<String> propertyPaths, int size,
441 int height, int widthOrDuration, String[] mimeTypes) {
442
443 TreeMap<UUID, List<MediaRepresentation>> result = new TreeMap<UUID, List<MediaRepresentation>>();
444 List<Media> taxonMedia = new ArrayList<Media>();
445 List<MediaRepresentation> mediaRepresentations = new ArrayList<MediaRepresentation>();
446
447 //add all media of the children to the result map
448 if (taxonNode != null){
449
450 List<TaxonNode> nodes = new ArrayList<TaxonNode>();
451
452 nodes.add(loadTaxonNode(taxonNode, propertyPaths));
453 nodes.addAll(loadChildNodesOfTaxonNode(taxonNode, propertyPaths));
454
455 if (nodes != null){
456 for(TaxonNode node : nodes){
457 Taxon taxon = node.getTaxon();
458 for (TaxonDescription taxonDescription: taxon.getDescriptions()){
459 for (DescriptionElementBase descriptionElement: taxonDescription.getElements()){
460 for(Media media : descriptionElement.getMedia()){
461 taxonMedia.add(media);
462
463 //find the best matching representation
464 mediaRepresentations.add(MediaUtils.findBestMatchingRepresentation(media,null, size, height, widthOrDuration, mimeTypes));
465
466 }
467 }
468 }
469 result.put(taxon.getUuid(), mediaRepresentations);
470
471 }
472 }
473
474 }
475
476 return result;
477
478 }
479
480 @Override
481 public Map<UUID, List<MediaRepresentation>> getAllMediaForChildNodes(Taxon taxon, Classification taxTree, List<String> propertyPaths, int size, int height, int widthOrDuration, String[] mimeTypes){
482 TaxonNode node = taxTree.getNode(taxon);
483
484 return getAllMediaForChildNodes(node, propertyPaths, size, height, widthOrDuration, mimeTypes);
485 }
486
487 @Override
488 @Transactional(readOnly = false)
489 public void updateTitleCache(Class<? extends Classification> clazz, Integer stepSize, IIdentifiableEntityCacheStrategy<Classification> cacheStrategy, IProgressMonitor monitor) {
490 if (clazz == null){
491 clazz = Classification.class;
492 }
493 super.updateTitleCacheImpl(clazz, stepSize, cacheStrategy, monitor);
494 }
495
496 /**
497 *
498 * @param allNodesOfClassification
499 * @return null - if allNodesOfClassification is empty <br>
500 */
501
502 private Map<String, List<TaxonNode>> getSortedGenusList(Collection<TaxonNode> allNodesOfClassification){
503
504 if(allNodesOfClassification == null || allNodesOfClassification.isEmpty()){
505 return null;
506 }
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+");
517 for(String s:split){
518 genusOrUninomial = s;
519 break;
520 }
521 }
522 //if node has children
523
524 //retrieve list from map if not create List
525 if(sortedGenusMap.containsKey(genusOrUninomial)){
526 List<TaxonNode> list = sortedGenusMap.get(genusOrUninomial);
527 list.add(node);
528 sortedGenusMap.put(genusOrUninomial, list);
529 }else{
530 //create List for genus
531 List<TaxonNode> list = new ArrayList<TaxonNode>();
532 list.add(node);
533 sortedGenusMap.put(genusOrUninomial, list);
534 }
535 }
536 return sortedGenusMap;
537 }
538
539 /**
540 *
541 * creates new Classification and parent TaxonNodes at genus level
542 *
543 *
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
548 */
549 @SuppressWarnings({ "rawtypes", "unchecked" })
550 @Transactional(readOnly = false)
551 @Override
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());
556
557 final String APPENDIX = "repaired";
558 String titleCache = org.apache.commons.lang.StringUtils.isBlank(classification.getTitleCache()) ? " " : classification.getTitleCache() ;
559 //TODO classification clone???
560 Classification newClassification = Classification.NewInstance(titleCache +" "+ APPENDIX);
561 newClassification.setReference(classification.getReference());
562
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
570 //FIXME NPE for name
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);
581 }else{
582 //get all childNodes
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);
593 }
594 }
595 break;
596 }
597 }
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);
606 }
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
613
614 if(!tn.isTopmostNode()){
615 continue; //skip to next taxonNode
616 }
617
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);
629 }
630 }
631 }
632 }
633 dao.saveOrUpdate(newClassification);
634 result.setCdmEntity(newClassification);
635 return result;
636 }
637
638 /**
639 *
640 * recursive method to get all childnodes of taxonNode in classification.
641 *
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
646 */
647 private List<TaxonNode> copyAllChildrenToTaxonNode(TaxonNode copyFromNode, TaxonNode copyToNode, UpdateResult result) {
648 List<TaxonNode> childNodes;
649 if(!copyFromNode.hasChildNodes()){
650 return null;
651 }else{
652 childNodes = copyFromNode.getChildNodes();
653 }
654 for(TaxonNode childNode:childNodes){
655 TaxonNode clone = (TaxonNode) childNode.clone();
656 result.addUnChangedObject(clone);
657 if(childNode.hasChildNodes()){
658 copyAllChildrenToTaxonNode(childNode, clone, result);
659 }
660 //FIXME: citation from node instead of classification
661 // copyToNode.addChildNode(clone,classification.getCitation(), classification.getMicroReference());
662 copyToNode.addChildNode(clone, clone.getReference(), clone.getMicroReference());
663 }
664 return childNodes;
665 }
666
667 /**
668 * {@inheritDoc}
669 */
670 @Override
671 public ClassificationLookupDTO classificationLookup(Classification classification) {
672 return dao.classificationLookup(classification);
673 }
674
675
676 @Override
677 public DeleteResult delete(UUID classificationUuid, TaxonDeletionConfigurator config){
678 DeleteResult result = new DeleteResult();
679 Classification classification = dao.findByUuid(classificationUuid);
680 if (classification == null){
681 result.addException(new IllegalArgumentException("The classification does not exist in database."));
682 result.setAbort();
683 return result;
684 }
685 if (!classification.hasChildNodes()){
686 dao.delete(classification);
687 }
688 if (config.getTaxonNodeConfig().getChildHandling().equals(ChildHandling.DELETE) ){
689 TaxonNode root = classification.getRootNode();
690 taxonNodeDao.delete(root, true);
691 dao.delete(classification);
692 }
693
694
695 return result;
696 }
697
698 @Override
699 public List<GroupedTaxonDTO> groupTaxaByHigherTaxon(List<UUID> originalTaxonUuids, UUID classificationUuid, Rank minRank, Rank maxRank){
700 List<GroupedTaxonDTO> result = new ArrayList<>();
701
702 //get treeindex for each taxonUUID
703 Map<UUID, TreeIndex> taxonIdTreeIndexMap = dao.treeIndexForTaxonUuids(classificationUuid, originalTaxonUuids);
704
705 //build treeindex list (or tree)
706 //TODO make it work with TreeIndex or move there
707 List<String> treeIndexClosureStr = new ArrayList<>();
708 for (TreeIndex treeIndex : taxonIdTreeIndexMap.values()){
709 String[] splits = treeIndex.toString().substring(1).split(ITreeNode.separator);
710 String currentIndex = ITreeNode.separator;
711 for (String split : splits){
712 if (split.equals("")){
713 continue;
714 }
715 currentIndex += split + ITreeNode.separator;
716 if (!treeIndexClosureStr.contains(currentIndex) && !split.startsWith(ITreeNode.treePrefix)){
717 treeIndexClosureStr.add(currentIndex);
718 }
719 }
720 }
721
722 //get rank sortindex for all parent taxa with sortindex <= minRank and sortIndex >= maxRank (if available)
723 Integer minRankOrderIndex = minRank == null ? null : minRank.getOrderIndex();
724 Integer maxRankOrderIndex = maxRank == null ? null : maxRank.getOrderIndex();
725 List<TreeIndex> treeIndexClosure = TreeIndex.NewListInstance(treeIndexClosureStr);
726
727 Map<TreeIndex, Integer> treeIndexSortIndexMapTmp = taxonNodeDao.rankOrderIndexForTreeIndex(treeIndexClosure, minRankOrderIndex, maxRankOrderIndex);
728
729 //remove all treeindex with "exists child in above map(and child.sortindex > xxx)
730 List<TreeIndex> treeIndexList = TreeIndex.sort(treeIndexSortIndexMapTmp.keySet());
731
732 Map<TreeIndex, Integer> treeIndexSortIndexMap = new HashMap<>();
733 TreeIndex lastTreeIndex = null;
734 for (TreeIndex treeIndex : treeIndexList){
735 if (lastTreeIndex != null && lastTreeIndex.hasChild(treeIndex)){
736 treeIndexSortIndexMap.remove(lastTreeIndex);
737 }
738 treeIndexSortIndexMap.put(treeIndex, treeIndexSortIndexMapTmp.get(treeIndex));
739 lastTreeIndex = treeIndex;
740 }
741
742 //get taxonID for treeIndexes
743 Map<TreeIndex, UuidAndTitleCache<?>> treeIndexTaxonIdMap = taxonNodeDao.taxonUuidsForTreeIndexes(treeIndexSortIndexMap.keySet());
744
745 //fill result list
746 for (UUID originalTaxonUuid : originalTaxonUuids){
747 GroupedTaxonDTO item = new GroupedTaxonDTO();
748 result.add(item);
749 item.setTaxonUuid(originalTaxonUuid);
750 TreeIndex groupTreeIndex = taxonIdTreeIndexMap.get(originalTaxonUuid);
751 String groupIndexX = TreeIndex.toString(groupTreeIndex);
752 while (groupTreeIndex != null){
753 if (treeIndexTaxonIdMap.get(groupTreeIndex) != null){
754 UuidAndTitleCache<?> uuidAndLabel = treeIndexTaxonIdMap.get(groupTreeIndex);
755 item.setGroupTaxonUuid(uuidAndLabel.getUuid());
756 item.setGroupTaxonName(uuidAndLabel.getTitleCache());
757 break;
758 }else{
759 groupTreeIndex = groupTreeIndex.parent();
760 // int index = groupIndex.substring(0, groupIndex.length()-1).lastIndexOf(ITreeNode.separator);
761 // groupIndex = index < 0 ? null : groupIndex.substring(0, index+1);
762 }
763 }
764 }
765
766 return result;
767 }
768
769 /**
770 * {@inheritDoc}
771 */
772 @Override
773 public List<GroupedTaxonDTO> groupTaxaByMarkedParents(List<UUID> originalTaxonUuids, UUID classificationUuid,
774 MarkerType markerType, Boolean flag) {
775
776 List<GroupedTaxonDTO> result = new ArrayList<>();
777
778 //get treeindex for each taxonUUID
779 Map<UUID, TreeIndex> taxonIdTreeIndexMap = dao.treeIndexForTaxonUuids(classificationUuid, originalTaxonUuids);
780
781 //get all marked tree indexes
782 Set<TreeIndex> markedTreeIndexes = dao.getMarkedTreeIndexes(markerType, flag);
783
784
785 Map<TreeIndex, TreeIndex> groupedMap = TreeIndex.group(markedTreeIndexes, taxonIdTreeIndexMap.values());
786 Set<TreeIndex> notNullGroups = new HashSet<>(groupedMap.values());
787 notNullGroups.remove(null);
788
789 //get taxonInfo for treeIndexes
790 Map<TreeIndex, UuidAndTitleCache<?>> treeIndexTaxonIdMap = taxonNodeDao.taxonUuidsForTreeIndexes(notNullGroups);
791
792 //fill result list
793 for (UUID originalTaxonUuid : originalTaxonUuids){
794 GroupedTaxonDTO item = new GroupedTaxonDTO();
795 result.add(item);
796 item.setTaxonUuid(originalTaxonUuid);
797
798 TreeIndex toBeGroupedTreeIndex = taxonIdTreeIndexMap.get(originalTaxonUuid);
799 TreeIndex groupTreeIndex = groupedMap.get(toBeGroupedTreeIndex);
800 UuidAndTitleCache<?> uuidAndLabel = treeIndexTaxonIdMap.get(groupTreeIndex);
801 if (uuidAndLabel != null){
802 item.setGroupTaxonUuid(uuidAndLabel.getUuid());
803 item.setGroupTaxonName(uuidAndLabel.getTitleCache());
804 }
805 }
806
807 return result;
808 }
809
810 /**
811 * {@inheritDoc}
812 */
813 @Override
814 public UUID getTaxonNodeUuidByTaxonUuid(UUID classificationUuid, UUID taxonUuid) {
815 Map<UUID, UUID> map = dao.getTaxonNodeUuidByTaxonUuid(classificationUuid, Arrays.asList(taxonUuid));
816 UUID taxonNodeUuid = map.get(taxonUuid);
817 return taxonNodeUuid;
818 }
819
820 /**
821 * {@inheritDoc}
822 */
823 @Override
824 public TaxonInContextDTO getTaxonInContext(UUID classificationUuid, UUID taxonBaseUuid,
825 Boolean doChildren, Boolean doSynonyms, List<UUID> ancestorMarkers,
826 NodeSortMode sortMode) {
827 TaxonInContextDTO result = new TaxonInContextDTO();
828
829 TaxonBase<?> taxonBase = taxonDao.load(taxonBaseUuid);
830 if (taxonBase == null){
831 throw new EntityNotFoundException("Taxon with uuid " + taxonBaseUuid + " not found in datasource");
832 }
833 boolean isSynonym = false;
834 Taxon acceptedTaxon;
835 if (taxonBase.isInstanceOf(Synonym.class)){
836 isSynonym = true;
837 Synonym synonym = CdmBase.deproxy(taxonBase, Synonym.class);
838 acceptedTaxon = synonym.getAcceptedTaxon();
839 if (acceptedTaxon == null) {
840 throw new EntityNotFoundException("Accepted taxon not found for synonym" );
841 }
842 TaxonStatus taxonStatus = TaxonStatus.Synonym;
843 if (synonym.getName()!= null && acceptedTaxon.getName() != null
844 && synonym.getName().getHomotypicalGroup().equals(acceptedTaxon.getName().getHomotypicalGroup())){
845 taxonStatus = TaxonStatus.SynonymObjective;
846 }
847 result.setTaxonStatus(taxonStatus);
848
849 }else{
850 acceptedTaxon = CdmBase.deproxy(taxonBase, Taxon.class);
851 result.setTaxonStatus(TaxonStatus.Accepted);
852 }
853 UUID acceptedTaxonUuid = acceptedTaxon.getUuid();
854
855 UUID taxonNodeUuid = getTaxonNodeUuidByTaxonUuid(classificationUuid, acceptedTaxonUuid);
856 if (taxonNodeUuid == null) {
857 throw new EntityNotFoundException("Taxon not found in classficiation with uuid " + classificationUuid + ". Either classification does not exist or does not contain taxon/synonym with uuid " + taxonBaseUuid );
858 }
859 result.setTaxonNodeUuid(taxonNodeUuid);
860
861 //TODO make it a dao call
862 Taxon parentTaxon = getParentTaxon(classificationUuid, acceptedTaxon);
863 if (parentTaxon != null){
864 result.setParentTaxonUuid(parentTaxon.getUuid());
865 result.setParentTaxonLabel(parentTaxon.getTitleCache());
866 if (parentTaxon.getName() != null){
867 result.setParentNameLabel(parentTaxon.getName().getTitleCache());
868 }
869 }
870
871
872 result.setTaxonUuid(taxonBaseUuid);
873 result.setClassificationUuid(classificationUuid);
874 if (taxonBase.getSec() != null){
875 result.setSecundumUuid(taxonBase.getSec().getUuid());
876 result.setSecundumLabel(taxonBase.getSec().getTitleCache());
877 }
878 result.setTaxonLabel(taxonBase.getTitleCache());
879
880 TaxonName<?,?> name = taxonBase.getName();
881 result.setNameUuid(name.getUuid());
882 result.setNameLabel(name.getTitleCache());
883 result.setNameWithoutAuthor(name.getNameCache());
884 result.setGenusOrUninomial(name.getGenusOrUninomial());
885 result.setInfraGenericEpithet(name.getInfraGenericEpithet());
886 result.setSpeciesEpithet(name.getSpecificEpithet());
887 result.setInfraSpecificEpithet(name.getInfraSpecificEpithet());
888
889 result.setAuthorship(name.getAuthorshipCache());
890
891 Rank rank = name.getRank();
892 if (rank != null){
893 result.setRankUuid(rank.getUuid());
894 String rankLabel = rank.getAbbreviation();
895 if (StringUtils.isBlank(rankLabel)){
896 rankLabel = rank.getLabel();
897 }
898 result.setRankLabel(rankLabel);
899 }
900
901 boolean recursive = false;
902 Integer pageSize = null;
903 Integer pageIndex = null;
904 Pager<TaxonNodeDto> children = taxonNodeService.pageChildNodesDTOs(taxonNodeUuid, recursive, doSynonyms, sortMode, pageSize, pageIndex);
905
906 //children
907 if(! isSynonym) {
908 for (TaxonNodeDto childDto : children.getRecords()){
909 if (doChildren && childDto.getStatus().equals(TaxonStatus.Accepted)){
910 EntityDTO<Taxon> child = new EntityDTO<Taxon>(childDto.getTaxonUuid(), childDto.getTitleCache());
911 result.addChild(child);
912 }else if (doSynonyms && childDto.getStatus().isSynonym()){
913 EntityDTO<Synonym> child = new EntityDTO<Synonym>(childDto.getTaxonUuid(), childDto.getTitleCache());
914 result.addSynonym(child);
915 }
916 }
917 }else{
918 result.setAcceptedTaxonUuid(acceptedTaxonUuid);
919 String nameTitel = acceptedTaxon.getName() == null ? null : acceptedTaxon.getName().getTitleCache();
920 result.setAcceptedTaxonLabel(acceptedTaxon.getTitleCache());
921 result.setAcceptedNameLabel(nameTitel);
922 }
923
924 //marked ancestors
925 if (ancestorMarkers != null && !ancestorMarkers.isEmpty()){
926 List<DefinedTermBase> markerTypesTerms = termDao.list(ancestorMarkers, pageSize, null, null, null);
927 List<MarkerType> markerTypes = new ArrayList<>();
928 for (DefinedTermBase<?> term : markerTypesTerms){
929 if (term.isInstanceOf(MarkerType.class)){
930 markerTypes.add(CdmBase.deproxy(term, MarkerType.class));
931 }
932 }
933 if (! markerTypes.isEmpty()){
934 TaxonNode node = taxonNodeDao.findByUuid(taxonNodeUuid);
935 handleAncestorsForMarkersRecursive(result, markerTypes, node);
936 }
937 }
938
939 return result;
940 }
941
942 /**
943 * @param classificationUuid
944 * @param acceptedTaxon
945 * @return
946 */
947 private Taxon getParentTaxon(UUID classificationUuid, Taxon acceptedTaxon) {
948 if (classificationUuid == null){
949 return null;
950 }
951 TaxonNode parent = null;
952 for (TaxonNode node : acceptedTaxon.getTaxonNodes()){
953 if (classificationUuid.equals(node.getClassification().getUuid())){
954 parent = node.getParent();
955 }
956 }
957 if (parent != null){
958 return parent.getTaxon();
959 }
960 return null;
961 }
962
963 /**
964 * @param result
965 * @param markerTypes
966 * @param node
967 */
968 private void handleAncestorsForMarkersRecursive(TaxonInContextDTO result, List<MarkerType> markerTypes, TaxonNode node) {
969 for (MarkerType type : markerTypes){
970 Taxon taxon = node.getTaxon();
971 if (taxon != null && taxon.hasMarker(type, true)){
972 String label = taxon.getName() == null? taxon.getTitleCache() : taxon.getName().getTitleCache();
973 MarkedEntityDTO<Taxon> dto = new MarkedEntityDTO<>(type, true, taxon.getUuid(), label);
974 result.addMarkedAncestor(dto);
975 }
976 }
977 TaxonNode parentNode = node.getParent();
978 if (parentNode != null){
979 handleAncestorsForMarkersRecursive(result, markerTypes, parentNode);
980 }
981 }
982
983
984 }