Project

General

Profile

Download (48.8 KB) Statistics
| Branch: | Tag: | Revision:
1
package eu.etaxonomy.cdm.api.service;
2

    
3
import java.math.BigDecimal;
4
import java.util.ArrayList;
5
import java.util.Arrays;
6
import java.util.Collection;
7
import java.util.Collections;
8
import java.util.HashMap;
9
import java.util.HashSet;
10
import java.util.List;
11
import java.util.Map;
12
import java.util.Optional;
13
import java.util.Set;
14
import java.util.UUID;
15
import java.util.stream.Collectors;
16

    
17
import org.apache.logging.log4j.LogManager;
18
import org.apache.logging.log4j.Logger;
19
import org.hibernate.Session;
20
import org.hibernate.query.Query;
21
import org.springframework.beans.factory.annotation.Autowired;
22
import org.springframework.stereotype.Service;
23
import org.springframework.transaction.annotation.Transactional;
24

    
25
import eu.etaxonomy.cdm.api.service.UpdateResult.Status;
26
import eu.etaxonomy.cdm.api.service.config.DeleteDescriptiveDataSetConfigurator;
27
import eu.etaxonomy.cdm.api.service.config.IdentifiableServiceConfiguratorImpl;
28
import eu.etaxonomy.cdm.api.service.config.RemoveDescriptionsFromDescriptiveDataSetConfigurator;
29
import eu.etaxonomy.cdm.api.service.dto.CategoricalDataDto;
30
import eu.etaxonomy.cdm.api.service.dto.DescriptionBaseDto;
31
import eu.etaxonomy.cdm.api.service.dto.DescriptionElementDto;
32
import eu.etaxonomy.cdm.api.service.dto.QuantitativeDataDto;
33
import eu.etaxonomy.cdm.api.service.dto.RowWrapperDTO;
34
import eu.etaxonomy.cdm.api.service.dto.SpecimenOrObservationDTOFactory;
35
import eu.etaxonomy.cdm.api.service.dto.SpecimenRowWrapperDTO;
36
import eu.etaxonomy.cdm.api.service.dto.StateDataDto;
37
import eu.etaxonomy.cdm.api.service.dto.StatisticalMeasurementValueDto;
38
import eu.etaxonomy.cdm.api.service.dto.TaxonRowWrapperDTO;
39
import eu.etaxonomy.cdm.common.monitor.IProgressMonitor;
40
import eu.etaxonomy.cdm.filter.TaxonNodeFilter;
41
import eu.etaxonomy.cdm.format.description.DefaultCategoricalDescriptionBuilder;
42
import eu.etaxonomy.cdm.format.description.DefaultQuantitativeDescriptionBuilder;
43
import eu.etaxonomy.cdm.hibernate.HibernateProxyHelper;
44
import eu.etaxonomy.cdm.model.common.CdmBase;
45
import eu.etaxonomy.cdm.model.common.IdentifiableSource;
46
import eu.etaxonomy.cdm.model.common.Language;
47
import eu.etaxonomy.cdm.model.description.CategoricalData;
48
import eu.etaxonomy.cdm.model.description.DescriptionBase;
49
import eu.etaxonomy.cdm.model.description.DescriptionElementBase;
50
import eu.etaxonomy.cdm.model.description.DescriptionType;
51
import eu.etaxonomy.cdm.model.description.DescriptiveDataSet;
52
import eu.etaxonomy.cdm.model.description.DescriptiveSystemRole;
53
import eu.etaxonomy.cdm.model.description.Feature;
54
import eu.etaxonomy.cdm.model.description.IndividualsAssociation;
55
import eu.etaxonomy.cdm.model.description.MeasurementUnit;
56
import eu.etaxonomy.cdm.model.description.PolytomousKey;
57
import eu.etaxonomy.cdm.model.description.QuantitativeData;
58
import eu.etaxonomy.cdm.model.description.SpecimenDescription;
59
import eu.etaxonomy.cdm.model.description.State;
60
import eu.etaxonomy.cdm.model.description.StatisticalMeasure;
61
import eu.etaxonomy.cdm.model.description.StatisticalMeasurementValue;
62
import eu.etaxonomy.cdm.model.description.TaxonDescription;
63
import eu.etaxonomy.cdm.model.description.TextData;
64
import eu.etaxonomy.cdm.model.location.NamedArea;
65
import eu.etaxonomy.cdm.model.occurrence.FieldUnit;
66
import eu.etaxonomy.cdm.model.occurrence.SpecimenOrObservationBase;
67
import eu.etaxonomy.cdm.model.reference.CdmLinkSource;
68
import eu.etaxonomy.cdm.model.taxon.Classification;
69
import eu.etaxonomy.cdm.model.taxon.Taxon;
70
import eu.etaxonomy.cdm.model.taxon.TaxonBase;
71
import eu.etaxonomy.cdm.model.taxon.TaxonNode;
72
import eu.etaxonomy.cdm.model.term.DefinedTermBase;
73
import eu.etaxonomy.cdm.persistence.dao.description.IDescriptiveDataSetDao;
74
import eu.etaxonomy.cdm.persistence.dao.term.IDefinedTermDao;
75
import eu.etaxonomy.cdm.persistence.dto.DescriptiveDataSetBaseDto;
76
import eu.etaxonomy.cdm.persistence.dto.MergeResult;
77
import eu.etaxonomy.cdm.persistence.dto.SpecimenNodeWrapper;
78
import eu.etaxonomy.cdm.persistence.dto.TaxonNodeDto;
79
import eu.etaxonomy.cdm.persistence.dto.TermDto;
80
import eu.etaxonomy.cdm.persistence.dto.TermTreeDto;
81
import eu.etaxonomy.cdm.persistence.dto.UuidAndTitleCache;
82
import eu.etaxonomy.cdm.strategy.cache.common.IIdentifiableEntityCacheStrategy;
83
import eu.etaxonomy.cdm.strategy.generate.PolytomousKeyGenerator;
84
import eu.etaxonomy.cdm.strategy.generate.PolytomousKeyGeneratorConfigurator;
85

    
86
@Service
87
@Transactional(readOnly=true)
88
public class DescriptiveDataSetService
89
        extends IdentifiableServiceBase<DescriptiveDataSet, IDescriptiveDataSetDao>
90
        implements IDescriptiveDataSetService {
91

    
92
    private static Logger logger = LogManager.getLogger();
93

    
94
    @Autowired
95
    private IOccurrenceService occurrenceService;
96

    
97
    @Autowired
98
    private ITaxonService taxonService;
99

    
100
    @Autowired
101
    private IPolytomousKeyService polytomousKeyService;
102

    
103
    @Autowired
104
    private IDefinedTermDao termDao;
105

    
106
    @Autowired
107
    private IDescriptionService descriptionService;
108

    
109
    @Autowired
110
    private ITaxonNodeService taxonNodeService;
111

    
112
	@Override
113
	@Autowired
114
	protected void setDao(IDescriptiveDataSetDao dao) {
115
		this.dao = dao;
116
	}
117

    
118
	@Override
119
    public Map<DescriptionBase, Set<DescriptionElementBase>> getDescriptionElements(DescriptiveDataSet descriptiveDataSet, Set<Feature> features, Integer pageSize,	Integer pageNumber,
120
			List<String> propertyPaths) {
121
		return dao.getDescriptionElements(descriptiveDataSet, features, pageSize, pageNumber, propertyPaths);
122
	}
123

    
124
	@Override
125
	public <T extends DescriptionElementBase> Map<UuidAndTitleCache, Map<UUID, Set<T>>> getTaxonFeatureDescriptionElementMap(
126
			Class<T> clazz, UUID descriptiveDataSetUuid, DescriptiveSystemRole role) {
127
		return dao.getTaxonFeatureDescriptionElementMap(clazz, descriptiveDataSetUuid, role);
128
	}
129

    
130
	@Override
131
    public List<UuidAndTitleCache<DescriptiveDataSet>> getDescriptiveDataSetUuidAndTitleCache(Integer limitOfInitialElements, String pattern) {
132
        return dao.getDescriptiveDataSetUuidAndTitleCache( limitOfInitialElements, pattern);
133
    }
134

    
135
	@Override
136
	public List<RowWrapperDTO<?>> getRowWrapper(UUID descriptiveDataSetUuid, IProgressMonitor monitor) {
137
	    DescriptiveDataSetBaseDto datasetDto = dao.getDescriptiveDataSetDtoByUuid(descriptiveDataSetUuid);
138
//	    DescriptiveDataSet descriptiveDataSet = load(descriptiveDataSetUuid);
139
	    monitor.beginTask("Load row wrapper", datasetDto.getDescriptionUuids().size());
140
	    List<RowWrapperDTO<?>> wrappers = new ArrayList<>();
141
	    Set<UUID> descriptions = datasetDto.getDescriptionUuids();
142
	    for (UUID description : descriptions) {
143
            if(monitor.isCanceled()){
144
                return new ArrayList<>();
145
            }
146
            DescriptionBaseDto descDto = descriptionService.loadDto(description);
147
            RowWrapperDTO<?> rowWrapper = null;
148
            if (descDto != null && descDto.getTaxonDto() != null &&
149
                    (descDto.getTypes().contains(DescriptionType.DEFAULT_VALUES_FOR_AGGREGATION)
150
                            || descDto.getTypes().contains(DescriptionType.AGGREGATED_STRUC_DESC)
151
                            || descDto.getTypes().contains(DescriptionType.SECONDARY_DATA)
152
                            )){
153
                rowWrapper = createTaxonRowWrapper(descDto, datasetDto.getUuid());
154
            }
155
            else if (descDto != null &&descDto.getSpecimenDto() != null && (descDto.getTypes() == null ||
156
                    !descDto.getTypes().contains(DescriptionType.CLONE_FOR_SOURCE))){
157
                rowWrapper = createSpecimenRowWrapper(descDto, descriptiveDataSetUuid);
158
            }
159
            if(rowWrapper!=null){
160
                wrappers.add(rowWrapper);
161
            }
162
            monitor.worked(1);
163
        }
164
	    return wrappers;
165
	}
166

    
167
    @Override
168
    public Collection<SpecimenNodeWrapper> loadSpecimens(DescriptiveDataSet descriptiveDataSet){
169
        List<UUID> filteredNodes = findFilteredTaxonNodes(descriptiveDataSet);
170
        if(filteredNodes.isEmpty()){
171
            return Collections.emptySet();
172
        }
173
        Collection<SpecimenNodeWrapper> result = occurrenceService.listUuidAndTitleCacheByAssociatedTaxon(filteredNodes, null, null);
174

    
175
        return result;
176
    }
177

    
178
    @Override
179
    public Collection<SpecimenNodeWrapper> loadSpecimens(UUID descriptiveDataSetUuid){
180
        DescriptiveDataSet dataSet = load(descriptiveDataSetUuid);
181
        return loadSpecimens(dataSet);
182
    }
183

    
184

    
185
    @Override
186
    public List<UUID> findFilteredTaxonNodes(DescriptiveDataSet descriptiveDataSet){
187
        TaxonNodeFilter filter = TaxonNodeFilter.NewRankInstance(descriptiveDataSet.getMinRank(), descriptiveDataSet.getMaxRank());
188
        descriptiveDataSet.getGeoFilter().forEach(area -> filter.orArea(area.getUuid()));
189
        descriptiveDataSet.getTaxonSubtreeFilter().forEach(node -> filter.orSubtree(node));
190
        filter.setIncludeUnpublished(true);
191

    
192
        return taxonNodeService.uuidList(filter);
193
    }
194

    
195
    @Override
196
    public List<TaxonNode> loadFilteredTaxonNodes(DescriptiveDataSet descriptiveDataSet, List<String> propertyPaths){
197
        return taxonNodeService.load(findFilteredTaxonNodes(descriptiveDataSet), propertyPaths);
198
    }
199

    
200
    @Override
201
    public DescriptionBaseDto findDefaultDescription(UUID specimenDescriptionUuid, UUID dataSetUuid){
202
        DescriptionBaseDto specimenDescription = descriptionService.loadDto(specimenDescriptionUuid);
203
        DescriptiveDataSetBaseDto dataSet = dao.getDescriptiveDataSetDtoByUuid(dataSetUuid);
204
        TaxonNodeDto node = findTaxonNodeForDescription(specimenDescription, dataSet);
205
        return recurseDefaultDescription(node, dataSet);
206
    }
207

    
208
    private DescriptionBaseDto recurseDefaultDescription(TaxonNodeDto node, DescriptiveDataSetBaseDto dataSet){
209
        DescriptionBaseDto defaultDescription = null;
210
        if(node!=null && node.getTaxonUuid()!=null){
211
            defaultDescription = getTaxonDescriptionForDescriptiveDataSetAndType(dataSet, node.getTaxonUuid(), DescriptionType.DEFAULT_VALUES_FOR_AGGREGATION);
212
            if(defaultDescription==null && node.getParentUUID()!=null){
213
                defaultDescription = recurseDefaultDescription(taxonNodeService.dto(node.getParentUUID()), dataSet);
214
            }
215
        }
216
        return defaultDescription;
217
    }
218

    
219
    private TaxonNodeDto findTaxonNodeForDescription(DescriptionBaseDto description, DescriptiveDataSetBaseDto descriptiveDataSet){
220
        UuidAndTitleCache<SpecimenOrObservationBase> specimen = description.getSpecimenDto();
221
        //get taxon node
222

    
223

    
224
        return descriptionService.findTaxonNodeDtoForIndividualAssociation(specimen.getUuid(), descriptiveDataSet.getSubTreeFilter().iterator().next().getClassificationUUID());
225
        //NOTE: don't remove cast as it does not compile on some systems
226
//        List<DescriptionBaseDto> descDtos = descriptionService.loadDtos(descriptiveDataSet.getDescriptionUuids());
227
//        descriptionService.
228
//        Set<IndividualsAssociation> associations = descDtos
229
//                .stream()
230
//                .flatMap(desc->desc.getElements().stream())// put all description element in one stream
231
//                .filter(element->element.get)
232
//                .map(ia->(IndividualsAssociation)ia)
233
//                .collect(Collectors.toSet());
234
//        UUID classification = descriptiveDataSet.getSubTreeFilter().iterator().next().getClassificationUUID();
235
//        for (IndividualsAssociation individualsAssociation : associations) {
236
//            if(individualsAssociation.getAssociatedSpecimenOrObservation().equals(specimen)){
237
//                return ((TaxonDescription) individualsAssociation.getInDescription()).getTaxon().getTaxonNode(classification);
238
//            }
239
//        }
240
//        return null;
241
    }
242

    
243
    @Override
244
    public TaxonRowWrapperDTO createTaxonRowWrapper(UUID taxonDescriptionUuid, UUID descriptiveDataSetUuid) {
245
        DescriptionBaseDto description = descriptionService.loadDto(taxonDescriptionUuid);
246
        return createTaxonRowWrapper(description, descriptiveDataSetUuid);
247
    }
248

    
249
    @Override
250
    @Transactional(readOnly=false)
251
    public UpdateResult addRowWrapperToDataset(Collection<SpecimenRowWrapperDTO> wrappers, UUID datasetUuid, boolean addDatasetSource){
252
        UpdateResult result = new UpdateResult();
253
        DescriptiveDataSet dataSet = load(datasetUuid);
254
        result.setCdmEntity(dataSet);
255

    
256
        List<UUID> taxonUuids = wrappers.stream().map(wrapper->wrapper.getTaxonNode().getTaxonUuid()).collect(Collectors.toList());
257
        List<TaxonBase> taxa = taxonService.load(taxonUuids, Arrays.asList(new String[]{"descriptions"}));
258

    
259
        for (SpecimenRowWrapperDTO wrapper : wrappers) {
260
            Optional<TaxonBase> findAny = taxa.stream().filter(taxon->taxon.getUuid().equals(wrapper.getTaxonNode().getTaxonUuid())).findAny();
261
            if(!findAny.isPresent()){
262
                result.addException(new IllegalArgumentException("Could not create wrapper for "+ wrapper.getSpecimenDto().getLabel()));
263
                continue;
264
            }
265
            Taxon taxon = (Taxon) findAny.get();
266

    
267
            SpecimenOrObservationBase<?> specimen = occurrenceService.load(wrapper.getSpecimenDto().getUuid());
268

    
269
            TaxonDescription taxonDescription = taxon.getDescriptions().stream()
270
                    .filter(desc->desc.getTypes().contains(DescriptionType.INDIVIDUALS_ASSOCIATION))
271
                    .findFirst().orElseGet(()->{
272
                        TaxonDescription td = TaxonDescription.NewInstance(taxon);
273
                        td.addType(DescriptionType.INDIVIDUALS_ASSOCIATION);
274
                        td.setTitleCache("Specimens used by " + dataSet.getTitleCache() + " for " + getTaxonLabel(taxon), true);
275
                        return td;});
276
            IndividualsAssociation association = null;
277
            for (DescriptionElementBase el:taxonDescription.getElements()){
278
                if (el instanceof IndividualsAssociation){
279
                    IndividualsAssociation indAss = (IndividualsAssociation)el;
280
                    if (indAss.getAssociatedSpecimenOrObservation().getUuid().equals(specimen.getUuid())){
281
                        association = indAss;
282
                    }
283
                }
284
            }
285

    
286
            if (association == null){
287
                association = IndividualsAssociation.NewInstance(specimen);
288
                taxonDescription.addElement(association);
289
                taxonService.saveOrUpdate(taxon);
290
                result.addUpdatedObject(taxon);
291
            }
292

    
293

    
294

    
295
            UUID specimenDescriptionUuid = wrapper.getDescription().getDescriptionUuid();
296
            DescriptionBaseDto descriptionDto = wrapper.getDescription();
297
            DescriptionBase<?> specimenDescription =  descriptionService.load(specimenDescriptionUuid);
298
            //if description already exist use the loaded one and add changed data otherwise create a new one and add to specimen
299
            if (specimenDescription == null){
300
                specimenDescription = SpecimenDescription.NewInstance(specimen);
301
                specimenDescription.setUuid(specimenDescriptionUuid);
302
                List<DescriptionElementDto> elementDtos = descriptionDto.getElements();
303

    
304
                for (DescriptionElementDto elementDto: elementDtos){
305
                    if (elementDto instanceof CategoricalDataDto){
306
                        eu.etaxonomy.cdm.model.description.Character feature = DefinedTermBase.getTermByClassAndUUID(eu.etaxonomy.cdm.model.description.Character.class, elementDto.getFeatureUuid());
307
                        CategoricalData data = CategoricalData.NewInstance(feature);
308
                        for (StateDataDto stateDto:((CategoricalDataDto) elementDto).getStates()){
309
                            State state = DefinedTermBase.getTermByClassAndUUID(State.class, stateDto.getState().getUuid());
310
                            data.addStateData(state);
311
                            specimenDescription.addElement(data);
312
                        }
313
                    }
314
                    if (elementDto instanceof QuantitativeDataDto){
315
                        eu.etaxonomy.cdm.model.description.Character feature = DefinedTermBase.getTermByClassAndUUID(eu.etaxonomy.cdm.model.description.Character.class, elementDto.getFeatureUuid());
316
                        QuantitativeData data = QuantitativeData.NewInstance(feature);
317
                        if (((QuantitativeDataDto) elementDto).getMeasurementUnit() != null){
318
                            MeasurementUnit unit = DefinedTermBase.getTermByClassAndUUID(MeasurementUnit.class, ((QuantitativeDataDto) elementDto).getMeasurementUnit().getUuid());
319
                            data.setUnit(unit);
320
                        }
321

    
322
                        for (StatisticalMeasurementValueDto stateDto:((QuantitativeDataDto) elementDto).getValues()){
323
                            StatisticalMeasure statMeasure = DefinedTermBase.getTermByClassAndUUID(StatisticalMeasure.class, stateDto.getType().getUuid());
324
                            StatisticalMeasurementValue value = StatisticalMeasurementValue.NewInstance(statMeasure, stateDto.getValue());
325
                            data.addStatisticalValue(value);
326
                            specimenDescription.addElement(data);
327
                        }
328
                    }
329
                }
330

    
331
            }else {
332
                List<DescriptionElementDto> elementDtos = descriptionDto.getElements();
333
                for (DescriptionElementDto elementDto: elementDtos){
334
                    if (elementDto instanceof CategoricalDataDto){
335
                        eu.etaxonomy.cdm.model.description.Character feature = DefinedTermBase.getTermByClassAndUUID(eu.etaxonomy.cdm.model.description.Character.class, elementDto.getFeatureUuid());
336
                        List<DescriptionElementBase> uniqueElementList = specimenDescription.getElements().stream().filter(element -> element.getUuid().equals(elementDto.getElementUuid())).collect(Collectors.toList());
337
                        List<State> allStates = new ArrayList<>();
338
                        CategoricalData element = null;
339
                        if (uniqueElementList.size() == 1){
340
                            element = HibernateProxyHelper.deproxy(uniqueElementList.get(0), CategoricalData.class);
341
                        }else{
342
                            element = CategoricalData.NewInstance(feature);
343
                        }
344
                        for (StateDataDto stateDto:((CategoricalDataDto) elementDto).getStates()){
345
                            State state = DefinedTermBase.getTermByClassAndUUID(State.class, stateDto.getState().getUuid());
346
                            allStates.add(state);
347
                        }
348
                        element.setStateDataOnly(allStates);
349
                    }
350
                    if (elementDto instanceof QuantitativeDataDto){
351
                        eu.etaxonomy.cdm.model.description.Character feature = DefinedTermBase.getTermByClassAndUUID(eu.etaxonomy.cdm.model.description.Character.class, elementDto.getFeatureUuid());
352
                        QuantitativeData data = QuantitativeData.NewInstance(feature);
353
                        if (((QuantitativeDataDto) elementDto).getMeasurementUnit() != null){
354
                            MeasurementUnit unit = DefinedTermBase.getTermByClassAndUUID(MeasurementUnit.class, ((QuantitativeDataDto) elementDto).getMeasurementUnit().getUuid());
355
                            data.setUnit(unit);
356
                        }
357

    
358
                        for (StatisticalMeasurementValueDto stateDto:((QuantitativeDataDto) elementDto).getValues()){
359
                            StatisticalMeasure statMeasure = DefinedTermBase.getTermByClassAndUUID(StatisticalMeasure.class, stateDto.getType().getUuid());
360
                            StatisticalMeasurementValue value = StatisticalMeasurementValue.NewInstance(statMeasure, stateDto.getValue());
361
                            data.addStatisticalValue(value);
362
                            specimenDescription.addElement(data);
363
                        }
364
                    }
365
                }
366
            }
367
            if(addDatasetSource){
368
                for (IdentifiableSource source: dataSet.getSources()) {
369
                    try {
370
                        specimenDescription.addSource(source.clone());
371
                    } catch (CloneNotSupportedException e) {
372
                        //nothing
373
                    }
374
                }
375

    
376
            }
377

    
378
            //add specimen description to data set
379
            specimenDescription.addDescriptiveDataSet(dataSet);
380
            //add taxon description with IndividualsAssociation to the specimen to data set
381
            taxonDescription.addDescriptiveDataSet(dataSet);
382
            result.addUpdatedObject(specimen);
383
            result.addUpdatedObject(specimenDescription);
384
            result.addUpdatedObject(taxonDescription);
385
        }
386
        saveOrUpdate(dataSet);
387
        return result;
388
    }
389

    
390
    private String getTaxonLabel(Taxon taxon) {
391
        if (taxon.getName() != null){
392
            return taxon.getName().getTitleCache();
393
        }else{
394
            return taxon.getTitleCache();
395
        }
396
    }
397

    
398
    private SpecimenRowWrapperDTO createSpecimenRowWrapper(DescriptionBaseDto description, UUID taxonNodeUuid,
399
            UUID datasetUuid) {
400
        TaxonNodeDto taxonNode = taxonNodeService.dto(taxonNodeUuid);
401
        DescriptiveDataSetBaseDto descriptiveDataSet = getDescriptiveDataSetDtoByUuid(datasetUuid);
402
//        UuidAndTitleCache<SpecimenOrObservationBase> specimen = description.getSpecimenDto();
403
        SpecimenOrObservationBase specimen = occurrenceService.find(description.getSpecimenDto().getUuid());
404

    
405
        //supplemental information
406
        if(taxonNode==null){
407
            taxonNode = findTaxonNodeForDescription(description, descriptiveDataSet);
408
        }
409
        FieldUnit fieldUnit = null;
410
        String identifier = null;
411
        NamedArea country = null;
412
        if(taxonNode==null){
413
            return null;
414
        }
415
        //taxon node was found
416

    
417
        //get field unit
418
        Collection<FieldUnit> fieldUnits = occurrenceService.findFieldUnits(specimen.getUuid(),
419
                Arrays.asList(new String[]{
420
                        "gatheringEvent",
421
                        "gatheringEvent.country"
422
                }));
423
        if(fieldUnits.size()>1){
424
            logger.error("More than one or no field unit found for specimen"); //$NON-NLS-1$
425
            return null;
426
        }
427
        else{
428
            if (fieldUnits.size()>0){
429
                fieldUnit = fieldUnits.iterator().next();
430
            }
431
        }
432
        //get identifier
433

    
434
        identifier = occurrenceService.getMostSignificantIdentifier(specimen.getUuid());
435
        //get country
436
        if(fieldUnit != null && fieldUnit.getGatheringEvent() != null){
437
            country = fieldUnit.getGatheringEvent().getCountry();
438
        }
439
        //get default taxon description
440
//        TaxonDescription defaultTaxonDescription = findDefaultDescription(description.getUuid(), descriptiveDataSet.getUuid());
441
        DescriptionBaseDto defaultTaxonDescription = recurseDefaultDescription(taxonNode, descriptiveDataSet);
442
        TaxonRowWrapperDTO taxonRowWrapper = defaultTaxonDescription != null
443
                ? createTaxonRowWrapper(defaultTaxonDescription.getDescriptionUuid(), descriptiveDataSet.getUuid()) : null;
444
//                use description not specimen for specimenRow
445
        SpecimenRowWrapperDTO specimenRowWrapperDTO = new SpecimenRowWrapperDTO(description, SpecimenOrObservationDTOFactory.fromEntity(specimen), specimen.getRecordBasis(), taxonNode, fieldUnit, identifier, country);
446
        specimenRowWrapperDTO.setDefaultDescription(taxonRowWrapper);
447
        return specimenRowWrapperDTO;
448
    }
449

    
450
    @Override
451
    public SpecimenRowWrapperDTO createSpecimenRowWrapper(DescriptionBaseDto description, UUID descriptiveDataSetUuid){
452
        return createSpecimenRowWrapper(description, null, descriptiveDataSetUuid);
453
	}
454

    
455
    @Override
456
    public SpecimenRowWrapperDTO createSpecimenRowWrapper(UUID specimenUuid, UUID taxonNodeUuid, UUID descriptiveDataSetUuid){
457

    
458
        SpecimenOrObservationBase<?> specimen = occurrenceService.load(specimenUuid);
459
        DescriptionBaseDto specimenDescription = findSpecimenDescription(descriptiveDataSetUuid, specimen);
460
        return createSpecimenRowWrapper(specimenDescription, taxonNodeUuid, descriptiveDataSetUuid);
461
    }
462

    
463
    @Override
464
    @Transactional(readOnly = false)
465
    public UpdateResult updateCaches(Class<? extends DescriptiveDataSet> clazz, Integer stepSize,
466
            IIdentifiableEntityCacheStrategy<DescriptiveDataSet> cacheStrategy, IProgressMonitor monitor) {
467
        if (clazz == null) {
468
            clazz = DescriptiveDataSet.class;
469
        }
470
        return super.updateCachesImpl(clazz, stepSize, cacheStrategy, monitor);
471
    }
472

    
473
//    private TaxonDescription findTaxonDescriptionByDescriptionType(DescriptiveDataSetBaseDto dataSet, UUID taxonUuid, DescriptionType descriptionType){
474
//        descriptionService.find
475
//        Optional<TaxonDescription> first = taxon.getDescriptions().stream()
476
//                .filter(desc -> desc.getTypes().stream().anyMatch(type -> type.equals(descriptionType)))
477
//                .filter(desc -> dataSet.getDescriptions().contains(desc))
478
//                .findFirst();
479
//        if(first.isPresent()){
480
//            return HibernateProxyHelper.deproxy(descriptionService.load(first.get().getUuid(),
481
//                  Arrays.asList("taxon", "descriptionElements", "descriptionElements.feature")), TaxonDescription.class);
482
//        }
483
//        return null;
484
//    }
485
//
486
//    @Override
487
//    public TaxonDescription findTaxonDescriptionByDescriptionType(UUID dataSetUuid, UUID taxonNodeUuid, DescriptionType descriptionType){
488
//        DescriptiveDataSet dataSet = load(dataSetUuid);
489
//        TaxonNode taxonNode = taxonNodeService.load(taxonNodeUuid);
490
//        return findTaxonDescriptionByDescriptionType(dataSet, taxonNode.getTaxon(), descriptionType);
491
//    }
492
    @Override
493
    public DescriptionBaseDto getTaxonDescriptionForDescriptiveDataSetAndType(DescriptiveDataSetBaseDto dataSet, UUID taxonUuid, DescriptionType descriptionType){
494
        Session session = getSession();
495
        String queryString = "SELECT d.uuid FROM DescriptiveDataSet a JOIN a.descriptions as d JOIN d.taxon t WHERE t.uuid = :taxonuuid AND a.uuid = :dataSetUuid ";  // and :descriptionType IN d.types
496

    
497
        Query<UUID> query;
498
        query = session.createQuery(queryString, UUID.class);
499
        query.setParameter("taxonuuid", taxonUuid);
500
        query.setParameter("dataSetUuid", dataSet.getUuid());
501
//        query.setParameter("descriptionType", descriptionType.getKey());
502

    
503
        List<UUID> result = query.getResultList();
504
        List<DescriptionBaseDto> list = new ArrayList<>();
505
        list.addAll(descriptionService.loadDtos(new HashSet<>(result)));
506

    
507
        if (list.isEmpty()){
508
            return null;
509
        }else {
510
    		List<DescriptionBaseDto> correctTypeOnly = new ArrayList<>();
511
    		for (DescriptionBaseDto dto: list) {
512
    			if (dto.getTypes().contains(descriptionType)) {
513
    				correctTypeOnly.add(dto);
514
    			}
515
    		}
516
    		if (correctTypeOnly.isEmpty()) {
517
    			return null;
518
    		}else {
519
    			return correctTypeOnly.get(0);
520
    		}
521
        }
522
    }
523

    
524
    @Override
525
    @Transactional(readOnly=false)
526
    public UpdateResult generatePolytomousKey(UUID descriptiveDataSetUuid, UUID taxonUuid) {
527
        UpdateResult result = new UpdateResult();
528

    
529
        PolytomousKeyGeneratorConfigurator keyConfig = new PolytomousKeyGeneratorConfigurator();
530
        DescriptiveDataSet descriptiveDataSet = load(descriptiveDataSetUuid);
531
        keyConfig.setDataSet(descriptiveDataSet);
532
        PolytomousKey key = new PolytomousKeyGenerator().invoke(keyConfig);
533
        IdentifiableServiceConfiguratorImpl<PolytomousKey> serviceConfig= new IdentifiableServiceConfiguratorImpl<>();
534
        serviceConfig.setTitleSearchString(descriptiveDataSet.getTitleCache());
535
        List<PolytomousKey> list = polytomousKeyService.findByTitle(serviceConfig).getRecords();
536
        if(list!=null){
537
            list.forEach(polytomousKey->polytomousKeyService.delete(polytomousKey));
538
        }
539
        key.setTitleCache(descriptiveDataSet.getTitleCache(), true);
540

    
541
        Taxon taxon = (Taxon) taxonService.load(taxonUuid);
542
        key.addTaxonomicScope(taxon);
543

    
544
        polytomousKeyService.saveOrUpdate(key);
545

    
546
        result.setCdmEntity(key);
547
        result.addUpdatedObject(taxon);
548
        return result;
549
    }
550

    
551
    @Override
552
    @Transactional(readOnly=false)
553
    public DeleteResult removeDescription(UUID descriptionUuid, UUID descriptiveDataSetUuid, RemoveDescriptionsFromDescriptiveDataSetConfigurator config) {
554
        DeleteResult result = new DeleteResult();
555
        DescriptiveDataSet dataSet = load(descriptiveDataSetUuid);
556
        DescriptionBase<?> descriptionBase = descriptionService.load(descriptionUuid);
557
        if(dataSet==null || descriptionBase==null){
558
            result.setError();
559
        }
560
        else{
561
            removeDescriptionFromDataSet(result, dataSet, descriptionBase, config);
562
        }
563
        return result;
564
    }
565

    
566

    
567
    @Override
568
    @Transactional(readOnly=false)
569
    public DeleteResult removeDescriptions(List<UUID> descriptionUuids, UUID descriptiveDataSetUuid, RemoveDescriptionsFromDescriptiveDataSetConfigurator config) {
570
        DeleteResult result = new DeleteResult();
571
        DescriptiveDataSet dataSet = load(descriptiveDataSetUuid);
572
        List<DescriptionBase> descriptions = descriptionService.load(descriptionUuids, null);
573
        if(dataSet==null || descriptions==null){
574
            result.setError();
575
        }
576
        else{
577
            for (DescriptionBase<?> description: descriptions){
578
                removeDescriptionFromDataSet(result, dataSet, description, config);
579
            }
580
        }
581
        return result;
582
    }
583

    
584
    private void removeDescriptionFromDataSet(DeleteResult result, DescriptiveDataSet dataSet,
585
            DescriptionBase<?> description, RemoveDescriptionsFromDescriptiveDataSetConfigurator config) {
586
        if (description == null){
587
            return;
588
        }
589
        boolean success = dataSet.removeDescription(description);
590
        result.addDeletedObject(description);// remove taxon description with IndividualsAssociation from data set
591
        if(description instanceof SpecimenDescription){
592
            @SuppressWarnings({ "unchecked", "cast" })
593
            //NOTE: don't remove cast as it does not compile on some systems
594
            Set<IndividualsAssociation> associations = (Set<IndividualsAssociation>)dataSet.getDescriptions()
595
                    .stream()
596
                    .flatMap(desc->desc.getElements().stream())// put all description element in one stream
597
                    .filter(element->element instanceof IndividualsAssociation)
598
                    .map(ia->(IndividualsAssociation)ia)
599
                    .collect(Collectors.toSet());
600

    
601
            for (IndividualsAssociation individualsAssociation : associations) {
602
                if(individualsAssociation.getAssociatedSpecimenOrObservation().equals(description.getDescribedSpecimenOrObservation())){
603
                    dataSet.removeDescription(individualsAssociation.getInDescription());
604
                    result.addUpdatedObject(individualsAssociation.getInDescription());
605
                }
606
            }
607
        }
608
        if (description instanceof TaxonDescription){
609
            DeleteResult isDeletable = descriptionService.isDeletable(description.getUuid());
610
            for (CdmBase relatedCdmBase: isDeletable.getRelatedObjects()){
611
                if (relatedCdmBase instanceof CdmLinkSource){
612
                    CdmLinkSource linkSource = (CdmLinkSource)relatedCdmBase;
613
                    if (linkSource.getTarget().equals(this)){
614

    
615
                    }
616
                }
617
            }
618

    
619

    
620
        }
621
        if (!config.isOnlyRemoveDescriptionsFromDataSet()){
622
            DeleteResult deleteResult = descriptionService.deleteDescription(description);
623
            result.includeResult(deleteResult);
624
            result.addUpdatedObject(dataSet);
625
        }else{
626
            MergeResult<DescriptiveDataSet> mergeResult = dao.merge(dataSet, true);
627
            result.addUpdatedObject(mergeResult.getMergedEntity());
628
        }
629

    
630
        result.setStatus(success?Status.OK:Status.ERROR);
631
    }
632

    
633
    @Override
634
    @Transactional(readOnly = false)
635
    public DeleteResult delete(UUID datasetUuid, DeleteDescriptiveDataSetConfigurator config,  IProgressMonitor monitor){
636
        DescriptiveDataSet dataSet = dao.load(datasetUuid);
637
        monitor.beginTask("Delete Descriptive Dataset", dataSet.getDescriptions().size() +1);
638

    
639
        DeleteResult result = new DeleteResult();
640
        DeleteResult descriptionResult = new DeleteResult();
641
        if (!dataSet.getDescriptions().isEmpty()){
642
            Set<DescriptionBase> descriptions = new HashSet<>();;
643
            for (DescriptionBase<?> desc: dataSet.getDescriptions()){
644
                descriptions.add(desc);
645
            }
646
            monitor.subTask("Delete descriptions");
647
            for (DescriptionBase<?> desc: descriptions){
648
                dataSet.removeDescription(desc);
649
                if (desc instanceof SpecimenDescription && config.isDeleteAllSpecimenDescriptions()){
650
                    descriptionResult.includeResult(descriptionService.deleteDescription(desc));
651
                }else if (desc instanceof TaxonDescription){
652
                    if( desc.getTypes().contains(DescriptionType.DEFAULT_VALUES_FOR_AGGREGATION) && config.isDeleteAllDefaultDescriptions()){
653
                        descriptionResult.includeResult(descriptionService.deleteDescription(desc));
654
                    }else if (desc.getTypes().contains(DescriptionType.SECONDARY_DATA) && config.isDeleteAllLiteratureDescriptions()){
655
                        descriptionResult.includeResult(descriptionService.deleteDescription(desc));
656
                    }else if (desc.getTypes().contains(DescriptionType.AGGREGATED_STRUC_DESC) && config.isDeleteAllAggregatedDescriptions()){
657
                        descriptionResult.includeResult(descriptionService.deleteDescription(desc));
658
                    }
659
                }
660
            }
661
        }
662
        dao.delete(dataSet);
663
        monitor.worked(1);
664
        monitor.done();
665
        result.includeResult(descriptionResult);
666
        result.setStatus(Status.OK);
667
        result.addDeletedObject(dataSet);
668
        return result;
669
    }
670

    
671
    @Override
672
    @Transactional(readOnly=false)
673
    public TaxonRowWrapperDTO createTaxonDescription(UUID dataSetUuid, UUID taxonNodeUuid, DescriptionType descriptionType){
674
        DescriptiveDataSet dataSet = load(dataSetUuid);
675
        TaxonNode taxonNode = taxonNodeService.load(taxonNodeUuid, Arrays.asList("taxon"));
676
        TaxonDescription newTaxonDescription = TaxonDescription.NewInstance(taxonNode.getTaxon());
677
        newTaxonDescription.setTitleCache(dataSet.getLabel()+": "+newTaxonDescription.generateTitle(), true); //$NON-NLS-2$
678
        newTaxonDescription.getTypes().add(descriptionType);
679
        dataSet.addDescription(newTaxonDescription);
680
        saveOrUpdate(dataSet);
681
        return createTaxonRowWrapper(newTaxonDescription.getUuid(), dataSet.getUuid());
682
    }
683

    
684
    @Override
685
    public Map<UUID, List<TermDto>> getSupportedStatesForFeature(Set<UUID> featureUuids){
686
        return termDao.getSupportedStatesForFeature(featureUuids);
687
    }
688

    
689
    @Override
690
    @Transactional(readOnly=false)
691
    public DescriptionBaseDto findSpecimenDescription(UUID descriptiveDataSetUuid, SpecimenOrObservationBase specimen){
692
        DescriptiveDataSetBaseDto dataSet = this.getDescriptiveDataSetDtoByUuid(descriptiveDataSetUuid);
693
//        SpecimenOrObservationBase specimen = occurrenceService.load(specimenUuid);
694

    
695
        TermTreeDto datasetFeatures = dataSet.getDescriptiveSystem();
696
        List<DescriptionElementBase> matchingDescriptionElements = new ArrayList<>();
697

    
698
        for (SpecimenDescription specimenDescription : (Set<SpecimenDescription>) specimen.getDescriptions()) {
699
            specimenDescription = (SpecimenDescription) descriptionService.load(specimenDescription.getUuid());
700

    
701
            //check if description is already added to data set
702
            if(dataSet.getDescriptionUuids().contains(specimenDescription.getUuid()) ){
703
                return DescriptionBaseDto.fromDescription(specimenDescription);
704
            }
705

    
706
            //gather specimen description features and check for match with dataset features
707
            Set<Feature> specimenDescriptionFeatures = new HashSet<>();
708
            for (DescriptionElementBase specimenDescriptionElement : specimenDescription.getElements()) {
709
                Feature feature = specimenDescriptionElement.getFeature();
710
                specimenDescriptionFeatures.add(feature);
711
                boolean contains = false;
712
                for (TermDto featureDto:datasetFeatures.getTerms()){
713
                    if (featureDto.getUuid().equals(feature.getUuid())){
714
                        contains = true;
715
                        break;
716
                    }
717
                }
718
                if(contains && RowWrapperDTO.hasData(specimenDescriptionElement)){
719
                    matchingDescriptionElements.add(specimenDescriptionElement);
720
                }
721
            }
722
        }
723
        //Create new specimen description if description has not already been added to the dataset
724
        SpecimenDescription newDesription = SpecimenDescription.NewInstance(specimen);
725
        newDesription.setTitleCache("Dataset "+dataSet.getTitleCache()+": "+newDesription.generateTitle(), true); //$NON-NLS-2$
726

    
727
        //check for equals description element (same feature and same values)
728
        Map<Feature, List<DescriptionElementBase>> featureToElementMap = new HashMap<>();
729
        for(DescriptionElementBase element:matchingDescriptionElements){
730
            List<DescriptionElementBase> list = featureToElementMap.get(element.getFeature());
731
            if(list==null){
732
                list = new ArrayList<>();
733
            }
734
            list.add(element);
735
            featureToElementMap.put(element.getFeature(), list);
736
        }
737
        Set<DescriptionElementBase> descriptionElementsToClone = new HashSet<>();
738
        for(Feature feature:featureToElementMap.keySet()){
739
            List<DescriptionElementBase> elements = featureToElementMap.get(feature);
740
            //no duplicate description elements found for this feature
741
            if(elements.size()==1){
742
                descriptionElementsToClone.add(elements.get(0));
743
            }
744
            //duplicates found -> check if all are equal
745
            else{
746
                DescriptionElementBase match = null;
747
                for (DescriptionElementBase descriptionElementBase : elements) {
748
                    if(match==null){
749
                        match = descriptionElementBase;
750
                    }
751
                    else if(!new DescriptionElementCompareWrapper(match).equals(new DescriptionElementCompareWrapper(descriptionElementBase))){
752
                        match = null;
753
                        //TODO: propagate message
754
//                        MessagingUtils.informationDialog(Messages.CharacterMatrix_MULTIPLE_DATA,
755
//                                String.format(Messages.CharacterMatrix_MULTIPLE_DATA_MESSAGE, feature.getLabel()));
756
                        break;
757
                    }
758
                }
759
                if(match!=null){
760
                    descriptionElementsToClone.add(match);
761
                }
762
            }
763
        }
764
        //clone matching descriptionElements
765
        for (DescriptionElementBase descriptionElementBase : descriptionElementsToClone) {
766
            DescriptionElementBase clone;
767
            clone = descriptionElementBase.clone(newDesription);
768
            clone.getSources().forEach(source -> {
769
                if(descriptionElementBase instanceof CategoricalData){
770
                    TextData label = new DefaultCategoricalDescriptionBuilder().build((CategoricalData) descriptionElementBase, Arrays.asList(new Language[]{Language.DEFAULT()}));
771
                    source.setOriginalInfo(label.getText(Language.DEFAULT()));
772
                }
773
                else if(descriptionElementBase instanceof QuantitativeData){
774
                    TextData label = new DefaultQuantitativeDescriptionBuilder().build((QuantitativeData) descriptionElementBase, Arrays.asList(new Language[]{Language.DEFAULT()}));
775
                    source.setOriginalInfo(label.getText(Language.DEFAULT()));
776
                }
777
            });
778
        }
779

    
780
        //add sources of data set
781
//        if(addDatasetSource){
782
//            dataSet.getSources().forEach(source->{
783
//                try {
784
//                    newDesription.addSource(source.clone());
785
//                } catch (CloneNotSupportedException e) {
786
//                    //nothing
787
//                }
788
//            });
789
//        }
790
        return DescriptionBaseDto.fromDescription(newDesription);
791

    
792
    }
793

    
794
    //TODO: this should either be solved in the model class itself
795
    //OR this should cover all possibilities including modifiers for example
796
    private class DescriptionElementCompareWrapper {
797

    
798
        private DescriptionElementBase element;
799
        private Set<UUID> stateUuids = new HashSet<>();
800
        private Set<BigDecimal> avgs = new HashSet<>();
801
        private Set<BigDecimal> exacts = new HashSet<>();
802
        private Set<BigDecimal> maxs = new HashSet<>();
803
        private Set<BigDecimal> mins = new HashSet<>();
804
        private Set<BigDecimal> sampleSizes = new HashSet<>();
805
        private Set<BigDecimal> standardDevs = new HashSet<>();
806
        private Set<BigDecimal> lowerBounds = new HashSet<>();
807
        private Set<BigDecimal> upperBounds = new HashSet<>();
808
        private Set<BigDecimal> variances = new HashSet<>();
809

    
810
        public DescriptionElementCompareWrapper(DescriptionElementBase element) {
811
            this.element = element;
812
            if(element.isInstanceOf(CategoricalData.class)){
813
                CategoricalData elementData = (CategoricalData)element;
814
                elementData.getStatesOnly().forEach(state->stateUuids.add(state.getUuid()));
815
            }
816
            else if(element.isInstanceOf(QuantitativeData.class)){
817
                QuantitativeData elementData = (QuantitativeData)element;
818
                elementData.getStatisticalValues().forEach(value->{
819
                    if(value.getType().equals(StatisticalMeasure.AVERAGE())){
820
                        avgs.add(value.getValue());
821
                    }
822
                    else if(value.getType().equals(StatisticalMeasure.EXACT_VALUE())){
823
                        exacts.add(value.getValue());
824

    
825
                    }
826
                    else if(value.getType().equals(StatisticalMeasure.MAX())){
827
                        maxs.add(value.getValue());
828
                    }
829
                    else if(value.getType().equals(StatisticalMeasure.MIN())){
830
                        mins.add(value.getValue());
831
                    }
832
                    else if(value.getType().equals(StatisticalMeasure.SAMPLE_SIZE())){
833
                        sampleSizes.add(value.getValue());
834

    
835
                    }
836
                    else if(value.getType().equals(StatisticalMeasure.STANDARD_DEVIATION())){
837
                        standardDevs.add(value.getValue());
838
                    }
839
                    else if(value.getType().equals(StatisticalMeasure.TYPICAL_LOWER_BOUNDARY())){
840
                        lowerBounds.add(value.getValue());
841

    
842
                    }
843
                    else if(value.getType().equals(StatisticalMeasure.TYPICAL_UPPER_BOUNDARY())){
844
                        upperBounds.add(value.getValue());
845
                    }
846
                    else if(value.getType().equals(StatisticalMeasure.VARIANCE())){
847
                        variances.add(value.getValue());
848
                    }
849
                });
850
            }
851
        }
852

    
853
        @Override
854
        public int hashCode() {
855
            final int prime = 31;
856
            int result = 1;
857
            result = prime * result + getOuterType().hashCode();
858
            result = prime * result + ((avgs == null) ? 0 : avgs.hashCode());
859
            result = prime * result + ((element == null) ? 0 : element.hashCode());
860
            result = prime * result + ((exacts == null) ? 0 : exacts.hashCode());
861
            result = prime * result + ((lowerBounds == null) ? 0 : lowerBounds.hashCode());
862
            result = prime * result + ((maxs == null) ? 0 : maxs.hashCode());
863
            result = prime * result + ((mins == null) ? 0 : mins.hashCode());
864
            result = prime * result + ((sampleSizes == null) ? 0 : sampleSizes.hashCode());
865
            result = prime * result + ((standardDevs == null) ? 0 : standardDevs.hashCode());
866
            result = prime * result + ((stateUuids == null) ? 0 : stateUuids.hashCode());
867
            result = prime * result + ((upperBounds == null) ? 0 : upperBounds.hashCode());
868
            result = prime * result + ((variances == null) ? 0 : variances.hashCode());
869
            return result;
870
        }
871

    
872
        @Override
873
        public boolean equals(Object obj) {
874
            if (this == obj) {
875
                return true;
876
            }
877
            if (obj == null) {
878
                return false;
879
            }
880
            if (getClass() != obj.getClass()) {
881
                return false;
882
            }
883
            DescriptionElementCompareWrapper other = (DescriptionElementCompareWrapper) obj;
884
            if (!getOuterType().equals(other.getOuterType())) {
885
                return false;
886
            }
887
            if (avgs == null) {
888
                if (other.avgs != null) {
889
                    return false;
890
                }
891
            } else if (!avgs.equals(other.avgs)) {
892
                return false;
893
            }
894
            if (element == null) {
895
                if (other.element != null) {
896
                    return false;
897
                }
898
            } else if (!element.equals(other.element)) {
899
                return false;
900
            }
901
            if (exacts == null) {
902
                if (other.exacts != null) {
903
                    return false;
904
                }
905
            } else if (!exacts.equals(other.exacts)) {
906
                return false;
907
            }
908
            if (lowerBounds == null) {
909
                if (other.lowerBounds != null) {
910
                    return false;
911
                }
912
            } else if (!lowerBounds.equals(other.lowerBounds)) {
913
                return false;
914
            }
915
            if (maxs == null) {
916
                if (other.maxs != null) {
917
                    return false;
918
                }
919
            } else if (!maxs.equals(other.maxs)) {
920
                return false;
921
            }
922
            if (mins == null) {
923
                if (other.mins != null) {
924
                    return false;
925
                }
926
            } else if (!mins.equals(other.mins)) {
927
                return false;
928
            }
929
            if (sampleSizes == null) {
930
                if (other.sampleSizes != null) {
931
                    return false;
932
                }
933
            } else if (!sampleSizes.equals(other.sampleSizes)) {
934
                return false;
935
            }
936
            if (standardDevs == null) {
937
                if (other.standardDevs != null) {
938
                    return false;
939
                }
940
            } else if (!standardDevs.equals(other.standardDevs)) {
941
                return false;
942
            }
943
            if (stateUuids == null) {
944
                if (other.stateUuids != null) {
945
                    return false;
946
                }
947
            } else if (!stateUuids.equals(other.stateUuids)) {
948
                return false;
949
            }
950
            if (upperBounds == null) {
951
                if (other.upperBounds != null) {
952
                    return false;
953
                }
954
            } else if (!upperBounds.equals(other.upperBounds)) {
955
                return false;
956
            }
957
            if (variances == null) {
958
                if (other.variances != null) {
959
                    return false;
960
                }
961
            } else if (!variances.equals(other.variances)) {
962
                return false;
963
            }
964
            return true;
965
        }
966

    
967
        private DescriptiveDataSetService getOuterType() {
968
            return DescriptiveDataSetService.this;
969
        }
970
    }
971

    
972
    @Override
973
    public DescriptiveDataSetBaseDto getDescriptiveDataSetDtoByUuid(UUID uuid) {
974
        return dao.getDescriptiveDataSetDtoByUuid(uuid);
975
    }
976

    
977
    @Override
978
    public TaxonRowWrapperDTO createTaxonRowWrapper(DescriptionBaseDto description, UUID descriptiveDataSetUuid) {
979
        Classification classification = null;
980
        DescriptiveDataSet descriptiveDataSet = dao.load(descriptiveDataSetUuid, null);
981
        Optional<TaxonNode> first = descriptiveDataSet.getTaxonSubtreeFilter().stream()
982
                .filter(node->node.getClassification()!=null).findFirst();
983
        Optional<Classification> classificationOptional = first.map(node->node.getClassification());
984
        Set<DescriptionBaseDto> descriptions = new HashSet<>();
985
        TaxonNodeDto nodeDto = null;
986
        if(classificationOptional.isPresent()){
987
            classification = classificationOptional.get();
988
            nodeDto = taxonNodeService.dto(description.getTaxonDto().getUuid(), classification.getUuid());
989
        }
990

    
991
        return new TaxonRowWrapperDTO(description, nodeDto, descriptions);
992
    }
993

    
994
//    @Override
995
//    public DescriptionBaseDto findTaxonDescriptionByDescriptionType(UUID dataSetUuid, UUID taxonNodeUuid, DescriptionType descriptionType){
996
//      DescriptiveDataSetBaseDto dataSet = getDescriptiveDataSetDtoByUuid(dataSetUuid);
997
//      TaxonNode taxonNode = taxonNodeService.load(taxonNodeUuid);
998
//      return findTaxonDescriptionByDescriptionType(dataSet, taxonNode.getTaxon(), descriptionType);
999
//  }
1000

    
1001
}
(13-13/95)