Project

General

Profile

Download (29.4 KB) Statistics
| Branch: | Tag: | Revision:
1
/**
2
* Copyright (C) 2021 EDIT
3
* European Distributed Institute of Taxonomy
4
* http://www.e-taxonomy.eu
5
*
6
* The contents of this file are subject to the Mozilla Public License Version 1.1
7
* See LICENSE.TXT at the top of this package for the full license terms.
8
*/
9
package eu.etaxonomy.cdm.api.service.description;
10

    
11
import static org.junit.Assert.assertEquals;
12
import static org.junit.Assert.assertTrue;
13

    
14
import java.io.FileNotFoundException;
15
import java.math.BigDecimal;
16
import java.util.ArrayList;
17
import java.util.HashSet;
18
import java.util.Iterator;
19
import java.util.List;
20
import java.util.Set;
21
import java.util.UUID;
22
import java.util.stream.Collectors;
23

    
24
import org.apache.log4j.Logger;
25
import org.junit.Assert;
26
import org.junit.Before;
27
import org.junit.Ignore;
28
import org.junit.Test;
29
import org.unitils.dbunit.annotation.DataSet;
30
import org.unitils.dbunit.annotation.DataSets;
31
import org.unitils.spring.annotation.SpringBeanByType;
32

    
33
import eu.etaxonomy.cdm.api.application.ICdmRepository;
34
import eu.etaxonomy.cdm.api.service.IClassificationService;
35
import eu.etaxonomy.cdm.api.service.IDescriptionService;
36
import eu.etaxonomy.cdm.api.service.IDescriptiveDataSetService;
37
import eu.etaxonomy.cdm.api.service.IReferenceService;
38
import eu.etaxonomy.cdm.api.service.ITaxonNodeService;
39
import eu.etaxonomy.cdm.api.service.ITaxonService;
40
import eu.etaxonomy.cdm.api.service.ITermService;
41
import eu.etaxonomy.cdm.api.service.ITermTreeService;
42
import eu.etaxonomy.cdm.api.service.IVocabularyService;
43
import eu.etaxonomy.cdm.api.service.UpdateResult;
44
import eu.etaxonomy.cdm.api.service.dto.CategoricalDataDto;
45
import eu.etaxonomy.cdm.api.service.dto.DescriptionBaseDto;
46
import eu.etaxonomy.cdm.api.service.dto.DescriptionElementDto;
47
import eu.etaxonomy.cdm.api.service.dto.QuantitativeDataDto;
48
import eu.etaxonomy.cdm.api.service.dto.RowWrapperDTO;
49
import eu.etaxonomy.cdm.api.service.dto.SpecimenRowWrapperDTO;
50
import eu.etaxonomy.cdm.api.service.dto.StateDataDto;
51
import eu.etaxonomy.cdm.api.service.dto.StatisticalMeasurementValueDto;
52
import eu.etaxonomy.cdm.common.JvmLimitsException;
53
import eu.etaxonomy.cdm.common.monitor.DefaultProgressMonitor;
54
import eu.etaxonomy.cdm.common.monitor.IProgressMonitor;
55
import eu.etaxonomy.cdm.model.common.CdmBase;
56
import eu.etaxonomy.cdm.model.description.CategoricalData;
57
import eu.etaxonomy.cdm.model.description.DescriptionBase;
58
import eu.etaxonomy.cdm.model.description.DescriptionElementBase;
59
import eu.etaxonomy.cdm.model.description.DescriptionType;
60
import eu.etaxonomy.cdm.model.description.DescriptiveDataSet;
61
import eu.etaxonomy.cdm.model.description.Feature;
62
import eu.etaxonomy.cdm.model.description.IndividualsAssociation;
63
import eu.etaxonomy.cdm.model.description.QuantitativeData;
64
import eu.etaxonomy.cdm.model.description.SpecimenDescription;
65
import eu.etaxonomy.cdm.model.description.State;
66
import eu.etaxonomy.cdm.model.description.StateData;
67
import eu.etaxonomy.cdm.model.description.StatisticalMeasure;
68
import eu.etaxonomy.cdm.model.description.StatisticalMeasurementValue;
69
import eu.etaxonomy.cdm.model.description.TaxonDescription;
70
import eu.etaxonomy.cdm.model.name.IBotanicalName;
71
import eu.etaxonomy.cdm.model.name.Rank;
72
import eu.etaxonomy.cdm.model.name.TaxonNameFactory;
73
import eu.etaxonomy.cdm.model.occurrence.DerivedUnit;
74
import eu.etaxonomy.cdm.model.reference.Reference;
75
import eu.etaxonomy.cdm.model.reference.ReferenceFactory;
76
import eu.etaxonomy.cdm.model.taxon.Classification;
77
import eu.etaxonomy.cdm.model.taxon.Taxon;
78
import eu.etaxonomy.cdm.model.taxon.TaxonNode;
79
import eu.etaxonomy.cdm.model.term.TermNode;
80
import eu.etaxonomy.cdm.model.term.TermTree;
81
import eu.etaxonomy.cdm.model.term.TermType;
82
import eu.etaxonomy.cdm.model.term.TermVocabulary;
83
import eu.etaxonomy.cdm.persistence.dto.FeatureDto;
84
import eu.etaxonomy.cdm.persistence.dto.TermDto;
85
import eu.etaxonomy.cdm.test.integration.CdmTransactionalIntegrationTest;
86
import eu.etaxonomy.cdm.test.unitils.CleanSweepInsertLoadStrategy;
87

    
88
/**
89
 * @author k.luther
90
 * @since 01.10.2021
91
 */
92
public class DescriptiveDataSetServiceTest extends CdmTransactionalIntegrationTest {
93

    
94
    @SuppressWarnings("unused")
95
    private static Logger logger = Logger.getLogger(DescriptiveDataSetServiceTest.class);
96

    
97

    
98
    private static final UUID T_LAPSANA_UUID = UUID.fromString("f65d47bd-4f49-4ab1-bc4a-bc4551eaa1a8");
99
    private static final UUID TN_LAPSANA_UUID = UUID.fromString("f4d29e9f-6484-4184-af2e-9704e96a17e3");
100

    
101
    private static final UUID T_LAPSANA_COMMUNIS_UUID = UUID.fromString("2a5ceebb-4830-4524-b330-78461bf8cb6b");
102

    
103
    private static final UUID T_LAPSANA_COMMUNIS_COMMUNIS_UUID = UUID.fromString("441a3c40-0c84-11de-8c30-0800200c9a66");
104

    
105
    private static final UUID T_LAPSANA_COMMUNIS_ADENOPHORA_UUID = UUID.fromString("e4acf200-63b6-11dd-ad8b-0800200c9a66");
106

    
107
    private static final UUID T_LAPSANA_COMMUNIS_ALPINA_UUID = UUID.fromString("596b1325-be50-4b0a-9aa2-3ecd610215f2");
108

    
109
    private static final UUID CLASSIFICATION_UUID = UUID.fromString("4b266053-a841-4980-b548-3f21d8d7d712");
110

    
111
    private static final UUID uuidFeatureLeafPA = UUID.fromString("c4dfd16f-f2ed-45e0-8f4d-7fe1ae880510");
112
    private static UUID uuidFeatureLeafLength = UUID.fromString("3c19b50b-4a8e-467e-b7d4-89ebc05a33e1");
113
    private static UUID uuidFeatureLeafColor = UUID.fromString("1e8f503c-5aeb-4788-b4f9-84128f7141c7");
114

    
115
    private static UUID uuidLeafColorBlue = UUID.fromString("9b4df19d-f89d-4788-9d71-d1f6f7cae910");
116
    private static UUID uuidLeafColorYellow = UUID.fromString("4cf0881b-0e7b-489a-9fdb-adbe6ae4e0ae");
117

    
118
    private static UUID uuidFeatureTree = UUID.fromString("c8a29a94-2754-4d78-9faa-dff3e1387b2d");
119

    
120

    
121
    @SpringBeanByType
122
    private ICdmRepository repository;
123

    
124
    @SpringBeanByType
125
    private ITermService termService;
126

    
127
    @SpringBeanByType
128
    private ITermTreeService termTreeService;
129

    
130
    @SpringBeanByType
131
    private IVocabularyService vocabularyService;
132

    
133
    @SpringBeanByType
134
    private IDescriptionService descriptionService;
135

    
136
    @SpringBeanByType
137
    private ITaxonService taxonService;
138

    
139
    @SpringBeanByType
140
    private ITaxonNodeService taxonNodeService;
141

    
142
    @SpringBeanByType
143
    private IClassificationService classificationService;
144

    
145
    @SpringBeanByType
146
    private IReferenceService referenceService;
147

    
148
    @SpringBeanByType
149
    private IDescriptiveDataSetService datasetService;
150

    
151
    private StructuredDescriptionAggregation engine;
152

    
153
    private IProgressMonitor monitor;
154

    
155
    @Before
156
    public void setUp() {
157

    
158
//        engine.setBatchMinFreeHeap(100 * 1024 * 1024);
159
        monitor = DefaultProgressMonitor.NewInstance();
160
    }
161

    
162
    @Test
163
    @DataSets({
164
        @DataSet(loadStrategy=CleanSweepInsertLoadStrategy.class, value="/eu/etaxonomy/cdm/database/ClearDB_with_Terms_DataSet.xml"),
165
        @DataSet(value="/eu/etaxonomy/cdm/database/TermsDataSet-with_auditing_info.xml"),
166
        @DataSet(value="StructuredDescriptionAggregationTest.xml"),
167
    })
168
    public void testGetRowWrapper(){
169
        createDefaultFeatureTree();
170
        DescriptiveDataSet dataSet = createTestDataset();
171
         commitAndStartNewTransaction();
172

    
173
        List<RowWrapperDTO<?>> result =  datasetService.getRowWrapper(dataSet.getUuid(), monitor);
174

    
175
        //There are 4 specimen descriptions and one literature description (taxon association)
176
        assertTrue(result.size() == 5);
177
        //check rowWrapper
178
        //specimen_1 2 categorical and 1 quantitative
179
        for (RowWrapperDTO row: result){
180
            if (row instanceof SpecimenRowWrapperDTO){
181
                SpecimenRowWrapperDTO specimen = (SpecimenRowWrapperDTO)row;
182
                if (specimen.getSpecimenDto().getLabel().equals("alpina specimen1")){
183
                    Set<DescriptionElementDto> elements = specimen.getDataValueForFeature(uuidFeatureLeafColor);
184
                    if (elements != null && !elements.isEmpty() ){
185
                        Iterator<DescriptionElementDto> it = elements.iterator();
186
                        DescriptionElementDto dto = null;
187
                        if (it.hasNext()){
188
                            dto = it.next();
189
                        }else{
190
                            Assert.fail("There is no element for feature leaf color, but should.");
191
                        }
192
                        if (dto instanceof CategoricalDataDto){
193
                            assertTrue("The states should contain one element", ((CategoricalDataDto)dto).getStates().size() == 1);
194
                            StateDataDto stateData = ((CategoricalDataDto)dto).getStates().iterator().next();
195
                            assertEquals(uuidLeafColorBlue, stateData.getState().getUuid());
196
                        }else{
197
                            Assert.fail("The element is not of type categorical data");
198
                        }
199
                    }else{
200
                        Assert.fail();
201
                    }
202

    
203

    
204
                    elements = specimen.getDataValueForFeature(uuidFeatureLeafLength);
205
                    if (elements != null && !elements.isEmpty() ){
206
                        Iterator<DescriptionElementDto> it = elements.iterator();
207
                        DescriptionElementDto dto = null;
208
                        if (it.hasNext()){
209
                            dto = it.next();
210
                        }else{
211
                            Assert.fail("There is no element for feature leaf length, but should.");
212
                        }
213
                        if (dto instanceof QuantitativeDataDto){
214
                            assertTrue("The statistical values should contain one element", ((QuantitativeDataDto)dto).getValues().size() == 1);
215
                            StatisticalMeasurementValueDto statValue = ((QuantitativeDataDto)dto).getValues().iterator().next();
216
                            assertEquals(new BigDecimal("5.0"), statValue.getValue());
217
                        }else{
218
                            Assert.fail("The element is not of type quantitative data");
219
                        }
220
                    }else{
221
                        Assert.fail();
222
                    }
223

    
224

    
225
                    elements = specimen.getDataValueForFeature(uuidFeatureLeafPA);
226
//                    assertTrue("The element should be categorical data ", element instanceof CategoricalDataDto);
227
//                    assertTrue("The statistical values should contain one element", ((CategoricalDataDto)element).getStates().size() == 1);
228
//                    StateDataDto stateData2 = ((CategoricalDataDto)element).getStates().iterator().next();
229
//                    assertEquals(State.uuidPresent, stateData2.getState().getUuid());
230

    
231
                }
232
            }
233
//            if (row instanceof TaxonRowWrapperDTO){
234
//                TaxonRowWrapperDTO taxonRow = (TaxonRowWrapperDTO)row;
235
//                Set<DescriptionElementDto> element = taxonRow.getDataValueForFeature(uuidFeatureLeafLength);
236
//                assertTrue(element instanceof QuantitativeDataDto);
237
//                assertTrue(((QuantitativeDataDto)element).getValues().size() == 2);
238
//            }
239
        }
240

    
241

    
242
        commitAndStartNewTransaction();
243

    
244
    }
245

    
246

    
247

    
248
    @Test
249
    @DataSets({
250
        @DataSet(loadStrategy=CleanSweepInsertLoadStrategy.class, value="/eu/etaxonomy/cdm/database/ClearDB_with_Terms_DataSet.xml"),
251
        @DataSet(value="/eu/etaxonomy/cdm/database/TermsDataSet-with_auditing_info.xml"),
252
        @DataSet(value="StructuredDescriptionAggregationTest.xml"),
253
    })
254
    public void addQuantitativeDataTest() {
255
        createDefaultFeatureTree();
256
        DescriptiveDataSet dataSet = createTestDataset();
257
        commitAndStartNewTransaction();
258

    
259
        List<RowWrapperDTO<?>> result = datasetService.getRowWrapper(dataSet.getUuid(), monitor);
260
        List<DescriptionBaseDto> descToUpdate = new ArrayList<>();
261
        UUID updatedDescription = null;
262
        int elementCount = 0;
263
        for (RowWrapperDTO row: result){
264
            if (row instanceof SpecimenRowWrapperDTO){
265
                SpecimenRowWrapperDTO specimen = (SpecimenRowWrapperDTO)row;
266
                DescriptionBaseDto descDto = specimen.getDescription();
267
                elementCount = descDto.getElements().size();
268
                Feature feature = (Feature)termService.find(uuidFeatureLeafLength);
269
                QuantitativeDataDto quantDto = new QuantitativeDataDto(FeatureDto.fromFeature(feature));
270
                TermDto typeDto = new TermDto(StatisticalMeasure.EXACT_VALUE().getUuid(), null, StatisticalMeasure.EXACT_VALUE().getTermType(), StatisticalMeasure.EXACT_VALUE().getPartOf() != null?StatisticalMeasure.EXACT_VALUE().getPartOf().getUuid(): null, StatisticalMeasure.EXACT_VALUE().getKindOf()!= null? StatisticalMeasure.EXACT_VALUE().getKindOf().getUuid(): null,
271
                        StatisticalMeasure.EXACT_VALUE().getVocabulary() != null? StatisticalMeasure.EXACT_VALUE().getVocabulary().getUuid(): null, null, StatisticalMeasure.EXACT_VALUE().getIdInVocabulary(), StatisticalMeasure.EXACT_VALUE().getTitleCache());
272
                StatisticalMeasurementValueDto statValue = new StatisticalMeasurementValueDto(typeDto, new BigDecimal("4.5"), null);
273
                Set<StatisticalMeasurementValueDto> values = new HashSet<>();
274
                values.add(statValue);
275
                quantDto.setValues(values);
276
                descDto.addElement(quantDto);
277
                descToUpdate.add(descDto);
278
                updatedDescription = descDto.getDescriptionUuid();
279

    
280
            }
281
        }
282
        descriptionService.mergeDescriptions(descToUpdate, dataSet.getUuid());
283

    
284
        commitAndStartNewTransaction();
285
        DescriptionBase description = descriptionService.load(updatedDescription);
286
        assertEquals(description.getElements().size(),elementCount +1);
287
        for(Object el: description.getElements()){
288
            if (el instanceof QuantitativeData){
289
                QuantitativeData descEl = (QuantitativeData)el;
290
                if (descEl.getFeature().getUuid().equals(uuidFeatureLeafLength)){
291
                    assertEquals(descEl.getExactValues().size(),1);
292
                }
293
            }
294
        }
295

    
296
    }
297

    
298
    @Test
299
    @DataSets({
300
        @DataSet(loadStrategy=CleanSweepInsertLoadStrategy.class, value="/eu/etaxonomy/cdm/database/ClearDB_with_Terms_DataSet.xml"),
301
        @DataSet(value="/eu/etaxonomy/cdm/database/TermsDataSet-with_auditing_info.xml"),
302
        @DataSet(value="StructuredDescriptionAggregationTest.xml"),
303
    })
304
    @Ignore
305
    public void incompleteCategoricalDataTest() throws JvmLimitsException{
306
        createDefaultFeatureTree();
307
        DescriptiveDataSet dataSet = DescriptiveDataSet.NewInstance();
308
        datasetService.save(dataSet);
309

    
310
        SpecimenDescription specDescAlpina1 = createSpecimenDescription(dataSet, T_LAPSANA_COMMUNIS_ALPINA_UUID, "alpina specimen1");
311
        addCategoricalData(specDescAlpina1, uuidFeatureLeafColor, null);
312

    
313
        TaxonNode tnLapsana = taxonNodeService.find(TN_LAPSANA_UUID);
314
        Assert.assertNotNull(tnLapsana);
315
        dataSet.addTaxonSubtree(tnLapsana);
316

    
317
        @SuppressWarnings("unchecked")
318
        TermTree<Feature> descriptiveSystem = termTreeService.find(uuidFeatureTree);
319
        dataSet.setDescriptiveSystem(descriptiveSystem);
320
        commitAndStartNewTransaction();
321

    
322

    
323

    
324
        Taxon taxLapsanaCommunisAlpina = (Taxon)taxonService.find(T_LAPSANA_COMMUNIS_ALPINA_UUID);
325
        TaxonDescription aggrDescLapsanaCommunisAlpina = testTaxonDescriptions(taxLapsanaCommunisAlpina, 1);
326
        List<StateData> sdAlpinaLeafColor = testCategoricalData(uuidFeatureLeafColor, 1, aggrDescLapsanaCommunisAlpina, false);
327
        testState(sdAlpinaLeafColor, uuidLeafColorBlue, 0);
328
        testState(sdAlpinaLeafColor, uuidLeafColorYellow, 0);
329
    }
330

    
331

    
332
    private void testStatusOk(UpdateResult result) {
333
        if (result.getStatus() != UpdateResult.Status.OK){
334
            Assert.fail("Aggregation should have status OK but was " + result.toString());
335
            for (Exception ex : result.getExceptions()){
336
                ex.printStackTrace();
337
            }
338
        }
339
    }
340

    
341
    private void addLiterature(DescriptiveDataSet dataSet) {
342

    
343
        //literature description
344
        Taxon taxon = (Taxon)taxonService.find(T_LAPSANA_COMMUNIS_ALPINA_UUID);
345
        TaxonDescription literatureDescription = TaxonDescription.NewInstance(taxon);
346
        literatureDescription.addType(DescriptionType.SECONDARY_DATA);
347
        addQuantitativeData(literatureDescription, uuidFeatureLeafLength, new BigDecimal("4.5"), new BigDecimal("6.5"));
348
        addCategoricalData(literatureDescription, uuidFeatureLeafColor, uuidLeafColorBlue);
349
        dataSet.addDescription(literatureDescription);
350
    }
351

    
352

    
353

    
354

    
355

    
356
    private DescriptiveDataSet createTestDataset() {
357
        DescriptiveDataSet dataSet = DescriptiveDataSet.NewInstance();
358
        dataSet.setLabel("Test dataset");
359
        datasetService.save(dataSet);
360

    
361
        SpecimenDescription specDescAlpina1 = createSpecimenDescription(dataSet, T_LAPSANA_COMMUNIS_ALPINA_UUID, "alpina specimen1");
362
        addCategoricalData(specDescAlpina1, uuidFeatureLeafPA, State.uuidPresent);
363
        addQuantitativeData(specDescAlpina1, uuidFeatureLeafLength, StatisticalMeasure.EXACT_VALUE(), new BigDecimal("5.0"));
364
        addCategoricalData(specDescAlpina1, uuidFeatureLeafColor, uuidLeafColorBlue);
365

    
366
        SpecimenDescription specDescAlpina2 = createSpecimenDescription(dataSet, T_LAPSANA_COMMUNIS_ALPINA_UUID, "alpina specimen2");
367
        addCategoricalData(specDescAlpina2, uuidFeatureLeafPA, State.uuidPresent);
368
        addQuantitativeData(specDescAlpina2, uuidFeatureLeafLength, StatisticalMeasure.EXACT_VALUE(), new BigDecimal("7.0"));
369
        addCategoricalData(specDescAlpina2, uuidFeatureLeafColor, uuidLeafColorBlue);
370

    
371
        SpecimenDescription specDescAlpina3 = createSpecimenDescription(dataSet, T_LAPSANA_COMMUNIS_ALPINA_UUID, "alpina specimen3");
372
        addCategoricalData(specDescAlpina3, uuidFeatureLeafPA, State.uuidPresent);
373
        addQuantitativeData(specDescAlpina3, uuidFeatureLeafLength, StatisticalMeasure.EXACT_VALUE(), new BigDecimal("8.0"));
374

    
375
        SpecimenDescription specDescAdenophora = createSpecimenDescription(dataSet, T_LAPSANA_COMMUNIS_ADENOPHORA_UUID, "adenophora specimen");
376
        addCategoricalData(specDescAdenophora, uuidFeatureLeafPA, State.uuidPresent);
377
        addQuantitativeData(specDescAdenophora, uuidFeatureLeafLength, StatisticalMeasure.EXACT_VALUE(), new BigDecimal("10.0"));
378
        addCategoricalData(specDescAdenophora, uuidFeatureLeafColor, uuidLeafColorYellow);
379

    
380
        TaxonNode tnLapsana = taxonNodeService.find(TN_LAPSANA_UUID);
381
        Assert.assertNotNull(tnLapsana);
382
        dataSet.addTaxonSubtree(tnLapsana);
383

    
384
        @SuppressWarnings("unchecked")
385
        TermTree<Feature> descriptiveSystem = termTreeService.find(uuidFeatureTree);
386
        dataSet.setDescriptiveSystem(descriptiveSystem);
387

    
388
        addLiterature(dataSet);
389
        return dataSet;
390
    }
391

    
392
    private TaxonDescription testTaxonDescriptions(Taxon taxon, int elementSize){
393
        List<TaxonDescription> taxonDescriptions = taxon.getDescriptions().stream()
394
                .filter(desc->desc.getTypes().contains(DescriptionType.AGGREGATED_STRUC_DESC))
395
                .collect(Collectors.toList());
396

    
397
        Assert.assertEquals(1, taxonDescriptions.size());
398
        TaxonDescription aggrDesc = taxonDescriptions.iterator().next();
399
        Set<DescriptionElementBase> elements = aggrDesc.getElements();
400
        Assert.assertEquals(elementSize, elements.size());
401
        return aggrDesc;
402
    }
403

    
404
    private void testQuantitativeData(UUID featureUuid, BigDecimal sampleSize, BigDecimal min,
405
            BigDecimal max, BigDecimal avg, TaxonDescription aggrDesc) {
406
        List<QuantitativeData> quantitativeDatas = aggrDesc.getElements().stream()
407
                .filter(element->element.getFeature().getUuid().equals(featureUuid))
408
                .map(catData->CdmBase.deproxy(catData, QuantitativeData.class))
409
                .collect(Collectors.toList());
410
        Assert.assertEquals(1, quantitativeDatas.size());
411
        QuantitativeData leafLength = quantitativeDatas.iterator().next();
412
        Assert.assertEquals(sampleSize, leafLength.getSampleSize());
413
        Assert.assertEquals(min, leafLength.getMin());
414
        Assert.assertEquals(max, leafLength.getMax());
415
        Assert.assertEquals(avg, leafLength.getAverage());
416
    }
417

    
418

    
419
    private List<StateData> testCategoricalData(UUID featureUuid, int stateDataCount, TaxonDescription taxonDescription, boolean withAddedData) {
420
        List<CategoricalData> categoricalDatas = taxonDescription.getElements().stream()
421
                .filter(element->element.getFeature().getUuid().equals(featureUuid))
422
                .map(catData->CdmBase.deproxy(catData, CategoricalData.class))
423
                .collect(Collectors.toList());
424
        int nCD = withAddedData ? 2 : 1;
425
        Assert.assertEquals(nCD, categoricalDatas.size());
426
        CategoricalData categoricalData;
427
        if (withAddedData){
428
            categoricalData = categoricalDatas.stream().filter(cd->cd.getStateData().get(0).getCount() != null ).findFirst().get();
429
        }else{
430
            categoricalData = categoricalDatas.iterator().next(); // categoricalDatas.stream().filter(cd->cd.getStateData().size() != 1).collect(Collectors.toList());
431
        }
432
        List<StateData> stateDatas = categoricalData.getStateData();
433
        Assert.assertEquals(stateDataCount, stateDatas.size());
434
        return stateDatas;
435
    }
436

    
437
    private void testState(List<StateData> stateDatas, UUID stateUuid, Integer stateDataCount){
438
        List<StateData> filteredStateDatas = stateDatas.stream()
439
                .filter(stateData->stateData.getState()!=null && stateData.getState().getUuid().equals(stateUuid))
440
                .collect(Collectors.toList());
441
        if(stateDataCount==0){
442
            // non-existence test
443
            Assert.assertEquals(0, filteredStateDatas.size());
444
            return;
445
        }
446
        Assert.assertEquals(1, filteredStateDatas.size());
447
        StateData stateData = filteredStateDatas.iterator().next();
448
        Assert.assertEquals(stateDataCount, stateData.getCount());
449
        Assert.assertEquals(stateUuid, stateData.getState().getUuid());
450
    }
451

    
452
    private void addQuantitativeData(DescriptionBase<?> desc, UUID uuidFeature, StatisticalMeasure type, BigDecimal value) {
453
        Feature feature = (Feature)termService.find(uuidFeature);
454
        QuantitativeData qd = QuantitativeData.NewInstance(feature);
455
        StatisticalMeasurementValue smv = StatisticalMeasurementValue.NewInstance(type, value);
456
        qd.addStatisticalValue(smv);
457
        desc.addElement(qd);
458
    }
459

    
460
    private void addQuantitativeData(DescriptionBase<?> desc, UUID uuidFeature, BigDecimal min, BigDecimal max) {
461
        Feature feature = (Feature)termService.find(uuidFeature);
462
        QuantitativeData qd = QuantitativeData.NewInstance(feature);
463
        StatisticalMeasurementValue smv = StatisticalMeasurementValue.NewInstance(StatisticalMeasure.MIN(), min);
464
        qd.addStatisticalValue(smv);
465
        smv = StatisticalMeasurementValue.NewInstance(StatisticalMeasure.MAX(), max);
466
        qd.addStatisticalValue(smv);
467
        desc.addElement(qd);
468
    }
469

    
470
    private void addCategoricalData(DescriptionBase<?> desc, UUID featureUuid, UUID stateUUID) {
471
        Feature feature = (Feature)termService.find(featureUuid);
472
        State state = (State)termService.find(stateUUID);
473
        CategoricalData cd = CategoricalData.NewInstance(state, feature);
474
        desc.addElement(cd);
475
    }
476

    
477
    private SpecimenDescription createSpecimenDescription(DescriptiveDataSet dataSet, UUID taxonUuid, String specLabel ) {
478
        Taxon taxon = (Taxon)taxonService.find(taxonUuid);
479
        TaxonDescription taxonDescription = TaxonDescription.NewInstance(taxon);
480
        DerivedUnit specimen = DerivedUnit.NewPreservedSpecimenInstance();
481
        specimen.setTitleCache(specLabel, true);
482
        IndividualsAssociation individualsAssociation = IndividualsAssociation.NewInstance(specimen);
483
        // TODO this has to be discussed; currently the description with the InidividualsAssociation is
484
        // needed in the dataset for performance reasons
485
        taxonDescription.addElement(individualsAssociation);
486
        dataSet.addDescription(taxonDescription);
487
        SpecimenDescription specDesc = SpecimenDescription.NewInstance(specimen);
488

    
489
        dataSet.addDescription(specDesc);
490
        return specDesc;
491
    }
492

    
493
    private Feature createFeature(UUID uuid, String label, boolean isQuantitative) {
494
        Feature feature = Feature.NewInstance("", label, null);
495
        feature.setUuid(uuid);
496
        feature.setSupportsQuantitativeData(isQuantitative);
497
        feature.setSupportsCategoricalData(!isQuantitative);
498
        feature.setSupportsTextData(false);
499
        termService.save(feature);
500
        return feature;
501
    }
502

    
503
    private State createState(String label, UUID uuid) {
504
        State state = State.NewInstance("", label, "");
505
        state.getTitleCache();  //for better debugging
506
        state.setUuid(uuid);
507
        termService.save(state);
508
        return state;
509
    }
510

    
511
    private void createDefaultFeatureTree() {
512
        //feature tree
513
        //leaf p/a
514
        //  leaf length
515
        //  leaf color
516
        TermTree<Feature> featureTree = TermTree.NewFeatureInstance();
517
        featureTree.setUuid(uuidFeatureTree);
518
        Feature featureLeafPA = createFeature(uuidFeatureLeafPA, "LeafPA", false);
519
        TermNode<Feature> leafPANode = featureTree.getRoot().addChild(featureLeafPA);
520
        Feature featureLeafLength = createFeature(uuidFeatureLeafLength, "LeafLength", true);
521
        leafPANode.addChild(featureLeafLength);
522
        Feature featureLeafColor = createFeature(uuidFeatureLeafColor, "LeafColor", false);
523
        leafPANode.addChild(featureLeafColor);
524
        State yellow = createState("Yellow", uuidLeafColorYellow);
525
        State blue = createState("Blue", uuidLeafColorBlue);
526
        TermVocabulary<State> stateVoc = TermVocabulary.NewInstance(TermType.State, State.class, "", "Colors", null, null);
527
        stateVoc.addTerm(yellow);
528
        stateVoc.addTerm(blue);
529
        featureLeafColor.addSupportedCategoricalEnumeration(stateVoc);
530
        vocabularyService.save(stateVoc);
531
    }
532

    
533

    
534
    @Override
535
    public void createTestDataSet() throws FileNotFoundException {
536

    
537
        // --- References --- //
538
        Reference sec = ReferenceFactory.newDatabase();
539
        sec.setTitleCache("Test", true);
540
        Reference nomRef = ReferenceFactory.newBook();
541
        sec.setTitleCache("Sp.Pl.", true);
542

    
543
        referenceService.save(sec);
544
        referenceService.save(nomRef);
545

    
546

    
547
        // --- Taxa --- //
548
        //  Lapsana
549
        //        L. communis
550
        //            L. communis subsp. communis
551
        //            L. communis subsp. adenophora
552
        //            L. communis subsp. alpina
553
        //  Sonchella
554
        //        S. dentata
555
        //        S. stenoma
556
        IBotanicalName n_lapsana = TaxonNameFactory.NewBotanicalInstance(Rank.GENUS());
557
        n_lapsana.setTitleCache("Lapsana", true);
558
        Taxon t_lapsana = Taxon.NewInstance(n_lapsana, sec);
559
        t_lapsana.setUuid(T_LAPSANA_UUID);
560
        taxonService.saveOrUpdate(t_lapsana);
561

    
562
        IBotanicalName n_lapsana_communis = TaxonNameFactory.NewBotanicalInstance(Rank.SPECIES());
563
        n_lapsana_communis.setTitleCache("L. communis", true);
564
        Taxon t_lapsana_communis = Taxon.NewInstance(n_lapsana_communis, sec);
565
        t_lapsana_communis.setUuid(T_LAPSANA_COMMUNIS_UUID);
566
        taxonService.saveOrUpdate(t_lapsana_communis);
567

    
568
        IBotanicalName n_lapsana_communis_communis = TaxonNameFactory.NewBotanicalInstance(Rank.SUBSPECIES());
569
        n_lapsana_communis_communis.setTitleCache("L. communis subsp. communis", true);
570
        Taxon t_lapsana_communis_communis = Taxon.NewInstance(n_lapsana_communis_communis, sec);
571
        t_lapsana_communis_communis.setUuid(T_LAPSANA_COMMUNIS_COMMUNIS_UUID);
572
        taxonService.saveOrUpdate(t_lapsana_communis_communis);
573

    
574
        IBotanicalName n_lapsana_communis_adenophora = TaxonNameFactory.NewBotanicalInstance(Rank.SUBSPECIES());
575
        n_lapsana_communis_adenophora.setTitleCache("L. communis subsp. adenophora", true);
576
        Taxon t_lapsana_communis_adenophora = Taxon.NewInstance(n_lapsana_communis_adenophora, sec);
577
        t_lapsana_communis_adenophora.setUuid(T_LAPSANA_COMMUNIS_ADENOPHORA_UUID);
578
        taxonService.saveOrUpdate(t_lapsana_communis_adenophora);
579

    
580
        IBotanicalName n_lapsana_communis_alpina = TaxonNameFactory.NewBotanicalInstance(Rank.SUBSPECIES());
581
        n_lapsana_communis_alpina.setTitleCache("L. communis subsp. alpina", true);
582
        Taxon t_lapsana_communis_alpina = Taxon.NewInstance(n_lapsana_communis_alpina, sec);
583
        t_lapsana_communis_alpina.setUuid(T_LAPSANA_COMMUNIS_ALPINA_UUID);
584
        taxonService.saveOrUpdate(t_lapsana_communis_alpina);
585

    
586
        // --- Classification --- //
587
        Classification classification = Classification.NewInstance("TestClassification");
588
        classification.setUuid(CLASSIFICATION_UUID);
589
        classificationService.save(classification);
590
        TaxonNode node_lapsana = classification.addChildTaxon(t_lapsana, sec, null);
591
        node_lapsana.setUuid(TN_LAPSANA_UUID);
592
        TaxonNode node_lapsana_communis = node_lapsana.addChildTaxon(t_lapsana_communis, sec, null);
593
        node_lapsana_communis.addChildTaxon(t_lapsana_communis_communis, sec, null);
594
        node_lapsana_communis.addChildTaxon(t_lapsana_communis_adenophora, sec, null);
595
        node_lapsana_communis.addChildTaxon(t_lapsana_communis_alpina, sec, null);
596
        classificationService.saveOrUpdate(classification);
597

    
598
        commitAndStartNewTransaction(null);
599

    
600
        writeDbUnitDataSetFile(new String[] {
601
                "TAXONBASE", "TAXONNAME","CLASSIFICATION",  "TAXONNODE","HOMOTYPICALGROUP",
602
                "REFERENCE", "AGENTBASE",
603
                "DESCRIPTIONELEMENTBASE", "DESCRIPTIONBASE",
604
                "LANGUAGESTRING",
605
                "HIBERNATE_SEQUENCES"
606
         });
607
    }
608

    
609
}
(1-1/3)