Project

General

Profile

Download (58.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
    @Autowired
292
    protected void setDao(ITaxonNodeDao dao) {
293
        this.dao = dao;
294
    }
295

    
296
    @Override
297
    @Transactional(readOnly = false)
298
    public DeleteResult makeTaxonNodeASynonymOfAnotherTaxonNode(TaxonNode oldTaxonNode, TaxonNode newAcceptedTaxonNode,
299
            SynonymType synonymType, Reference citation, String microReference, SecReferenceHandlingEnum secHandling, boolean setNameInSource)  {
300

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

    
307
        if(oldTaxonNode.equals(newAcceptedTaxonNode)){
308
            throw new IllegalArgumentException("Taxon can not be made synonym of its own.");
309
        }
310

    
311
        Classification classification = oldTaxonNode.getClassification();
312
        Taxon oldTaxon = HibernateProxyHelper.deproxy(oldTaxonNode.getTaxon());
313
        Taxon newAcceptedTaxon = (Taxon)this.taxonService.find(newAcceptedTaxonNode.getTaxon().getUuid());
314
        newAcceptedTaxon = HibernateProxyHelper.deproxy(newAcceptedTaxon);
315
        // Move oldTaxon to newTaxon
316
        //TaxonName synonymName = oldTaxon.getName();
317
        TaxonName newSynonymName = CdmBase.deproxy(oldTaxon.getName());
318
        HomotypicalGroup group = CdmBase.deproxy(newSynonymName.getHomotypicalGroup());
319
        if (synonymType == null){
320
            if (newSynonymName.isHomotypic(newAcceptedTaxon.getName())){
321
                synonymType = SynonymType.HOMOTYPIC_SYNONYM_OF();
322
            }else{
323
                synonymType = SynonymType.HETEROTYPIC_SYNONYM_OF();
324
            }
325
        }
326

    
327
        //set homotypic group
328
        TaxonName newAcceptedTaxonName = HibernateProxyHelper.deproxy(newAcceptedTaxon.getName(), TaxonName.class);
329
        newAcceptedTaxon.setName(newAcceptedTaxonName);
330
        Reference secNewAccepted = newAcceptedTaxon.getSec();
331
        Reference secOldAccepted = oldTaxon.getSec();
332
        boolean uuidsEqual = (secNewAccepted != null && secOldAccepted != null && secNewAccepted.equals(secOldAccepted)) || (secNewAccepted == null && secOldAccepted == null);
333
        Reference newSec = citation;
334
        //keep when same only warns in ui, the sec still
335
        if (secHandling != null &&  secHandling.equals(SecReferenceHandlingEnum.KeepOrWarn) ){
336
            newSec = oldTaxon.getSec();
337
        }
338
        if (secHandling != null && secHandling.equals(SecReferenceHandlingEnum.AlwaysDelete)){
339
            newSec = null;
340
        }
341

    
342
        Synonym newSyn = newAcceptedTaxon.addSynonymName(newSynonymName, newSec, microReference, synonymType);
343
        if (newSec == null){
344
            newSyn.setSec(newSec);
345
        }
346
        newSyn.setPublish(oldTaxon.isPublish());
347

    
348
        // Move Synonyms to new Taxon
349
        // From ticket 3163 we can move taxon with accepted name having homotypic synonyms
350
        List<Synonym> synonymsInHomotypicalGroup = null;
351

    
352
        //the synonyms of the homotypical group of the old taxon
353
        if (synonymType.equals(SynonymType.HOMOTYPIC_SYNONYM_OF())){
354
        	synonymsInHomotypicalGroup = oldTaxon.getSynonymsInGroup(group);
355
        }
356

    
357
        Set<Synonym> syns = new HashSet<>(oldTaxon.getSynonyms());
358
        for(Synonym synonym : syns){
359
            SynonymType srt;
360
            if(synonym.getHomotypicGroup()!= null
361
                    && synonym.getHomotypicGroup().equals(newAcceptedTaxonName.getHomotypicalGroup())) {
362
                srt = SynonymType.HOMOTYPIC_SYNONYM_OF();
363
            } else if(synonym.getType() != null && synonym.getType().equals(SynonymType.HOMOTYPIC_SYNONYM_OF())) {
364
            	if (synonymType.equals(SynonymType.HOMOTYPIC_SYNONYM_OF())){
365
            		srt = SynonymType.HOMOTYPIC_SYNONYM_OF();
366
            	} else{
367
            		srt = SynonymType.HETEROTYPIC_SYNONYM_OF();
368
            	}
369
            } else {
370
                if (synonymsInHomotypicalGroup != null && synonymsInHomotypicalGroup.contains(synonym)){
371
                    srt = SynonymType.HOMOTYPIC_SYNONYM_OF();
372
                }else{
373
                    srt = synonym.getType();
374
                }
375

    
376
            }
377
            if (secHandling != null &&  !secHandling.equals(SecReferenceHandlingEnum.KeepOrWarn)){
378
                synonym.setSec(newSec);
379
            }
380
            newAcceptedTaxon.addSynonym(synonym, srt);
381

    
382
        }
383

    
384

    
385
        // CHILD NODES
386
        if(oldTaxonNode.getChildNodes() != null && oldTaxonNode.getChildNodes().size() != 0){
387
        	List<TaxonNode> childNodes = new ArrayList<>();
388
        	for (TaxonNode childNode : oldTaxonNode.getChildNodes()){
389
        		childNodes.add(childNode);
390
        	}
391
            for(TaxonNode childNode :childNodes){
392
                newAcceptedTaxonNode.addChildNode(childNode, childNode.getReference(), childNode.getMicroReference()); // childNode.getSynonymToBeUsed()
393
            }
394
        }
395

    
396
        //Move Taxon RelationShips to new Taxon
397
        for(TaxonRelationship taxonRelationship : oldTaxon.getTaxonRelations()){
398
            Taxon fromTaxon = HibernateProxyHelper.deproxy(taxonRelationship.getFromTaxon());
399
            Taxon toTaxon = HibernateProxyHelper.deproxy(taxonRelationship.getToTaxon());
400
            if (fromTaxon == oldTaxon){
401
                newAcceptedTaxon.addTaxonRelation(taxonRelationship.getToTaxon(), taxonRelationship.getType(),
402
                        taxonRelationship.getCitation(), taxonRelationship.getCitationMicroReference());
403

    
404
            }else if(toTaxon == oldTaxon){
405
               fromTaxon.addTaxonRelation(newAcceptedTaxon, taxonRelationship.getType(),
406
                        taxonRelationship.getCitation(), taxonRelationship.getCitationMicroReference());
407
               taxonService.saveOrUpdate(fromTaxon);
408

    
409
            }else{
410
                logger.warn("Taxon is not part of its own Taxonrelationship");
411
            }
412
            // Remove old relationships
413

    
414
            fromTaxon.removeTaxonRelation(taxonRelationship);
415
            toTaxon.removeTaxonRelation(taxonRelationship);
416
            taxonRelationship.setToTaxon(null);
417
            taxonRelationship.setFromTaxon(null);
418
        }
419

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

    
440
        taxonService.saveOrUpdate(newAcceptedTaxon);
441

    
442
        taxonService.saveOrUpdate(oldTaxon);
443
        taxonService.getSession().flush();
444

    
445
        TaxonDeletionConfigurator conf = new TaxonDeletionConfigurator();
446
        conf.setDeleteSynonymsIfPossible(false);
447
        conf.setDeleteNameIfPossible(false);
448
        DeleteResult result = taxonService.isDeletable(oldTaxon.getUuid(), conf);
449

    
450

    
451
        if (result.isOk()){
452
        	 result = taxonService.deleteTaxon(oldTaxon.getUuid(), conf, classification.getUuid());
453

    
454
        }else{
455
        	result.setStatus(Status.OK);
456
        	TaxonNodeDeletionConfigurator config = new TaxonNodeDeletionConfigurator();
457
        	config.setDeleteElement(false);
458
        	conf.setTaxonNodeConfig(config);
459
        	result.includeResult(deleteTaxonNode(oldTaxonNode, conf));
460
        }
461

    
462
        result.addUpdatedObject(newAcceptedTaxon);
463

    
464

    
465
        //oldTaxonNode.delete();
466
        return result;
467
    }
468
    @Override
469
    @Transactional(readOnly = false)
470
    public DeleteResult makeTaxonNodeSynonymsOfAnotherTaxonNode( Set<UUID> oldTaxonNodeUuids,
471
            UUID newAcceptedTaxonNodeUUIDs,
472
            SynonymType synonymType,
473
            UUID citation,
474
            String microReference,
475
            SecReferenceHandlingEnum secHandling,
476
            boolean setNameInSource) {
477
    	DeleteResult result = new DeleteResult();
478
    	for (UUID nodeUuid: oldTaxonNodeUuids) {
479
    		result.includeResult(makeTaxonNodeASynonymOfAnotherTaxonNode(nodeUuid, newAcceptedTaxonNodeUUIDs, synonymType, citation, microReference, secHandling, setNameInSource));
480
    	}
481
    	return result;
482
    }
483

    
484
    @Override
485
    @Transactional(readOnly = false)
486
    public DeleteResult makeTaxonNodeASynonymOfAnotherTaxonNode(UUID oldTaxonNodeUuid,
487
            UUID newAcceptedTaxonNodeUUID,
488
            SynonymType synonymType,
489
            UUID citationUuid,
490
            String microReference,
491
            SecReferenceHandlingEnum secHandling,
492
            boolean setNameInSource) {
493

    
494
        TaxonNode oldTaxonNode = dao.load(oldTaxonNodeUuid);
495
        TaxonNode oldTaxonParentNode = oldTaxonNode.getParent();
496
        TaxonNode newTaxonNode = dao.load(newAcceptedTaxonNodeUUID);
497
        Reference citation = referenceDao.load(citationUuid);
498

    
499
        switch (secHandling){
500
        case AlwaysDelete:
501
            citation = null;
502
            break;
503
        case UseNewParentSec:
504
            citation = newTaxonNode.getTaxon() != null? newTaxonNode.getTaxon().getSec(): null;
505
            break;
506
        case KeepOrWarn:
507

    
508
            Reference synSec = oldTaxonNode.getTaxon().getSec();
509
            if (synSec != null ){
510
                citation = CdmBase.deproxy(synSec);
511
            }
512
            break;
513
        case KeepOrSelect:
514

    
515
            break;
516
        default:
517
            break;
518
    }
519

    
520

    
521
        DeleteResult result = makeTaxonNodeASynonymOfAnotherTaxonNode(oldTaxonNode,
522
                newTaxonNode,
523
                synonymType,
524
                citation,
525
                microReference,
526
                secHandling, setNameInSource);
527

    
528
        result.addUpdatedCdmId(new CdmEntityIdentifier(oldTaxonParentNode.getId(), TaxonNode.class));
529
        result.addUpdatedCdmId(new CdmEntityIdentifier(newTaxonNode.getId(), TaxonNode.class));
530
        result.setCdmEntity(oldTaxonParentNode);
531
        return result;
532
    }
533

    
534
    @Override
535
    @Transactional(readOnly = false)
536
    public DeleteResult deleteTaxonNodes(List<TaxonNode> list, TaxonDeletionConfigurator config) {
537

    
538
        if (config == null){
539
        	config = new TaxonDeletionConfigurator();
540
        }
541
        DeleteResult result = new DeleteResult();
542
        Classification classification = null;
543
        List<TaxonNode> taxonNodes = new ArrayList<>(list);
544

    
545
        for (TaxonNode treeNode:taxonNodes){
546
        	if (treeNode != null){
547

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

    
582
            		} else {
583
            			//move the children to the parent
584

    
585
            			for (TaxonNode child: childNodesList){
586
            				parent.addChildNode(child, child.getReference(), child.getMicroReference());
587
            			}
588

    
589
            		}
590
            	}
591

    
592
	            classification = taxonNode.getClassification();
593

    
594
	            if (classification.getRootNode().equals(taxonNode)){
595
	            	classification.removeRootNode();
596
	            	classification = null;
597
	            }else if (classification.getChildNodes().contains(taxonNode)){
598
            		Taxon taxon = taxonNode.getTaxon();
599
            		classification.deleteChildNode(taxonNode);
600

    
601
	            	//node is rootNode
602
	            	if (taxon != null){
603

    
604
	            		if (config.getTaxonNodeConfig().isDeleteTaxon()){
605
	            		    taxonService.saveOrUpdate(taxon);
606
	            		    saveOrUpdate(taxonNode);
607

    
608
			            	TaxonDeletionConfigurator configNew = new TaxonDeletionConfigurator();
609
			            	configNew.setClassificationUuid(classification.getUuid());
610
			            	DeleteResult resultTaxon = taxonService.deleteTaxon(taxon.getUuid(), configNew, classification.getUuid());
611
			            	if (!resultTaxon.isOk()){
612
                                result.addExceptions(resultTaxon.getExceptions());
613
                                result.setStatus(resultTaxon.getStatus());
614
                            }
615

    
616
		            	}
617
	            	}
618
            		classification = null;
619

    
620
	            } else {
621
	            	//classification = null;
622
	            	Taxon taxon = taxonNode.getTaxon();
623
	            	taxon = CdmBase.deproxy(taxon);
624
	            	if (taxon != null){
625
	            		taxon.removeTaxonNode(taxonNode);
626
	            		if (config.getTaxonNodeConfig().isDeleteTaxon()){
627
			            	TaxonDeletionConfigurator configNew = new TaxonDeletionConfigurator();
628
			            	saveOrUpdate(taxonNode);
629
			            	taxonService.saveOrUpdate(taxon);
630
			            	DeleteResult resultTaxon = taxonService.deleteTaxon(taxon.getUuid(), configNew, classification.getUuid());
631

    
632
                            if (!resultTaxon.isOk()){
633
                                result.addExceptions(resultTaxon.getExceptions());
634
                                result.setStatus(resultTaxon.getStatus());
635
                            }
636
		            	}
637
	            	}
638

    
639
	            }
640

    
641
	            result.addUpdatedObject(parent);
642
	            if(result.getCdmEntity() == null){
643
	                result.setCdmEntity(taxonNode);
644
                }
645
	            UUID uuid = dao.delete(taxonNode);
646
	            logger.debug("Deleted node " +uuid.toString());
647

    
648
	        }
649
        }
650
        /*if (classification != null){
651
            result.addUpdatedObject(classification);
652
        	DeleteResult resultClassification = classService.delete(classification);
653
        	 if (!resultClassification.isOk()){
654
                 result.addExceptions(resultClassification.getExceptions());
655
                 result.setStatus(resultClassification.getStatus());
656
             }
657
        }*/
658
        return result;
659
    }
660

    
661

    
662
    @Override
663
    @Transactional(readOnly = false)
664
    public DeleteResult deleteTaxonNodes(Collection<UUID> nodeUuids, TaxonDeletionConfigurator config) {
665
        List<TaxonNode> nodes = new ArrayList<>();
666
        for(UUID nodeUuid : nodeUuids) {
667
            nodes.add(dao.load(nodeUuid));
668
        }
669
        return deleteTaxonNodes(nodes, config);
670
    }
671

    
672

    
673
    @Override
674
    @Transactional(readOnly = false)
675
    public DeleteResult deleteTaxonNode(UUID nodeUUID, TaxonDeletionConfigurator config) {
676

    
677
    	TaxonNode node = CdmBase.deproxy(dao.load(nodeUUID));
678
    	return deleteTaxonNode(node, config);
679
    }
680

    
681
    @Override
682
    @Transactional(readOnly = false)
683
    public DeleteResult deleteTaxonNode(TaxonNode node, TaxonDeletionConfigurator config) {
684
        DeleteResult result = new DeleteResult();
685
        if (node == null){
686
            result.setAbort();
687
            result.addException(new Exception("The TaxonNode was already deleted."));
688
            return result;
689
        }
690
        Taxon taxon = null;
691
        try{
692
            taxon = HibernateProxyHelper.deproxy(node.getTaxon());
693
        }catch(NullPointerException e){
694
            result.setAbort();
695
            result.addException(new Exception("The Taxon was already deleted."));
696

    
697
        }
698

    
699

    
700
    	TaxonNode parent = HibernateProxyHelper.deproxy(node.getParent(), TaxonNode.class);
701
    	if (config == null){
702
    		config = new TaxonDeletionConfigurator();
703
    	}
704

    
705

    
706
    	if (config.getTaxonNodeConfig().getChildHandling().equals(ChildHandling.MOVE_TO_PARENT)){
707
    	   Object[] children = node.getChildNodes().toArray();
708
    	   TaxonNode childNode;
709
    	   for (Object child: children){
710
    	       childNode = (TaxonNode) child;
711
    	       parent.addChildNode(childNode, childNode.getReference(), childNode.getMicroReference());
712

    
713
    	   }
714
    	}else{
715
    	    result.includeResult(deleteTaxonNodes(node.getChildNodes(), config));
716
    	}
717

    
718
    	//remove node from DescriptiveDataSet
719
        commonService.getReferencingObjects(node).stream()
720
        .filter(obj->obj instanceof DescriptiveDataSet)
721
        .forEach(dataSet->{
722
            ((DescriptiveDataSet)dataSet).removeTaxonSubtree(node);
723
            dataSetService.saveOrUpdate((DescriptiveDataSet) dataSet);
724
        });
725

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

    
745
    	result.addUpdatedObject(parent);
746

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

    
773

    
774
    @Override
775
    public List<TaxonNode> listAllNodesForClassification(Classification classification, Integer start, Integer end) {
776
        return dao.getTaxonOfAcceptedTaxaByClassification(classification, start, end);
777
    }
778

    
779
    @Override
780
    public int countAllNodesForClassification(Classification classification) {
781
        return dao.countTaxonOfAcceptedTaxaByClassification(classification);
782
    }
783

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

    
797
    @Override
798
    @Transactional
799
    public UpdateResult moveTaxonNode(TaxonNode taxonNode, TaxonNode newParent, int movingType, SecReferenceHandlingEnum secHandling, Reference sec){
800
        UpdateResult result = new UpdateResult();
801

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

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

    
831
        taxonNode = newParent.addChildNode(taxonNode, sortIndex, taxonNode.getReference(),  taxonNode.getMicroReference());
832
        result.addUpdatedObject(taxonNode);
833

    
834
        return result;
835
    }
836

    
837
    @Override
838
    @Transactional
839
    public UpdateResult moveTaxonNodes(Set<UUID> taxonNodeUuids, UUID newParentNodeUuid, int movingType, SecReferenceHandlingEnum secHandling, UUID secUuid, IProgressMonitor monitor){
840

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

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

    
873
        monitor.done();
874
        return result;
875
    }
876

    
877
    @Override
878
    public Pager<TaxonNodeAgentRelation> pageTaxonNodeAgentRelations(UUID taxonUuid, UUID classificationUuid,
879
            UUID agentUuid, UUID rankUuid, UUID relTypeUuid, Integer pageSize, Integer pageIndex, List<String> propertyPaths) {
880

    
881
        List<TaxonNodeAgentRelation> records = null;
882

    
883
        long count = dao.countTaxonNodeAgentRelations(taxonUuid, classificationUuid, agentUuid, rankUuid, relTypeUuid);
884
        if(PagerUtils.hasResultsInRange(count, pageIndex, pageSize)) {
885
            records = dao.listTaxonNodeAgentRelations(taxonUuid, classificationUuid,
886
                    agentUuid, rankUuid, relTypeUuid, PagerUtils.startFor(pageSize, pageIndex), PagerUtils.limitFor(pageSize), propertyPaths);
887
        }
888

    
889
        Pager<TaxonNodeAgentRelation> pager = new DefaultPagerImpl<>(pageIndex, count, pageSize, records);
890
        return pager;
891
    }
892

    
893
    @Override
894
    @Transactional
895
    public UpdateResult createNewTaxonNode(UUID parentNodeUuid, CreateTaxonDTO taxonDto,
896
            NamedSource source, String microref,
897
            TaxonNodeStatus status, Map<Language,LanguageString> statusNote){
898

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

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

    
953
            child = parent.addChildTaxon(taxon, source);
954
            child.setStatus(status);
955

    
956
            if (statusNote != null){
957
                child.getStatusNote().putAll(statusNote);
958
            }
959

    
960
        }catch(Exception e){
961
            result.addException(e);
962
            result.setError();
963
            return result;
964
        }
965
        child = dao.save(child);
966

    
967
        result.addUpdatedObject(parent);
968
        if (child != null){
969
            result.setCdmEntity(child);
970
        }
971
        return result;
972
    }
973

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

    
991
    @Override
992
    @Transactional(readOnly=false)
993
    public UpdateResult setSecundumForSubtree(SecundumForSubtreeConfigurator config) {
994
        UpdateResult result = new UpdateResult();
995
        IProgressMonitor monitor = config.getMonitor();
996

    
997
        if (monitor == null){
998
            monitor = DefaultProgressMonitor.NewInstance();
999
        }
1000
        monitor.beginTask("Update secundum reference for subtree", 100);
1001
        monitor.subTask("Check start conditions");
1002

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

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

    
1031
        monitor.subTask("Count records");
1032
        try {
1033
            boolean includeRelatedTaxa = config.isIncludeProParteSynonyms() || config.isIncludeMisapplications();
1034

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

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

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

    
1095
        if (config.getSubtreeUuid() == null){
1096
            result.setError();
1097
            result.addException(new NullPointerException("No subtree given"));
1098
            monitor.done();
1099
            return result;
1100
        }
1101
        monitor.worked(1);
1102

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

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

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

    
1174
        monitor.done();
1175
        return result;
1176
    }
1177

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

    
1189
    @Override
1190
    public long count(TaxonNodeFilter filter){
1191
        return nodeFilterDao.count(filter);
1192
    }
1193

    
1194
    @Override
1195
    public List<UUID> uuidList(TaxonNodeFilter filter){
1196
        return nodeFilterDao.listUuids(filter);
1197
    }
1198

    
1199
    @Override
1200
    public List<Integer> idList(TaxonNodeFilter filter){
1201
        return nodeFilterDao.idList(filter);
1202
    }
1203

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

    
1248
    @Override
1249
    public List<TaxonDistributionDTO> getTaxonDistributionDTO(List<UUID> nodeUuids, List<String> propertyPaths,
1250
            Authentication authentication, boolean openChildren, TaxonNodeSortMode sortMode){
1251

    
1252
        nodeUuids = nodeUuids.stream().distinct().collect(Collectors.toList());
1253
        List<TaxonNode> nodes = new ArrayList<>();
1254

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

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

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

    
1305
    @Override
1306
    public <S extends TaxonNode> Pager<S> page(Class<S> clazz, List<Restriction<?>> restrictions, Integer pageSize,
1307
            Integer pageIndex, List<OrderHint> orderHints, List<String> propertyPaths, boolean includeUnpublished) {
1308

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

    
1320
    @Override
1321
    public List<TaxonDistributionDTO> getTaxonDistributionDTO(List<UUID> nodeUuids,
1322
            List<String> propertyPaths, boolean openChildren) {
1323
        return getTaxonDistributionDTO(nodeUuids, propertyPaths, null, openChildren, null);
1324
    }
1325

    
1326
    @Override
1327
    @Transactional(readOnly = false)
1328
    public UpdateResult cloneSubtree(SubtreeCloneConfigurator config) {
1329
        UpdateResult result = new UpdateResult();
1330

    
1331
        if (config.getSubTreeUuids().isEmpty()){
1332
            return result;
1333
        }
1334

    
1335
        //TODO error handling
1336
        Reference taxonSecundum = config.isReuseTaxa() || config.isReuseTaxonSecundum() || config.getTaxonSecundumUuid() == null ?
1337
                null : referenceDao.findByUuid(config.getTaxonSecundumUuid());
1338
        config.setTaxonSecundum(taxonSecundum);
1339

    
1340
        Reference parentChildReference = config.isReuseParentChildReference() || config.getParentChildReferenceUuid() == null ?
1341
                null : referenceDao.findByUuid(config.getParentChildReferenceUuid());
1342
        config.setParentChildReference(parentChildReference);
1343

    
1344
        Reference taxonRelationshipReference = config.getRelationTypeToOldTaxon() == null ?
1345
                null : referenceDao.findByUuid(config.getRelationshipReferenceUuid());
1346
        config.setRelationshipReference(taxonRelationshipReference);
1347

    
1348
        Classification classificationClone = Classification.NewInstance(config.getNewClassificationName());
1349

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

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

    
1373
    private void cloneTaxonRecursive(TaxonNode originalParentNode, TaxonNode parentNodeClone,
1374
            SubtreeCloneConfigurator config){
1375

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

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

    
1395
                if (!config.isReuseTaxonSecundum()){
1396
                    cloneTaxon.setSec(config.getTaxonSecundum());
1397
                }
1398

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

    
1408
            //probably necessary as taxon nodes do not cascade
1409
            dao.saveOrUpdate(childNodeClone);
1410

    
1411
        }else{
1412
            childNodeClone = parentNodeClone;
1413
        }
1414
        //add children
1415
        if (config.isDoRecursive()){
1416
            List<TaxonNode> originalChildNodes = originalParentNode.getChildNodes();
1417
            HHH_9751_Util.removeAllNull(originalChildNodes);
1418

    
1419
            for (TaxonNode originalChildNode : originalChildNodes) {
1420
                cloneTaxonRecursive(originalChildNode, childNodeClone, config);
1421
            }
1422
        }
1423
    }
1424

    
1425
    @Override
1426
    public HomotypicGroupDto getHomotypicGroupDto(UUID homotypicGroupUuid, UUID nodeUuid) {
1427

    
1428
        HomotypicalGroup group = homotypicalGroupDao.load(homotypicGroupUuid);
1429
        if (group == null){
1430
            return null;
1431
        }
1432
        return new HomotypicGroupDto(group, nodeUuid);
1433
    }
1434
}
(88-88/97)