Project

General

Profile

Download (48.4 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.log4j.Logger;
18
import org.hibernate.Query;
19
import org.hibernate.Session;
20
import org.springframework.beans.factory.annotation.Autowired;
21
import org.springframework.stereotype.Service;
22
import org.springframework.transaction.annotation.Transactional;
23

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

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

    
91
    private static Logger logger = Logger.getLogger(DescriptiveDataSetService.class);
92

    
93
    @Autowired
94
    private IOccurrenceService occurrenceService;
95

    
96
    @Autowired
97
    private ITaxonService taxonService;
98

    
99
    @Autowired
100
    private IPolytomousKeyService polytomousKeyService;
101

    
102
    @Autowired
103
    private IDefinedTermDao termDao;
104

    
105
    @Autowired
106
    private IDescriptionService descriptionService;
107

    
108
    @Autowired
109
    private ITaxonNodeService taxonNodeService;
110

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

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

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

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

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

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

    
174
        return result;
175
    }
176

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

    
183

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

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

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

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

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

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

    
222

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

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

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

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

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

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

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

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

    
292

    
293

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

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

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

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

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

    
375
            }
376

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

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

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

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

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

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

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

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

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

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

    
472
//    private TaxonDescription findTaxonDescriptionByDescriptionType(DescriptiveDataSetBaseDto dataSet, UUID taxonUuid, DescriptionType descriptionType){
473
//        descriptionService.find
474
//        Optional<TaxonDescription> first = taxon.getDescriptions().stream()
475
//                .filter(desc -> desc.getTypes().stream().anyMatch(type -> type.equals(descriptionType)))
476
//                .filter(desc -> dataSet.getDescriptions().contains(desc))
477
//                .findFirst();
478
//        if(first.isPresent()){
479
//            return HibernateProxyHelper.deproxy(descriptionService.load(first.get().getUuid(),
480
//                  Arrays.asList("taxon", "descriptionElements", "descriptionElements.feature")), TaxonDescription.class);
481
//        }
482
//        return null;
483
//    }
484
//
485
//    @Override
486
//    public TaxonDescription findTaxonDescriptionByDescriptionType(UUID dataSetUuid, UUID taxonNodeUuid, DescriptionType descriptionType){
487
//        DescriptiveDataSet dataSet = load(dataSetUuid);
488
//        TaxonNode taxonNode = taxonNodeService.load(taxonNodeUuid);
489
//        return findTaxonDescriptionByDescriptionType(dataSet, taxonNode.getTaxon(), descriptionType);
490
//    }
491
    @Override
492
    public DescriptionBaseDto getTaxonDescriptionForDescriptiveDataSetAndType(DescriptiveDataSetBaseDto dataSet, UUID taxonUuid, DescriptionType descriptionType){
493
        Session session = getSession();
494
        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 d.type = :descriptionType";
495

    
496
        Query query;
497
        query = session.createQuery(queryString);
498
        query.setParameter("taxonuuid", taxonUuid);
499
        query.setParameter("dataSetUuid", dataSet.getUuid());
500
        query.setParameter("descriptionType", descriptionType);
501

    
502
        @SuppressWarnings("unchecked")
503
        List<UUID> result = query.list();
504
        List<DescriptionBaseDto> list = new ArrayList<>();
505
        list.addAll(descriptionService.loadDtos(new HashSet(result)));
506
        if (list.isEmpty()){
507
            return null;
508
        }
509
        return list.get(0);
510
    }
511

    
512
    @Override
513
    @Transactional(readOnly=false)
514
    public UpdateResult generatePolytomousKey(UUID descriptiveDataSetUuid, UUID taxonUuid) {
515
        UpdateResult result = new UpdateResult();
516

    
517
        PolytomousKeyGeneratorConfigurator keyConfig = new PolytomousKeyGeneratorConfigurator();
518
        DescriptiveDataSet descriptiveDataSet = load(descriptiveDataSetUuid);
519
        keyConfig.setDataSet(descriptiveDataSet);
520
        PolytomousKey key = new PolytomousKeyGenerator().invoke(keyConfig);
521
        IdentifiableServiceConfiguratorImpl<PolytomousKey> serviceConfig= new IdentifiableServiceConfiguratorImpl<>();
522
        serviceConfig.setTitleSearchString(descriptiveDataSet.getTitleCache());
523
        List<PolytomousKey> list = polytomousKeyService.findByTitle(serviceConfig).getRecords();
524
        if(list!=null){
525
            list.forEach(polytomousKey->polytomousKeyService.delete(polytomousKey));
526
        }
527
        key.setTitleCache(descriptiveDataSet.getTitleCache(), true);
528

    
529
        Taxon taxon = (Taxon) taxonService.load(taxonUuid);
530
        key.addTaxonomicScope(taxon);
531

    
532
        polytomousKeyService.saveOrUpdate(key);
533

    
534
        result.setCdmEntity(key);
535
        result.addUpdatedObject(taxon);
536
        return result;
537
    }
538

    
539
    @Override
540
    @Transactional(readOnly=false)
541
    public DeleteResult removeDescription(UUID descriptionUuid, UUID descriptiveDataSetUuid, RemoveDescriptionsFromDescriptiveDataSetConfigurator config) {
542
        DeleteResult result = new DeleteResult();
543
        DescriptiveDataSet dataSet = load(descriptiveDataSetUuid);
544
        DescriptionBase<?> descriptionBase = descriptionService.load(descriptionUuid);
545
        if(dataSet==null || descriptionBase==null){
546
            result.setError();
547
        }
548
        else{
549
            removeDescriptionFromDataSet(result, dataSet, descriptionBase, config);
550
        }
551
        return result;
552
    }
553

    
554

    
555
    @Override
556
    @Transactional(readOnly=false)
557
    public DeleteResult removeDescriptions(List<UUID> descriptionUuids, UUID descriptiveDataSetUuid, RemoveDescriptionsFromDescriptiveDataSetConfigurator config) {
558
        DeleteResult result = new DeleteResult();
559
        DescriptiveDataSet dataSet = load(descriptiveDataSetUuid);
560
        List<DescriptionBase> descriptions = descriptionService.load(descriptionUuids, null);
561
        if(dataSet==null || descriptions==null){
562
            result.setError();
563
        }
564
        else{
565
            for (DescriptionBase<?> description: descriptions){
566
                removeDescriptionFromDataSet(result, dataSet, description, config);
567
            }
568
        }
569
        return result;
570
    }
571

    
572
    private void removeDescriptionFromDataSet(DeleteResult result, DescriptiveDataSet dataSet,
573
            DescriptionBase<?> description, RemoveDescriptionsFromDescriptiveDataSetConfigurator config) {
574
        if (description == null){
575
            return;
576
        }
577
        boolean success = dataSet.removeDescription(description);
578
        result.addDeletedObject(description);// remove taxon description with IndividualsAssociation from data set
579
        if(description instanceof SpecimenDescription){
580
            @SuppressWarnings({ "unchecked", "cast" })
581
            //NOTE: don't remove cast as it does not compile on some systems
582
            Set<IndividualsAssociation> associations = (Set<IndividualsAssociation>)dataSet.getDescriptions()
583
                    .stream()
584
                    .flatMap(desc->desc.getElements().stream())// put all description element in one stream
585
                    .filter(element->element instanceof IndividualsAssociation)
586
                    .map(ia->(IndividualsAssociation)ia)
587
                    .collect(Collectors.toSet());
588

    
589
            for (IndividualsAssociation individualsAssociation : associations) {
590
                if(individualsAssociation.getAssociatedSpecimenOrObservation().equals(description.getDescribedSpecimenOrObservation())){
591
                    dataSet.removeDescription(individualsAssociation.getInDescription());
592
                    result.addUpdatedObject(individualsAssociation.getInDescription());
593
                }
594
            }
595
        }
596
        if (description instanceof TaxonDescription){
597
            DeleteResult isDeletable = descriptionService.isDeletable(description.getUuid());
598
            for (CdmBase relatedCdmBase: isDeletable.getRelatedObjects()){
599
                if (relatedCdmBase instanceof CdmLinkSource){
600
                    CdmLinkSource linkSource = (CdmLinkSource)relatedCdmBase;
601
                    if (linkSource.getTarget().equals(this)){
602

    
603
                    }
604
                }
605
            }
606

    
607

    
608
        }
609
        if (!config.isOnlyRemoveDescriptionsFromDataSet()){
610
            DeleteResult deleteResult = descriptionService.deleteDescription(description);
611
            result.includeResult(deleteResult);
612
            result.addUpdatedObject(dataSet);
613
        }else{
614
            MergeResult<DescriptiveDataSet> mergeResult = dao.merge(dataSet, true);
615
            result.addUpdatedObject(mergeResult.getMergedEntity());
616
        }
617

    
618
        result.setStatus(success?Status.OK:Status.ERROR);
619
    }
620

    
621
    @Override
622
    @Transactional(readOnly = false)
623
    public DeleteResult delete(UUID datasetUuid, DeleteDescriptiveDataSetConfigurator config,  IProgressMonitor monitor){
624
        DescriptiveDataSet dataSet = dao.load(datasetUuid);
625
        monitor.beginTask("Delete Descriptive Dataset", dataSet.getDescriptions().size() +1);
626

    
627
        DeleteResult result = new DeleteResult();
628
        DeleteResult descriptionResult = new DeleteResult();
629
        if (!dataSet.getDescriptions().isEmpty()){
630
            Set<DescriptionBase> descriptions = new HashSet<>();;
631
            for (DescriptionBase<?> desc: dataSet.getDescriptions()){
632
                descriptions.add(desc);
633
            }
634
            monitor.subTask("Delete descriptions");
635
            for (DescriptionBase<?> desc: descriptions){
636
                dataSet.removeDescription(desc);
637
                if (desc instanceof SpecimenDescription && config.isDeleteAllSpecimenDescriptions()){
638
                    descriptionResult.includeResult(descriptionService.deleteDescription(desc));
639
                }else if (desc instanceof TaxonDescription){
640
                    if( desc.getTypes().contains(DescriptionType.DEFAULT_VALUES_FOR_AGGREGATION) && config.isDeleteAllDefaultDescriptions()){
641
                        descriptionResult.includeResult(descriptionService.deleteDescription(desc));
642
                    }else if (desc.getTypes().contains(DescriptionType.SECONDARY_DATA) && config.isDeleteAllLiteratureDescriptions()){
643
                        descriptionResult.includeResult(descriptionService.deleteDescription(desc));
644
                    }else if (desc.getTypes().contains(DescriptionType.AGGREGATED_STRUC_DESC) && config.isDeleteAllAggregatedDescriptions()){
645
                        descriptionResult.includeResult(descriptionService.deleteDescription(desc));
646
                    }
647
                }
648
            }
649
        }
650
        dao.delete(dataSet);
651
        monitor.worked(1);
652
        monitor.done();
653
        result.includeResult(descriptionResult);
654
        result.setStatus(Status.OK);
655
        result.addDeletedObject(dataSet);
656
        return result;
657
    }
658

    
659
    @Override
660
    @Transactional(readOnly=false)
661
    public TaxonRowWrapperDTO createTaxonDescription(UUID dataSetUuid, UUID taxonNodeUuid, DescriptionType descriptionType){
662
        DescriptiveDataSet dataSet = load(dataSetUuid);
663
        TaxonNode taxonNode = taxonNodeService.load(taxonNodeUuid, Arrays.asList("taxon"));
664
        TaxonDescription newTaxonDescription = TaxonDescription.NewInstance(taxonNode.getTaxon());
665
        newTaxonDescription.setTitleCache(dataSet.getLabel()+": "+newTaxonDescription.generateTitle(), true); //$NON-NLS-2$
666
        newTaxonDescription.getTypes().add(descriptionType);
667
        dataSet.addDescription(newTaxonDescription);
668
        saveOrUpdate(dataSet);
669
        return createTaxonRowWrapper(newTaxonDescription.getUuid(), dataSet.getUuid());
670
    }
671

    
672
    @Override
673
    public Map<UUID, List<TermDto>> getSupportedStatesForFeature(Set<UUID> featureUuids){
674
        return termDao.getSupportedStatesForFeature(featureUuids);
675
    }
676

    
677
    @Override
678
    @Transactional(readOnly=false)
679
    public DescriptionBaseDto findSpecimenDescription(UUID descriptiveDataSetUuid, SpecimenOrObservationBase specimen){
680
        DescriptiveDataSetBaseDto dataSet = this.getDescriptiveDataSetDtoByUuid(descriptiveDataSetUuid);
681
//        SpecimenOrObservationBase specimen = occurrenceService.load(specimenUuid);
682

    
683
        TermTreeDto datasetFeatures = dataSet.getDescriptiveSystem();
684
        List<DescriptionElementBase> matchingDescriptionElements = new ArrayList<>();
685

    
686
        for (SpecimenDescription specimenDescription : (Set<SpecimenDescription>) specimen.getDescriptions()) {
687
            specimenDescription = (SpecimenDescription) descriptionService.load(specimenDescription.getUuid());
688

    
689
            //check if description is already added to data set
690
            if(dataSet.getDescriptionUuids().contains(specimenDescription.getUuid()) ){
691
                return DescriptionBaseDto.fromDescription(specimenDescription);
692
            }
693

    
694
            //gather specimen description features and check for match with dataset features
695
            Set<Feature> specimenDescriptionFeatures = new HashSet<>();
696
            for (DescriptionElementBase specimenDescriptionElement : specimenDescription.getElements()) {
697
                Feature feature = specimenDescriptionElement.getFeature();
698
                specimenDescriptionFeatures.add(feature);
699
                boolean contains = false;
700
                for (TermDto featureDto:datasetFeatures.getTerms()){
701
                    if (featureDto.getUuid().equals(feature.getUuid())){
702
                        contains = true;
703
                        break;
704
                    }
705
                }
706
                if(contains && RowWrapperDTO.hasData(specimenDescriptionElement)){
707
                    matchingDescriptionElements.add(specimenDescriptionElement);
708
                }
709
            }
710
        }
711
        //Create new specimen description if description has not already been added to the dataset
712
        SpecimenDescription newDesription = SpecimenDescription.NewInstance(specimen);
713
        newDesription.setTitleCache("Dataset "+dataSet.getTitleCache()+": "+newDesription.generateTitle(), true); //$NON-NLS-2$
714

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

    
768
        //add sources of data set
769
//        if(addDatasetSource){
770
//            dataSet.getSources().forEach(source->{
771
//                try {
772
//                    newDesription.addSource(source.clone());
773
//                } catch (CloneNotSupportedException e) {
774
//                    //nothing
775
//                }
776
//            });
777
//        }
778
        return DescriptionBaseDto.fromDescription(newDesription);
779

    
780
    }
781

    
782
    //TODO: this should either be solved in the model class itself
783
    //OR this should cover all possibilities including modifiers for example
784
    private class DescriptionElementCompareWrapper {
785

    
786
        private DescriptionElementBase element;
787
        private Set<UUID> stateUuids = new HashSet<>();
788
        private Set<BigDecimal> avgs = new HashSet<>();
789
        private Set<BigDecimal> exacts = new HashSet<>();
790
        private Set<BigDecimal> maxs = new HashSet<>();
791
        private Set<BigDecimal> mins = new HashSet<>();
792
        private Set<BigDecimal> sampleSizes = new HashSet<>();
793
        private Set<BigDecimal> standardDevs = new HashSet<>();
794
        private Set<BigDecimal> lowerBounds = new HashSet<>();
795
        private Set<BigDecimal> upperBounds = new HashSet<>();
796
        private Set<BigDecimal> variances = new HashSet<>();
797

    
798
        public DescriptionElementCompareWrapper(DescriptionElementBase element) {
799
            this.element = element;
800
            if(element.isInstanceOf(CategoricalData.class)){
801
                CategoricalData elementData = (CategoricalData)element;
802
                elementData.getStatesOnly().forEach(state->stateUuids.add(state.getUuid()));
803
            }
804
            else if(element.isInstanceOf(QuantitativeData.class)){
805
                QuantitativeData elementData = (QuantitativeData)element;
806
                elementData.getStatisticalValues().forEach(value->{
807
                    if(value.getType().equals(StatisticalMeasure.AVERAGE())){
808
                        avgs.add(value.getValue());
809
                    }
810
                    else if(value.getType().equals(StatisticalMeasure.EXACT_VALUE())){
811
                        exacts.add(value.getValue());
812

    
813
                    }
814
                    else if(value.getType().equals(StatisticalMeasure.MAX())){
815
                        maxs.add(value.getValue());
816
                    }
817
                    else if(value.getType().equals(StatisticalMeasure.MIN())){
818
                        mins.add(value.getValue());
819
                    }
820
                    else if(value.getType().equals(StatisticalMeasure.SAMPLE_SIZE())){
821
                        sampleSizes.add(value.getValue());
822

    
823
                    }
824
                    else if(value.getType().equals(StatisticalMeasure.STANDARD_DEVIATION())){
825
                        standardDevs.add(value.getValue());
826
                    }
827
                    else if(value.getType().equals(StatisticalMeasure.TYPICAL_LOWER_BOUNDARY())){
828
                        lowerBounds.add(value.getValue());
829

    
830
                    }
831
                    else if(value.getType().equals(StatisticalMeasure.TYPICAL_UPPER_BOUNDARY())){
832
                        upperBounds.add(value.getValue());
833
                    }
834
                    else if(value.getType().equals(StatisticalMeasure.VARIANCE())){
835
                        variances.add(value.getValue());
836
                    }
837
                });
838
            }
839
        }
840

    
841
        @Override
842
        public int hashCode() {
843
            final int prime = 31;
844
            int result = 1;
845
            result = prime * result + getOuterType().hashCode();
846
            result = prime * result + ((avgs == null) ? 0 : avgs.hashCode());
847
            result = prime * result + ((element == null) ? 0 : element.hashCode());
848
            result = prime * result + ((exacts == null) ? 0 : exacts.hashCode());
849
            result = prime * result + ((lowerBounds == null) ? 0 : lowerBounds.hashCode());
850
            result = prime * result + ((maxs == null) ? 0 : maxs.hashCode());
851
            result = prime * result + ((mins == null) ? 0 : mins.hashCode());
852
            result = prime * result + ((sampleSizes == null) ? 0 : sampleSizes.hashCode());
853
            result = prime * result + ((standardDevs == null) ? 0 : standardDevs.hashCode());
854
            result = prime * result + ((stateUuids == null) ? 0 : stateUuids.hashCode());
855
            result = prime * result + ((upperBounds == null) ? 0 : upperBounds.hashCode());
856
            result = prime * result + ((variances == null) ? 0 : variances.hashCode());
857
            return result;
858
        }
859

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

    
955
        private DescriptiveDataSetService getOuterType() {
956
            return DescriptiveDataSetService.this;
957
        }
958
    }
959

    
960
    @Override
961
    public DescriptiveDataSetBaseDto getDescriptiveDataSetDtoByUuid(UUID uuid) {
962
        return dao.getDescriptiveDataSetDtoByUuid(uuid);
963
    }
964

    
965
    @Override
966
    public TaxonRowWrapperDTO createTaxonRowWrapper(DescriptionBaseDto description, UUID descriptiveDataSetUuid) {
967
        Classification classification = null;
968
        DescriptiveDataSet descriptiveDataSet = dao.load(descriptiveDataSetUuid, null);
969
        Optional<TaxonNode> first = descriptiveDataSet.getTaxonSubtreeFilter().stream()
970
                .filter(node->node.getClassification()!=null).findFirst();
971
        Optional<Classification> classificationOptional = first.map(node->node.getClassification());
972
        Set<DescriptionBaseDto> descriptions = new HashSet<>();
973
        TaxonNodeDto nodeDto = null;
974
        if(classificationOptional.isPresent()){
975
            classification = classificationOptional.get();
976
            nodeDto = taxonNodeService.dto(description.getTaxonDto().getUuid(), classification.getUuid());
977
        }
978

    
979
        return new TaxonRowWrapperDTO(description, nodeDto, descriptions);
980
    }
981

    
982
//    @Override
983
//    public DescriptionBaseDto findTaxonDescriptionByDescriptionType(UUID dataSetUuid, UUID taxonNodeUuid, DescriptionType descriptionType){
984
//      DescriptiveDataSetBaseDto dataSet = getDescriptiveDataSetDtoByUuid(dataSetUuid);
985
//      TaxonNode taxonNode = taxonNodeService.load(taxonNodeUuid);
986
//      return findTaxonDescriptionByDescriptionType(dataSet, taxonNode.getTaxon(), descriptionType);
987
//  }
988

    
989
}
(13-13/95)