Project

General

Profile

Revision 44320911

ID44320911b950cfcd6ef9e37cf9eb3ea09eccdaae
Parent a81e3c1b
Child 4f90ce94

Added by Andreas Müller over 1 year ago

ref #8891 Add CategoricalData and QuantitativeData to DwCA export

View differences:

cdmlib-io/src/main/java/eu/etaxonomy/cdm/io/dwca/out/DwcaDescriptionExport.java
19 19

  
20 20
import org.apache.log4j.Logger;
21 21

  
22
import eu.etaxonomy.cdm.format.description.CategoricalDataFormatter;
23
import eu.etaxonomy.cdm.format.description.QuantitativeDataFormatter;
22 24
import eu.etaxonomy.cdm.model.common.CdmBase;
23 25
import eu.etaxonomy.cdm.model.common.Language;
24 26
import eu.etaxonomy.cdm.model.common.LanguageString;
27
import eu.etaxonomy.cdm.model.description.CategoricalData;
25 28
import eu.etaxonomy.cdm.model.description.DescriptionElementBase;
26 29
import eu.etaxonomy.cdm.model.description.Feature;
30
import eu.etaxonomy.cdm.model.description.QuantitativeData;
31
import eu.etaxonomy.cdm.model.description.StateData;
32
import eu.etaxonomy.cdm.model.description.StatisticalMeasurementValue;
27 33
import eu.etaxonomy.cdm.model.description.TaxonDescription;
28 34
import eu.etaxonomy.cdm.model.description.TextData;
29 35
import eu.etaxonomy.cdm.model.taxon.Taxon;
......
48 54
	 * Constructor
49 55
	 */
50 56
	public DwcaDescriptionExport(DwcaTaxExportState state) {
51
		super();
52 57
		this.ioName = this.getClass().getSimpleName();
53 58
	    metaRecord = new DwcaMetaDataRecord(! IS_CORE, fileName, ROW_TYPE);
54 59
	    state.addMetaRecord(metaRecord);
......
58 63
	@Override
59 64
	protected void doInvoke(DwcaTaxExportState state){}
60 65

  
61

  
62
    /**
63
     * @param state
64
     * @param node
65
     * @throws IOException
66
     * @throws FileNotFoundException
67
     * @throws UnsupportedEncodingException
68
     */
69 66
    @Override
70 67
    protected void handleTaxonNode(DwcaTaxExportState state, TaxonNode node)
71 68
            throws IOException, FileNotFoundException, UnsupportedEncodingException {
72
        DwcaTaxExportConfigurator config = state.getConfig();
73 69

  
70
        DwcaTaxExportConfigurator config = state.getConfig();
74 71
        try {
75 72
            Taxon taxon = CdmBase.deproxy(node.getTaxon());
76 73
            Set<TaxonDescription> descriptions = node.getTaxon().getDescriptions();
77 74
            for (TaxonDescription description : descriptions){
78 75
            	for (DescriptionElementBase el : description.getElements()){
79
            		if (el.isInstanceOf(TextData.class) ){
80
            			Feature feature = el.getFeature();
81
            			if (feature != null &&
82
            					! feature.equals(Feature.IMAGE()) &&
83
            					! config.getFeatureExclusions().contains(feature.getUuid()) &&
84
            					! state.recordExists(file,el)){
85
            				DwcaDescriptionRecord record = new DwcaDescriptionRecord(metaRecord, config);
86
            				TextData textData = CdmBase.deproxy(el,TextData.class);
87
            				handleDescription(state, record, textData, taxon, config);
88
            				PrintWriter writer = createPrintWriter(state, DwcaTaxExportFile.DESCRIPTION);
89
            	            record.write(state, writer);
90
            				state.addExistingRecord(file, textData);
91
            			}
92
            		}
76
            	    el = CdmBase.deproxy(el);  //just in case
77
            	    Feature feature = el.getFeature();
78
            	    //TODO there is a lot of redundancy here as it had been implemented as a quick fix
79
            	    //needs to be cleaned up
80
            	    if (feature != null &&
81
                            ! feature.equals(Feature.IMAGE()) &&
82
                            ! config.getFeatureExclusions().contains(feature.getUuid()) &&
83
                            ! state.recordExists(file,el)){
84
            	        if (el.isInstanceOf(TextData.class) ){
85
            	            DwcaDescriptionRecord record = new DwcaDescriptionRecord(metaRecord, config);
86
        	                TextData textData = CdmBase.deproxy(el,TextData.class);
87
        	                handleTextData(state, record, textData, taxon, config);
88
        	                PrintWriter writer = createPrintWriter(state, DwcaTaxExportFile.DESCRIPTION);
89
        	                record.write(state, writer);
90
        	                state.addExistingRecord(file, textData);
91
            	        }else if (el.isInstanceOf(CategoricalData.class)){
92
                            DwcaDescriptionRecord record = new DwcaDescriptionRecord(metaRecord, config);
93
                            CategoricalData cd = CdmBase.deproxy(el,CategoricalData.class);
94
                            handleCategoricalData(state, record, cd, taxon, config);
95
                            PrintWriter writer = createPrintWriter(state, DwcaTaxExportFile.DESCRIPTION);
96
                            record.write(state, writer);
97
                            state.addExistingRecord(file, cd);
98
            	        }else if (el.isInstanceOf(QuantitativeData.class)){
99
                            DwcaDescriptionRecord record = new DwcaDescriptionRecord(metaRecord, config);
100
                            QuantitativeData qd = CdmBase.deproxy(el, QuantitativeData.class);
101
                            handleQuantitativeData(state, record, qd, taxon, config);
102
                            PrintWriter writer = createPrintWriter(state, DwcaTaxExportFile.DESCRIPTION);
103
                            record.write(state, writer);
104
                            state.addExistingRecord(file, qd);
105
            	        }
106
            	    }
93 107
            	}
94 108
            }
95 109
        } catch (Exception e) {
......
100 114
        }
101 115
    }
102 116

  
117
    private void handleCategoricalData(DwcaTaxExportState state, DwcaDescriptionRecord record,
118
            CategoricalData catData, Taxon taxon, DwcaTaxExportConfigurator config){
119

  
120
        record.setId(taxon.getId());
121
        record.setUuid(taxon.getUuid());
122

  
123
        if (catData.getFeature() == null){
124
            String message = "No feature available for text data ("+catData.getId()+"). Feature is required field. Taxon: " + this.getTaxonLogString(taxon);
125
            state.getResult().addWarning(message);
126
        }
127
        record.setType(catData.getFeature());
128

  
129
        List<StateData> stateDatas = catData.getStateData();
130
        if (stateDatas.isEmpty()){
131
            String message = "No state data available for categorical data ("+catData.getId()+"). Text is required field. Taxon: " + this.getTaxonLogString(taxon);
132
            state.getResult().addWarning(message);
133
        }else{
134
            List<Language> preferredLanguages = new ArrayList<>();
135
            preferredLanguages.add(Language.DEFAULT());
136
            CategoricalDataFormatter formatter = new CategoricalDataFormatter(catData, null);
137
            formatter.format(catData);
138
            record.setDescription(formatter.format(catData));
139
            //TODO
140
//            record.setLanguage(languageText.getLanguage());
141
        }
142

  
143
        //sources
144
        record.setSource(getSources(catData, config));
145

  
146
        //TODO missing , relationship to credits?
147
        record.setCreator(null);
148
        //TODO missing, relationship to credits?
149
        record.setContributor(null);
150
        //TODO missing
151
        record.setAudience(null);
152
        record.setLicense(catData.getInDescription().getRights());
153
        //TODO missing
154
        record.setRightsHolder(null);
155
    }
156

  
103 157

  
104
	private void handleDescription(DwcaTaxExportState state, DwcaDescriptionRecord record, TextData textData, Taxon taxon, DwcaTaxExportConfigurator config) {
105
		record.setId(taxon.getId());
158
    private void handleQuantitativeData(DwcaTaxExportState state, DwcaDescriptionRecord record,
159
            QuantitativeData quantData, Taxon taxon, DwcaTaxExportConfigurator config){
160

  
161
        record.setId(taxon.getId());
162
        record.setUuid(taxon.getUuid());
163

  
164
        if (quantData.getFeature() == null){
165
            String message = "No feature available for text data ("+quantData.getId()+"). Feature is required field. Taxon: " + this.getTaxonLogString(taxon);
166
            state.getResult().addWarning(message);
167
        }
168
        record.setType(quantData.getFeature());
169

  
170
        Set<StatisticalMeasurementValue> values = quantData.getStatisticalValues();
171
        if (values.isEmpty()){
172
            String message = "No values available for quantitative data ("+quantData.getId()+"). Values are required. Taxon: " + this.getTaxonLogString(taxon);
173
            state.getResult().addWarning(message);
174
        }else{
175
            List<Language> preferredLanguages = new ArrayList<>();
176
            preferredLanguages.add(Language.DEFAULT());
177
            QuantitativeDataFormatter formatter = new QuantitativeDataFormatter(quantData, null);
178
            formatter.format(quantData);
179
            record.setDescription(formatter.format(quantData));
180
            //TODO
181
//            record.setLanguage(languageText.getLanguage());
182
        }
183

  
184
        handleDescriptionElement(record, quantData, config);
185
    }
186

  
187
	private void handleTextData(DwcaTaxExportState state, DwcaDescriptionRecord record,
188
	        TextData textData, Taxon taxon, DwcaTaxExportConfigurator config) {
189

  
190
	    record.setId(taxon.getId());
106 191
		record.setUuid(taxon.getUuid());
107 192

  
108 193
		//TODO make this part of the Configuration
109 194
		//TODO question: multiple entries for each language??
110 195
		List<Language> preferredLanguages = new ArrayList<>();
111 196
		preferredLanguages.add(Language.DEFAULT());
112
		LanguageString languageText = textData.getPreferredLanguageString(preferredLanguages);
113

  
114 197

  
115 198
		if (textData.getFeature() == null){
116 199
			String message = "No feature available for text data ("+textData.getId()+"). Feature is required field. Taxon: " + this.getTaxonLogString(taxon);
117
	         state.getResult().addWarning(message);
200
	        state.getResult().addWarning(message);
118 201
		}
119 202
		record.setType(textData.getFeature());
120 203

  
204
		LanguageString languageText = textData.getPreferredLanguageString(preferredLanguages);
121 205
		if (languageText == null){
122 206
			String message = "No text in default language available for text data ("+textData.getId()+"). Text is required field. Taxon: " + this.getTaxonLogString(taxon);
123 207
	        state.getResult().addWarning(message);
......
126 210
			record.setLanguage(languageText.getLanguage());
127 211
		}
128 212

  
129
		//sources
130
		record.setSource(getSources(textData, config));
131

  
132
		//TODO missing , relationship to credits?
133
		record.setCreator(null);
134
		//TODO missing, relationship to credits?
135
		record.setContributor(null);
136
		//TODO missing
137
		record.setAudience(null);
138
		record.setLicense(textData.getInDescription().getRights());
139
		//TODO missing
140
		record.setRightsHolder(null);
141

  
213
		handleDescriptionElement(record, textData, config);
142 214
	}
143 215

  
216
    private void handleDescriptionElement(DwcaDescriptionRecord record,
217
            DescriptionElementBase descriptionElement,
218
            DwcaTaxExportConfigurator config) {
219

  
220
        //sources
221
        record.setSource(getSources(descriptionElement, config));
222

  
223
        //TODO missing , relationship to credits?
224
        record.setCreator(null);
225
        //TODO missing, relationship to credits?
226
        record.setContributor(null);
227
        //TODO missing
228
        record.setAudience(null);
229
        record.setLicense(descriptionElement.getInDescription().getRights());
230
        //TODO missing
231
        record.setRightsHolder(null);
232
    }
233

  
144 234
	@Override
145 235
	protected boolean doCheck(DwcaTaxExportState state) {
146 236
		boolean result = true;
cdmlib-io/src/test/java/eu/etaxonomy/cdm/io/dwca/out/DwcaExportTest.java
17 17

  
18 18
import org.apache.log4j.Logger;
19 19
import org.junit.Assert;
20
import org.junit.Before;
20 21
import org.junit.Test;
21 22
import org.unitils.dbunit.annotation.DataSet;
22 23
import org.unitils.spring.annotation.SpringBeanByName;
......
24 25

  
25 26
import eu.etaxonomy.cdm.api.service.IClassificationService;
26 27
import eu.etaxonomy.cdm.api.service.ITaxonNodeService;
28
import eu.etaxonomy.cdm.api.service.ITermService;
27 29
import eu.etaxonomy.cdm.filter.TaxonNodeFilter;
28 30
import eu.etaxonomy.cdm.io.common.CdmApplicationAwareDefaultExport;
29 31
import eu.etaxonomy.cdm.io.common.ExportDataWrapper;
30 32
import eu.etaxonomy.cdm.io.common.ExportResult;
31 33
import eu.etaxonomy.cdm.io.common.IExportConfigurator.TARGET;
32 34
import eu.etaxonomy.cdm.model.common.CdmBase;
35
import eu.etaxonomy.cdm.model.common.Language;
36
import eu.etaxonomy.cdm.model.description.CategoricalData;
33 37
import eu.etaxonomy.cdm.model.description.Distribution;
38
import eu.etaxonomy.cdm.model.description.Feature;
34 39
import eu.etaxonomy.cdm.model.description.PresenceAbsenceTerm;
40
import eu.etaxonomy.cdm.model.description.QuantitativeData;
41
import eu.etaxonomy.cdm.model.description.State;
35 42
import eu.etaxonomy.cdm.model.description.TaxonDescription;
43
import eu.etaxonomy.cdm.model.description.TextData;
36 44
import eu.etaxonomy.cdm.model.location.NamedArea;
37 45
import eu.etaxonomy.cdm.model.name.NomenclaturalCode;
38 46
import eu.etaxonomy.cdm.model.name.Rank;
......
47 55
import eu.etaxonomy.cdm.test.unitils.CleanSweepInsertLoadStrategy;
48 56

  
49 57
/**
58
 * Test for Darwin Core Archive (DwCA) export.
59
 *
50 60
 * @author a.mueller
51 61
 * @since 25.06.2017
52
 *
53 62
 */
54 63
public class DwcaExportTest  extends CdmTransactionalIntegrationTest{
55 64

  
......
59 68
    private static final UUID UUID_SUBSPEC_NODE = UUID.fromString("f8c9933a-fe3a-42ce-8a92-000e27bfdfac");
60 69
    private static final String UUID_UNPUBLISHED_TAXON = "e5cdc392-4e0b-49ad-84e9-8c4b22d1827c";
61 70

  
62

  
63 71
    @SpringBeanByName
64 72
    private CdmApplicationAwareDefaultExport<DwcaTaxExportConfigurator> defaultExport;
65 73

  
......
69 77
    @SpringBeanByType
70 78
    private ITaxonNodeService taxonNodeService;
71 79

  
80
    @SpringBeanByType
81
    private ITermService termService;
82

  
83
    private static State state1;
84

  
85
    @Before
86
    public void setUp(){
87

  
88
        if (state1 == null){
89
            state1 = State.NewInstance("state1 text", "state1", "st.1");
90
            termService.save(state1);
91
        }
92
    }
93

  
72 94

  
73 95
    @Test
74 96
    @DataSet(loadStrategy=CleanSweepInsertLoadStrategy.class, value="/eu/etaxonomy/cdm/database/ClearDBDataSet.xml")
......
251 273
        byte[] distribution = data.get(DwcaTaxExportFile.DISTRIBUTION.getTableName());
252 274
        Assert.assertNotNull("Distribution must not be null", distribution);
253 275
        String distributionStr = new String(distribution);
254
        expected =  "\"9182e136-f2e2-4f9a-9010-3f35908fb5e0\",\"c204c529-d8d2-458f-b939-96f0ebd2cbe8\",\"Africa\",,,\"present\",,\"uncertain\",,,,,,";
276
        expected = "\"9182e136-f2e2-4f9a-9010-3f35908fb5e0\",\"c204c529-d8d2-458f-b939-96f0ebd2cbe8\",\"Africa\",,,\"present\",,\"uncertain\",,,,,,";
255 277
        Assert.assertTrue(distributionStr.contains(expected));
256 278

  
279
        //description
280
        byte[] description = data.get(DwcaTaxExportFile.DESCRIPTION.getTableName());
281
        Assert.assertNotNull("Description must not be null", distribution);
282
        String descriptionStr = new String(description);
283
        System.out.println(descriptionStr);
284

  
285
        //   quantitative data
286
        expected = "\"9182e136-f2e2-4f9a-9010-3f35908fb5e0\",\"0.1-1.3 [n=2.0]\",\"Chromosome Numbers\"";
287
        Assert.assertTrue(descriptionStr.contains(expected));
288
        //   textdata
289
        expected = "\"9182e136-f2e2-4f9a-9010-3f35908fb5e0\",\"My Description\",\"Description\",,\"eng\",,,,,";
290
        Assert.assertTrue(descriptionStr.contains(expected));
291
        //   categorical data
292
        expected = "\"9182e136-f2e2-4f9a-9010-3f35908fb5e0\",\"state1\",\"Ecology\"";
293
        Assert.assertTrue(descriptionStr.contains(expected));
257 294
    }
258 295

  
259 296
    @Test
......
318 355

  
319 356
    }
320 357

  
321
    /**
322
     * {@inheritDoc}
323
     */
324
    public void createFullTestDataSet() {
358
    private void createFullTestDataSet() {
325 359
        Set<TaxonNode> nodesToSave = new HashSet<>();
326 360
        Reference sec1 = ReferenceFactory.newGeneric();
327 361
        setUuid(sec1, "4b6acca1-959b-4790-b76e-e474a0882990");
......
336 370
        TaxonName familyName = parser.parseReferencedName("Family L., Sp. Pl. 3: 22. 1752",
337 371
                NomenclaturalCode.ICNAFP, Rank.FAMILY());
338 372
        setUuid(familyName,"e983cc5e-4c77-4c80-8cb0-73d43df31ef7");
339
        setUuid((Reference)familyName.getNomenclaturalReference(), "b0dd7f4a-0c7f-4372-bc5d-3b676363bc63");
373
        setUuid(familyName.getNomenclaturalReference(), "b0dd7f4a-0c7f-4372-bc5d-3b676363bc63");
340 374
        Taxon family = Taxon.NewInstance(familyName, sec1);
341 375
        setUuid(family,"3162e136-f2e2-4f9a-9010-3f35908fbae1");
342 376
        TaxonNode node1 = classification.addChildTaxon(family, sec1, "22");
......
347 381
        TaxonName genusName = parser.parseReferencedName("Genus Humb., The book of botany 3: 22. 1804",
348 382
                NomenclaturalCode.ICNAFP, Rank.GENUS());
349 383
        setUuid(genusName,"5e83cc5e-4c77-4d80-8cb0-73d63df35ee3");
350
        setUuid((Reference)genusName.getNomenclaturalReference(), "5ed27f4a-6c7f-4372-bc5d-3b67636abc52");
384
        setUuid(genusName.getNomenclaturalReference(), "5ed27f4a-6c7f-4372-bc5d-3b67636abc52");
351 385
        Taxon genus = Taxon.NewInstance(genusName, sec1);
352 386
        setUuid(genus,"3f52e136-f2e1-4f9a-9010-2f35908fbd39");
353 387

  
......
359 393
        TaxonName speciesName = parser.parseReferencedName("Genus species Mill., The book of botany 3: 22. 1804",
360 394
                NomenclaturalCode.ICNAFP, Rank.SPECIES());
361 395
        setUuid(speciesName,"f983cc5e-4c77-4c80-8cb0-73d43df31ee9");
362
        setUuid((Reference)speciesName.getNomenclaturalReference(), "a0dd7f4a-0c7f-4372-bc5d-3b676363bc0e");
396
        setUuid(speciesName.getNomenclaturalReference(), "a0dd7f4a-0c7f-4372-bc5d-3b676363bc0e");
363 397
        Taxon species = Taxon.NewInstance(speciesName, sec1);
364 398
        setUuid(species,"9182e136-f2e2-4f9a-9010-3f35908fb5e0");
365 399

  
......
371 405
        TaxonName subspeciesName = parser.parseReferencedName("Genus species subsp. subspec Mill., The book of botany 3: 22. 1804",
372 406
                NomenclaturalCode.ICNAFP, Rank.SUBSPECIES());
373 407
        setUuid(subspeciesName,"3483cc5e-4c77-4c80-8cb0-73d43df31ee3");
374
        setUuid((Reference)subspeciesName.getNomenclaturalReference(), "b8dd7f4a-0c7f-4372-bc5d-3b676363bc0f");
408
        setUuid(subspeciesName.getNomenclaturalReference(), "b8dd7f4a-0c7f-4372-bc5d-3b676363bc0f");
375 409

  
376 410
        Taxon subspecies = Taxon.NewInstance(subspeciesName, sec1);
377 411
        setUuid(subspecies, "b2c86698-500e-4efb-b9ae-6bb6e701d4bc");
......
383 417
        TaxonName unpublishedName = parser.parseReferencedName("Genus species subsp. unpublish Mill., The book of botany 3: 22. 1804",
384 418
                NomenclaturalCode.ICNAFP, Rank.SUBSPECIES());
385 419
        setUuid(unpublishedName,"ebcf6bb6-6da8-46fe-9c22-127aa4cb9549");
386
        setUuid((Reference)unpublishedName.getNomenclaturalReference(), "51725dbd-e4a1-43ea-8363-fe8eb1152a49");
420
        setUuid(unpublishedName.getNomenclaturalReference(), "51725dbd-e4a1-43ea-8363-fe8eb1152a49");
387 421

  
388 422
        Taxon unpublishedSpecies = Taxon.NewInstance(unpublishedName, sec1);
389 423
        unpublishedSpecies.setPublish(false);
......
397 431

  
398 432
        TaxonDescription description = TaxonDescription.NewInstance(species);
399 433

  
434
        //Distribution
400 435
        Distribution distribution = Distribution.NewInstance(NamedArea.AFRICA(), PresenceAbsenceTerm.PRESENT());
401 436
        setUuid(distribution,"674e9e27-9102-4166-8626-8cb871a9a89b");
402 437
        description.addElement(distribution);
403
        commitAndStartNewTransaction(null);
404 438

  
439
        //TextData
440
        TextData textData = TextData.NewInstance(Feature.DESCRIPTION());
441
        textData.putText(Language.DEFAULT(), "My Description");
442
        setUuid(textData,"16a3f63b-c554-4479-ad36-ca9c677fbb19");
443
        description.addElement(textData);
444

  
445
        //CategoricalData
446
        CategoricalData catData = CategoricalData.NewInstance(state1, Feature.ECOLOGY());
447
        setUuid(catData,"84b8bfd3-d982-4b5d-8d0a-fe5d80183ec4");
448
        description.addElement(catData);
449

  
450
        //QuantitativeData
451
        QuantitativeData quantData = QuantitativeData.NewMinMaxInstance(Feature.CHROMOSOME_NUMBER(), 0.1f, 1.3f);
452
        quantData.setSampleSize(2f, null);
453
        setUuid(quantData,"011264eb-d3d4-44be-86f3-e6f69a21f36b");
454
        description.addElement(quantData);
455

  
456
        commitAndStartNewTransaction(null);
405 457

  
406 458
    }
407 459

  
cdmlib-model/src/main/java/eu/etaxonomy/cdm/format/AbstractCdmFormatter.java
52 52
        formatKeyMap.put(FormatKey.COMMA, ",");
53 53
    }
54 54

  
55

  
56
    protected boolean isNotBlank(String str) {
57
        return StringUtils.isNotBlank(str);
58
    }
59

  
60
    protected boolean isBlank(String str) {
61
        return StringUtils.isBlank(str);
62
    }
63

  
55 64
}
cdmlib-model/src/main/java/eu/etaxonomy/cdm/format/CdmFormatterFactory.java
9 9
package eu.etaxonomy.cdm.format;
10 10

  
11 11
import eu.etaxonomy.cdm.format.ICdmFormatter.FormatKey;
12
import eu.etaxonomy.cdm.format.occurrences.DefaultCdmFormatter;
13 12
import eu.etaxonomy.cdm.format.occurrences.DerivedUnitFormatter;
14 13
import eu.etaxonomy.cdm.format.occurrences.FieldUnitFormatter;
15 14
import eu.etaxonomy.cdm.format.occurrences.MediaSpecimenFormatter;
......
45 44
	 */
46 45
	public static ICdmFormatter getFormatter(Object object,
47 46
			FormatKey... formatKeys) {
48
		ICdmFormatter formatter = null;
49 47
		if (object instanceof CdmBase) {
50 48
			CdmBase cdmBase = (CdmBase) object;
51 49
			if (cdmBase.isInstanceOf(Sequence.class)) {
......
64 62
				return new FieldUnitFormatter(object, formatKeys);
65 63
			}
66 64
		}
67
		if (formatter == null) {
68
			formatter = new DefaultCdmFormatter(object, formatKeys);
69
		}
70
		return formatter;
65
		return new DefaultCdmFormatter(object, formatKeys);
71 66
	}
72 67

  
73 68
	/**
cdmlib-model/src/main/java/eu/etaxonomy/cdm/format/description/CategoricalDataFormatter.java
1
/**
2
* Copyright (C) 2020 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.format.description;
10

  
11
import java.util.ArrayList;
12
import java.util.List;
13

  
14
import eu.etaxonomy.cdm.common.CdmUtils;
15
import eu.etaxonomy.cdm.model.common.Language;
16
import eu.etaxonomy.cdm.model.description.CategoricalData;
17
import eu.etaxonomy.cdm.model.description.StateData;
18

  
19
/**
20
 * Formatter for {@link CategoricalData}.
21
 *
22
 * @author a.mueller
23
 * @since 11.03.2020
24
 */
25
public class CategoricalDataFormatter
26
        extends DesciptionElementFormatterBase<CategoricalData>{
27

  
28
    public CategoricalDataFormatter(Object object, FormatKey[] formatKeys) {
29
        super(object, formatKeys, CategoricalData.class);
30
    }
31

  
32
    @Override
33
    public String doFormat(CategoricalData catData) {
34

  
35
        List<StateData> stateDatas = catData.getStateData();
36
         //TODO add as method argument
37
        List<Language> preferredLanguages = new ArrayList<>();
38
        preferredLanguages.add(Language.DEFAULT());
39
        String stateDataText = getStateDatasText(stateDatas, preferredLanguages);
40
        return stateDataText;
41
    }
42

  
43
    private String getStateDatasText(List<StateData> stateDatas, List<Language> preferredLanguages) {
44
        String result = "";
45
        for (StateData stateData : stateDatas){
46
            result = CdmUtils.concat(", ", result, getStateDataText(stateData, preferredLanguages));
47
        }
48
        //TODO add modifier text
49
        return result;
50
    }
51

  
52
    private String getStateDataText(StateData stateData, List<Language> preferredLanguages) {
53
        String result = "";
54
        result += getLabel(stateData.getState(), preferredLanguages);
55
        //TODO modifier
56
        return result;
57
    }
58

  
59

  
60
}
cdmlib-model/src/main/java/eu/etaxonomy/cdm/format/description/DesciptionElementFormatterBase.java
1
/**
2
* Copyright (C) 2020 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.format.description;
10

  
11
import java.util.List;
12

  
13
import eu.etaxonomy.cdm.format.DefaultCdmFormatter;
14
import eu.etaxonomy.cdm.model.common.CdmBase;
15
import eu.etaxonomy.cdm.model.common.ICdmBase;
16
import eu.etaxonomy.cdm.model.common.Language;
17
import eu.etaxonomy.cdm.model.description.DescriptionElementBase;
18
import eu.etaxonomy.cdm.model.term.DefinedTermBase;
19
import eu.etaxonomy.cdm.model.term.Representation;
20

  
21
/**
22
 * Formatter base class for {@link DescriptionElementBase} instances.
23
 *
24
 * @author a.mueller
25
 * @since 12.03.2020
26
 */
27
public abstract class DesciptionElementFormatterBase<T extends DescriptionElementBase>
28
        extends DefaultCdmFormatter{
29

  
30
    protected static final String MISSING_TERM_LABEL = "-no state-"; //TODO
31

  
32
    private Class<T> clazz;
33

  
34
    protected DesciptionElementFormatterBase(Object object, FormatKey[] formatKeys, Class<T> clazz) {
35
        super(object, formatKeys);
36
        this.clazz = clazz;
37
    }
38

  
39
    @Override
40
    public String format(Object object, FormatKey... formatKeys) {
41
        if (formatKeys == null){
42
            return format(object);
43
        }else{
44
            throw new UnsupportedOperationException("Formatting with FormatKey is not yet supported by " + this.getClass().getSimpleName());
45
        }
46
    }
47

  
48
    @Override
49
    public String format(Object object) {
50
        if (! (object instanceof ICdmBase)){
51
            throw new IllegalArgumentException("object is not of type ICdmBase");
52
        }
53
        ICdmBase cdmBase = (ICdmBase)object;
54
        if (!cdmBase.isInstanceOf(clazz)){
55
            throw new IllegalArgumentException("object is not of type " + clazz.getSimpleName());
56
        }
57
        T descEl = CdmBase.deproxy(object, clazz);
58

  
59
        return doFormat(descEl);
60
    }
61

  
62
    protected abstract String doFormat(T descEl);
63

  
64

  
65
    protected String getLabel(DefinedTermBase<?> term, List<Language> preferredLanguages) {
66
        if (term == null){
67
            return MISSING_TERM_LABEL;
68
        }
69
        Representation representation = term.getPreferredRepresentation(preferredLanguages);
70
        if (representation == null){
71
            return term.toString();
72
        }
73
        if (isNotBlank(representation.getLabel())){
74
            return representation.getLabel();
75
        }else if (isNotBlank(representation.getAbbreviatedLabel())){
76
            return representation.getAbbreviatedLabel();
77
        }else if (isNotBlank(representation.getText())){
78
            return representation.getText();
79
        }else{
80
            return representation.toString();
81
        }
82
    }
83

  
84
}
cdmlib-model/src/main/java/eu/etaxonomy/cdm/format/description/QuantitativeDataFormatter.java
1
/**
2
* Copyright (C) 2020 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.format.description;
10

  
11
import eu.etaxonomy.cdm.common.CdmUtils;
12
import eu.etaxonomy.cdm.model.description.MeasurementUnit;
13
import eu.etaxonomy.cdm.model.description.QuantitativeData;
14

  
15
/**
16
 * Formatter for {@link QuantitativeData}.
17
 *
18
 * @author a.mueller
19
 * @since 12.03.2020
20
 */
21
public class QuantitativeDataFormatter
22
            extends DesciptionElementFormatterBase<QuantitativeData> {
23

  
24
    protected static final String MISSING_TERM_LABEL = "-no state-"; //TODO
25

  
26
    public QuantitativeDataFormatter(Object object, FormatKey[] formatKeys) {
27
        super(object, formatKeys, QuantitativeData.class);
28
    }
29

  
30
    @Override
31
    public String doFormat(QuantitativeData quantData) {
32

  
33
        String result = "";
34

  
35
        //values
36
        Float min = quantData.getMin();
37
        Float max = quantData.getMax();
38
        String minMax = "";
39
        if (min != null){
40
            minMax = String.valueOf(min);
41
            if (max!= null && !min.equals(max)){
42
                minMax = CdmUtils.concat("-", minMax, String.valueOf(max));  //TODO which "-"
43
            }
44
        }else if (max != null){
45
            minMax = "<" + String.valueOf(max);
46
        }
47
        String exactValueStr = "";
48
        for(Float exactValue : quantData.getExactValues()){
49
            if (exactValue != null){
50
                exactValueStr += CdmUtils.concat(";", exactValueStr, String.valueOf(exactValue));
51
            }
52
        }
53
        if (isNotBlank(minMax)){
54
            result = minMax;
55
            if (isNotBlank(exactValueStr)){
56
                result = result + "(" + exactValueStr + ")";
57
            }
58
        }else if(isNotBlank(exactValueStr)){
59
            result = exactValueStr;
60
        }
61

  
62
        //unit
63
        MeasurementUnit unit = quantData.getUnit();
64
        //TODO
65
        String unitStr = unit != null ? unit.getIdInVocabulary(): null;
66
        result = CdmUtils.concat(" ", result, unitStr);
67

  
68
        //bracket
69
        Float n = quantData.getSampleSize();
70
        String size = (n == null) ? "" : "n="+String.valueOf(n);
71
        String strBracket = isNotBlank(size) ? "[" + size + "]" : "";
72

  
73
        result = CdmUtils.concat(" ", result, strBracket);
74
        return result;
75
    }
76

  
77
}
cdmlib-model/src/main/java/eu/etaxonomy/cdm/model/description/MeasurementUnit.java
49 49
	@SuppressWarnings("unused")
50 50
	private static final Logger logger = Logger.getLogger(MeasurementUnit.class);
51 51

  
52
	private static final UUID uuidMeter = UUID.fromString("8bef5055-789c-41e5-bea2-8dc2ea8ecdf6");
53
	private static final UUID uuidSecond = UUID.fromString("7cb20e73-d3c3-4290-bb55-98f7d1e76670");
54
	private static final UUID uuidMillimeter = UUID.fromString("62b0c1fd-a502-4fba-a2c7-8df004fd2b66");
55
	private static final UUID uuidMicrometer = UUID.fromString("128a5a38-6b92-45d2-8866-0d3c12a4915c");
56
	private static final UUID uuidCentimeter = UUID.fromString("950c5919-53e4-47ab-9efd-0ea86daa98ca");
57
	private static final UUID uuidPerSquareMillimeter = UUID.fromString("22e70b61-6474-4061-b0c9-49f86ef6b8ff");
58

  
52 59
	protected static Map<UUID, MeasurementUnit> termMap = null;
53 60

  
54 61
//********************************** Constructor *******************************************************************/
......
106 113
			termMap.put(term.getUuid(), term);
107 114
		}
108 115
	}
116

  
117
	//******************************* STATIC METHODS *****************************************
118

  
119
    protected static MeasurementUnit getTermByUuid(UUID uuid){
120
        if (termMap == null || termMap.isEmpty()){
121
            return getTermByClassAndUUID(MeasurementUnit.class, uuid);
122
        } else {
123
            return termMap.get(uuid);
124
        }
125
    }
126

  
127
    /**
128
     * Returns the "meter" unit.
129
     */
130
    public static final MeasurementUnit METER(){
131
        return getTermByUuid(uuidMeter);
132
    }
109 133
}
cdmlib-model/src/test/java/eu/etaxonomy/cdm/format/CategoricalDataFormatterTest.java
1
/**
2
* Copyright (C) 2020 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.format;
10

  
11
import org.junit.Assert;
12
import org.junit.Before;
13
import org.junit.BeforeClass;
14
import org.junit.Test;
15

  
16
import eu.etaxonomy.cdm.format.ICdmFormatter.FormatKey;
17
import eu.etaxonomy.cdm.format.description.CategoricalDataFormatter;
18
import eu.etaxonomy.cdm.model.common.Language;
19
import eu.etaxonomy.cdm.model.description.CategoricalData;
20
import eu.etaxonomy.cdm.model.description.Feature;
21
import eu.etaxonomy.cdm.model.description.State;
22
import eu.etaxonomy.cdm.model.description.StateData;
23
import eu.etaxonomy.cdm.model.term.DefaultTermInitializer;
24

  
25
/**
26
 * Test for {@link CategoricalDataFormatter}.
27
 *
28
 * @author a.mueller
29
 * @since 11.03.2020
30
 */
31
public class CategoricalDataFormatterTest {
32

  
33
    private State state1;
34
    private State state2;
35
    private State state3;
36
    private StateData stateData1;
37
    private StateData stateData2;
38
    private StateData stateData3;
39

  
40
    @Before
41
    public void setUp() throws Exception {
42
        state1 = State.NewInstance("state1 text", "state1", "st.1");
43
        state2 = State.NewInstance("state2 text", "state2", "st.2");
44
        state3 = State.NewInstance("state3 text", "state3", "st.3");
45
        stateData1 = StateData.NewInstance(state1);
46
        stateData2 = StateData.NewInstance(state2);
47
        stateData3 = StateData.NewInstance(state3);
48
    }
49

  
50
    @BeforeClass
51
    public static void setUpBeforeClass() throws Exception {
52
        if (Language.DEFAULT() == null){
53
            new DefaultTermInitializer().initialize();
54
        }
55
    }
56

  
57
    @Test
58
    public void testFormat() {
59
        CategoricalData catData = CategoricalData.NewInstance(Feature.HABITAT());
60
        catData.addStateData(stateData1);
61
        FormatKey[] formatKey = null;
62
        CategoricalDataFormatter formatter = new CategoricalDataFormatter(catData, formatKey);
63
        String text = formatter.format(catData, formatKey);
64
        Assert.assertEquals("state1", text);
65
        catData.addStateData(stateData2);
66
        text = formatter.format(catData, formatKey);
67
        Assert.assertEquals("state1, state2", text);
68
        catData.addStateData(stateData3);
69
        text = formatter.format(catData, formatKey);
70
        Assert.assertEquals("state1, state2, state3", text);
71
        //TODO test with modifiers and maybe with other basedata like timeperiod etc.
72
    }
73

  
74
}
cdmlib-model/src/test/java/eu/etaxonomy/cdm/format/QuantitativeDataFormatterTest.java
1
/**
2
* Copyright (C) 2020 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.format;
10

  
11
import org.junit.Assert;
12
import org.junit.Before;
13
import org.junit.BeforeClass;
14
import org.junit.Test;
15

  
16
import eu.etaxonomy.cdm.format.ICdmFormatter.FormatKey;
17
import eu.etaxonomy.cdm.format.description.QuantitativeDataFormatter;
18
import eu.etaxonomy.cdm.model.common.Language;
19
import eu.etaxonomy.cdm.model.description.Feature;
20
import eu.etaxonomy.cdm.model.description.MeasurementUnit;
21
import eu.etaxonomy.cdm.model.description.QuantitativeData;
22
import eu.etaxonomy.cdm.model.description.StatisticalMeasure;
23
import eu.etaxonomy.cdm.model.description.StatisticalMeasurementValue;
24
import eu.etaxonomy.cdm.model.term.DefaultTermInitializer;
25

  
26
/**
27
 * Test for {@link QuantitativeDataFormatter}.
28
 *
29
 * @author a.mueller
30
 * @since 12.03.2020
31
 */
32
public class QuantitativeDataFormatterTest {
33

  
34
    private StatisticalMeasurementValue min1;
35
    private StatisticalMeasurementValue max1;
36
    private StatisticalMeasurementValue n1;
37

  
38
    @Before
39
    public void setUp() throws Exception {
40
        min1 = StatisticalMeasurementValue.NewInstance(StatisticalMeasure.MIN(), 0.1f);
41
        max1 = StatisticalMeasurementValue.NewInstance(StatisticalMeasure.MAX(), 1.3f);
42
        n1 = StatisticalMeasurementValue.NewInstance(StatisticalMeasure.SAMPLE_SIZE(), 2);
43
    }
44

  
45
    @BeforeClass
46
    public static void setUpBeforeClass() throws Exception {
47
        if (Language.DEFAULT() == null){
48
            new DefaultTermInitializer().initialize();
49
        }
50
    }
51

  
52
    @Test
53
    public void testFormat() {
54
        QuantitativeData quantData = QuantitativeData.NewInstance(Feature.CHROMOSOME_NUMBER());
55
        FormatKey[] formatKey = null;
56

  
57
        quantData.addStatisticalValue(min1);
58
        quantData.addStatisticalValue(max1);
59

  
60
        QuantitativeDataFormatter formatter = new QuantitativeDataFormatter(quantData, formatKey);
61
        String text = formatter.format(quantData, formatKey);
62
        Assert.assertEquals("0.1-1.3", text);
63
        quantData.addStatisticalValue(n1);
64
        MeasurementUnit unit = MeasurementUnit.METER();
65
        quantData.setUnit(unit);
66

  
67
        text = formatter.format(quantData, formatKey);
68
        Assert.assertEquals("0.1-1.3 m [n=2.0]", text);
69

  
70
    }
71

  
72
}

Also available in: Unified diff

Add picture from clipboard (Maximum size: 40 MB)