Project

General

Profile

Download (49.6 KB) Statistics
| Branch: | Tag: | Revision:
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
import java.util.stream.Collectors;
25

    
26
import javax.persistence.EntityNotFoundException;
27

    
28
import org.apache.commons.collections.CollectionUtils;
29
import org.apache.commons.lang.StringUtils;
30
import org.apache.log4j.Logger;
31
import org.springframework.beans.factory.annotation.Autowired;
32
import org.springframework.stereotype.Service;
33
import org.springframework.transaction.annotation.Transactional;
34

    
35
import eu.etaxonomy.cdm.api.service.config.CreateHierarchyForClassificationConfigurator;
36
import eu.etaxonomy.cdm.api.service.config.NodeDeletionConfigurator.ChildHandling;
37
import eu.etaxonomy.cdm.api.service.config.SubtreeCloneConfigurator;
38
import eu.etaxonomy.cdm.api.service.config.TaxonDeletionConfigurator;
39
import eu.etaxonomy.cdm.api.service.dto.EntityDTO;
40
import eu.etaxonomy.cdm.api.service.dto.GroupedTaxonDTO;
41
import eu.etaxonomy.cdm.api.service.dto.MarkedEntityDTO;
42
import eu.etaxonomy.cdm.api.service.dto.TaxonInContextDTO;
43
import eu.etaxonomy.cdm.api.service.pager.Pager;
44
import eu.etaxonomy.cdm.api.service.pager.PagerUtils;
45
import eu.etaxonomy.cdm.api.service.pager.impl.AbstractPagerImpl;
46
import eu.etaxonomy.cdm.api.service.pager.impl.DefaultPagerImpl;
47
import eu.etaxonomy.cdm.common.monitor.IProgressMonitor;
48
import eu.etaxonomy.cdm.exception.FilterException;
49
import eu.etaxonomy.cdm.exception.UnpublishedException;
50
import eu.etaxonomy.cdm.hibernate.HHH_9751_Util;
51
import eu.etaxonomy.cdm.model.common.CdmBase;
52
import eu.etaxonomy.cdm.model.common.ITreeNode;
53
import eu.etaxonomy.cdm.model.common.MarkerType;
54
import eu.etaxonomy.cdm.model.common.TreeIndex;
55
import eu.etaxonomy.cdm.model.description.DescriptionElementBase;
56
import eu.etaxonomy.cdm.model.description.TaxonDescription;
57
import eu.etaxonomy.cdm.model.media.Media;
58
import eu.etaxonomy.cdm.model.media.MediaRepresentation;
59
import eu.etaxonomy.cdm.model.media.MediaUtils;
60
import eu.etaxonomy.cdm.model.name.INonViralName;
61
import eu.etaxonomy.cdm.model.name.Rank;
62
import eu.etaxonomy.cdm.model.name.TaxonName;
63
import eu.etaxonomy.cdm.model.reference.Reference;
64
import eu.etaxonomy.cdm.model.taxon.Classification;
65
import eu.etaxonomy.cdm.model.taxon.ITaxonNodeComparator;
66
import eu.etaxonomy.cdm.model.taxon.ITaxonTreeNode;
67
import eu.etaxonomy.cdm.model.taxon.Synonym;
68
import eu.etaxonomy.cdm.model.taxon.Taxon;
69
import eu.etaxonomy.cdm.model.taxon.TaxonBase;
70
import eu.etaxonomy.cdm.model.taxon.TaxonNode;
71
import eu.etaxonomy.cdm.model.taxon.TaxonRelationship;
72
import eu.etaxonomy.cdm.model.term.DefinedTermBase;
73
import eu.etaxonomy.cdm.persistence.dao.initializer.IBeanInitializer;
74
import eu.etaxonomy.cdm.persistence.dao.reference.IReferenceDao;
75
import eu.etaxonomy.cdm.persistence.dao.taxon.IClassificationDao;
76
import eu.etaxonomy.cdm.persistence.dao.taxon.ITaxonDao;
77
import eu.etaxonomy.cdm.persistence.dao.taxon.ITaxonNodeDao;
78
import eu.etaxonomy.cdm.persistence.dao.term.IDefinedTermDao;
79
import eu.etaxonomy.cdm.persistence.dto.ClassificationLookupDTO;
80
import eu.etaxonomy.cdm.persistence.dto.TaxonNodeDto;
81
import eu.etaxonomy.cdm.persistence.dto.TaxonStatus;
82
import eu.etaxonomy.cdm.persistence.dto.UuidAndTitleCache;
83
import eu.etaxonomy.cdm.persistence.query.OrderHint;
84
import eu.etaxonomy.cdm.strategy.cache.common.IIdentifiableEntityCacheStrategy;
85
import eu.etaxonomy.cdm.strategy.parser.NonViralNameParserImpl;
86

    
87
/**
88
 * @author n.hoffmann
89
 * @since Sep 21, 2009
90
 */
91
@Service
92
@Transactional(readOnly = true)
93
public class ClassificationServiceImpl
94
             extends IdentifiableServiceBase<Classification, IClassificationDao>
95
             implements IClassificationService {
96

    
97
    private static final Logger logger = Logger.getLogger(ClassificationServiceImpl.class);
98

    
99
    @Autowired
100
    private ITaxonNodeDao taxonNodeDao;
101

    
102
    @Autowired
103
    private ITaxonDao taxonDao;
104

    
105
    @Autowired
106
    private ITaxonNodeService taxonNodeService;
107

    
108
    @Autowired
109
    private IReferenceDao referenceDao;
110

    
111
    @Autowired
112
    private IDefinedTermDao termDao;
113

    
114
    @Autowired
115
    private IBeanInitializer defaultBeanInitializer;
116

    
117
    @Override
118
    @Autowired
119
    protected void setDao(IClassificationDao dao) {
120
        this.dao = dao;
121
    }
122

    
123
    private Comparator<? super TaxonNode> taxonNodeComparator;
124

    
125
    @Autowired
126
    public void setTaxonNodeComparator(ITaxonNodeComparator<? super TaxonNode> taxonNodeComparator){
127
        this.taxonNodeComparator = (Comparator<? super TaxonNode>) taxonNodeComparator;
128
    }
129

    
130
    @Override
131
    public TaxonNode loadTaxonNodeByTaxon(Taxon taxon, UUID classificationUuid, List<String> propertyPaths){
132
        Classification tree = dao.load(classificationUuid);
133
        TaxonNode node = tree.getNode(taxon);
134

    
135
        return loadTaxonNode(node.getUuid(), propertyPaths);
136
    }
137

    
138
    public TaxonNode loadTaxonNode(UUID taxonNodeUuid, List<String> propertyPaths){
139
        return taxonNodeDao.load(taxonNodeUuid, propertyPaths);
140
    }
141

    
142
    @Override
143
    @Transactional(readOnly = false)
144
    public UpdateResult cloneClassification(SubtreeCloneConfigurator config) {
145
        UpdateResult result = new UpdateResult();
146

    
147
        if (config.getSubTreeUuids().isEmpty()){
148
            return result;
149
        }
150

    
151
        //TODO error handling
152
        Reference taxonSecundum = config.isReuseTaxa() || config.isReuseTaxonSecundum() || config.getTaxonSecundumUuid() == null ?
153
                null : referenceDao.findByUuid(config.getTaxonSecundumUuid());
154
        config.setTaxonSecundum(taxonSecundum);
155

    
156
        Reference parentChildReference = config.isReuseParentChildReference() || config.getParentChildReferenceUuid() == null ?
157
                null : referenceDao.findByUuid(config.getParentChildReferenceUuid());
158
        config.setParentChildReference(parentChildReference);
159

    
160
        Reference taxonRelationshipReference = config.getRelationTypeToOldTaxon() == null ?
161
                null : referenceDao.findByUuid(config.getRelationshipReferenceUuid());
162
        config.setRelationshipReference(taxonRelationshipReference);
163

    
164
        Classification classificationClone = Classification.NewInstance(config.getClassificationName());
165

    
166
        if (config.isReuseClassificationReference()){
167
            TaxonNode anyNode = taxonNodeDao.findByUuid(config.getSubTreeUuids().iterator().next());
168
            if (anyNode != null){
169
                Reference oldClassificationRef = anyNode.getClassification().getReference();
170
                classificationClone.setReference(oldClassificationRef);
171
            }
172
        }else if (config.getClassificationReferenceUuid() != null) {
173
            Reference classificationReference = referenceDao.findByUuid(config.getClassificationReferenceUuid());
174
            classificationClone.setReference(classificationReference);
175
        }
176

    
177
    	//clone taxa and taxon nodes
178
//    	List<Integer> childNodeIds = taxonNodeService.idList(taxonNodeFilter);
179
//    	List<TaxonNode> childNodes = taxonNodeService.loadByIds(childNodeIds, null);
180
    	List<TaxonNode> rootNodes = taxonNodeService.find(config.getSubTreeUuids());
181
    	for (TaxonNode taxonNode : rootNodes) {
182
    	    addChildTaxaToClone(taxonNode, classificationClone.getRootNode(), config);
183
    	}
184
    	dao.saveOrUpdate(classificationClone);
185
    	result.setCdmEntity(classificationClone);
186
    	return result;
187
    }
188

    
189
    private void addChildTaxaToClone(TaxonNode originalParentNode, TaxonNode parentNodeClone,
190
            SubtreeCloneConfigurator config){
191

    
192
        Taxon originalTaxon = CdmBase.deproxy(originalParentNode.getTaxon());
193
        if (originalTaxon == null){
194
            for (TaxonNode originalChildChildNode : originalParentNode.getChildNodes()) {
195
                addChildTaxaToClone(originalChildChildNode, parentNodeClone, config);
196
            }
197
        }else{
198
            TaxonNode childNodeClone;
199
            String microReference = null;
200
            if (config.isReuseTaxa()){
201
                childNodeClone = parentNodeClone.addChildTaxon(originalTaxon, config.getParentChildReference(), microReference);
202
            }else{
203
                Taxon cloneTaxon = originalTaxon.clone(config.isIncludeSynonymsIncludingManAndProParte(),
204
                        config.isIncludeTaxonRelationshipsExcludingManAndProParte(),
205
                        config.isIncludeDescriptiveData(), config.isIncludeMedia());
206

    
207
                //name
208
                if (!config.isReuseNames()){
209
                    cloneTaxon.setName(cloneTaxon.getName().clone());
210
                }
211

    
212
                if (!config.isReuseTaxonSecundum()){
213
                    cloneTaxon.setSec(config.getTaxonSecundum());
214
                }
215

    
216
                //add relation between taxa
217
                if (config.getRelationTypeToOldTaxon() != null){
218
                    TaxonRelationship rel = cloneTaxon.addTaxonRelation(originalParentNode.getTaxon(), config.getRelationTypeToOldTaxon(),
219
                            config.getRelationshipReference(), microReference);
220
                    rel.setDoubtful(config.isRelationDoubtful());
221
                }
222
                childNodeClone = parentNodeClone.addChildTaxon(cloneTaxon, config.getParentChildReference(), microReference);
223
            }
224

    
225
            //probably necessary as taxon nodes do not cascade
226
            taxonNodeDao.saveOrUpdate(childNodeClone);
227
            //add children
228
            List<TaxonNode> originalChildNodes = originalParentNode.getChildNodes();
229
            HHH_9751_Util.removeAllNull(originalChildNodes);
230

    
231
            for (TaxonNode originalChildNode : originalChildNodes) {
232
                addChildTaxaToClone(originalChildNode, childNodeClone, config);
233
            }
234
        }
235
    }
236

    
237
    @Override
238
    public List<TaxonNode> listRankSpecificRootNodes(Classification classification,
239
            TaxonNode subtree, Rank rank,
240
            boolean includeUnpublished, Integer pageSize, Integer pageIndex, List<String> propertyPaths) {
241
        return pageRankSpecificRootNodes(classification, subtree, rank, includeUnpublished, pageSize, pageIndex, propertyPaths).getRecords();
242
    }
243

    
244
    @Override
245
    public List<TaxonNodeDto> listRankSpecificRootNodeDtos(Classification classification, TaxonNode subtree,
246
            Rank rank, boolean includeUnpublished, Integer pageSize, Integer pageIndex, TaxonNodeDtoSortMode sortMode,
247
            List<String> propertyPaths) {
248
        List<TaxonNode> list = listRankSpecificRootNodes(classification, subtree, rank, includeUnpublished, pageSize, pageIndex, propertyPaths);
249
        return list.stream().filter(e ->  e != null).map(e -> new TaxonNodeDto(e)).sorted(sortMode.newComparator()).collect(Collectors.toList());
250
    }
251

    
252
    @Override
253
    public Pager<TaxonNode> pageRankSpecificRootNodes(Classification classification, Rank rank,
254
            boolean includeUnpublished, Integer pageSize, Integer pageIndex, List<String> propertyPaths) {
255
        return pageRankSpecificRootNodes(classification, null, rank, includeUnpublished, pageSize, pageIndex, propertyPaths);
256
    }
257

    
258
    @Override
259
    public Pager<TaxonNode> pageRankSpecificRootNodes(Classification classification, TaxonNode subtree, Rank rank,
260
            boolean includeUnpublished, Integer pageSize, Integer pageIndex, List<String> propertyPaths) {
261
        long[] numberOfResults = dao.countRankSpecificRootNodes(classification, subtree, includeUnpublished, rank);
262
        long totalNumberOfResults = numberOfResults[0] + (numberOfResults.length > 1 ? numberOfResults[1] : 0);
263

    
264
        List<TaxonNode> results = new ArrayList<>();
265

    
266
        if (AbstractPagerImpl.hasResultsInRange(totalNumberOfResults, pageIndex, pageSize)) { // no point checking again
267
            Integer limit = PagerUtils.limitFor(pageSize);
268
            Integer start = PagerUtils.startFor(pageSize, pageIndex);
269

    
270
            Integer remainingLimit = limit;
271
            int[] queryIndexes = rank == null ? new int[]{0} : new int[]{0,1};
272

    
273
            for(int queryIndex: queryIndexes) {
274
                if(start != null && start > numberOfResults[queryIndex]) {
275
                    // start in next query with new start value
276
                    start = start - (int)numberOfResults[queryIndex];
277
                    continue;
278
                }
279

    
280
                List<TaxonNode> perQueryResults = dao.listRankSpecificRootNodes(classification,
281
                        subtree, rank, includeUnpublished, remainingLimit,
282
                        start, propertyPaths, queryIndex);
283
                results.addAll(perQueryResults);
284
                if(remainingLimit != null ){
285
                    remainingLimit = remainingLimit - results.size();
286
                    if(remainingLimit <= 0) {
287
                        // no need to run further queries if first query returned enough items!
288
                        break;
289
                    }
290
                    // start at with fist item of next query to fetch the remaining items
291
                    start = 0;
292
                }
293
            }
294
        }
295
//        long start_t = System.currentTimeMillis();
296
        Collections.sort(results, taxonNodeComparator); // TODO is ordering during the hibernate query in the dao possible?
297
//        System.err.println("service.pageRankSpecificRootNodes() - Collections.sort(results,  taxonNodeComparator) " + (System.currentTimeMillis() - start_t));
298
        return new DefaultPagerImpl<>(pageIndex, totalNumberOfResults, pageSize, results);
299

    
300
    }
301

    
302
    @Override
303
    public List<TaxonNode> loadTreeBranch(TaxonNode taxonNode, Rank baseRank,
304
            boolean includeUnpublished, List<String> propertyPaths) throws UnpublishedException{
305
        return loadTreeBranch(taxonNode, null, baseRank, includeUnpublished, propertyPaths);
306
    }
307

    
308
    @Override
309
    public List<TaxonNode> loadTreeBranch(TaxonNode taxonNode, TaxonNode subtree, Rank baseRank,
310
            boolean includeUnpublished, List<String> propertyPaths) throws UnpublishedException{
311

    
312
        TaxonNode thisNode = taxonNodeDao.load(taxonNode.getUuid(), propertyPaths);
313
        if(baseRank != null){
314
            baseRank = (Rank) termDao.load(baseRank.getUuid());
315
        }
316
        if (!includeUnpublished && thisNode.getTaxon() != null && !thisNode.getTaxon().isPublish()){
317
            throw new UnpublishedException("Final taxon in tree branch is unpublished.");
318
        }
319

    
320
        List<TaxonNode> pathToRoot = new ArrayList<>();
321
        pathToRoot.add(thisNode);
322

    
323
        while(!thisNode.isTopmostNode()){
324
            //TODO why do we need to deproxy here?
325
            //     without this thisNode.getParent() will return NULL in
326
            //     some cases (environment dependend?) even if the parent exits
327
            TaxonNode parentNode = CdmBase.deproxy(thisNode).getParent();
328

    
329
            if(parentNode == null){
330
                throw new NullPointerException("Taxon node " + thisNode + " must have a parent since it is not top most");
331
            }
332
            if(parentNode.getTaxon() == null){
333
                throw new NullPointerException("The taxon associated with taxon node " + parentNode + " is NULL");
334
            }
335
            if(!includeUnpublished && !parentNode.getTaxon().isPublish()){
336
                throw new UnpublishedException("Some taxon in tree branch is unpublished.");
337
            }
338
            if(parentNode.getTaxon().getName() == null){
339
                throw new NullPointerException("The name of the taxon associated with taxonNode " + parentNode + " is NULL");
340
            }
341

    
342
            Rank parentNodeRank = (parentNode.getTaxon().getName() == null) ? null : parentNode.getTaxon().getName().getRank();
343
            // stop if the next parent is higher than the baseRank
344
            if(baseRank != null && parentNodeRank != null && baseRank.isLower(parentNodeRank)){
345
                break;
346
            }
347
            if((subtree!= null && !subtree.isAncestor(parentNode) )){
348
                break;
349
            }
350

    
351
            pathToRoot.add(parentNode);
352
            thisNode = parentNode;
353
        }
354

    
355
        // initialize and invert order of nodes in list
356
        defaultBeanInitializer.initializeAll(pathToRoot, propertyPaths);
357
        Collections.reverse(pathToRoot);
358

    
359
        return pathToRoot;
360
    }
361

    
362
    @Override
363
    public List<TaxonNode> loadTreeBranchToTaxon(Taxon taxon, Classification classification, Rank baseRank,
364
            boolean includeUnpublished, List<String> propertyPaths) throws UnpublishedException{
365
        return loadTreeBranchToTaxon(taxon, classification, null, baseRank, includeUnpublished, propertyPaths);
366
    }
367

    
368
    @Override
369
    public List<TaxonNodeDto> loadTreeBranchDTOsToTaxon(Taxon taxon, Classification classification,
370
            TaxonNode subtree, Rank baseRank,
371
            boolean includeUnpublished, List<String> propertyPaths) throws UnpublishedException {
372
        List<TaxonNode> list = loadTreeBranchToTaxon(taxon, classification, subtree, baseRank, includeUnpublished, propertyPaths);
373
        return list.stream().map(e -> new TaxonNodeDto(e)).collect(Collectors.toList());
374
    }
375

    
376
    @Override
377
    public List<TaxonNode> loadTreeBranchToTaxon(Taxon taxon, Classification classification,
378
            TaxonNode subtree, Rank baseRank,
379
            boolean includeUnpublished, List<String> propertyPaths) throws UnpublishedException{
380

    
381
        UUID nodeUuid = getTaxonNodeUuidByTaxonUuid(classification.getUuid(), taxon.getUuid());
382
        TaxonNode node = taxonNodeService.find(nodeUuid);
383
        if(node == null){
384
            logger.warn("The specified taxon is not found in the given tree.");
385
            return null;
386
        }else if (subtree != null && !node.isDescendant(subtree)){
387
            //TODO handle as exception? E.g. FilterException, AccessDeniedException?
388
            logger.warn("The specified taxon is not found for the given subtree.");
389
            return null;
390
        }
391

    
392
        return loadTreeBranch(node, subtree, baseRank, includeUnpublished, propertyPaths);
393
    }
394

    
395

    
396
    @Override
397
    public List<TaxonNode> loadChildNodesOfTaxonNode(TaxonNode taxonNode,
398
            List<String> propertyPaths) {
399
        taxonNode = taxonNodeDao.load(taxonNode.getUuid());
400
        List<TaxonNode> childNodes = new ArrayList<TaxonNode>(taxonNode.getChildNodes());
401
        defaultBeanInitializer.initializeAll(childNodes, propertyPaths);
402
        Collections.sort(childNodes, taxonNodeComparator);
403
        return childNodes;
404
    }
405

    
406
    @Override
407
    public List<TaxonNode> listChildNodesOfTaxon(UUID taxonUuid, UUID classificationUuid,
408
            boolean includeUnpublished, Integer pageSize, Integer pageIndex, List<String> propertyPaths){
409
        try {
410
            return listChildNodesOfTaxon(taxonUuid, classificationUuid, null, includeUnpublished, pageSize, pageIndex, propertyPaths);
411
        } catch (FilterException e) {
412
            throw new RuntimeException(e);  //this should not happen as filter is null
413
        }
414
    }
415

    
416
    @Override
417
    public List<TaxonNode> listChildNodesOfTaxon(UUID taxonUuid, UUID classificationUuid, UUID subtreeUuid,
418
            boolean includeUnpublished, Integer pageSize, Integer pageIndex, List<String> propertyPaths) throws FilterException{
419

    
420
        Classification classification = dao.load(classificationUuid);
421
        Taxon taxon = (Taxon) taxonDao.load(taxonUuid);
422
        TaxonNode subtree = taxonNodeDao.load(subtreeUuid);
423
        if (subtreeUuid != null && subtree == null){
424
            throw new FilterException("Taxon node for subtree filter can not be found in database", true);
425
        }
426

    
427
        List<TaxonNode> results = dao.listChildrenOf(
428
                taxon, classification, subtree, includeUnpublished, pageSize, pageIndex, propertyPaths);
429
        Collections.sort(results, taxonNodeComparator); // FIXME this is only a HACK, order during the hibernate query in the dao
430
        return results;
431
    }
432

    
433
    @Override
434
    public List<TaxonNodeDto> listChildNodeDtosOfTaxon(UUID taxonUuid, UUID classificationUuid, UUID subtreeUuid, boolean includeUnpublished,
435
            Integer pageSize, Integer pageIndex, TaxonNodeDtoSortMode sortMode, List<String> propertyPaths) throws FilterException{
436
        Classification classification = dao.load(classificationUuid);
437
        Taxon taxon = (Taxon) taxonDao.load(taxonUuid);
438
        TaxonNode subtree = taxonNodeDao.load(subtreeUuid);
439
        if (subtreeUuid != null && subtree == null){
440
            throw new FilterException("Taxon node for subtree filter can not be found in database", true);
441
        }
442

    
443
        List<TaxonNode> results = dao.listChildrenOf(
444
                taxon, classification, subtree, includeUnpublished, pageSize, pageIndex, propertyPaths);
445
        Comparator<TaxonNodeDto> comparator = sortMode.newComparator();
446
        // TODO order during the hibernate query in the dao?
447
        List<TaxonNodeDto> dtos = results.stream().map(e -> new TaxonNodeDto(e)).sorted(comparator).collect(Collectors.toList());
448
        return dtos;
449
    }
450

    
451
    @Override
452
    public Pager<TaxonNode> pageSiblingsOfTaxon(UUID taxonUuid, UUID classificationUuid, boolean includeUnpublished,
453
            Integer pageSize, Integer pageIndex, List<String> propertyPaths){
454

    
455
        Classification classification = dao.load(classificationUuid);
456
        Taxon taxon = (Taxon) taxonDao.load(taxonUuid);
457

    
458
        long numberOfResults = dao.countSiblingsOf(taxon, classification, includeUnpublished);
459

    
460
        List<TaxonNode> results;
461
        if(PagerUtils.hasResultsInRange(numberOfResults, pageIndex, pageSize)) {
462
            results = dao.listSiblingsOf(taxon, classification, includeUnpublished, pageSize, pageIndex, propertyPaths);
463
            Collections.sort(results, taxonNodeComparator); // FIXME this is only a HACK, order during the hibernate query in the dao
464
        } else {
465
            results = new ArrayList<>();
466
        }
467

    
468
        return new DefaultPagerImpl<>(pageIndex, numberOfResults, pageSize, results);
469
    }
470

    
471
    @Override
472
    public List<TaxonNode> listSiblingsOfTaxon(UUID taxonUuid, UUID classificationUuid, boolean includeUnpublished,
473
            Integer pageSize, Integer pageIndex, List<String> propertyPaths){
474

    
475
        Pager<TaxonNode> pager = pageSiblingsOfTaxon(taxonUuid, classificationUuid, includeUnpublished, pageSize, pageIndex, propertyPaths);
476
        return pager.getRecords();
477
    }
478

    
479
    @Override
480
    public ITaxonTreeNode getTreeNodeByUuid(UUID uuid){
481
        ITaxonTreeNode treeNode = taxonNodeDao.findByUuid(uuid);
482
        if(treeNode == null){
483
            treeNode = dao.findByUuid(uuid);
484
        }
485

    
486
        return treeNode;
487
    }
488

    
489
    @Override
490
    public TaxonNode getRootNode(UUID classificationUuid){
491
        return dao.getRootNode(classificationUuid);
492
    }
493

    
494
    @Override
495
    public List<Classification> listClassifications(Integer limit, Integer start, List<OrderHint> orderHints, List<String> propertyPaths) {
496
        return dao.list(limit, start, orderHints, propertyPaths);
497
    }
498

    
499
    @Override
500
    public UUID removeTreeNode(ITaxonTreeNode treeNode) {
501
        if(treeNode instanceof Classification){
502
            return dao.delete((Classification) treeNode);
503
        }else if(treeNode instanceof TaxonNode){
504
            return taxonNodeDao.delete((TaxonNode)treeNode);
505
        }
506
        return null;
507
    }
508

    
509
    @Override
510
    public Map<UUID, TaxonNode> saveTaxonNodeAll(
511
            Collection<TaxonNode> taxonNodeCollection) {
512
        return taxonNodeDao.saveAll(taxonNodeCollection);
513
    }
514

    
515
    @Override
516
    public UUID saveClassification(Classification classification) {
517

    
518
       taxonNodeDao.saveOrUpdateAll(classification.getAllNodes());
519
       UUID result =dao.saveOrUpdate(classification);
520
       return result;
521
    }
522

    
523
    @Override
524
    public UUID saveTreeNode(ITaxonTreeNode treeNode) {
525
        if(treeNode instanceof Classification){
526
            return dao.save((Classification) treeNode).getUuid();
527
        }else if(treeNode instanceof TaxonNode){
528
            return taxonNodeDao.save((TaxonNode)treeNode).getUuid();
529
        }
530
        return null;
531
    }
532

    
533
    @Override
534
    public List<TaxonNode> getAllNodes(){
535
        return taxonNodeDao.list(null,null);
536
    }
537

    
538
    @Override
539
    public List<UuidAndTitleCache<TaxonNode>> getTaxonNodeUuidAndTitleCacheOfAcceptedTaxaByClassification(UUID classificationUuid, Integer limit, String pattern, boolean searchForClassifications, boolean includeDoubtful) {
540
        return taxonNodeDao.getTaxonNodeUuidAndTitleCacheOfAcceptedTaxaByClassification(dao.load(classificationUuid),  limit, pattern, searchForClassifications, includeDoubtful);
541
    }
542

    
543
    @Override
544
    public List<UuidAndTitleCache<TaxonNode>> getTaxonNodeUuidAndTitleCacheOfAcceptedTaxaByClassification(Classification classification,  Integer limit, String pattern, boolean searchForClassifications) {
545
        return taxonNodeDao.getTaxonNodeUuidAndTitleCacheOfAcceptedTaxaByClassification(classification,  limit, pattern, searchForClassifications);
546
    }
547

    
548
    @Override
549
    public List<UuidAndTitleCache<TaxonNode>> getTaxonNodeUuidAndTitleCacheOfAcceptedTaxaByClassification(UUID classificationUuid, boolean searchForClassifications ) {
550
        return taxonNodeDao.getTaxonNodeUuidAndTitleCacheOfAcceptedTaxaByClassification(dao.load(classificationUuid), null, null, searchForClassifications);
551
    }
552

    
553
    @Override
554
    public List<UuidAndTitleCache<TaxonNode>> getTaxonNodeUuidAndTitleCacheOfAcceptedTaxaByClassification(Classification classification, boolean searchForClassifications ) {
555
        return taxonNodeDao.getTaxonNodeUuidAndTitleCacheOfAcceptedTaxaByClassification(classification, null, null, searchForClassifications);
556
    }
557

    
558
    @Override
559
    public List<UuidAndTitleCache<Classification>> getUuidAndTitleCache(Integer limit, String pattern) {
560
        return dao.getUuidAndTitleCache(limit, pattern);
561
    }
562

    
563
    @Override
564
    public Map<UUID, List<MediaRepresentation>> getAllMediaForChildNodes(
565
            TaxonNode taxonNode, List<String> propertyPaths, int size,
566
            int height, int widthOrDuration, String[] mimeTypes) {
567

    
568
        TreeMap<UUID, List<MediaRepresentation>> result = new TreeMap<>();
569
        List<MediaRepresentation> mediaRepresentations = new ArrayList<>();
570

    
571
        //add all media of the children to the result map
572
        if (taxonNode != null){
573

    
574
            List<TaxonNode> nodes = new ArrayList<>();
575

    
576
            nodes.add(loadTaxonNode(taxonNode.getUuid(), propertyPaths));
577
            nodes.addAll(loadChildNodesOfTaxonNode(taxonNode, propertyPaths));
578

    
579
            for(TaxonNode node : nodes){
580
                Taxon taxon = node.getTaxon();
581
                for (TaxonDescription taxonDescription: taxon.getDescriptions()){
582
                    for (DescriptionElementBase descriptionElement: taxonDescription.getElements()){
583
                        for(Media media : descriptionElement.getMedia()){
584
                            //find the best matching representation
585
                            mediaRepresentations.add(MediaUtils.findBestMatchingRepresentation(media,null, size, height, widthOrDuration, mimeTypes, MediaUtils.MissingValueStrategy.MAX));
586
                        }
587
                    }
588
                }
589
                result.put(taxon.getUuid(), mediaRepresentations);
590
            }
591
        }
592

    
593
        return result;
594
    }
595

    
596
    @Override
597
    @Transactional(readOnly = false)
598
    public UpdateResult updateCaches(Class<? extends Classification> clazz, Integer stepSize, IIdentifiableEntityCacheStrategy<Classification> cacheStrategy, IProgressMonitor monitor) {
599
        if (clazz == null){
600
            clazz = Classification.class;
601
        }
602
        return super.updateCachesImpl(clazz, stepSize, cacheStrategy, monitor);
603
    }
604

    
605
    /**
606
     *
607
     * @param allNodesOfClassification
608
     * @return null - if  allNodesOfClassification is empty <br>
609
     */
610

    
611
    private Map<String, List<TaxonNode>> getSortedGenusList(Collection<TaxonNode> allNodesOfClassification){
612

    
613
    	if(allNodesOfClassification == null || allNodesOfClassification.isEmpty()){
614
    		return null;
615
    	}
616
    	Map<String, List<TaxonNode>> sortedGenusMap = new HashMap<>();
617
    	for(TaxonNode node:allNodesOfClassification){
618
    		Taxon taxon = node.getTaxon();
619
    		INonViralName name = taxon.getName();
620
    		String genusOrUninomial = name.getGenusOrUninomial();
621
    		//if rank unknown split string and take first word
622
    		if(genusOrUninomial == null){
623
    			String titleCache = taxon.getTitleCache();
624
    			String[] split = titleCache.split("\\s+");
625
    			for(String s:split){
626
    				genusOrUninomial = s;
627
    				break;
628
    			}
629
    		}
630
    		//if node has children
631

    
632
    		//retrieve list from map if not create List
633
    		if(sortedGenusMap.containsKey(genusOrUninomial)){
634
    			List<TaxonNode> list = sortedGenusMap.get(genusOrUninomial);
635
    			list.add(node);
636
    			sortedGenusMap.put(genusOrUninomial, list);
637
    		}else{
638
    			//create List for genus
639
    			List<TaxonNode> list = new ArrayList<>();
640
    			list.add(node);
641
    			sortedGenusMap.put(genusOrUninomial, list);
642
    		}
643
    	}
644
    	return sortedGenusMap;
645
    }
646

    
647
    /**
648
     *
649
     * creates new Classification and parent TaxonNodes at genus level
650
     *
651
     *
652
     * @param map GenusMap which holds a name (Genus) and all the same Taxa as a list
653
     * @param classification you want to improve the hierarchy (will not be modified)
654
     * @param configurator to change certain settings, if null then standard settings will be taken
655
     * @return new classification with parentNodes for each entry in the map
656
     */
657
    @SuppressWarnings({ "unchecked" })
658
	@Transactional(readOnly = false)
659
	@Override
660
    public UpdateResult createHierarchyInClassification(Classification classification, CreateHierarchyForClassificationConfigurator configurator){
661
        UpdateResult result = new UpdateResult();
662
    	classification = dao.findByUuid(classification.getUuid());
663
    	Map<String, List<TaxonNode>> map = getSortedGenusList(classification.getAllNodes());
664

    
665
    	final String APPENDIX = "repaired";
666
    	String titleCache = StringUtils.isBlank(classification.getTitleCache()) ? " " : classification.getTitleCache() ;
667
    	//TODO classification clone???
668
    	Classification newClassification = Classification.NewInstance(titleCache +" "+ APPENDIX);
669
    	newClassification.setReference(classification.getReference());
670

    
671
    	for(Map.Entry<String, List<TaxonNode>> entry:map.entrySet()){
672
    		String genus = entry.getKey();
673
    		List<TaxonNode> listOfTaxonNodes = entry.getValue();
674
    		TaxonNode parentNode = null;
675
    		//Search for genus in list
676
    		for(TaxonNode tNode:listOfTaxonNodes){
677
    			//take that taxonNode as parent and remove from list with all it possible children
678
    			//FIXME NPE for name
679
    			TaxonName name = tNode.getTaxon().getName();
680
    			if(name.getNameCache().equalsIgnoreCase(genus)){
681
    				TaxonNode clone = tNode.clone();
682
    				if(!tNode.hasChildNodes()){
683
    					//FIXME remove classification
684
//    					parentNode = newClassification.addChildNode(clone, 0, classification.getCitation(), classification.getMicroReference());
685
    					parentNode = newClassification.addChildNode(clone, 0, clone.getReference(), clone.getMicroReference());
686
    					//remove taxonNode from list because just added to classification
687
    					result.addUpdatedObject(tNode);
688
    					listOfTaxonNodes.remove(tNode);
689
    				}else{
690
    					//get all childNodes
691
    					//save prior Hierarchy and remove them from the list
692
    					List<TaxonNode> copyAllChildrenToTaxonNode = copyAllChildrenToTaxonNode(tNode, clone, result);
693
//    					parentNode = newClassification.addChildNode(clone, 0, classification.getCitation(), classification.getMicroReference());
694
      					//FIXME remove classification
695
    					parentNode = newClassification.addChildNode(clone, 0, clone.getReference(), clone.getMicroReference());
696
    					//remove taxonNode from list because just added to classification
697
    					result.addUpdatedObject(tNode);
698
    					listOfTaxonNodes.remove(tNode);
699
    					if(copyAllChildrenToTaxonNode != null){
700
    						listOfTaxonNodes = (List<TaxonNode>) CollectionUtils.removeAll(listOfTaxonNodes, copyAllChildrenToTaxonNode);
701
    					}
702
    				}
703
    				break;
704
    			}
705
    		}
706
    		if(parentNode == null){
707
    			//if no match found in list, create parentNode
708
    			NonViralNameParserImpl parser = NonViralNameParserImpl.NewInstance();
709
    			TaxonName TaxonName = (TaxonName)parser.parseFullName(genus);
710
    			//TODO Sec via configurator
711
    			Taxon taxon = Taxon.NewInstance(TaxonName, null);
712
    			parentNode = newClassification.addChildTaxon(taxon, 0, null, null);
713
    			result.addUpdatedObject(parentNode);
714
    		}
715
    		//iterate over the rest of the list
716
    		for(TaxonNode tn : listOfTaxonNodes){
717
    			//if TaxonNode has a parent and this is not the classification then skip it
718
    			//and add to new classification via the parentNode as children of it
719
    			//this should assures to keep the already existing hierarchy
720
    			//FIXME: Assert is not rootnode --> entrypoint is not classification in future but rather rootNode
721

    
722
    			if(!tn.isTopmostNode()){
723
    				continue; //skip to next taxonNode
724
    			}
725

    
726
    			TaxonNode clone = tn.clone();
727
    			//FIXME: citation from node
728
    			//TODO: addchildNode without citation and references
729
//    			TaxonNode taxonNode = parentNode.addChildNode(clone, classification.getCitation(), classification.getMicroReference());
730
    			TaxonNode taxonNode = parentNode.addChildNode(clone, clone.getReference(), clone.getMicroReference());
731
    			result.addUnChangedObject(clone);
732
    			if(tn.hasChildNodes()){
733
    				//save hierarchy in new classification
734
    				List<TaxonNode> copyAllChildrenToTaxonNode = copyAllChildrenToTaxonNode(tn, taxonNode, result);
735
    				if(copyAllChildrenToTaxonNode != null){
736
    					listOfTaxonNodes = (List<TaxonNode>) CollectionUtils.removeAll(listOfTaxonNodes, copyAllChildrenToTaxonNode);
737
    				}
738
    			}
739
    		}
740
    	}
741
    	dao.saveOrUpdate(newClassification);
742
    	result.setCdmEntity(newClassification);
743
    	return result;
744
    }
745

    
746
    /**
747
     *
748
     * recursive method to get all childnodes of taxonNode in classification.
749
     *
750
     * @param classification just for References and Citation, can be null
751
     * @param copyFromNode TaxonNode with Children
752
     * @param copyToNode TaxonNode which will receive the children
753
     * @return List of ChildNode which has been added. If node has no children returns null
754
     */
755
   private List<TaxonNode> copyAllChildrenToTaxonNode(TaxonNode copyFromNode, TaxonNode copyToNode, UpdateResult result) {
756
		List<TaxonNode> childNodes;
757
		if(!copyFromNode.hasChildNodes()){
758
			return null;
759
		}else{
760
			childNodes = copyFromNode.getChildNodes();
761
		}
762
		for(TaxonNode childNode:childNodes){
763
			TaxonNode clone = childNode.clone();
764
			result.addUnChangedObject(clone);
765
			if(childNode.hasChildNodes()){
766
				copyAllChildrenToTaxonNode(childNode, clone, result);
767
			}
768
			//FIXME: citation from node instead of classification
769
//			copyToNode.addChildNode(clone,classification.getCitation(), classification.getMicroReference());
770
			copyToNode.addChildNode(clone, clone.getReference(), clone.getMicroReference());
771
		}
772
		return childNodes;
773
	}
774

    
775
    @Override
776
    public ClassificationLookupDTO classificationLookup(Classification classification) {
777
        return dao.classificationLookup(classification);
778
    }
779

    
780
    @Override
781
    @Transactional
782
    public DeleteResult delete(UUID classificationUuid, TaxonDeletionConfigurator config){
783
        DeleteResult result = new DeleteResult();
784
        Classification classification = dao.findByUuid(classificationUuid);
785
        if (classification == null){
786
            result.addException(new IllegalArgumentException("The classification does not exist in database."));
787
            result.setAbort();
788
            return result;
789
        }
790
        if (!classification.hasChildNodes()){
791
            dao.delete(classification);
792
            result.addDeletedObject(classification);
793
            return result;
794
        }
795
        if (config.getTaxonNodeConfig().getChildHandling().equals(ChildHandling.DELETE)){
796
//            TaxonNode root = classification.getRootNode();
797
//            result.includeResult(taxonNodeService.deleteTaxonNode(HibernateProxyHelper.deproxy(root), config));
798
//            result.addDeletedObject(classification);
799
            dao.delete(classification);
800
            result.addDeletedObject(classification);
801
            return result;
802
        }
803

    
804

    
805
        return result;
806
    }
807

    
808
    @Override
809
    public List<GroupedTaxonDTO> groupTaxaByHigherTaxon(List<UUID> originalTaxonUuids, UUID classificationUuid, Rank minRank, Rank maxRank){
810
        List<GroupedTaxonDTO> result = new ArrayList<>();
811

    
812
        //get treeindex for each taxonUUID
813
        Map<UUID, TreeIndex> taxonIdTreeIndexMap = dao.treeIndexForTaxonUuids(classificationUuid, originalTaxonUuids);
814

    
815
        //build treeindex list (or tree)
816
        //TODO make it work with TreeIndex or move there
817
        List<String> treeIndexClosureStr = new ArrayList<>();
818
        for (TreeIndex treeIndex : taxonIdTreeIndexMap.values()){
819
            String[] splits = treeIndex.toString().substring(1).split(ITreeNode.separator);
820
            String currentIndex = ITreeNode.separator;
821
            for (String split : splits){
822
                if (split.equals("")){
823
                    continue;
824
                }
825
                currentIndex += split + ITreeNode.separator;
826
                if (!treeIndexClosureStr.contains(currentIndex) && !split.startsWith(ITreeNode.treePrefix)){
827
                    treeIndexClosureStr.add(currentIndex);
828
                }
829
            }
830
        }
831

    
832
        //get rank sortindex for all parent taxa with sortindex <= minRank and sortIndex >= maxRank (if available)
833
        Integer minRankOrderIndex = minRank == null ? null : minRank.getOrderIndex();
834
        Integer maxRankOrderIndex = maxRank == null ? null : maxRank.getOrderIndex();
835
        List<TreeIndex> treeIndexClosure = TreeIndex.NewListInstance(treeIndexClosureStr);
836

    
837
        Map<TreeIndex, Integer> treeIndexSortIndexMapTmp = taxonNodeDao.rankOrderIndexForTreeIndex(treeIndexClosure, minRankOrderIndex, maxRankOrderIndex);
838

    
839
        //remove all treeindex with "exists child in above map(and child.sortindex > xxx)
840
        List<TreeIndex> treeIndexList = TreeIndex.sort(treeIndexSortIndexMapTmp.keySet());
841

    
842
        Map<TreeIndex, Integer> treeIndexSortIndexMap = new HashMap<>();
843
        TreeIndex lastTreeIndex = null;
844
        for (TreeIndex treeIndex : treeIndexList){
845
            if (lastTreeIndex != null && lastTreeIndex.hasChild(treeIndex)){
846
                treeIndexSortIndexMap.remove(lastTreeIndex);
847
            }
848
            treeIndexSortIndexMap.put(treeIndex, treeIndexSortIndexMapTmp.get(treeIndex));
849
            lastTreeIndex = treeIndex;
850
        }
851

    
852
        //get taxonID for treeIndexes
853
        Map<TreeIndex, UuidAndTitleCache<?>> treeIndexTaxonIdMap = taxonNodeDao.taxonUuidsForTreeIndexes(treeIndexSortIndexMap.keySet());
854

    
855
        //fill result list
856
        for (UUID originalTaxonUuid : originalTaxonUuids){
857
            GroupedTaxonDTO item = new GroupedTaxonDTO();
858
            result.add(item);
859
            item.setTaxonUuid(originalTaxonUuid);
860
            TreeIndex groupTreeIndex = taxonIdTreeIndexMap.get(originalTaxonUuid);
861
            String groupIndexX = TreeIndex.toString(groupTreeIndex);
862
            while (groupTreeIndex != null){
863
                if (treeIndexTaxonIdMap.get(groupTreeIndex) != null){
864
                    UuidAndTitleCache<?> uuidAndLabel = treeIndexTaxonIdMap.get(groupTreeIndex);
865
                    item.setGroupTaxonUuid(uuidAndLabel.getUuid());
866
                    item.setGroupTaxonName(uuidAndLabel.getTitleCache());
867
                    break;
868
                }else{
869
                    groupTreeIndex = groupTreeIndex.parent();
870
//                    int index = groupIndex.substring(0, groupIndex.length()-1).lastIndexOf(ITreeNode.separator);
871
//                    groupIndex = index < 0 ? null : groupIndex.substring(0, index+1);
872
                }
873
            }
874
        }
875

    
876
        return result;
877
    }
878

    
879
    @Override
880
    public List<GroupedTaxonDTO> groupTaxaByMarkedParents(List<UUID> originalTaxonUuids, UUID classificationUuid,
881
            MarkerType markerType, Boolean flag) {
882

    
883
        List<GroupedTaxonDTO> result = new ArrayList<>();
884

    
885
        //get treeindex for each taxonUUID
886
        Map<UUID, TreeIndex> taxonIdTreeIndexMap = dao.treeIndexForTaxonUuids(classificationUuid, originalTaxonUuids);
887

    
888
        //get all marked tree indexes
889
        Set<TreeIndex> markedTreeIndexes = dao.getMarkedTreeIndexes(markerType, flag);
890

    
891
        Map<TreeIndex, TreeIndex> groupedMap = TreeIndex.group(markedTreeIndexes, taxonIdTreeIndexMap.values());
892
        Set<TreeIndex> notNullGroups = new HashSet<>(groupedMap.values());
893
        notNullGroups.remove(null);
894

    
895
        //get taxonInfo for treeIndexes
896
        Map<TreeIndex, UuidAndTitleCache<?>> treeIndexTaxonIdMap = taxonNodeDao.taxonUuidsForTreeIndexes(notNullGroups);
897

    
898
        //fill result list
899
        for (UUID originalTaxonUuid : originalTaxonUuids){
900
            GroupedTaxonDTO item = new GroupedTaxonDTO();
901
            result.add(item);
902
            item.setTaxonUuid(originalTaxonUuid);
903

    
904
            TreeIndex toBeGroupedTreeIndex = taxonIdTreeIndexMap.get(originalTaxonUuid);
905
            TreeIndex groupTreeIndex = groupedMap.get(toBeGroupedTreeIndex);
906
            UuidAndTitleCache<?> uuidAndLabel = treeIndexTaxonIdMap.get(groupTreeIndex);
907
            if (uuidAndLabel != null){
908
                item.setGroupTaxonUuid(uuidAndLabel.getUuid());
909
                item.setGroupTaxonName(uuidAndLabel.getTitleCache());
910
            }
911
        }
912

    
913
        return result;
914
    }
915

    
916
    @Override
917
    public UUID getTaxonNodeUuidByTaxonUuid(UUID classificationUuid, UUID taxonUuid) {
918
        Map<UUID, UUID> map = dao.getTaxonNodeUuidByTaxonUuid(classificationUuid, Arrays.asList(taxonUuid));
919
        UUID taxonNodeUuid = map.get(taxonUuid);
920
        return taxonNodeUuid;
921
    }
922

    
923
    @Override
924
    public TaxonInContextDTO getTaxonInContext(UUID classificationUuid, UUID taxonBaseUuid,
925
            Boolean doChildren, Boolean doSynonyms, boolean includeUnpublished, List<UUID> ancestorMarkers,
926
            TaxonNodeSortMode sortMode) {
927

    
928
        TaxonInContextDTO result = new TaxonInContextDTO();
929

    
930
        TaxonBase<?> taxonBase = taxonDao.load(taxonBaseUuid);
931
        if (taxonBase == null){
932
            throw new EntityNotFoundException("Taxon with uuid " + taxonBaseUuid + " not found in datasource");
933
        }
934
        boolean isSynonym = false;
935
        Taxon acceptedTaxon;
936
        if (taxonBase.isInstanceOf(Synonym.class)){
937
            isSynonym = true;
938
            Synonym synonym = CdmBase.deproxy(taxonBase, Synonym.class);
939
            acceptedTaxon = synonym.getAcceptedTaxon();
940
            if (acceptedTaxon == null) {
941
                throw new EntityNotFoundException("Accepted taxon not found for synonym"  );
942
            }
943
            TaxonStatus taxonStatus = TaxonStatus.Synonym;
944
            if (synonym.getName()!= null && acceptedTaxon.getName() != null
945
                    && synonym.getName().getHomotypicalGroup().equals(acceptedTaxon.getName().getHomotypicalGroup())){
946
                taxonStatus = TaxonStatus.SynonymObjective;
947
            }
948
            result.setTaxonStatus(taxonStatus);
949

    
950
        }else{
951
            acceptedTaxon = CdmBase.deproxy(taxonBase, Taxon.class);
952
            result.setTaxonStatus(TaxonStatus.Accepted);
953
        }
954
        UUID acceptedTaxonUuid = acceptedTaxon.getUuid();
955

    
956
        UUID taxonNodeUuid = getTaxonNodeUuidByTaxonUuid(classificationUuid, acceptedTaxonUuid);
957
        if (taxonNodeUuid == null) {
958
            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 );
959
        }
960
        result.setTaxonNodeUuid(taxonNodeUuid);
961

    
962
        //TODO make it a dao call
963
        Taxon parentTaxon = getParentTaxon(classificationUuid, acceptedTaxon);
964
        if (parentTaxon != null){
965
            result.setParentTaxonUuid(parentTaxon.getUuid());
966
            result.setParentTaxonLabel(parentTaxon.getTitleCache());
967
            if (parentTaxon.getName() != null){
968
                result.setParentNameLabel(parentTaxon.getName().getTitleCache());
969
            }
970
        }
971

    
972
        result.setTaxonUuid(taxonBaseUuid);
973
        result.setClassificationUuid(classificationUuid);
974
        if (taxonBase.getSec() != null){
975
            result.setSecundumUuid(taxonBase.getSec().getUuid());
976
            result.setSecundumLabel(taxonBase.getSec().getTitleCache());
977
        }
978
        result.setTaxonLabel(taxonBase.getTitleCache());
979

    
980
        TaxonName name = taxonBase.getName();
981
        result.setNameUuid(name.getUuid());
982
        result.setNameLabel(name.getTitleCache());
983
        result.setNameWithoutAuthor(name.getNameCache());
984
        result.setGenusOrUninomial(name.getGenusOrUninomial());
985
        result.setInfraGenericEpithet(name.getInfraGenericEpithet());
986
        result.setSpeciesEpithet(name.getSpecificEpithet());
987
        result.setInfraSpecificEpithet(name.getInfraSpecificEpithet());
988

    
989
        result.setAuthorship(name.getAuthorshipCache());
990

    
991
        Rank rank = name.getRank();
992
        if (rank != null){
993
            result.setRankUuid(rank.getUuid());
994
            String rankLabel = rank.getAbbreviation();
995
            if (StringUtils.isBlank(rankLabel)){
996
                rankLabel = rank.getLabel();
997
            }
998
            result.setRankLabel(rankLabel);
999
        }
1000

    
1001
        boolean recursive = false;
1002
        Integer pageSize = null;
1003
        Integer pageIndex = null;
1004
        Pager<TaxonNodeDto> children = taxonNodeService.pageChildNodesDTOs(taxonNodeUuid, recursive, includeUnpublished, doSynonyms,
1005
                sortMode, pageSize, pageIndex);
1006

    
1007
        //children
1008
        if(! isSynonym) {
1009
            for (TaxonNodeDto childDto : children.getRecords()){
1010
                if (doChildren && childDto.getTaxonStatus().equals(TaxonStatus.Accepted)){
1011
                    EntityDTO<Taxon> child = new EntityDTO<Taxon>(childDto.getTaxonUuid(), childDto.getTitleCache());
1012
                    result.addChild(child);
1013
                }else if (doSynonyms && childDto.getTaxonStatus().isSynonym()){
1014
                    EntityDTO<Synonym> child = new EntityDTO<>(childDto.getTaxonUuid(), childDto.getTitleCache());
1015
                    result.addSynonym(child);
1016
                }
1017
            }
1018
        }else{
1019
            result.setAcceptedTaxonUuid(acceptedTaxonUuid);
1020
            String nameTitel = acceptedTaxon.getName() == null ? null : acceptedTaxon.getName().getTitleCache();
1021
            result.setAcceptedTaxonLabel(acceptedTaxon.getTitleCache());
1022
            result.setAcceptedNameLabel(nameTitel);
1023
        }
1024

    
1025
        //marked ancestors
1026
        if (ancestorMarkers != null && !ancestorMarkers.isEmpty()){
1027
            @SuppressWarnings("rawtypes")
1028
            List<DefinedTermBase> markerTypesTerms = termDao.list(ancestorMarkers, pageSize, null, null, null);
1029
            List<MarkerType> markerTypes = new ArrayList<>();
1030
            for (DefinedTermBase<?> term : markerTypesTerms){
1031
                if (term.isInstanceOf(MarkerType.class)){
1032
                    markerTypes.add(CdmBase.deproxy(term, MarkerType.class));
1033
                }
1034
            }
1035
            if (! markerTypes.isEmpty()){
1036
                TaxonNode node = taxonNodeDao.findByUuid(taxonNodeUuid);
1037
                handleAncestorsForMarkersRecursive(result, markerTypes, node);
1038
            }
1039
        }
1040

    
1041
        return result;
1042
    }
1043

    
1044
    private Taxon getParentTaxon(UUID classificationUuid, Taxon acceptedTaxon) {
1045
        if (classificationUuid == null){
1046
            return null;
1047
        }
1048
        TaxonNode parent = null;
1049
        for (TaxonNode node : acceptedTaxon.getTaxonNodes()){
1050
            if (classificationUuid.equals(node.getClassification().getUuid())){
1051
                parent = node.getParent();
1052
            }
1053
        }
1054
        if (parent != null){
1055
            return parent.getTaxon();
1056
        }
1057
        return null;
1058
    }
1059

    
1060
    private void handleAncestorsForMarkersRecursive(TaxonInContextDTO result, List<MarkerType> markerTypes, TaxonNode node) {
1061
       for (MarkerType type : markerTypes){
1062
            Taxon taxon = node.getTaxon();
1063
            if (taxon != null && taxon.hasMarker(type, true)){
1064
                String label =  taxon.getName() == null? taxon.getTitleCache() : taxon.getName().getTitleCache();
1065
                MarkedEntityDTO<Taxon> dto = new MarkedEntityDTO<>(type, true, taxon.getUuid(), label);
1066
                result.addMarkedAncestor(dto);
1067
            }
1068
        }
1069
        TaxonNode parentNode = node.getParent();
1070
        if (parentNode != null){
1071
            handleAncestorsForMarkersRecursive(result, markerTypes, parentNode);
1072
        }
1073
    }
1074

    
1075
    @Override
1076
    public List<UuidAndTitleCache<TaxonNode>> getTaxonNodeUuidAndTitleCacheOfAcceptedTaxaByClassification(
1077
            Classification classification) {
1078
        return getTaxonNodeUuidAndTitleCacheOfAcceptedTaxaByClassification(classification, false);
1079
    }
1080

    
1081
    @Override
1082
    public List<UuidAndTitleCache<TaxonNode>> getTaxonNodeUuidAndTitleCacheOfAcceptedTaxaByClassification(
1083
            UUID classificationUuid) {
1084
        return getTaxonNodeUuidAndTitleCacheOfAcceptedTaxaByClassification(classificationUuid, false);
1085
    }
1086

    
1087
    @Override
1088
    public List<UuidAndTitleCache<TaxonNode>> getTaxonNodeUuidAndTitleCacheOfAcceptedTaxaByClassification(
1089
            UUID classificationUuid, Integer limit, String pattern) {
1090
        return  getTaxonNodeUuidAndTitleCacheOfAcceptedTaxaByClassification(classificationUuid,  limit, pattern, false);
1091
    }
1092

    
1093
    @Override
1094
    public List<UuidAndTitleCache<TaxonNode>> getTaxonNodeUuidAndTitleCacheOfAcceptedTaxaByClassification(
1095
            Classification classification, Integer limit, String pattern) {
1096
        return getTaxonNodeUuidAndTitleCacheOfAcceptedTaxaByClassification(classification, limit, pattern, false);
1097
    }
1098

    
1099
    @Override
1100
    public List<UuidAndTitleCache<TaxonNode>> getTaxonNodeUuidAndTitleCacheOfAcceptedTaxaByClassification(
1101
            UUID classificationUuid, Integer limit, String pattern, boolean searchForClassifications) {
1102
        return getTaxonNodeUuidAndTitleCacheOfAcceptedTaxaByClassification(
1103
                classificationUuid, limit, pattern, searchForClassifications, false);
1104
    }
1105
}
(5-5/100)