Project

General

Profile

Download (59.5 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
            }
389
            if (secHandling != null &&  !secHandling.equals(SecReferenceHandlingEnum.KeepOrWarn)){
390
                synonym.setSec(newSec);
391
            }
392
            newAcceptedTaxon.addSynonym(synonym, srt);
393

    
394
        }
395

    
396

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

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

    
416
            }else if(toTaxon == oldTaxon){
417
               fromTaxon.addTaxonRelation(newAcceptedTaxon, taxonRelationship.getType(),
418
                        taxonRelationship.getCitation(), taxonRelationship.getCitationMicroReference());
419
               taxonService.saveOrUpdate(fromTaxon);
420

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

    
426
            fromTaxon.removeTaxonRelation(taxonRelationship);
427
            toTaxon.removeTaxonRelation(taxonRelationship);
428
            taxonRelationship.setToTaxon(null);
429
            taxonRelationship.setFromTaxon(null);
430
        }
431

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

    
452
        taxonService.saveOrUpdate(newAcceptedTaxon);
453

    
454
        taxonService.saveOrUpdate(oldTaxon);
455
        taxonService.getSession().flush();
456

    
457
        TaxonDeletionConfigurator conf = new TaxonDeletionConfigurator();
458
        conf.setDeleteSynonymsIfPossible(false);
459
        conf.setDeleteNameIfPossible(false);
460
        DeleteResult result = taxonService.isDeletable(oldTaxon.getUuid(), conf);
461

    
462

    
463
        if (result.isOk()){
464
        	 result = taxonService.deleteTaxon(oldTaxon.getUuid(), conf, classification.getUuid());
465

    
466
        }else{
467
        	result.setStatus(Status.OK);
468
        	TaxonNodeDeletionConfigurator config = new TaxonNodeDeletionConfigurator();
469
        	config.setDeleteElement(false);
470
        	conf.setTaxonNodeConfig(config);
471
        	result.includeResult(deleteTaxonNode(oldTaxonNode, conf));
472
        }
473

    
474
        result.addUpdatedObject(newAcceptedTaxon);
475

    
476

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

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

    
506
        TaxonNode oldTaxonNode = dao.load(oldTaxonNodeUuid);
507
        TaxonNode oldTaxonParentNode = oldTaxonNode.getParent();
508
        TaxonNode newTaxonNode = dao.load(newAcceptedTaxonNodeUUID);
509
        Reference citation = referenceDao.load(citationUuid);
510

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

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

    
527
            break;
528
        default:
529
            break;
530
    }
531

    
532

    
533
        DeleteResult result = makeTaxonNodeASynonymOfAnotherTaxonNode(oldTaxonNode,
534
                newTaxonNode,
535
                synonymType,
536
                citation,
537
                microReference,
538
                secHandling, setNameInSource);
539

    
540
        result.addUpdatedCdmId(new CdmEntityIdentifier(oldTaxonParentNode.getId(), TaxonNode.class));
541
        result.addUpdatedCdmId(new CdmEntityIdentifier(newTaxonNode.getId(), TaxonNode.class));
542
        result.setCdmEntity(oldTaxonParentNode);
543
        return result;
544
    }
545

    
546
    @Override
547
    @Transactional(readOnly = false)
548
    public DeleteResult deleteTaxonNodes(List<TaxonNode> list, TaxonDeletionConfigurator config) {
549

    
550
        if (config == null){
551
        	config = new TaxonDeletionConfigurator();
552
        }
553
        DeleteResult result = new DeleteResult();
554
        Classification classification = null;
555
        List<TaxonNode> taxonNodes = new ArrayList<>(list);
556

    
557
        for (TaxonNode treeNode:taxonNodes){
558
        	if (treeNode != null){
559

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

    
594
            		} else {
595
            			//move the children to the parent
596

    
597
            			for (TaxonNode child: childNodesList){
598
            				parent.addChildNode(child, child.getReference(), child.getMicroReference());
599
            			}
600

    
601
            		}
602
            	}
603

    
604
	            classification = taxonNode.getClassification();
605

    
606
	            if (classification.getRootNode().equals(taxonNode)){
607
	            	classification.removeRootNode();
608
	            	classification = null;
609
	            }else if (classification.getChildNodes().contains(taxonNode)){
610
            		Taxon taxon = taxonNode.getTaxon();
611
            		classification.deleteChildNode(taxonNode);
612

    
613
	            	//node is rootNode
614
	            	if (taxon != null){
615

    
616
	            		if (config.getTaxonNodeConfig().isDeleteTaxon()){
617
	            		    taxonService.saveOrUpdate(taxon);
618
	            		    saveOrUpdate(taxonNode);
619

    
620
			            	TaxonDeletionConfigurator configNew = new TaxonDeletionConfigurator();
621
			            	configNew.setClassificationUuid(classification.getUuid());
622
			            	DeleteResult resultTaxon = taxonService.deleteTaxon(taxon.getUuid(), configNew, classification.getUuid());
623
			            	if (!resultTaxon.isOk()){
624
                                result.addExceptions(resultTaxon.getExceptions());
625
                                result.setStatus(resultTaxon.getStatus());
626
                            }
627

    
628
		            	}
629
	            	}
630
            		classification = null;
631

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

    
644
                            if (!resultTaxon.isOk()){
645
                                result.addExceptions(resultTaxon.getExceptions());
646
                                result.setStatus(resultTaxon.getStatus());
647
                            }
648
		            	}
649
	            	}
650

    
651
	            }
652

    
653
	            result.addUpdatedObject(parent);
654
	            if(result.getCdmEntity() == null){
655
	                result.setCdmEntity(taxonNode);
656
                }
657
	            UUID uuid = dao.delete(taxonNode);
658
	            logger.debug("Deleted node " +uuid.toString());
659

    
660
	        }
661
        }
662
        /*if (classification != null){
663
            result.addUpdatedObject(classification);
664
        	DeleteResult resultClassification = classService.delete(classification);
665
        	 if (!resultClassification.isOk()){
666
                 result.addExceptions(resultClassification.getExceptions());
667
                 result.setStatus(resultClassification.getStatus());
668
             }
669
        }*/
670
        return result;
671
    }
672

    
673

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

    
684

    
685
    @Override
686
    @Transactional(readOnly = false)
687
    public DeleteResult deleteTaxonNode(UUID nodeUUID, TaxonDeletionConfigurator config) {
688

    
689
    	TaxonNode node = CdmBase.deproxy(dao.load(nodeUUID));
690
    	return deleteTaxonNode(node, config);
691
    }
692

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

    
709
        }
710

    
711

    
712
    	TaxonNode parent = HibernateProxyHelper.deproxy(node.getParent(), TaxonNode.class);
713
    	if (config == null){
714
    		config = new TaxonDeletionConfigurator();
715
    	}
716

    
717

    
718
    	if (config.getTaxonNodeConfig().getChildHandling().equals(ChildHandling.MOVE_TO_PARENT)){
719
    	   Object[] children = node.getChildNodes().toArray();
720
    	   TaxonNode childNode;
721
    	   for (Object child: children){
722
    	       childNode = (TaxonNode) child;
723
    	       parent.addChildNode(childNode, childNode.getReference(), childNode.getMicroReference());
724

    
725
    	   }
726
    	}else{
727
    	    result.includeResult(deleteTaxonNodes(node.getChildNodes(), config));
728
    	}
729

    
730
    	//remove node from DescriptiveDataSet
731
        commonService.getReferencingObjects(node).stream()
732
        .filter(obj->obj instanceof DescriptiveDataSet)
733
        .forEach(dataSet->{
734
            ((DescriptiveDataSet)dataSet).removeTaxonSubtree(node);
735
            dataSetService.saveOrUpdate((DescriptiveDataSet) dataSet);
736
        });
737

    
738
    	if (taxon != null){
739
        	if (config.getTaxonNodeConfig().isDeleteTaxon() && (config.isDeleteInAllClassifications() || taxon.getTaxonNodes().size() == 1)){
740
        		result = taxonService.deleteTaxon(taxon.getUuid(), config, node.getClassification().getUuid());
741
        		result.addUpdatedObject(parent);
742
        		if (result.isOk()){
743
        			return result;
744
        		}
745
        	} else {
746
        	    result.addUpdatedObject(taxon);
747
        	}
748
    	}
749
    	result.setCdmEntity(node);
750
    	boolean success = true;
751
    	if (taxon != null){
752
    	    success = taxon.removeTaxonNode(node);
753
    	    taxonService.saveOrUpdate(taxon);
754
    	}
755
    	dao.saveOrUpdate(parent);
756

    
757
    	result.addUpdatedObject(parent);
758

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

    
785

    
786
    @Override
787
    public List<TaxonNode> listAllNodesForClassification(Classification classification, Integer start, Integer end) {
788
        return dao.getTaxonOfAcceptedTaxaByClassification(classification, start, end);
789
    }
790

    
791
    @Override
792
    public int countAllNodesForClassification(Classification classification) {
793
        return dao.countTaxonOfAcceptedTaxaByClassification(classification);
794
    }
795

    
796
    @Override
797
    @Transactional
798
    public UpdateResult moveTaxonNode(UUID taxonNodeUuid, UUID targetNodeUuid, int movingType, SecReferenceHandlingEnum secHandling, UUID secUuid){
799
        TaxonNode taxonNode = HibernateProxyHelper.deproxy(dao.load(taxonNodeUuid));
800
    	TaxonNode targetNode = HibernateProxyHelper.deproxy(dao.load(targetNodeUuid));
801
    	Reference sec = null;
802
    	if (secUuid != null){
803
    	    sec = HibernateProxyHelper.deproxy(referenceDao.load(secUuid));
804
    	}
805
    	UpdateResult result = moveTaxonNode(taxonNode, targetNode, movingType, secHandling, sec);
806
    	return result;
807
    }
808

    
809
    @Override
810
    @Transactional
811
    public UpdateResult moveTaxonNode(TaxonNode taxonNode, TaxonNode newParent, int movingType, SecReferenceHandlingEnum secHandling, Reference sec){
812
        UpdateResult result = new UpdateResult();
813

    
814
        TaxonNode parentParent = HibernateProxyHelper.deproxy(newParent.getParent());
815
        Integer sortIndex = -1;
816
        if (movingType == 0){
817
            sortIndex = 0;
818
        }else if (movingType == 1){
819
            sortIndex = newParent.getSortIndex();
820
            newParent = parentParent;
821
        } else if (movingType == 2){
822
            sortIndex = newParent.getSortIndex() +1;
823
            newParent = parentParent;
824
        } else{
825
            result.setAbort();
826
            result.addException(new Exception("The moving type "+ movingType +" is not supported."));
827
        }
828

    
829
        if (secHandling.equals(SecReferenceHandlingEnum.AlwaysSelect) || (secHandling.equals(SecReferenceHandlingEnum.KeepOrSelect) && sec != null)){
830
            if (taxonNode.getTaxon() != null){
831
                taxonNode.getTaxon().setSec(sec);
832
            }
833
        }else if (secHandling.equals(SecReferenceHandlingEnum.AlwaysDelete)){
834
            if (taxonNode.getTaxon() != null){
835
                taxonNode.getTaxon().setSec(null);
836
            }
837
        }else if (secHandling.equals(SecReferenceHandlingEnum.UseNewParentSec)){
838
            if (taxonNode.getTaxon() != null && newParent.getTaxon()!= null){
839
                taxonNode.getTaxon().setSec(newParent.getTaxon().getSec());
840
            }
841
        }
842

    
843
        taxonNode = newParent.addChildNode(taxonNode, sortIndex, taxonNode.getReference(),  taxonNode.getMicroReference());
844
        result.addUpdatedObject(taxonNode);
845

    
846
        return result;
847
    }
848

    
849
    @Override
850
    @Transactional
851
    public UpdateResult moveTaxonNodes(Set<UUID> taxonNodeUuids, UUID newParentNodeUuid, int movingType, SecReferenceHandlingEnum secHandling, UUID secUuid, IProgressMonitor monitor){
852

    
853
        if (monitor == null){
854
            monitor = DefaultProgressMonitor.NewInstance();
855
        }
856
        UpdateResult result = new UpdateResult();
857
        List<String> taxonNodePropertyPath = new ArrayList<>();
858
        taxonNodePropertyPath.add("taxon.secSource.*");
859
        taxonNodePropertyPath.add("parent.taxon.secSource.*");
860
        TaxonNode targetNode = dao.load(newParentNodeUuid, taxonNodePropertyPath);
861
        List<TaxonNode> nodes = dao.list(taxonNodeUuids, null, null, null, null);
862
        Reference sec = referenceDao.load(secUuid);
863

    
864
        monitor.beginTask("Move Taxonnodes", nodes.size()*2);
865
        monitor.subTask("move taxon nodes");
866
        for (TaxonNode node: nodes){
867
            if (!monitor.isCanceled()){
868
                if (!nodes.contains(node.getParent())){
869
                    result.includeResult(moveTaxonNode(node, targetNode, movingType, secHandling, sec));
870
                }
871
                monitor.worked(1);
872
            }else{
873
                monitor.done();
874
                result.setAbort();
875
                break;
876
            }
877
        }
878
        if (!monitor.isCanceled()){
879
            monitor.subTask("saving and reindex");
880
            dao.saveOrUpdateAll(nodes);
881
        }else{
882
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
883
        }
884

    
885
        monitor.done();
886
        return result;
887
    }
888

    
889
    @Override
890
    public Pager<TaxonNodeAgentRelation> pageTaxonNodeAgentRelations(UUID taxonUuid, UUID classificationUuid,
891
            UUID agentUuid, UUID rankUuid, UUID relTypeUuid, Integer pageSize, Integer pageIndex, List<String> propertyPaths) {
892

    
893
        List<TaxonNodeAgentRelation> records = null;
894

    
895
        long count = dao.countTaxonNodeAgentRelations(taxonUuid, classificationUuid, agentUuid, rankUuid, relTypeUuid);
896
        if(PagerUtils.hasResultsInRange(count, pageIndex, pageSize)) {
897
            records = dao.listTaxonNodeAgentRelations(taxonUuid, classificationUuid,
898
                    agentUuid, rankUuid, relTypeUuid, PagerUtils.startFor(pageSize, pageIndex), PagerUtils.limitFor(pageSize), propertyPaths);
899
        }
900

    
901
        Pager<TaxonNodeAgentRelation> pager = new DefaultPagerImpl<>(pageIndex, count, pageSize, records);
902
        return pager;
903
    }
904

    
905
    @Override
906
    @Transactional
907
    public UpdateResult createNewTaxonNode(UUID parentNodeUuid, CreateTaxonDTO taxonDto,
908
            NamedSource source, String microref,
909
            TaxonNodeStatus status, Map<Language,LanguageString> statusNote){
910

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

    
952
            parent = dao.load(parentNodeUuid);
953
            if (source != null){
954
                if (source.isPersited()){
955
                    source = (NamedSource) sourceDao.load(source.getUuid());
956
                }
957
                if (source.getCitation() != null){
958
                    source.setCitation(referenceService.load(source.getCitation().getUuid()));
959
                }
960
                if (source.getNameUsedInSource() !=null){
961
                    source.setNameUsedInSource(nameService.load(source.getNameUsedInSource().getUuid()));
962
                }
963
            }
964

    
965
            child = parent.addChildTaxon(taxon, source);
966
            child.setStatus(status);
967

    
968
            if (statusNote != null){
969
                child.getStatusNote().putAll(statusNote);
970
            }
971

    
972
        }catch(Exception e){
973
            result.addException(e);
974
            result.setError();
975
            return result;
976
        }
977
        child = dao.save(child);
978

    
979
        result.addUpdatedObject(parent);
980
        if (child != null){
981
            result.setCdmEntity(child);
982
        }
983
        return result;
984
    }
985

    
986
    @Override
987
    @Transactional
988
    public UpdateResult addTaxonNodeAgentRelation(UUID taxonNodeUUID, UUID agentUUID, DefinedTerm relationshipType){
989
        UpdateResult result = new UpdateResult();
990
        TaxonNode node = dao.load(taxonNodeUUID);
991
        TeamOrPersonBase<?> agent = (TeamOrPersonBase<?>) agentService.load(agentUUID);
992
        node.addAgentRelation(relationshipType, agent);
993
        try{
994
            dao.merge(node, true);
995
        }catch (Exception e){
996
            result.setError();
997
            result.addException(e);
998
        }
999
        result.setCdmEntity(node);
1000
        return result;
1001
    }
1002

    
1003
    @Override
1004
    @Transactional(readOnly=false)
1005
    public UpdateResult setSecundumForSubtree(SecundumForSubtreeConfigurator config) {
1006
        UpdateResult result = new UpdateResult();
1007
        IProgressMonitor monitor = config.getMonitor();
1008

    
1009
        if (monitor == null){
1010
            monitor = DefaultProgressMonitor.NewInstance();
1011
        }
1012
        monitor.beginTask("Update secundum reference for subtree", 100);
1013
        monitor.subTask("Check start conditions");
1014

    
1015
        if (config.getSubtreeUuid() == null){
1016
            result.setError();
1017
            result.addException(new NullPointerException("No subtree given"));
1018
            monitor.done();
1019
            return result;
1020
        }
1021
        monitor.worked(1);
1022
        TaxonNode subTree = load(config.getSubtreeUuid());
1023
        if (subTree == null){
1024
            result.setError();
1025
            result.addException(new NullPointerException("Subtree does not exist"));
1026
            monitor.done();
1027
            return result;
1028
        }
1029
        monitor.worked(1);
1030

    
1031
        Reference newSec = null;
1032
        if (config.getNewSecundum() != null){
1033
            newSec = referenceService.load(config.getNewSecundum().getUuid());
1034
            if (newSec == null){
1035
                result.setError();
1036
                result.addException(new NullPointerException("New secundum reference does not exist"));
1037
                monitor.done();
1038
                return result;
1039
            }
1040
        }
1041
        monitor.worked(1);
1042

    
1043
        monitor.subTask("Count records");
1044
        try {
1045
            boolean includeRelatedTaxa = config.isIncludeProParteSynonyms() || config.isIncludeMisapplications();
1046

    
1047
            TreeIndex subTreeIndex = TreeIndex.NewInstance(subTree.treeIndex());
1048
            int count = config.isIncludeAcceptedTaxa() ? dao.countSecundumForSubtreeAcceptedTaxa(subTreeIndex, newSec, config.isOverwriteExisting(), config.isIncludeSharedTaxa(), config.isEmptySecundumDetail()):0;
1049
            monitor.worked(2);
1050
            count += config.isIncludeSynonyms() ? dao.countSecundumForSubtreeSynonyms(subTreeIndex, newSec, config.isOverwriteExisting(), config.isIncludeSharedTaxa(), config.isEmptySecundumDetail()) :0;
1051
            monitor.worked(3);
1052
            count += includeRelatedTaxa ? dao.countSecundumForSubtreeRelations(subTreeIndex, newSec, config.isOverwriteExisting(), config.isIncludeSharedTaxa(), config.isEmptySecundumDetail()):0;
1053
            monitor.worked(2);
1054
            if (monitor.isCanceled()){
1055
                return result;
1056
            }
1057

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

    
1096
    @Override
1097
    @Transactional(readOnly=false)
1098
    public UpdateResult setPublishForSubtree(PublishForSubtreeConfigurator config){
1099
        UpdateResult result = new UpdateResult();
1100
        IProgressMonitor monitor = config.getMonitor();
1101
        if (monitor == null){
1102
            monitor = DefaultProgressMonitor.NewInstance();
1103
        }
1104
        monitor.beginTask("Update publish flag for subtree", 100);
1105
        monitor.subTask("Check start conditions");
1106

    
1107
        if (config.getSubtreeUuid() == null){
1108
            result.setError();
1109
            result.addException(new NullPointerException("No subtree given"));
1110
            monitor.done();
1111
            return result;
1112
        }
1113
        monitor.worked(1);
1114

    
1115
        TaxonNode subTree = find(config.getSubtreeUuid());
1116
        if (subTree == null){
1117
            result.setError();
1118
            result.addException(new NullPointerException("Subtree does not exist"));
1119
            monitor.done();
1120
            return result;
1121
        }
1122
        monitor.worked(1);
1123

    
1124
        monitor.subTask("Count records");
1125
        boolean includeAcceptedTaxa = config.isIncludeAcceptedTaxa();
1126
        boolean publish = config.isPublish();
1127
        boolean includeSynonyms = config.isIncludeSynonyms();
1128
        boolean includeSharedTaxa = config.isIncludeSharedTaxa();
1129
        boolean includeHybrids = config.isIncludeHybrids();
1130
        boolean includeRelatedTaxa = config.isIncludeProParteSynonyms() || config.isIncludeMisapplications();
1131
        try {
1132
            TreeIndex subTreeIndex = TreeIndex.NewInstance(subTree.treeIndex());
1133
            int count = includeAcceptedTaxa ? dao.countPublishForSubtreeAcceptedTaxa(subTreeIndex, publish, includeSharedTaxa, includeHybrids):0;
1134
            monitor.worked(3);
1135
            count += includeSynonyms ? dao.countPublishForSubtreeSynonyms(subTreeIndex, publish, includeSharedTaxa, includeHybrids):0;
1136
            monitor.worked(3);
1137
            count += includeRelatedTaxa ? dao.countPublishForSubtreeRelatedTaxa(subTreeIndex, publish, includeSharedTaxa, includeHybrids):0;
1138
            monitor.worked(2);
1139
            if (monitor.isCanceled()){
1140
                return result;
1141
            }
1142

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

    
1186
        monitor.done();
1187
        return result;
1188
    }
1189

    
1190
    private Set<UUID> getRelationTypesForSubtree(ForSubtreeConfiguratorBase config) {
1191
        Set<UUID> relationTypes = new HashSet<>();
1192
        if (config.isIncludeMisapplications()){
1193
            relationTypes.addAll(TaxonRelationshipType.misappliedNameUuids());
1194
        }
1195
        if (config.isIncludeProParteSynonyms()){
1196
            relationTypes.addAll(TaxonRelationshipType.proParteOrPartialSynonymUuids());
1197
        }
1198
        return relationTypes;
1199
    }
1200

    
1201
    @Override
1202
    public long count(TaxonNodeFilter filter){
1203
        return nodeFilterDao.count(filter);
1204
    }
1205

    
1206
    @Override
1207
    public List<UUID> uuidList(TaxonNodeFilter filter){
1208
        return nodeFilterDao.listUuids(filter);
1209
    }
1210

    
1211
    @Override
1212
    public List<Integer> idList(TaxonNodeFilter filter){
1213
        return nodeFilterDao.idList(filter);
1214
    }
1215

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

    
1260
    @Override
1261
    public List<TaxonDistributionDTO> getTaxonDistributionDTO(List<UUID> nodeUuids, List<String> propertyPaths,
1262
            Authentication authentication, boolean openChildren, TaxonNodeSortMode sortMode){
1263

    
1264
        nodeUuids = nodeUuids.stream().distinct().collect(Collectors.toList());
1265
        List<TaxonNode> nodes = new ArrayList<>();
1266

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

    
1291
        List<TaxonDistributionDTO> result = new ArrayList<>();
1292
        boolean hasPermission = false;
1293
        for(TaxonNode node: nodes){
1294
            if (authentication != null ) {
1295
                hasPermission = permissionEvaluator.hasPermission(authentication, node, Operation.UPDATE);
1296
            }else {
1297
                hasPermission = true;
1298
            }
1299
            if (node.getTaxon() != null && hasPermission){
1300
                try{
1301
                    TaxonDistributionDTO dto = new TaxonDistributionDTO(node);
1302
                    result.add(dto);
1303
                }catch(Exception e){
1304
                    logger.error(e.getMessage(), e);
1305
                }
1306
            }
1307
        }
1308
        return result;
1309
    }
1310

    
1311
    @Override
1312
    public <S extends TaxonNode> Pager<S> page(Class<S> clazz, List<Restriction<?>> restrictions, Integer pageSize,
1313
            Integer pageIndex, List<OrderHint> orderHints, List<String> propertyPaths) {
1314
        return page(clazz, restrictions, pageSize, pageIndex, orderHints, propertyPaths, INCLUDE_UNPUBLISHED);
1315
    }
1316

    
1317
    @Override
1318
    public <S extends TaxonNode> Pager<S> page(Class<S> clazz, List<Restriction<?>> restrictions, Integer pageSize,
1319
            Integer pageIndex, List<OrderHint> orderHints, List<String> propertyPaths, boolean includeUnpublished) {
1320

    
1321
        List<S> records;
1322
        long resultSize = dao.count(clazz, restrictions);
1323
        if(AbstractPagerImpl.hasResultsInRange(resultSize, pageIndex, pageSize)){
1324
            records = dao.list(clazz, restrictions, pageSize, pageIndex, orderHints, propertyPaths, includeUnpublished);
1325
        } else {
1326
            records = new ArrayList<>();
1327
        }
1328
        Pager<S> pager = new DefaultPagerImpl<>(pageIndex, resultSize, pageSize, records);
1329
        return pager;
1330
    }
1331

    
1332
    @Override
1333
    public List<TaxonDistributionDTO> getTaxonDistributionDTO(List<UUID> nodeUuids,
1334
            List<String> propertyPaths, boolean openChildren) {
1335
        return getTaxonDistributionDTO(nodeUuids, propertyPaths, null, openChildren, null);
1336
    }
1337

    
1338
    @Override
1339
    @Transactional(readOnly = false)
1340
    public UpdateResult cloneSubtree(SubtreeCloneConfigurator config) {
1341
        UpdateResult result = new UpdateResult();
1342

    
1343
        if (config.getSubTreeUuids().isEmpty()){
1344
            return result;
1345
        }
1346

    
1347
        //TODO error handling
1348
        Reference taxonSecundum = config.isReuseTaxa() || config.isReuseTaxonSecundum() || config.getTaxonSecundumUuid() == null ?
1349
                null : referenceDao.findByUuid(config.getTaxonSecundumUuid());
1350
        config.setTaxonSecundum(taxonSecundum);
1351

    
1352
        Reference parentChildReference = config.isReuseParentChildReference() || config.getParentChildReferenceUuid() == null ?
1353
                null : referenceDao.findByUuid(config.getParentChildReferenceUuid());
1354
        config.setParentChildReference(parentChildReference);
1355

    
1356
        Reference taxonRelationshipReference = config.getRelationTypeToOldTaxon() == null ?
1357
                null : referenceDao.findByUuid(config.getRelationshipReferenceUuid());
1358
        config.setRelationshipReference(taxonRelationshipReference);
1359

    
1360
        Classification classificationClone = Classification.NewInstance(config.getNewClassificationName());
1361

    
1362
        if (config.isReuseClassificationReference()){
1363
            TaxonNode anyNode = dao.findByUuid(config.getSubTreeUuids().iterator().next());
1364
            if (anyNode != null){
1365
                Reference oldClassificationRef = anyNode.getClassification().getReference();
1366
                classificationClone.setReference(oldClassificationRef);
1367
            }
1368
        }else if (config.getClassificationReferenceUuid() != null) {
1369
            Reference classificationReference = referenceDao.findByUuid(config.getClassificationReferenceUuid());
1370
            classificationClone.setReference(classificationReference);
1371
        }
1372

    
1373
        //clone taxa and taxon nodes
1374
//      List<Integer> childNodeIds = taxonNodeService.idList(taxonNodeFilter);
1375
//      List<TaxonNode> childNodes = taxonNodeService.loadByIds(childNodeIds, null);
1376
        List<TaxonNode> rootNodes = this.find(config.getSubTreeUuids());
1377
        for (TaxonNode taxonNode : rootNodes) {
1378
            cloneTaxonRecursive(taxonNode, classificationClone.getRootNode(), config);
1379
        }
1380
        classificationDao.saveOrUpdate(classificationClone);
1381
        result.setCdmEntity(classificationClone);
1382
        return result;
1383
    }
1384

    
1385
    private void cloneTaxonRecursive(TaxonNode originalParentNode, TaxonNode parentNodeClone,
1386
            SubtreeCloneConfigurator config){
1387

    
1388
        Taxon originalTaxon = CdmBase.deproxy(originalParentNode.getTaxon());
1389
        TaxonNode childNodeClone;
1390
        if (originalTaxon != null){
1391
            String microReference = null;
1392
            if (config.isReuseTaxa()){
1393
                childNodeClone = parentNodeClone.addChildTaxon(originalTaxon, config.getParentChildReference(), microReference);
1394
            }else{
1395
                Taxon cloneTaxon = originalTaxon.clone(config.isIncludeSynonymsIncludingManAndProParte(),
1396
                        config.isIncludeTaxonRelationshipsExcludingManAndProParte(),
1397
                        config.isIncludeDescriptiveData(), config.isIncludeMedia());
1398

    
1399
                //name
1400
                if (!config.isReuseNames()){
1401
                    cloneTaxon.setName(cloneTaxon.getName().clone());
1402
                    //TODO needs further handling for name relationships etc., see #9349
1403
                    cloneTaxon.getSynonyms().forEach(syn ->
1404
                        syn.setName(syn.getName() == null ? null : syn.getName().clone()));
1405
                }
1406

    
1407
                if (!config.isReuseTaxonSecundum()){
1408
                    cloneTaxon.setSec(config.getTaxonSecundum());
1409
                }
1410

    
1411
                //add relation between taxa
1412
                if (config.getRelationTypeToOldTaxon() != null){
1413
                    TaxonRelationship rel = cloneTaxon.addTaxonRelation(originalParentNode.getTaxon(), config.getRelationTypeToOldTaxon(),
1414
                            config.getRelationshipReference(), microReference);
1415
                    rel.setDoubtful(config.isRelationDoubtful());
1416
                }
1417
                childNodeClone = parentNodeClone.addChildTaxon(cloneTaxon, config.getParentChildReference(), microReference);
1418
            }
1419

    
1420
            //probably necessary as taxon nodes do not cascade
1421
            dao.saveOrUpdate(childNodeClone);
1422

    
1423
        }else{
1424
            childNodeClone = parentNodeClone;
1425
        }
1426
        //add children
1427
        if (config.isDoRecursive()){
1428
            List<TaxonNode> originalChildNodes = originalParentNode.getChildNodes();
1429
            HHH_9751_Util.removeAllNull(originalChildNodes);
1430

    
1431
            for (TaxonNode originalChildNode : originalChildNodes) {
1432
                cloneTaxonRecursive(originalChildNode, childNodeClone, config);
1433
            }
1434
        }
1435
    }
1436

    
1437
    @Override
1438
    public HomotypicGroupDto getHomotypicGroupDto(UUID homotypicGroupUuid, UUID nodeUuid) {
1439

    
1440
        HomotypicalGroup group = homotypicalGroupDao.load(homotypicGroupUuid);
1441
        if (group == null){
1442
            return null;
1443
        }
1444
        return new HomotypicGroupDto(group, nodeUuid);
1445
    }
1446

    
1447
    @Override
1448
    public TaxonNodeDto getTaxonNodeDto(UUID nodeUuid) {
1449
        return dao.getTaxonNodeDto(nodeUuid);
1450
    }
1451

    
1452
    @Override
1453
    public List<TaxonNodeDto> getTaxonNodeDtos(List<UUID> nodeUuids) {
1454
        return dao.getTaxonNodeDtos(nodeUuids);
1455
    }
1456
}
(88-88/97)