Project

General

Profile

Download (59.8 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
package eu.etaxonomy.cdm.api.service;
10

    
11
import java.util.ArrayList;
12
import java.util.Arrays;
13
import java.util.Collection;
14
import java.util.Collections;
15
import java.util.Comparator;
16
import java.util.HashSet;
17
import java.util.Iterator;
18
import java.util.List;
19
import java.util.Map;
20
import java.util.Set;
21
import java.util.UUID;
22
import java.util.stream.Collectors;
23

    
24
import org.apache.log4j.Logger;
25
import org.springframework.beans.factory.annotation.Autowired;
26
import org.springframework.security.core.Authentication;
27
import org.springframework.stereotype.Service;
28
import org.springframework.transaction.annotation.Transactional;
29
import org.springframework.transaction.interceptor.TransactionAspectSupport;
30

    
31
import eu.etaxonomy.cdm.api.service.UpdateResult.Status;
32
import eu.etaxonomy.cdm.api.service.config.ForSubtreeConfiguratorBase;
33
import eu.etaxonomy.cdm.api.service.config.NodeDeletionConfigurator.ChildHandling;
34
import eu.etaxonomy.cdm.api.service.config.PublishForSubtreeConfigurator;
35
import eu.etaxonomy.cdm.api.service.config.SecundumForSubtreeConfigurator;
36
import eu.etaxonomy.cdm.api.service.config.SubtreeCloneConfigurator;
37
import eu.etaxonomy.cdm.api.service.config.TaxonDeletionConfigurator;
38
import eu.etaxonomy.cdm.api.service.config.TaxonNodeDeletionConfigurator;
39
import eu.etaxonomy.cdm.api.service.dto.CdmEntityIdentifier;
40
import eu.etaxonomy.cdm.api.service.dto.CreateTaxonDTO;
41
import eu.etaxonomy.cdm.api.service.dto.TaxonDistributionDTO;
42
import eu.etaxonomy.cdm.api.service.pager.Pager;
43
import eu.etaxonomy.cdm.api.service.pager.PagerUtils;
44
import eu.etaxonomy.cdm.api.service.pager.impl.AbstractPagerImpl;
45
import eu.etaxonomy.cdm.api.service.pager.impl.DefaultPagerImpl;
46
import eu.etaxonomy.cdm.common.monitor.DefaultProgressMonitor;
47
import eu.etaxonomy.cdm.common.monitor.IProgressMonitor;
48
import eu.etaxonomy.cdm.common.monitor.SubProgressMonitor;
49
import eu.etaxonomy.cdm.compare.taxon.HomotypicGroupTaxonComparator;
50
import eu.etaxonomy.cdm.compare.taxon.TaxonNodeSortMode;
51
import eu.etaxonomy.cdm.filter.TaxonNodeFilter;
52
import eu.etaxonomy.cdm.hibernate.HHH_9751_Util;
53
import eu.etaxonomy.cdm.hibernate.HibernateProxyHelper;
54
import eu.etaxonomy.cdm.model.agent.TeamOrPersonBase;
55
import eu.etaxonomy.cdm.model.common.CdmBase;
56
import eu.etaxonomy.cdm.model.common.Language;
57
import eu.etaxonomy.cdm.model.common.LanguageString;
58
import eu.etaxonomy.cdm.model.common.TreeIndex;
59
import eu.etaxonomy.cdm.model.description.DescriptionElementBase;
60
import eu.etaxonomy.cdm.model.description.DescriptionElementSource;
61
import eu.etaxonomy.cdm.model.description.DescriptiveDataSet;
62
import eu.etaxonomy.cdm.model.description.TaxonDescription;
63
import eu.etaxonomy.cdm.model.metadata.SecReferenceHandlingEnum;
64
import eu.etaxonomy.cdm.model.name.HomotypicalGroup;
65
import eu.etaxonomy.cdm.model.name.HybridRelationship;
66
import eu.etaxonomy.cdm.model.name.Rank;
67
import eu.etaxonomy.cdm.model.name.TaxonName;
68
import eu.etaxonomy.cdm.model.permission.Operation;
69
import eu.etaxonomy.cdm.model.reference.NamedSource;
70
import eu.etaxonomy.cdm.model.reference.Reference;
71
import eu.etaxonomy.cdm.model.taxon.Classification;
72
import eu.etaxonomy.cdm.model.taxon.ITaxonTreeNode;
73
import eu.etaxonomy.cdm.model.taxon.Synonym;
74
import eu.etaxonomy.cdm.model.taxon.SynonymType;
75
import eu.etaxonomy.cdm.model.taxon.Taxon;
76
import eu.etaxonomy.cdm.model.taxon.TaxonBase;
77
import eu.etaxonomy.cdm.model.taxon.TaxonNode;
78
import eu.etaxonomy.cdm.model.taxon.TaxonNodeAgentRelation;
79
import eu.etaxonomy.cdm.model.taxon.TaxonNodeStatus;
80
import eu.etaxonomy.cdm.model.taxon.TaxonRelationship;
81
import eu.etaxonomy.cdm.model.taxon.TaxonRelationshipType;
82
import eu.etaxonomy.cdm.model.term.DefinedTerm;
83
import eu.etaxonomy.cdm.persistence.dao.common.Restriction;
84
import eu.etaxonomy.cdm.persistence.dao.initializer.IBeanInitializer;
85
import eu.etaxonomy.cdm.persistence.dao.name.IHomotypicalGroupDao;
86
import eu.etaxonomy.cdm.persistence.dao.reference.IOriginalSourceDao;
87
import eu.etaxonomy.cdm.persistence.dao.reference.IReferenceDao;
88
import eu.etaxonomy.cdm.persistence.dao.taxon.IClassificationDao;
89
import eu.etaxonomy.cdm.persistence.dao.taxon.ITaxonNodeDao;
90
import eu.etaxonomy.cdm.persistence.dao.taxon.ITaxonNodeFilterDao;
91
import eu.etaxonomy.cdm.persistence.dto.HomotypicGroupDto;
92
import eu.etaxonomy.cdm.persistence.dto.TaxonNodeDto;
93
import eu.etaxonomy.cdm.persistence.permission.ICdmPermissionEvaluator;
94
import eu.etaxonomy.cdm.persistence.query.OrderHint;
95

    
96
/**
97
 * @author n.hoffmann
98
 * @since Apr 9, 2010
99
 */
100
@Service
101
@Transactional(readOnly = true)
102
public class TaxonNodeServiceImpl
103
           extends AnnotatableServiceBase<TaxonNode, ITaxonNodeDao>
104
           implements ITaxonNodeService{
105

    
106
    private static final Logger logger = Logger.getLogger(TaxonNodeServiceImpl.class);
107

    
108
    @Autowired
109
    private IBeanInitializer defaultBeanInitializer;
110

    
111
    @Autowired
112
    private ITaxonService taxonService;
113

    
114
    @Autowired
115
    private IReferenceService referenceService;
116

    
117
    @Autowired
118
    private IDescriptiveDataSetService dataSetService;
119

    
120
    @Autowired
121
    private IAgentService agentService;
122

    
123
    @Autowired
124
    private INameService nameService;
125

    
126
    @Autowired
127
    private IOriginalSourceDao sourceDao;
128

    
129
    @Autowired
130
    private ITaxonNodeFilterDao nodeFilterDao;
131

    
132
    @Autowired
133
    private IReferenceDao referenceDao;
134

    
135
    @Autowired
136
    private IClassificationDao classificationDao;
137

    
138
    @Autowired
139
    private IHomotypicalGroupDao homotypicalGroupDao;
140

    
141
    @Autowired
142
    IProgressMonitorService progressMonitorService;
143

    
144
    @Autowired
145
    private ICdmPermissionEvaluator permissionEvaluator;
146

    
147
    @Override
148
    public List<TaxonNode> loadChildNodesOfTaxonNode(TaxonNode taxonNode,
149
            List<String> propertyPaths, boolean recursive,  boolean includeUnpublished,
150
            TaxonNodeSortMode sortMode) {
151

    
152
        taxonNode = load(taxonNode.getUuid());
153
        List<TaxonNode> childNodes;
154
        if (recursive == true){
155
            Comparator<TaxonNode> comparator = sortMode == null? null : sortMode.comparator();
156
            childNodes = dao.listChildrenOf(taxonNode, null, null, recursive, includeUnpublished, propertyPaths, comparator);
157
        }else if (includeUnpublished){
158
            childNodes = new ArrayList<>(taxonNode.getChildNodes());
159
        }else{
160
            childNodes = new ArrayList<>();
161
            for (TaxonNode node:taxonNode.getChildNodes()){
162
                if (node.getTaxon().isPublish()){
163
                    childNodes.add(node);
164
                }
165
            }
166
        }
167

    
168
        HHH_9751_Util.removeAllNull(childNodes);
169

    
170
        if (recursive == false && sortMode != null){
171
            Comparator<TaxonNode> comparator = sortMode.comparator();
172
        	Collections.sort(childNodes, comparator);
173
        }
174
        defaultBeanInitializer.initializeAll(childNodes, propertyPaths);
175
        return childNodes;
176
    }
177

    
178
    @Override
179
    public List<TaxonNode> listChildrenOf(TaxonNode node, Integer pageSize, Integer pageIndex,
180
            boolean recursive, boolean includeUnpublished, List<String> propertyPaths){
181
        return dao.listChildrenOf(node, pageSize, pageIndex, recursive, includeUnpublished, propertyPaths, null);
182
    }
183

    
184
    @Override
185
    public TaxonNodeDto getParentUuidAndTitleCache(ITaxonTreeNode child) {
186
        UUID uuid = child.getUuid();
187
        int id = child.getId();
188
        TaxonNodeDto uuidAndTitleCache = new TaxonNodeDto(uuid, id, null);
189
        return getParentUuidAndTitleCache(uuidAndTitleCache);
190
    }
191

    
192
    @Override
193
    public TaxonNodeDto getParentUuidAndTitleCache(TaxonNodeDto child) {
194
        return dao.getParentUuidAndTitleCache(child);
195
    }
196

    
197
    @Override
198
    public List<TaxonNodeDto> listChildNodesAsTaxonNodeDto(TaxonNodeDto parent) {
199
        return dao.listChildNodesAsTaxonNodeDto(parent);
200
    }
201

    
202
    @Override
203
    public List<TaxonNodeDto> getUuidAndTitleCache(Integer limit, String pattern, UUID classificationUuid) {
204
        return dao.getUuidAndTitleCache(limit, pattern, classificationUuid, true);
205
    }
206

    
207
    @Override
208
    public List<TaxonNodeDto> listChildNodesAsTaxonNodeDto(ITaxonTreeNode parent) {
209
        List<String> propertyPaths = new ArrayList<>();
210
        propertyPaths.add("parent");
211
        parent = dao.load(parent.getId(), propertyPaths);
212
        TaxonNodeDto uuidAndTitleCache = new TaxonNodeDto(parent);
213
        return listChildNodesAsTaxonNodeDto(uuidAndTitleCache);
214
    }
215

    
216
    @Override
217
    public List<TaxonNodeDto> taxonNodeDtoParentRank(Classification classification, Rank rank, TaxonName name) {
218
    	return dao.getParentTaxonNodeDtoForRank(classification, rank, name);
219
    }
220

    
221
    @Override
222
    public List<TaxonNodeDto> taxonNodeDtoParentRank(Classification classification, Rank rank, TaxonBase<?> taxonBase) {
223
        return dao.getParentTaxonNodeDtoForRank(classification, rank, taxonBase);
224
    }
225

    
226
    @Override
227
    public Pager<TaxonNodeDto> pageChildNodesDTOs(UUID taxonNodeUuid, boolean recursive,  boolean includeUnpublished,
228
            boolean doSynonyms, TaxonNodeSortMode sortMode,
229
            Integer pageSize, Integer pageIndex) {
230

    
231
        TaxonNode parentNode = dao.load(taxonNodeUuid);
232

    
233
        List<CdmBase> allRecords = new ArrayList<>();
234

    
235
        //acceptedTaxa
236
        List<TaxonNode> childNodes = loadChildNodesOfTaxonNode(parentNode, null, recursive, includeUnpublished, sortMode);
237
        allRecords.addAll(childNodes);
238

    
239
        //add synonyms if pager is not yet full synonyms
240
        if (doSynonyms){
241
            List<Synonym> synList = new ArrayList<>(parentNode.getTaxon().getSynonyms());
242
            Collections.sort(synList, new HomotypicGroupTaxonComparator(null));
243
            //TODO: test sorting
244

    
245
            allRecords.addAll(synList);
246
        }
247

    
248
        List<TaxonNodeDto> dtos = new ArrayList<>(pageSize==null?25:pageSize);
249
        long totalCount = Long.valueOf(allRecords.size());
250

    
251
        TaxonName parentName = null;
252

    
253
        for(CdmBase item : PagerUtils.pageList(allRecords, pageIndex, pageSize)) {
254
            if (item.isInstanceOf(TaxonNode.class)){
255
                dtos.add(new TaxonNodeDto(CdmBase.deproxy(item, TaxonNode.class)));
256
            }else if (item.isInstanceOf(Synonym.class)){
257
                Synonym synonym = CdmBase.deproxy(item, Synonym.class);
258
                parentName = parentName == null? parentNode.getTaxon().getName(): parentName;
259
                boolean isHomotypic = synonym.getName().isHomotypic(parentName);
260
                dtos.add(new TaxonNodeDto(synonym, isHomotypic));
261
            }
262
        }
263
        return new DefaultPagerImpl<>(pageIndex, totalCount, pageSize , dtos);
264
    }
265

    
266
    @Override
267
    public TaxonNodeDto parentDto(UUID taxonNodeUuid) {
268
        if (taxonNodeUuid == null){
269
            return null;
270
        }
271
        TaxonNode taxonNode = dao.load(taxonNodeUuid);
272
        if(taxonNode.getParent() != null) {
273
            return new TaxonNodeDto(taxonNode.getParent());
274
        }
275
        return null;
276
    }
277

    
278
    @Override
279
    public TaxonNodeDto dto(UUID taxonNodeUuid) {
280
        if (taxonNodeUuid == null){
281
            return null;
282
        }
283
        TaxonNode taxonNode = dao.load(taxonNodeUuid);
284
        if (taxonNode != null){
285
            return new TaxonNodeDto(taxonNode);
286
        }
287
        return null;
288
    }
289

    
290
    @Override
291
    public TaxonNodeDto dto(UUID taxonUuid, UUID classificationUuid) {
292
        if (taxonUuid == null){
293
            return null;
294
        }
295
        List<TaxonNodeDto> taxonNodes = dao.getTaxonNodeForTaxonInClassificationDto(taxonUuid, classificationUuid);
296
        if (!taxonNodes.isEmpty()){
297
            return taxonNodes.get(0);
298
        }
299
        return null;
300
    }
301

    
302
    @Override
303
    @Autowired
304
    protected void setDao(ITaxonNodeDao dao) {
305
        this.dao = dao;
306
    }
307

    
308
    @Override
309
    @Transactional(readOnly = false)
310
    public DeleteResult makeTaxonNodeASynonymOfAnotherTaxonNode(TaxonNode oldTaxonNode, TaxonNode newAcceptedTaxonNode,
311
            SynonymType synonymType, Reference citation, String microReference, SecReferenceHandlingEnum secHandling, boolean setNameInSource)  {
312

    
313
        // TODO at the moment this method only moves synonym-, concept relations and descriptions to the new accepted taxon
314
        // in a future version we also want to move cdm data like annotations, marker, so., but we will need a policy for that
315
        if (oldTaxonNode == null || newAcceptedTaxonNode == null || oldTaxonNode.getTaxon().getName() == null){
316
            throw new IllegalArgumentException("A mandatory parameter was null.");
317
        }
318

    
319
        if(oldTaxonNode.equals(newAcceptedTaxonNode)){
320
            throw new IllegalArgumentException("Taxon can not be made synonym of its own.");
321
        }
322

    
323
        Classification classification = oldTaxonNode.getClassification();
324
        Taxon oldTaxon = HibernateProxyHelper.deproxy(oldTaxonNode.getTaxon());
325
        Taxon newAcceptedTaxon = (Taxon)this.taxonService.find(newAcceptedTaxonNode.getTaxon().getUuid());
326
        newAcceptedTaxon = HibernateProxyHelper.deproxy(newAcceptedTaxon);
327
        // Move oldTaxon to newTaxon
328
        //TaxonName synonymName = oldTaxon.getName();
329
        TaxonName newSynonymName = CdmBase.deproxy(oldTaxon.getName());
330
        HomotypicalGroup group = CdmBase.deproxy(newSynonymName.getHomotypicalGroup());
331
        if (synonymType == null){
332
            if (newSynonymName.isHomotypic(newAcceptedTaxon.getName())){
333
                synonymType = SynonymType.HOMOTYPIC_SYNONYM_OF();
334
            }else{
335
                synonymType = SynonymType.HETEROTYPIC_SYNONYM_OF();
336
            }
337
        }
338

    
339
        //set homotypic group
340
        TaxonName newAcceptedTaxonName = HibernateProxyHelper.deproxy(newAcceptedTaxon.getName(), TaxonName.class);
341
        newAcceptedTaxon.setName(newAcceptedTaxonName);
342
        Reference secNewAccepted = newAcceptedTaxon.getSec();
343
        Reference secOldAccepted = oldTaxon.getSec();
344
        boolean uuidsEqual = (secNewAccepted != null && secOldAccepted != null && secNewAccepted.equals(secOldAccepted)) || (secNewAccepted == null && secOldAccepted == null);
345
        Reference newSec = citation;
346
        //keep when same only warns in ui, the sec still
347
        if (secHandling != null &&  secHandling.equals(SecReferenceHandlingEnum.KeepOrWarn) ){
348
            newSec = oldTaxon.getSec();
349
        }
350
        if (secHandling != null && secHandling.equals(SecReferenceHandlingEnum.AlwaysDelete)){
351
            newSec = null;
352
        }
353

    
354
        Synonym newSyn = newAcceptedTaxon.addSynonymName(newSynonymName, newSec, microReference, synonymType);
355
        if (newSec == null){
356
            newSyn.setSec(newSec);
357
        }
358
        newSyn.setPublish(oldTaxon.isPublish());
359

    
360
        // Move Synonyms to new Taxon
361
        // From ticket 3163 we can move taxon with accepted name having homotypic synonyms
362
        List<Synonym> synonymsInHomotypicalGroup = null;
363

    
364
        //the synonyms of the homotypical group of the old taxon
365
        if (synonymType.equals(SynonymType.HOMOTYPIC_SYNONYM_OF())){
366
        	synonymsInHomotypicalGroup = oldTaxon.getSynonymsInGroup(group);
367
        }
368

    
369
        Set<Synonym> syns = new HashSet<>(oldTaxon.getSynonyms());
370
        for(Synonym synonym : syns){
371
            SynonymType srt;
372
            if(synonym.getHomotypicGroup()!= null
373
                    && synonym.getHomotypicGroup().equals(newAcceptedTaxonName.getHomotypicalGroup())) {
374
                srt = SynonymType.HOMOTYPIC_SYNONYM_OF();
375
            } else if(synonym.getType() != null && synonym.getType().equals(SynonymType.HOMOTYPIC_SYNONYM_OF())) {
376
            	if (synonymType.equals(SynonymType.HOMOTYPIC_SYNONYM_OF())){
377
            		srt = SynonymType.HOMOTYPIC_SYNONYM_OF();
378
            	} else{
379
            		srt = SynonymType.HETEROTYPIC_SYNONYM_OF();
380
            	}
381
            } else {
382
                if (synonymsInHomotypicalGroup != null && synonymsInHomotypicalGroup.contains(synonym)){
383
                    srt = SynonymType.HOMOTYPIC_SYNONYM_OF();
384
                }else{
385
                    srt = synonym.getType();
386
                }
387
            }
388
            if (secHandling != null &&  !secHandling.equals(SecReferenceHandlingEnum.KeepOrWarn)){
389
                synonym.setSec(newSec);
390
            }
391
            newAcceptedTaxon.addSynonym(synonym, srt);
392
        }
393

    
394
        // CHILD NODES
395
        if(oldTaxonNode.getChildNodes() != null && oldTaxonNode.getChildNodes().size() != 0){
396
        	List<TaxonNode> childNodes = new ArrayList<>();
397
        	for (TaxonNode childNode : oldTaxonNode.getChildNodes()){
398
        		childNodes.add(childNode);
399
        	}
400
            for(TaxonNode childNode :childNodes){
401
                newAcceptedTaxonNode.addChildNode(childNode, childNode.getReference(), childNode.getMicroReference()); // childNode.getSynonymToBeUsed()
402
            }
403
        }
404

    
405
        //Move Taxon RelationShips to new Taxon
406
        for(TaxonRelationship taxonRelationship : oldTaxon.getTaxonRelations()){
407
            Taxon fromTaxon = HibernateProxyHelper.deproxy(taxonRelationship.getFromTaxon());
408
            Taxon toTaxon = HibernateProxyHelper.deproxy(taxonRelationship.getToTaxon());
409
            if (fromTaxon == oldTaxon){
410
                newAcceptedTaxon.addTaxonRelation(taxonRelationship.getToTaxon(), taxonRelationship.getType(),
411
                        taxonRelationship.getCitation(), taxonRelationship.getCitationMicroReference());
412

    
413
            }else if(toTaxon == oldTaxon){
414
               fromTaxon.addTaxonRelation(newAcceptedTaxon, taxonRelationship.getType(),
415
                        taxonRelationship.getCitation(), taxonRelationship.getCitationMicroReference());
416
               taxonService.saveOrUpdate(fromTaxon);
417

    
418
            }else{
419
                logger.warn("Taxon is not part of its own Taxonrelationship");
420
            }
421
            // Remove old relationships
422

    
423
            fromTaxon.removeTaxonRelation(taxonRelationship);
424
            toTaxon.removeTaxonRelation(taxonRelationship);
425
            taxonRelationship.setToTaxon(null);
426
            taxonRelationship.setFromTaxon(null);
427
        }
428

    
429
        //Move descriptions to new taxon
430
        List<TaxonDescription> descriptions = new ArrayList<TaxonDescription>( oldTaxon.getDescriptions()); //to avoid concurrent modification errors (newAcceptedTaxon.addDescription() modifies also oldtaxon.descritpions())
431
        for(TaxonDescription description : descriptions){
432
            String message = "Description copied from former accepted taxon: %s (Old title: %s)";
433
            message = String.format(message, oldTaxon.getTitleCache(), description.getTitleCache());
434
            description.setTitleCache(message, true);
435
            if (setNameInSource) {
436
                for (DescriptionElementBase element: description.getElements()){
437
                    for (DescriptionElementSource source: element.getSources()){
438
                        if (source.getNameUsedInSource() == null){
439
                            source.setNameUsedInSource(newSynonymName);
440
                        }
441
                    }
442
                }
443
            }
444
            //oldTaxon.removeDescription(description, false);
445
            newAcceptedTaxon.addDescription(description);
446
        }
447
        oldTaxon.clearDescriptions();
448

    
449
        taxonService.saveOrUpdate(newAcceptedTaxon);
450

    
451
        taxonService.saveOrUpdate(oldTaxon);
452
        taxonService.getSession().flush();
453

    
454
        TaxonDeletionConfigurator conf = new TaxonDeletionConfigurator();
455
        conf.setDeleteSynonymsIfPossible(false);
456
        conf.setDeleteNameIfPossible(false);
457
        DeleteResult taxonDeleteResult = taxonService.isDeletable(oldTaxon.getUuid(), conf);
458

    
459
        DeleteResult result;
460
        if (taxonDeleteResult.isOk()){
461
        	 result = taxonService.deleteTaxon(oldTaxon.getUuid(), conf, classification.getUuid());
462
        }else{
463
        	TaxonNodeDeletionConfigurator config = new TaxonNodeDeletionConfigurator();
464
        	config.setDeleteElement(false);
465
        	conf.setTaxonNodeConfig(config);
466
        	result = deleteTaxonNode(oldTaxonNode, conf);
467
        	result.getRelatedObjects().addAll(taxonDeleteResult.getRelatedObjects());  //we want to know what causes that the taxon can not be deleted
468
        	result.getExceptions().addAll(taxonDeleteResult.getExceptions()); //same for the exceptions
469
        }
470

    
471
        result.addUpdatedObject(newAcceptedTaxon);
472

    
473
        //oldTaxonNode.delete();
474
        return result;
475
    }
476

    
477
    @Override
478
    @Transactional(readOnly = false)
479
    public DeleteResult makeTaxonNodeSynonymsOfAnotherTaxonNode( Set<UUID> oldTaxonNodeUuids,
480
            UUID newAcceptedTaxonNodeUUIDs,
481
            SynonymType synonymType,
482
            UUID citation,
483
            String microReference,
484
            SecReferenceHandlingEnum secHandling,
485
            boolean setNameInSource) {
486
    	DeleteResult result = new DeleteResult();
487
    	for (UUID nodeUuid: oldTaxonNodeUuids) {
488
    		result.includeResult(makeTaxonNodeASynonymOfAnotherTaxonNode(nodeUuid, newAcceptedTaxonNodeUUIDs, synonymType, citation, microReference, secHandling, setNameInSource));
489
    	}
490
    	return result;
491
    }
492

    
493
    @Override
494
    @Transactional(readOnly = false)
495
    public DeleteResult makeTaxonNodeASynonymOfAnotherTaxonNode(UUID oldTaxonNodeUuid,
496
            UUID newAcceptedTaxonNodeUUID,
497
            SynonymType synonymType,
498
            UUID citationUuid,
499
            String microReference,
500
            SecReferenceHandlingEnum secHandling,
501
            boolean setNameInSource) {
502

    
503
        TaxonNode oldTaxonNode = dao.load(oldTaxonNodeUuid);
504
        TaxonNode oldTaxonParentNode = oldTaxonNode.getParent();
505
        TaxonNode newTaxonNode = dao.load(newAcceptedTaxonNodeUUID);
506
        Reference citation = referenceDao.load(citationUuid);
507

    
508
        switch (secHandling){
509
            case AlwaysDelete:
510
                citation = null;
511
                break;
512
            case UseNewParentSec:
513
                citation = newTaxonNode.getTaxon() != null? newTaxonNode.getTaxon().getSec(): null;
514
                break;
515
            case KeepOrWarn:
516

    
517
                Reference synSec = oldTaxonNode.getTaxon().getSec();
518
                if (synSec != null ){
519
                    citation = CdmBase.deproxy(synSec);
520
                }
521
                break;
522
            case KeepOrSelect:
523

    
524
                break;
525
            default:
526
                break;
527
        }
528

    
529
        DeleteResult result = makeTaxonNodeASynonymOfAnotherTaxonNode(oldTaxonNode,
530
                newTaxonNode,
531
                synonymType,
532
                citation,
533
                microReference,
534
                secHandling, setNameInSource);
535

    
536
        result.addUpdatedCdmId(CdmEntityIdentifier.NewInstance(oldTaxonParentNode));
537
        result.addUpdatedCdmId(CdmEntityIdentifier.NewInstance(newTaxonNode));
538
        result.setCdmEntity(oldTaxonParentNode);
539
        return result;
540
    }
541

    
542
    @Override
543
    @Transactional(readOnly = false)
544
    public DeleteResult deleteTaxonNodes(List<TaxonNode> list, TaxonDeletionConfigurator config) {
545

    
546
        if (config == null){
547
        	config = new TaxonDeletionConfigurator();
548
        }
549
        DeleteResult result = new DeleteResult();
550
        Classification classification = null;
551
        List<TaxonNode> taxonNodes = new ArrayList<>(list);
552

    
553
        for (TaxonNode treeNode:taxonNodes){
554
        	if (treeNode != null){
555

    
556
        		TaxonNode taxonNode;
557
	            taxonNode = CdmBase.deproxy(treeNode);
558
	            TaxonNode parent = taxonNode.getParent();
559
	            	//check whether the node has children or the children are already deleted
560
	            if(taxonNode.hasChildNodes()) {
561
            		List<TaxonNode> children = new ArrayList<> ();
562
            		List<TaxonNode> childNodesList = taxonNode.getChildNodes();
563
        			children.addAll(childNodesList);
564
        			//To avoid NPE when child is also in list of taxonNodes, remove it from the list
565
        			Iterator<TaxonNode> it = taxonNodes.iterator();
566
        			for (TaxonNode child: children) {
567
        				while (it.hasNext()) {
568
        					if (it.next().equals(child)) {
569
        						it.remove();
570
        					}
571
        				}
572
        			}
573
        			int compare = config.getTaxonNodeConfig().getChildHandling().compareTo(ChildHandling.DELETE);
574
        			boolean childHandling = (compare == 0)? true: false;
575
            		if (childHandling){
576
            			boolean changeDeleteTaxon = false;
577
            			if (!config.getTaxonNodeConfig().isDeleteTaxon()){
578
            				config.getTaxonNodeConfig().setDeleteTaxon(true);
579
            				changeDeleteTaxon = true;
580
            			}
581
            			DeleteResult resultNodes = deleteTaxonNodes(children, config);
582
            			if (!resultNodes.isOk()){
583
                            result.addExceptions(resultNodes.getExceptions());
584
                            result.setStatus(resultNodes.getStatus());
585
                        }
586
            			if (changeDeleteTaxon){
587
            				config.getTaxonNodeConfig().setDeleteTaxon(false);
588
            			}
589

    
590
            		} else {
591
            			//move the children to the parent
592

    
593
            			for (TaxonNode child: childNodesList){
594
            				parent.addChildNode(child, child.getReference(), child.getMicroReference());
595
            			}
596
            		}
597
            	}
598

    
599
	            classification = taxonNode.getClassification();
600

    
601
	            if (classification.getRootNode().equals(taxonNode)){
602
	            	classification.removeRootNode();
603
	            	classification = null;
604
	            }else if (classification.getChildNodes().contains(taxonNode)){
605
            		Taxon taxon = taxonNode.getTaxon();
606
            		classification.deleteChildNode(taxonNode);
607

    
608
	            	//node is rootNode
609
	            	if (taxon != null){
610

    
611
	            		if (config.getTaxonNodeConfig().isDeleteTaxon()){
612
	            		    taxonService.saveOrUpdate(taxon);
613
	            		    saveOrUpdate(taxonNode);
614

    
615
			            	TaxonDeletionConfigurator configNew = new TaxonDeletionConfigurator();
616
			            	configNew.setClassificationUuid(classification.getUuid());
617
			            	DeleteResult resultTaxon = taxonService.deleteTaxon(taxon.getUuid(), configNew, classification.getUuid());
618
			            	if (!resultTaxon.isOk()){
619
                                result.addExceptions(resultTaxon.getExceptions());
620
                                result.setStatus(resultTaxon.getStatus());
621
                            }
622

    
623
		            	}
624
	            	}
625
            		classification = null;
626

    
627
	            } else {
628
	            	//classification = null;
629
	            	Taxon taxon = taxonNode.getTaxon();
630
	            	taxon = CdmBase.deproxy(taxon);
631
	            	if (taxon != null){
632
	            		taxon.removeTaxonNode(taxonNode);
633
	            		if (config.getTaxonNodeConfig().isDeleteTaxon()){
634
			            	TaxonDeletionConfigurator configNew = new TaxonDeletionConfigurator();
635
			            	saveOrUpdate(taxonNode);
636
			            	taxonService.saveOrUpdate(taxon);
637
			            	DeleteResult resultTaxon = taxonService.deleteTaxon(taxon.getUuid(), configNew, classification.getUuid());
638

    
639
                            if (!resultTaxon.isOk()){
640
                                result.addExceptions(resultTaxon.getExceptions());
641
                                result.setStatus(resultTaxon.getStatus());
642
                            }
643
		            	}
644
	            	}
645

    
646
	            }
647

    
648
	            result.addUpdatedObject(parent);
649
	            if(result.getCdmEntity() == null){
650
	                result.setCdmEntity(taxonNode);
651
                }
652
	            UUID uuid = dao.delete(taxonNode);
653
	            logger.debug("Deleted node " +uuid.toString());
654

    
655
	        }
656
        }
657
        /*if (classification != null){
658
            result.addUpdatedObject(classification);
659
        	DeleteResult resultClassification = classService.delete(classification);
660
        	 if (!resultClassification.isOk()){
661
                 result.addExceptions(resultClassification.getExceptions());
662
                 result.setStatus(resultClassification.getStatus());
663
             }
664
        }*/
665
        return result;
666
    }
667

    
668

    
669
    @Override
670
    @Transactional(readOnly = false)
671
    public DeleteResult deleteTaxonNodes(Collection<UUID> nodeUuids, TaxonDeletionConfigurator config) {
672
        List<TaxonNode> nodes = new ArrayList<>();
673
        for(UUID nodeUuid : nodeUuids) {
674
            nodes.add(dao.load(nodeUuid));
675
        }
676
        return deleteTaxonNodes(nodes, config);
677
    }
678

    
679

    
680
    @Override
681
    @Transactional(readOnly = false)
682
    public DeleteResult deleteTaxonNode(UUID nodeUUID, TaxonDeletionConfigurator config) {
683

    
684
    	TaxonNode node = CdmBase.deproxy(dao.load(nodeUUID));
685
    	return deleteTaxonNode(node, config);
686
    }
687

    
688
    @Override
689
    @Transactional(readOnly = false)
690
    public DeleteResult deleteTaxonNode(TaxonNode node, TaxonDeletionConfigurator config) {
691
        DeleteResult result = new DeleteResult();
692
        if (node == null){
693
            result.setAbort();
694
            result.addException(new Exception("The TaxonNode was already deleted."));
695
            return result;
696
        }
697
        Taxon taxon = null;
698
        try{
699
            taxon = HibernateProxyHelper.deproxy(node.getTaxon());
700
        }catch(NullPointerException e){
701
            result.setAbort();
702
            result.addException(new Exception("The Taxon was already deleted."));
703
        }
704

    
705
    	TaxonNode parent = HibernateProxyHelper.deproxy(node.getParent(), TaxonNode.class);
706
    	if (config == null){
707
    		config = new TaxonDeletionConfigurator();
708
    	}
709

    
710
    	if (config.getTaxonNodeConfig().getChildHandling().equals(ChildHandling.MOVE_TO_PARENT)){
711
    	   Object[] children = node.getChildNodes().toArray();
712
    	   TaxonNode childNode;
713
    	   for (Object child: children){
714
    	       childNode = (TaxonNode) child;
715
    	       parent.addChildNode(childNode, childNode.getReference(), childNode.getMicroReference());
716
    	   }
717
    	}else{
718
    	    DeleteResult tmpResult = deleteTaxonNodes(node.getChildNodes(), config);
719
    	    result.includeResult(tmpResult);
720
    	}
721

    
722
    	//remove node from DescriptiveDataSet
723
        commonService.getReferencingObjects(node).stream()
724
            .filter(obj->obj instanceof DescriptiveDataSet)
725
            .forEach(dataSet->{
726
                ((DescriptiveDataSet)dataSet).removeTaxonSubtree(node);
727
                dataSetService.saveOrUpdate((DescriptiveDataSet) dataSet);
728
        });
729

    
730
    	if (taxon != null){
731
        	if (config.getTaxonNodeConfig().isDeleteTaxon() && (config.isDeleteInAllClassifications() || taxon.getTaxonNodes().size() == 1)){
732
        		result = taxonService.deleteTaxon(taxon.getUuid(), config, node.getClassification().getUuid());
733
        		result.addUpdatedObject(parent);
734
        		if (result.isOk()){
735
        			return result;
736
        		}
737
        	} else {
738
        	    result.addUpdatedObject(taxon);
739
        	}
740
    	}
741
    	result.setCdmEntity(node);
742
    	boolean success = true;
743
    	if (taxon != null){
744
    	    success = taxon.removeTaxonNode(node);
745
    	    taxonService.saveOrUpdate(taxon);
746
    	}
747
    	dao.saveOrUpdate(parent);
748

    
749
    	result.addUpdatedObject(parent);
750

    
751
    	if (success){
752
			result.setStatus(Status.OK);
753
			if (parent != null){
754
    			parent = HibernateProxyHelper.deproxy(parent, TaxonNode.class);
755
    			int index = parent.getChildNodes().indexOf(node);
756
    			if (index > -1){
757
    			    parent.removeChild(index);
758
    			}
759
			}
760
    		if (!dao.delete(node, config.getTaxonNodeConfig().getChildHandling().equals(ChildHandling.DELETE)).equals(null)){
761
    		    result.getUpdatedObjects().remove(node);
762
    			result.addDeletedObject(node);
763
    			return result;
764
    		} else {
765
    			result.setError();
766
    			return result;
767
    		}
768
    	}else{
769
    	    if (dao.findByUuid(node.getUuid()) != null){
770
        		result.setError();
771
        		result.addException(new Exception("The node can not be removed from the taxon."));
772
    		}
773
    		return result;
774
    	}
775
    }
776

    
777

    
778
    @Override
779
    public List<TaxonNode> listAllNodesForClassification(Classification classification, Integer start, Integer end) {
780
        return dao.getTaxonOfAcceptedTaxaByClassification(classification, start, end);
781
    }
782

    
783
    @Override
784
    public int countAllNodesForClassification(Classification classification) {
785
        return dao.countTaxonOfAcceptedTaxaByClassification(classification);
786
    }
787

    
788
    @Override
789
    @Transactional
790
    public UpdateResult moveTaxonNode(UUID taxonNodeUuid, UUID targetNodeUuid, int movingType, SecReferenceHandlingEnum secHandling, UUID secUuid){
791
        TaxonNode taxonNode = HibernateProxyHelper.deproxy(dao.load(taxonNodeUuid));
792
    	TaxonNode targetNode = HibernateProxyHelper.deproxy(dao.load(targetNodeUuid));
793
    	Reference sec = null;
794
    	if (secUuid != null){
795
    	    sec = HibernateProxyHelper.deproxy(referenceDao.load(secUuid));
796
    	}
797
    	UpdateResult result = moveTaxonNode(taxonNode, targetNode, movingType, secHandling, sec);
798
    	return result;
799
    }
800

    
801
    @Override
802
    @Transactional
803
    public UpdateResult moveTaxonNode(TaxonNode taxonNode, TaxonNode newParent, int movingType, SecReferenceHandlingEnum secHandling, Reference sec){
804
        UpdateResult result = new UpdateResult();
805

    
806
        TaxonNode parentParent = HibernateProxyHelper.deproxy(newParent.getParent());
807
        Integer sortIndex = -1;
808
        if (movingType == 0){
809
            sortIndex = 0;
810
        }else if (movingType == 1){
811
            sortIndex = newParent.getSortIndex();
812
            newParent = parentParent;
813
        } else if (movingType == 2){
814
            sortIndex = newParent.getSortIndex() +1;
815
            newParent = parentParent;
816
        } else{
817
            result.setAbort();
818
            result.addException(new Exception("The moving type "+ movingType +" is not supported."));
819
        }
820

    
821
        if (secHandling.equals(SecReferenceHandlingEnum.AlwaysSelect) || (secHandling.equals(SecReferenceHandlingEnum.KeepOrSelect) && sec != null)){
822
            if (taxonNode.getTaxon() != null){
823
                taxonNode.getTaxon().setSec(sec);
824
            }
825
        }else if (secHandling.equals(SecReferenceHandlingEnum.AlwaysDelete)){
826
            if (taxonNode.getTaxon() != null){
827
                taxonNode.getTaxon().setSec(null);
828
            }
829
        }else if (secHandling.equals(SecReferenceHandlingEnum.UseNewParentSec)){
830
            if (taxonNode.getTaxon() != null && newParent.getTaxon()!= null){
831
                taxonNode.getTaxon().setSec(newParent.getTaxon().getSec());
832
            }
833
        }
834

    
835
        taxonNode = newParent.addChildNode(taxonNode, sortIndex, taxonNode.getReference(),  taxonNode.getMicroReference());
836
        result.addUpdatedObject(taxonNode);
837

    
838
        return result;
839
    }
840

    
841
    @Override
842
    @Transactional
843
    public UpdateResult moveTaxonNodes(Set<UUID> taxonNodeUuids, UUID newParentNodeUuid, int movingType, SecReferenceHandlingEnum secHandling, UUID secUuid, IProgressMonitor monitor){
844

    
845
        if (monitor == null){
846
            monitor = DefaultProgressMonitor.NewInstance();
847
        }
848
        UpdateResult result = new UpdateResult();
849
        List<String> taxonNodePropertyPath = new ArrayList<>();
850
        taxonNodePropertyPath.add("taxon.secSource.*");
851
        taxonNodePropertyPath.add("parent.taxon.secSource.*");
852
        TaxonNode targetNode = dao.load(newParentNodeUuid, taxonNodePropertyPath);
853
        List<TaxonNode> nodes = dao.list(taxonNodeUuids, null, null, null, null);
854
        Reference sec = referenceDao.load(secUuid);
855

    
856
        monitor.beginTask("Move Taxonnodes", nodes.size()*2);
857
        monitor.subTask("move taxon nodes");
858
        for (TaxonNode node: nodes){
859
            if (!monitor.isCanceled()){
860
                if (!nodes.contains(node.getParent())){
861
                    result.includeResult(moveTaxonNode(node, targetNode, movingType, secHandling, sec));
862
                }
863
                monitor.worked(1);
864
            }else{
865
                monitor.done();
866
                result.setAbort();
867
                break;
868
            }
869
        }
870
        if (!monitor.isCanceled()){
871
            monitor.subTask("saving and reindex");
872
            dao.saveOrUpdateAll(nodes);
873
        }else{
874
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
875
        }
876

    
877
        monitor.done();
878
        return result;
879
    }
880

    
881
    @Override
882
    public Pager<TaxonNodeAgentRelation> pageTaxonNodeAgentRelations(UUID taxonUuid, UUID classificationUuid,
883
            UUID agentUuid, UUID rankUuid, UUID relTypeUuid, Integer pageSize, Integer pageIndex, List<String> propertyPaths) {
884

    
885
        List<TaxonNodeAgentRelation> records = null;
886

    
887
        long count = dao.countTaxonNodeAgentRelations(taxonUuid, classificationUuid, agentUuid, rankUuid, relTypeUuid);
888
        if(PagerUtils.hasResultsInRange(count, pageIndex, pageSize)) {
889
            records = dao.listTaxonNodeAgentRelations(taxonUuid, classificationUuid,
890
                    agentUuid, rankUuid, relTypeUuid, PagerUtils.startFor(pageSize, pageIndex), PagerUtils.limitFor(pageSize), propertyPaths);
891
        }
892

    
893
        Pager<TaxonNodeAgentRelation> pager = new DefaultPagerImpl<>(pageIndex, count, pageSize, records);
894
        return pager;
895
    }
896

    
897
    @Override
898
    @Transactional
899
    public UpdateResult createNewTaxonNode(UUID parentNodeUuid, CreateTaxonDTO taxonDto,
900
            NamedSource source, String microref,
901
            TaxonNodeStatus status, Map<Language,LanguageString> statusNote){
902

    
903
        UpdateResult result = new UpdateResult();
904
        TaxonNode child = null;
905
        TaxonNode parent = null;
906
        try{
907
            TaxonName name = null;
908
            Taxon taxon = null;
909
            if (taxonDto.getTaxonUuid() != null){
910
                taxon = (Taxon) taxonService.load(taxonDto.getTaxonUuid());
911
                if (taxon == null){
912
                    throw new RuntimeException("Taxon for not found for id " + taxonDto.getTaxonUuid());
913
                }
914
            }else{
915
                if (taxonDto.getNameUuid() != null){
916
                    name = nameService.load(taxonDto.getNameUuid());
917
                    if (name == null){
918
                        throw new RuntimeException("Taxon name not found for id " + taxonDto.getTaxonUuid());
919
                    }
920
                } else {
921
                    UpdateResult tmpResult = nameService.parseName(taxonDto.getTaxonNameString(),
922
                            taxonDto.getCode(), taxonDto.getPreferredRank(),  true);
923
                    result.addUpdatedObjects(tmpResult.getUpdatedObjects());
924
                    name = (TaxonName)tmpResult.getCdmEntity();
925
                }
926
                Reference sec = null;
927
                if (taxonDto.getSecUuid() != null ){
928
                    sec = referenceService.load(taxonDto.getSecUuid());
929
                }
930
                if (name != null && !name.isPersited()){
931
                    for (HybridRelationship rel : name.getHybridChildRelations()){
932
                        if (!rel.getHybridName().isPersited()) {
933
                            nameService.save(rel.getHybridName());
934
                        }
935
                        if (!rel.getParentName().isPersited()) {
936
                            nameService.save(rel.getParentName());
937
                        }
938
                    }
939
                }
940
                taxon = Taxon.NewInstance(name, sec);
941
                taxon.setPublish(taxonDto.isPublish());
942
            }
943

    
944
            parent = dao.load(parentNodeUuid);
945
            if (source != null){
946
                if (source.isPersited()){
947
                    source = (NamedSource) sourceDao.load(source.getUuid());
948
                }
949
                if (source.getCitation() != null){
950
                    source.setCitation(referenceService.load(source.getCitation().getUuid()));
951
                }
952
                if (source.getNameUsedInSource() !=null){
953
                    source.setNameUsedInSource(nameService.load(source.getNameUsedInSource().getUuid()));
954
                }
955
            }
956

    
957
            child = parent.addChildTaxon(taxon, source);
958
            child.setStatus(status);
959

    
960
            if (statusNote != null){
961
                child.getStatusNote().putAll(statusNote);
962
            }
963

    
964
        }catch(Exception e){
965
            result.addException(e);
966
            result.setError();
967
            return result;
968
        }
969
        child = dao.save(child);
970

    
971
        result.addUpdatedObject(parent);
972
        if (child != null){
973
            result.setCdmEntity(child);
974
        }
975
        return result;
976
    }
977

    
978
    @Override
979
    @Transactional
980
    public UpdateResult addTaxonNodeAgentRelation(UUID taxonNodeUUID, UUID agentUUID, DefinedTerm relationshipType){
981
        UpdateResult result = new UpdateResult();
982
        TaxonNode node = dao.load(taxonNodeUUID);
983
        TeamOrPersonBase<?> agent = (TeamOrPersonBase<?>) agentService.load(agentUUID);
984
        node.addAgentRelation(relationshipType, agent);
985
        try{
986
            dao.merge(node, true);
987
        }catch (Exception e){
988
            result.setError();
989
            result.addException(e);
990
        }
991
        result.setCdmEntity(node);
992
        return result;
993
    }
994

    
995
    @Override
996
    @Transactional(readOnly=false)
997
    public UpdateResult setSecundumForSubtree(SecundumForSubtreeConfigurator config) {
998
        UpdateResult result = new UpdateResult();
999
        IProgressMonitor monitor = config.getMonitor();
1000

    
1001
        if (monitor == null){
1002
            monitor = DefaultProgressMonitor.NewInstance();
1003
        }
1004
        monitor.beginTask("Update secundum reference for subtree", 100);
1005
        monitor.subTask("Check start conditions");
1006

    
1007
        if (config.getSubtreeUuid() == null){
1008
            result.setError();
1009
            result.addException(new NullPointerException("No subtree given"));
1010
            monitor.done();
1011
            return result;
1012
        }
1013
        monitor.worked(1);
1014
        TaxonNode subTree = load(config.getSubtreeUuid());
1015
        if (subTree == null){
1016
            result.setError();
1017
            result.addException(new NullPointerException("Subtree does not exist"));
1018
            monitor.done();
1019
            return result;
1020
        }
1021
        monitor.worked(1);
1022

    
1023
        Reference newSec = null;
1024
        if (config.getNewSecundum() != null){
1025
            newSec = referenceService.load(config.getNewSecundum().getUuid());
1026
            if (newSec == null){
1027
                result.setError();
1028
                result.addException(new NullPointerException("New secundum reference does not exist"));
1029
                monitor.done();
1030
                return result;
1031
            }
1032
        }
1033
        monitor.worked(1);
1034

    
1035
        monitor.subTask("Count records");
1036
        try {
1037
            boolean includeRelatedTaxa = config.isIncludeProParteSynonyms() || config.isIncludeMisapplications();
1038

    
1039
            TreeIndex subTreeIndex = TreeIndex.NewInstance(subTree.treeIndex());
1040
            int count = config.isIncludeAcceptedTaxa() ? dao.countSecundumForSubtreeAcceptedTaxa(subTreeIndex, newSec, config.isOverwriteExisting(), config.isIncludeSharedTaxa(), config.isEmptySecundumDetail()):0;
1041
            monitor.worked(2);
1042
            count += config.isIncludeSynonyms() ? dao.countSecundumForSubtreeSynonyms(subTreeIndex, newSec, config.isOverwriteExisting(), config.isIncludeSharedTaxa(), config.isEmptySecundumDetail()) :0;
1043
            monitor.worked(3);
1044
            count += includeRelatedTaxa ? dao.countSecundumForSubtreeRelations(subTreeIndex, newSec, config.isOverwriteExisting(), config.isIncludeSharedTaxa(), config.isEmptySecundumDetail()):0;
1045
            monitor.worked(2);
1046
            if (monitor.isCanceled()){
1047
                return result;
1048
            }
1049

    
1050
            SubProgressMonitor subMonitor = SubProgressMonitor.NewStarted(monitor, 90, "Updating secundum for subtree", count * 2);  //*2 1 tick for update and 1 tick for commit
1051
            //Reference ref = config.getNewSecundum();
1052
            if (config.isIncludeAcceptedTaxa()){
1053
                monitor.subTask("Update Accepted Taxa");
1054
                Set<CdmBase> updatedTaxa = dao.setSecundumForSubtreeAcceptedTaxa(subTreeIndex, newSec,
1055
                        config.isOverwriteExisting(), config.isIncludeSharedTaxa(), config.isEmptySecundumDetail(), subMonitor);
1056
                result.addUpdatedObjects(updatedTaxa);
1057
                if (monitor.isCanceled()){
1058
                    return result;
1059
                }
1060
            }
1061
            if (config.isIncludeSynonyms()){
1062
               monitor.subTask("Update Synonyms");
1063
               Set<CdmBase> updatedSynonyms = dao.setSecundumForSubtreeSynonyms(subTreeIndex, newSec,
1064
                       config.isOverwriteExisting(), config.isIncludeSharedTaxa() , config.isEmptySecundumDetail(), subMonitor);
1065
               result.addUpdatedObjects(updatedSynonyms);
1066
               if (monitor.isCanceled()){
1067
                   return result;
1068
               }
1069
            }
1070
            if (includeRelatedTaxa){
1071
                monitor.subTask("Update Related Taxa");
1072
                Set<UUID> relationTypes = getRelationTypesForSubtree(config);
1073
                Set<CdmBase> updatedRels = dao.setSecundumForSubtreeRelations(subTreeIndex, newSec,
1074
                        relationTypes, config.isOverwriteExisting(), config.isIncludeSharedTaxa() , config.isEmptySecundumDetail(), subMonitor);
1075
                result.addUpdatedObjects(updatedRels);
1076
                if (monitor.isCanceled()){
1077
                    return result;
1078
                }
1079
            }
1080
        } catch (Exception e) {
1081
            result.setError();
1082
            result.addException(e);
1083
        }
1084
        monitor.done();
1085
        return result;
1086
    }
1087

    
1088
    @Override
1089
    @Transactional(readOnly=false)
1090
    public UpdateResult setPublishForSubtree(PublishForSubtreeConfigurator config){
1091
        UpdateResult result = new UpdateResult();
1092
        IProgressMonitor monitor = config.getMonitor();
1093
        if (monitor == null){
1094
            monitor = DefaultProgressMonitor.NewInstance();
1095
        }
1096
        monitor.beginTask("Update publish flag for subtree", 100);
1097
        monitor.subTask("Check start conditions");
1098

    
1099
        if (config.getSubtreeUuid() == null){
1100
            result.setError();
1101
            result.addException(new NullPointerException("No subtree given"));
1102
            monitor.done();
1103
            return result;
1104
        }
1105
        monitor.worked(1);
1106

    
1107
        TaxonNode subTree = find(config.getSubtreeUuid());
1108
        if (subTree == null){
1109
            result.setError();
1110
            result.addException(new NullPointerException("Subtree does not exist"));
1111
            monitor.done();
1112
            return result;
1113
        }
1114
        monitor.worked(1);
1115

    
1116
        monitor.subTask("Count records");
1117
        boolean includeAcceptedTaxa = config.isIncludeAcceptedTaxa();
1118
        boolean publish = config.isPublish();
1119
        boolean includeSynonyms = config.isIncludeSynonyms();
1120
        boolean includeSharedTaxa = config.isIncludeSharedTaxa();
1121
        boolean includeHybrids = config.isIncludeHybrids();
1122
        boolean includeRelatedTaxa = config.isIncludeProParteSynonyms() || config.isIncludeMisapplications();
1123
        try {
1124
            TreeIndex subTreeIndex = TreeIndex.NewInstance(subTree.treeIndex());
1125
            int count = includeAcceptedTaxa ? dao.countPublishForSubtreeAcceptedTaxa(subTreeIndex, publish, includeSharedTaxa, includeHybrids):0;
1126
            monitor.worked(3);
1127
            count += includeSynonyms ? dao.countPublishForSubtreeSynonyms(subTreeIndex, publish, includeSharedTaxa, includeHybrids):0;
1128
            monitor.worked(3);
1129
            count += includeRelatedTaxa ? dao.countPublishForSubtreeRelatedTaxa(subTreeIndex, publish, includeSharedTaxa, includeHybrids):0;
1130
            monitor.worked(2);
1131
            if (monitor.isCanceled()){
1132
                return result;
1133
            }
1134

    
1135
            SubProgressMonitor subMonitor = SubProgressMonitor.NewStarted(monitor, 90, "Updating secundum for subtree", count);
1136
            if (includeAcceptedTaxa){
1137
                monitor.subTask("Update Accepted Taxa");
1138
                @SuppressWarnings("rawtypes")
1139
                Set<TaxonBase> updatedTaxa = dao.setPublishForSubtreeAcceptedTaxa(subTreeIndex,
1140
                        publish, includeSharedTaxa, includeHybrids, subMonitor);
1141
                result.addUpdatedObjects(updatedTaxa);
1142
                if (monitor.isCanceled()){
1143
                    return result;
1144
                }
1145
            }
1146
            if (includeSynonyms){
1147
                monitor.subTask("Update Synonyms");
1148
                @SuppressWarnings("rawtypes")
1149
                Set<TaxonBase> updatedSynonyms = dao.setPublishForSubtreeSynonyms(subTreeIndex,
1150
                        publish, includeSharedTaxa, includeHybrids, subMonitor);
1151
                result.addUpdatedObjects(updatedSynonyms);
1152
                if (monitor.isCanceled()){
1153
                    return result;
1154
                }
1155
            }
1156
            if (includeRelatedTaxa){
1157
                monitor.subTask("Update Related Taxa");
1158
                Set<UUID> relationTypes = getRelationTypesForSubtree(config);
1159
                if (config.isIncludeMisapplications()){
1160
                    relationTypes.addAll(TaxonRelationshipType.misappliedNameUuids());
1161
                }
1162
                if (config.isIncludeProParteSynonyms()){
1163
                    relationTypes.addAll(TaxonRelationshipType.proParteOrPartialSynonymUuids());
1164
                }
1165
                @SuppressWarnings("rawtypes")
1166
                Set<TaxonBase> updatedTaxa = dao.setPublishForSubtreeRelatedTaxa(subTreeIndex, publish,
1167
                        relationTypes, includeSharedTaxa, includeHybrids, subMonitor);
1168
                result.addUpdatedObjects(updatedTaxa);
1169
                if (monitor.isCanceled()){
1170
                    return result;
1171
                }
1172
            }
1173
        } catch (Exception e) {
1174
            result.setError();
1175
            result.addException(e);
1176
        }
1177

    
1178
        monitor.done();
1179
        return result;
1180
    }
1181

    
1182
    private Set<UUID> getRelationTypesForSubtree(ForSubtreeConfiguratorBase config) {
1183
        Set<UUID> relationTypes = new HashSet<>();
1184
        if (config.isIncludeMisapplications()){
1185
            relationTypes.addAll(TaxonRelationshipType.misappliedNameUuids());
1186
        }
1187
        if (config.isIncludeProParteSynonyms()){
1188
            relationTypes.addAll(TaxonRelationshipType.proParteOrPartialSynonymUuids());
1189
        }
1190
        return relationTypes;
1191
    }
1192

    
1193
    @Override
1194
    public long count(TaxonNodeFilter filter){
1195
        return nodeFilterDao.count(filter);
1196
    }
1197

    
1198
    @Override
1199
    public List<UUID> uuidList(TaxonNodeFilter filter){
1200
        return nodeFilterDao.listUuids(filter);
1201
    }
1202

    
1203
    @Override
1204
    public List<Integer> idList(TaxonNodeFilter filter){
1205
        return nodeFilterDao.idList(filter);
1206
    }
1207

    
1208
    @Override
1209
    public TaxonNodeDto findCommonParentDto(Collection<TaxonNodeDto> nodes) {
1210
        TaxonNodeDto commonParent = null;
1211
        List<String> treePath = null;
1212
        for (TaxonNodeDto nodeDto : nodes) {
1213
            String nodeTreeIndex = nodeDto.getTreeIndex();
1214
            nodeTreeIndex = nodeTreeIndex.replaceFirst("#", "");
1215
            String[] split = nodeTreeIndex.split("#");
1216
            if(treePath == null){
1217
                treePath = Arrays.asList(split);
1218
            }
1219
            else{
1220
                List<String> match = new ArrayList<>();
1221
                for(int i=0;i<treePath.size();i++){
1222
                    if(i>=split.length){
1223
                        //current tree index is shorter so break
1224
                        break;
1225
                    }
1226
                    else if(split[i].equals(treePath.get(i))){
1227
                        //match found
1228
                        match.add(treePath.get(i));
1229
                    }
1230
                    else{
1231
                        //first mismatch found
1232
                        break;
1233
                    }
1234
                }
1235
                treePath = match;
1236
                if(treePath.isEmpty()){
1237
                    //no common parent found for at least two nodes
1238
                    //-> they belong to a different classification
1239
                    break;
1240
                }
1241
            }
1242
        }
1243
        if(treePath!=null && !treePath.isEmpty()) {
1244
            //get last index
1245
            int nodeId = Integer.parseInt(treePath.get(treePath.size()-1));
1246
            TaxonNode taxonNode = dao.load(nodeId, null);
1247
            commonParent = new TaxonNodeDto(taxonNode);
1248
        }
1249
        return commonParent;
1250
    }
1251

    
1252
    @Override
1253
    public List<TaxonDistributionDTO> getTaxonDistributionDTO(List<UUID> nodeUuids, List<String> propertyPaths,
1254
            Authentication authentication, boolean openChildren, TaxonNodeSortMode sortMode){
1255

    
1256
        nodeUuids = nodeUuids.stream().distinct().collect(Collectors.toList());
1257
        List<TaxonNode> nodes = new ArrayList<>();
1258

    
1259
        List<TaxonNode> parentNodes = load(nodeUuids, propertyPaths);
1260
        if (sortMode != null){
1261
            parentNodes.sort(sortMode.comparator());
1262
        }
1263
        if (openChildren){
1264
            //TODO we could remove nodes which are children of other nodes in parentNodes list here as they are duplicates
1265
            for (TaxonNode node: parentNodes){
1266
                if (node == null || nodes.contains(node)){
1267
                    continue;
1268
                }
1269
                nodes.add(node);
1270
                List<TaxonNode> children = new ArrayList<>();
1271
                children.addAll(loadChildNodesOfTaxonNode(node,
1272
                        propertyPaths, true,  true, sortMode));
1273
                for (TaxonNode child: children){
1274
                    if (!nodes.contains(child)){
1275
                        nodes.add(child);
1276
                    }
1277
                }
1278
            }
1279
        }else{
1280
            nodes.addAll(nodes);
1281
        }
1282

    
1283
        List<TaxonDistributionDTO> result = new ArrayList<>();
1284
        boolean hasPermission = false;
1285
        for(TaxonNode node: nodes){
1286
            if (authentication != null ) {
1287
                hasPermission = permissionEvaluator.hasPermission(authentication, node, Operation.UPDATE);
1288
            }else {
1289
                hasPermission = true;
1290
            }
1291
            if (node.getTaxon() != null && hasPermission){
1292
                try{
1293
                    TaxonDistributionDTO dto = new TaxonDistributionDTO(node);
1294
                    result.add(dto);
1295
                }catch(Exception e){
1296
                    logger.error(e.getMessage(), e);
1297
                }
1298
            }
1299
        }
1300
        return result;
1301
    }
1302

    
1303
    @Override
1304
    public <S extends TaxonNode> Pager<S> page(Class<S> clazz, List<Restriction<?>> restrictions, Integer pageSize,
1305
            Integer pageIndex, List<OrderHint> orderHints, List<String> propertyPaths) {
1306
        return page(clazz, restrictions, pageSize, pageIndex, orderHints, propertyPaths, INCLUDE_UNPUBLISHED);
1307
    }
1308

    
1309
    @Override
1310
    public <S extends TaxonNode> Pager<S> page(Class<S> clazz, List<Restriction<?>> restrictions, Integer pageSize,
1311
            Integer pageIndex, List<OrderHint> orderHints, List<String> propertyPaths, boolean includeUnpublished) {
1312

    
1313
        List<S> records;
1314
        long resultSize = dao.count(clazz, restrictions);
1315
        if(AbstractPagerImpl.hasResultsInRange(resultSize, pageIndex, pageSize)){
1316
            records = dao.list(clazz, restrictions, pageSize, pageIndex, orderHints, propertyPaths, includeUnpublished);
1317
        } else {
1318
            records = new ArrayList<>();
1319
        }
1320
        Pager<S> pager = new DefaultPagerImpl<>(pageIndex, resultSize, pageSize, records);
1321
        return pager;
1322
    }
1323

    
1324
    @Override
1325
    public List<TaxonDistributionDTO> getTaxonDistributionDTO(List<UUID> nodeUuids,
1326
            List<String> propertyPaths, boolean openChildren) {
1327
        return getTaxonDistributionDTO(nodeUuids, propertyPaths, null, openChildren, null);
1328
    }
1329

    
1330
    @Override
1331
    @Transactional(readOnly = false)
1332
    public UpdateResult cloneSubtree(SubtreeCloneConfigurator config) {
1333
        UpdateResult result = new UpdateResult();
1334

    
1335
        if (config.getSubTreeUuids().isEmpty()){
1336
            return result;
1337
        }
1338

    
1339
        //TODO error handling
1340
        Reference taxonSecundum = config.isReuseTaxa() || config.isReuseTaxonSecundum() || config.getTaxonSecundumUuid() == null ?
1341
                null : referenceDao.findByUuid(config.getTaxonSecundumUuid());
1342
        config.setTaxonSecundum(taxonSecundum);
1343

    
1344
        Reference parentChildReference = config.isReuseParentChildReference() || config.getParentChildReferenceUuid() == null ?
1345
                null : referenceDao.findByUuid(config.getParentChildReferenceUuid());
1346
        config.setParentChildReference(parentChildReference);
1347

    
1348
        Reference taxonRelationshipReference = config.getRelationTypeToOldTaxon() == null ?
1349
                null : referenceDao.findByUuid(config.getRelationshipReferenceUuid());
1350
        config.setRelationshipReference(taxonRelationshipReference);
1351

    
1352
        Classification classificationClone = Classification.NewInstance(config.getNewClassificationName());
1353

    
1354
        if (config.isReuseClassificationReference()){
1355
            TaxonNode anyNode = dao.findByUuid(config.getSubTreeUuids().iterator().next());
1356
            if (anyNode != null){
1357
                Reference oldClassificationRef = anyNode.getClassification().getReference();
1358
                classificationClone.setReference(oldClassificationRef);
1359
            }
1360
        }else if (config.getClassificationReferenceUuid() != null) {
1361
            Reference classificationReference = referenceDao.findByUuid(config.getClassificationReferenceUuid());
1362
            classificationClone.setReference(classificationReference);
1363
        }
1364

    
1365
        //clone taxa and taxon nodes
1366
//      List<Integer> childNodeIds = taxonNodeService.idList(taxonNodeFilter);
1367
//      List<TaxonNode> childNodes = taxonNodeService.loadByIds(childNodeIds, null);
1368
        List<TaxonNode> rootNodes = this.find(config.getSubTreeUuids());
1369
        for (TaxonNode taxonNode : rootNodes) {
1370
            cloneTaxonRecursive(taxonNode, classificationClone.getRootNode(), config);
1371
        }
1372
        classificationDao.saveOrUpdate(classificationClone);
1373
        result.setCdmEntity(classificationClone);
1374
        return result;
1375
    }
1376

    
1377
    private void cloneTaxonRecursive(TaxonNode originalParentNode, TaxonNode parentNodeClone,
1378
            SubtreeCloneConfigurator config){
1379

    
1380
        Taxon originalTaxon = CdmBase.deproxy(originalParentNode.getTaxon());
1381
        TaxonNode childNodeClone;
1382
        if (originalTaxon != null){
1383
            String microReference = null;
1384
            if (config.isReuseTaxa()){
1385
                childNodeClone = parentNodeClone.addChildTaxon(originalTaxon, config.getParentChildReference(), microReference);
1386
            }else{
1387
                Taxon cloneTaxon = originalTaxon.clone(config.isIncludeSynonymsIncludingManAndProParte(),
1388
                        config.isIncludeTaxonRelationshipsExcludingManAndProParte(),
1389
                        config.isIncludeDescriptiveData(), config.isIncludeMedia());
1390

    
1391
                //name
1392
                if (!config.isReuseNames()){
1393
                    cloneTaxon.setName(cloneTaxon.getName().clone());
1394
                    //TODO needs further handling for name relationships etc., see #9349
1395
                    cloneTaxon.getSynonyms().forEach(syn ->
1396
                        syn.setName(syn.getName() == null ? null : syn.getName().clone()));
1397
                }
1398

    
1399
                if (!config.isReuseTaxonSecundum()){
1400
                    cloneTaxon.setSec(config.getTaxonSecundum());
1401
                }
1402

    
1403
                //add relation between taxa
1404
                if (config.getRelationTypeToOldTaxon() != null){
1405
                    TaxonRelationship rel = cloneTaxon.addTaxonRelation(originalParentNode.getTaxon(), config.getRelationTypeToOldTaxon(),
1406
                            config.getRelationshipReference(), microReference);
1407
                    rel.setDoubtful(config.isRelationDoubtful());
1408
                }
1409
                childNodeClone = parentNodeClone.addChildTaxon(cloneTaxon, config.getParentChildReference(), microReference);
1410
            }
1411

    
1412
            //probably necessary as taxon nodes do not cascade
1413
            dao.saveOrUpdate(childNodeClone);
1414

    
1415
        }else{
1416
            childNodeClone = parentNodeClone;
1417
        }
1418
        //add children
1419
        if (config.isDoRecursive()){
1420
            List<TaxonNode> originalChildNodes = originalParentNode.getChildNodes();
1421
            HHH_9751_Util.removeAllNull(originalChildNodes);
1422

    
1423
            for (TaxonNode originalChildNode : originalChildNodes) {
1424
                cloneTaxonRecursive(originalChildNode, childNodeClone, config);
1425
            }
1426
        }
1427
    }
1428

    
1429
    @Override
1430
    public HomotypicGroupDto getHomotypicGroupDto(UUID homotypicGroupUuid, UUID nodeUuid) {
1431

    
1432
        HomotypicalGroup group = homotypicalGroupDao.load(homotypicGroupUuid);
1433
        if (group == null){
1434
            return null;
1435
        }
1436
        return new HomotypicGroupDto(group, nodeUuid);
1437
    }
1438

    
1439
    @Override
1440
    public TaxonNodeDto getTaxonNodeDto(UUID nodeUuid) {
1441
        return dao.getTaxonNodeDto(nodeUuid);
1442
    }
1443

    
1444
    @Override
1445
    public List<TaxonNodeDto> getTaxonNodeDtos(List<UUID> nodeUuids) {
1446
        return dao.getTaxonNodeDtos(nodeUuids);
1447
    }
1448
}
(88-88/97)