Project

General

Profile

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

    
10
package eu.etaxonomy.cdm.io.algaterra;
11

    
12
import java.sql.ResultSet;
13
import java.sql.SQLException;
14
import java.util.HashMap;
15
import java.util.HashSet;
16
import java.util.Map;
17
import java.util.Set;
18
import java.util.UUID;
19

    
20
import org.apache.commons.lang.StringUtils;
21
import org.apache.log4j.Logger;
22
import org.springframework.stereotype.Component;
23

    
24
import eu.etaxonomy.cdm.api.facade.DerivedUnitFacade;
25
import eu.etaxonomy.cdm.io.algaterra.validation.AlgaTerraMorphologyImportValidator;
26
import eu.etaxonomy.cdm.io.berlinModel.in.BerlinModelImportConfigurator;
27
import eu.etaxonomy.cdm.io.berlinModel.in.BerlinModelImportState;
28
import eu.etaxonomy.cdm.io.common.IOValidator;
29
import eu.etaxonomy.cdm.io.common.ResultSetPartitioner;
30
import eu.etaxonomy.cdm.io.common.mapping.UndefinedTransformerMethodException;
31
import eu.etaxonomy.cdm.model.common.CdmBase;
32
import eu.etaxonomy.cdm.model.common.DefinedTerm;
33
import eu.etaxonomy.cdm.model.common.DefinedTermBase;
34
import eu.etaxonomy.cdm.model.common.Language;
35
import eu.etaxonomy.cdm.model.common.Marker;
36
import eu.etaxonomy.cdm.model.common.MarkerType;
37
import eu.etaxonomy.cdm.model.common.TermType;
38
import eu.etaxonomy.cdm.model.common.TermVocabulary;
39
import eu.etaxonomy.cdm.model.description.CategoricalData;
40
import eu.etaxonomy.cdm.model.description.DescriptionBase;
41
import eu.etaxonomy.cdm.model.description.Feature;
42
import eu.etaxonomy.cdm.model.description.MeasurementUnit;
43
import eu.etaxonomy.cdm.model.description.QuantitativeData;
44
import eu.etaxonomy.cdm.model.description.State;
45
import eu.etaxonomy.cdm.model.description.StatisticalMeasure;
46
import eu.etaxonomy.cdm.model.description.StatisticalMeasurementValue;
47
import eu.etaxonomy.cdm.model.description.TextData;
48
import eu.etaxonomy.cdm.model.occurrence.Collection;
49
import eu.etaxonomy.cdm.model.occurrence.DerivedUnit;
50
import eu.etaxonomy.cdm.model.occurrence.FieldUnit;
51
import eu.etaxonomy.cdm.model.occurrence.SpecimenOrObservationBase;
52
import eu.etaxonomy.cdm.model.occurrence.SpecimenOrObservationType;
53
import eu.etaxonomy.cdm.model.reference.Reference;
54

    
55

    
56
/**
57
 * @author a.mueller
58
 * @created 01.09.2012
59
 */
60
@Component
61
public class AlgaTerraMorphologyImport  extends AlgaTerraSpecimenImportBase {
62
	private static final Logger logger = Logger.getLogger(AlgaTerraMorphologyImport.class);
63

    
64
	
65
	private static int modCount = 5000;
66
	private static final String pluralString = "eco facts";
67
	private static final String dbTableName = "EcoFact";  //??  
68

    
69

    
70
	public AlgaTerraMorphologyImport(){
71
		super(dbTableName, pluralString);
72
	}
73
	
74
	
75
	
76
	/* (non-Javadoc)
77
	 * @see eu.etaxonomy.cdm.io.berlinModel.in.BerlinModelImportBase#getIdQuery()
78
	 */
79
	@Override
80
	protected String getIdQuery(BerlinModelImportState state) {
81
		String result = " SELECT EcoFactId " + 
82
				" FROM EcoFact  " +
83
				" ORDER BY EcoFact.DuplicateFk, EcoFact.EcoFactId ";
84
		return result;
85
	}
86

    
87
	/* (non-Javadoc)
88
	 * @see eu.etaxonomy.cdm.io.berlinModel.in.BerlinModelImportBase#getRecordQuery(eu.etaxonomy.cdm.io.berlinModel.in.BerlinModelImportConfigurator)
89
	 */
90
	@Override
91
	protected String getRecordQuery(BerlinModelImportConfigurator config) {
92
			String strQuery =   
93
            " SELECT EcoFact.*, EcoFact.EcoFactId as unitId, " + 
94
               " tg.ID AS GazetteerId, tg.L2Code, tg.L3Code, tg.L4Code, tg.Country, tg.ISOCountry, " +
95
               " ec.UUID as climateUuid, eh.UUID as habitatUuid, elf.UUID as lifeFormUuid " +
96
            " FROM EcoFact " +
97
                 " LEFT OUTER JOIN TDWGGazetteer tg ON EcoFact.TDWGGazetteerFk = tg.ID " +
98
                 " LEFT OUTER JOIN EcoClimate  ec  ON EcoFact.ClimateFk  = ec.ClimateId " +
99
                 " LEFT OUTER JOIN EcoHabitat  eh  ON EcoFact.HabitatFk  = eh.HabitatId " +
100
                 " LEFT OUTER JOIN EcoLifeForm elf ON EcoFact.LifeFormFk = elf.LifeFormId " +
101
              " WHERE (EcoFact.EcoFactId IN (" + ID_LIST_TOKEN + ")  )"  
102
            + " ORDER BY EcoFact.DuplicateFk, EcoFact.EcoFactId "
103
            ;
104
		return strQuery;
105
	}
106

    
107
	/* (non-Javadoc)
108
	 * @see eu.etaxonomy.cdm.io.berlinModel.in.IPartitionedIO#doPartition(eu.etaxonomy.cdm.io.berlinModel.in.ResultSetPartitioner, eu.etaxonomy.cdm.io.berlinModel.in.BerlinModelImportState)
109
	 */
110
	public boolean doPartition(ResultSetPartitioner partitioner, BerlinModelImportState bmState) {
111
		boolean success = true;
112
		
113
		AlgaTerraImportState state = (AlgaTerraImportState)bmState;
114
		try {
115
			makeVocabulariesAndFeatures(state);
116
		} catch (SQLException e1) {
117
			logger.warn("Exception occurred when trying to create Ecofact vocabularies: " + e1.getMessage());
118
			e1.printStackTrace();
119
		}
120
		Set<SpecimenOrObservationBase> objectsToSave = new HashSet<SpecimenOrObservationBase>();
121
		
122
		//TODO do we still need this map? EcoFacts are not handled separate from Facts.
123
		//However, they have duplicates on derived unit level. Also check duplicateFk. 
124
		Map<String, FieldUnit> ecoFactFieldObservationMap = (Map<String, FieldUnit>) partitioner.getObjectMap(ECO_FACT_FIELD_OBSERVATION_NAMESPACE);
125
		
126
		ResultSet rs = partitioner.getResultSet();
127

    
128
		try {
129
			
130
			int i = 0;
131

    
132
			//for each reference
133
            while (rs.next()){
134
                
135
        		if ((i++ % modCount) == 0 && i!= 1 ){ logger.info(pluralString + " handled: " + (i-1));}
136
				
137
				int ecoFactId = rs.getInt("EcoFactId");
138
				Integer duplicateFk = nullSafeInt(rs, "DuplicateFk");
139
				
140
				//FIXME RecordBasis is in Fact table, which is not part of the query anymore.
141
				//Some EcoFacts have multiple RecordBasis types in Fact. Henning will check this.
142
//				String recordBasis = rs.getString("RecordBasis");
143
				String recordBasis = "PreservedSpecimen";
144
				
145
				try {
146
					
147
					//source ref
148
					Reference<?> sourceRef = state.getTransactionalSourceReference();
149
				
150
					//facade
151
					SpecimenOrObservationType type = makeDerivedUnitType(recordBasis);
152
					
153
					DerivedUnitFacade facade;
154
					//field observation
155
					if (duplicateFk == null){
156
						facade = DerivedUnitFacade.NewInstance(type);
157
						handleFieldObservationSpecimen(rs, facade, state, partitioner);
158
						handleEcoFactSpecificFieldObservation(rs,facade, state);
159
						FieldUnit fieldObservation = facade.getFieldUnit(true);
160
						ecoFactFieldObservationMap.put(String.valueOf(ecoFactId), fieldObservation);
161
					}else{
162
						FieldUnit fieldObservation = ecoFactFieldObservationMap.get(String.valueOf(duplicateFk));
163
						facade = DerivedUnitFacade.NewInstance(type, fieldObservation);
164
					}
165
						
166
					handleFirstDerivedSpecimen(rs, facade, state, partitioner);
167
					handleEcoFactSpecificDerivedUnit(rs,facade, state);
168

    
169
					
170
					DerivedUnit objectToSave = facade.innerDerivedUnit();
171
					objectsToSave.add(objectToSave); 
172
					
173

    
174
				} catch (Exception e) {
175
					logger.warn("Exception in ecoFact: ecoFactId " + ecoFactId + ". " + e.getMessage());
176
					e.printStackTrace();
177
				} 
178
                
179
            }
180
           
181
//            logger.warn("Specimen: " + countSpecimen + ", Descriptions: " + countDescriptions );
182

    
183
			logger.warn("Taxa to save: " + objectsToSave.size());
184
			getOccurrenceService().save(objectsToSave);	
185
			
186
			return success;
187
		} catch (SQLException e) {
188
			logger.error("SQLException:" +  e);
189
			return false;
190
		}
191
	}
192
	
193
	protected String getDerivedUnitNameSpace(){
194
		return ECO_FACT_DERIVED_UNIT_NAMESPACE;
195
	}
196
	
197
	protected String getFieldObservationNameSpace(){
198
		return ECO_FACT_FIELD_OBSERVATION_NAMESPACE;
199
	}
200

    
201

    
202

    
203
	private void handleEcoFactSpecificFieldObservation(ResultSet rs, DerivedUnitFacade facade, AlgaTerraImportState state) throws SQLException {
204
		
205
		Object alkalinityFlag = rs.getBoolean("AlkalinityFlag");
206
		
207
		//alkalinity marker
208
		if (alkalinityFlag != null){
209
			MarkerType alkalinityMarkerType = getMarkerType(state, uuidMarkerAlkalinity, "Alkalinity", "Alkalinity", null);
210
			boolean alkFlag = Boolean.valueOf(alkalinityFlag.toString());
211
			Marker alkalinityMarker = Marker.NewInstance(alkalinityMarkerType, alkFlag);
212
			facade.getFieldUnit(true).addMarker(alkalinityMarker);
213
		}
214
		
215
		
216
		DescriptionBase<?> fieldDescription = getFieldObservationDescription(facade);
217

    
218
		//habitat, ecology, community, etc.
219
		String habitat = rs.getString("HabitatExplanation");
220
		
221
		if (isNotBlank(habitat)){
222
			Feature habitatExplanation = getFeature(state, uuidFeatureHabitatExplanation, "Habitat Explanation", "HabitatExplanation", null, null);
223
			TextData textData = TextData.NewInstance(habitatExplanation);
224
			textData.putText(Language.DEFAULT(), habitat);
225
			fieldDescription.addElement(textData);
226
		}
227
		
228
		String community = rs.getString("Comunity");
229
		if (isNotBlank(community)){
230
			Feature communityFeature = getFeature(state, uuidFeatureSpecimenCommunity, "Community", "The community of a specimen (e.g. other algae in the same sample)", null, null);
231
			TextData textData = TextData.NewInstance(communityFeature);
232
			textData.putText(Language.DEFAULT(), community);
233
			fieldDescription.addElement(textData);
234
		}
235

    
236
		String additionalData = rs.getString("AdditionalData");
237
		if (isNotBlank(additionalData)){  //or handle it as Annotation ??
238
			Feature additionalDataFeature = getFeature(state, uuidFeatureAdditionalData, "Additional Data", "Additional Data", null, null);
239
			TextData textData = TextData.NewInstance(additionalDataFeature);
240
			textData.putText(Language.DEFAULT(), additionalData);
241
			fieldDescription.addElement(textData);
242
		}
243
		
244
		String climateUuid = rs.getString("climateUuid");
245
		String habitatUuid = rs.getString("habitatUuid");
246
		String lifeFormUuid = rs.getString("lifeFormUuid");
247
		
248
		addCategoricalValue(state, fieldDescription, climateUuid, uuidFeatureAlgaTerraClimate);
249
		addCategoricalValue(state, fieldDescription, habitatUuid, Feature.HABITAT().getUuid());
250
		addCategoricalValue(state, fieldDescription, lifeFormUuid, uuidFeatureAlgaTerraLifeForm);
251
		
252

    
253
		
254
		//parameters
255
		makeParameter(state, rs, getFieldObservationDescription(facade));
256

    
257
	}
258
	
259
	private void handleEcoFactSpecificDerivedUnit(ResultSet rs, DerivedUnitFacade facade, AlgaTerraImportState state) throws SQLException {
260
		//collection
261
		String voucher = rs.getString("Voucher");
262
		if (StringUtils.isNotBlank(voucher)){
263
			facade.setAccessionNumber(voucher);
264
		}
265
	}
266

    
267

    
268

    
269

    
270

    
271
	private void addCategoricalValue(AlgaTerraImportState importState, DescriptionBase description, String uuidTerm, UUID featureUuid) {
272
		if (uuidTerm != null){
273
			State state = this.getStateTerm(importState, UUID.fromString(uuidTerm));
274
			Feature feature = getFeature(importState, featureUuid);
275
			CategoricalData categoricalData = CategoricalData.NewInstance(state, feature);
276
			description.addElement(categoricalData);
277
		}
278
	}
279

    
280
	private void makeParameter(AlgaTerraImportState state, ResultSet rs, DescriptionBase<?> descriptionBase) throws SQLException {
281
		for (int i = 1; i <= 10; i++){
282
			String valueStr = rs.getString(String.format("P%dValue", i));
283
			String unitStr = rs.getString(String.format("P%dUnit", i));
284
			String parameter = rs.getString(String.format("P%dParameter", i));
285
			String method = rs.getString(String.format("P%dMethod", i));
286
			
287
			//method
288
			if (StringUtils.isNotBlank(method)){
289
				logger.warn("Methods not yet handled: " + method);
290
			}
291
			//parameter
292
			TermVocabulary<Feature> vocParameter = getVocabulary(TermType.Feature, uuidVocParameter, "Feature vocabulary for AlgaTerra measurement parameters", "Parameters", null, null, false, Feature.COMMON_NAME());
293
			if (StringUtils.isNotBlank(parameter)){
294
				UUID featureUuid = getParameterFeatureUuid(state, parameter);
295
				Feature feature = getFeature(state, featureUuid, parameter, parameter, null, vocParameter);
296
				QuantitativeData quantData = QuantitativeData.NewInstance(feature);
297
				
298
				//unit
299
				MeasurementUnit unit = getMeasurementUnit(state, unitStr);
300
				quantData.setUnit(unit);
301
				try {
302
					
303
					Set<DefinedTerm> valueModifier = new HashSet<DefinedTerm>();
304
					valueStr = normalizeAndModifyValue(state, valueStr, valueModifier);
305
					//value
306
					Float valueFlt = Float.valueOf(valueStr);  //TODO maybe change model to Double ??
307
					
308
					StatisticalMeasure measureSingleValue = getStatisticalMeasure(state, uuidStatMeasureSingleValue, "Value", "Single measurement value", null, null);
309
					StatisticalMeasurementValue value = StatisticalMeasurementValue.NewInstance(measureSingleValue, valueFlt); 
310
					quantData.addStatisticalValue(value);
311
					descriptionBase.addElement(quantData);
312
					
313
				} catch (NumberFormatException e) {
314
					logger.warn(String.format("Value '%s' can't be converted to double. Parameter %s not imported.", valueStr, parameter));
315
				}
316
			}else if (isNotBlank(valueStr) || isNotBlank(unitStr) ){
317
				logger.warn("There is value or unit without parameter: " + i);
318
			}
319
			
320
			
321
		}
322
		
323
	}
324

    
325
	private String normalizeAndModifyValue(AlgaTerraImportState state, String valueStr, Set<DefinedTerm> valueModifier) {
326
		valueStr = valueStr.replace(",", ".");
327
		if (valueStr.startsWith("<")){
328
			TermVocabulary<DefinedTerm> measurementValueModifierVocabulary = getVocabulary(TermType.Modifier, uuidMeasurementValueModifier, "Measurement value modifier", "Measurement value modifier", null, null, false, DefinedTerm.NewModifierInstance(null, null, null));
329
			DefinedTerm modifier = getModifier(state, uuidModifierLowerThan, "Lower", "Lower than the given measurement value", "<", measurementValueModifierVocabulary);
330
			valueModifier.add(modifier);
331
			valueStr = valueStr.replace("<", "");
332
		}
333
		if (valueStr.startsWith(">")){
334
			TermVocabulary<DefinedTerm> measurementValueModifierVocabulary = getVocabulary(TermType.Modifier, uuidMeasurementValueModifier, "Measurement value modifier", "Measurement value modifier", null, null, false, DefinedTerm.NewModifierInstance(null, null, null));
335
			DefinedTerm modifier = getModifier(state, uuidModifierGreaterThan, "Lower", "Lower than the given measurement value", "<", measurementValueModifierVocabulary);
336
			valueModifier.add(modifier);
337
			valueStr = valueStr.replace(">", "");
338
		}
339
		return valueStr;
340
	}
341

    
342

    
343

    
344
	private UUID getParameterFeatureUuid(AlgaTerraImportState state, String key) {
345
		try {
346
			return AlgaTerraImportTransformer.getFeatureUuid(key);
347
		} catch (UndefinedTransformerMethodException e) {
348
			throw new RuntimeException(e);
349
		}
350
	}
351

    
352

    
353

    
354
	/**
355
	 * TODO move to InputTransformerBase
356
	 * @param state
357
	 * @param unitStr
358
	 * @return
359
	 */
360
	private MeasurementUnit getMeasurementUnit(AlgaTerraImportState state, String unitStr) {
361
		if (StringUtils.isNotBlank(unitStr)){
362
			UUID uuid = AlgaTerraImportTransformer.getMeasurementUnitUuid(unitStr);
363
			if (uuid != null){
364
				return getMeasurementUnit(state, uuid, unitStr, unitStr, unitStr, null);
365
			}else{
366
				logger.warn("MeasurementUnit was not recognized");
367
				return null;
368
			}
369
		}else{
370
			return null;
371
		}
372
	}
373

    
374

    
375
	@Override
376
	public Map<Object, Map<String, ? extends CdmBase>> getRelatedObjectsForPartition(ResultSet rs) {
377
		String nameSpace;
378
		Class cdmClass;
379
		Set<String> idSet;
380
		Map<Object, Map<String, ? extends CdmBase>> result = new HashMap<Object, Map<String, ? extends CdmBase>>();
381
		
382
		try{
383
			Set<String> fieldObservationIdSet = new HashSet<String>();
384
			Set<String> termsIdSet = new HashSet<String>();
385
			Set<String> collectionIdSet = new HashSet<String>();
386
			
387
			while (rs.next()){
388
				handleForeignKey(rs, fieldObservationIdSet, "DuplicateFk");
389
				handleForeignKey(rs, termsIdSet, "ClimateFk");
390
				handleForeignKey(rs, termsIdSet, "HabitatFk");
391
				handleForeignKey(rs, termsIdSet, "LifeFormFk");
392
				handleForeignKey(rs, collectionIdSet, "CollectionFk");
393
			}
394
			
395
			//field observation map for duplicates
396
			nameSpace = AlgaTerraMorphologyImport.ECO_FACT_FIELD_OBSERVATION_NAMESPACE;
397
			cdmClass = FieldUnit.class;
398
			idSet = fieldObservationIdSet;
399
			Map<String, FieldUnit> fieldObservationMap = (Map<String, FieldUnit>)getCommonService().getSourcedObjectsByIdInSource(cdmClass, idSet, nameSpace);
400
			result.put(nameSpace, fieldObservationMap);
401

    
402
			//collections
403
			nameSpace = AlgaTerraCollectionImport.NAMESPACE_COLLECTION;
404
			cdmClass = Collection.class;
405
			idSet = collectionIdSet;
406
			Map<String, Collection> collectionMap = (Map<String, Collection>)getCommonService().getSourcedObjectsByIdInSource(cdmClass, idSet, nameSpace);
407
			result.put(nameSpace, collectionMap);
408

    
409
			//sub-collections
410
			nameSpace = AlgaTerraCollectionImport.NAMESPACE_SUBCOLLECTION;
411
			cdmClass = Collection.class;
412
			idSet = collectionIdSet;
413
			Map<String, Collection> subCollectionMap = (Map<String, Collection>)getCommonService().getSourcedObjectsByIdInSource(cdmClass, idSet, nameSpace);
414
			result.put(nameSpace, subCollectionMap);
415

    
416
			//terms
417
			nameSpace = AlgaTerraMorphologyImport.TERMS_NAMESPACE;
418
			cdmClass = FieldUnit.class;
419
			idSet = termsIdSet;
420
			Map<String, DefinedTermBase> termMap = (Map<String, DefinedTermBase>)getCommonService().getSourcedObjectsByIdInSource(cdmClass, idSet, nameSpace);
421
			result.put(nameSpace, termMap);
422
			
423
		} catch (SQLException e) {
424
			throw new RuntimeException(e);
425
		}
426
		return result;
427
	}
428

    
429

    
430

    
431
	/* (non-Javadoc)
432
	 * @see eu.etaxonomy.cdm.io.common.CdmIoBase#doCheck(eu.etaxonomy.cdm.io.common.IoStateBase)
433
	 */
434
	@Override
435
	protected boolean doCheck(BerlinModelImportState state){
436
		IOValidator<BerlinModelImportState> validator = new AlgaTerraMorphologyImportValidator();
437
		return validator.validate(state);
438
	}
439

    
440

    
441
	/* (non-Javadoc)
442
	 * @see eu.etaxonomy.cdm.io.common.CdmIoBase#isIgnore(eu.etaxonomy.cdm.io.common.IImportConfigurator)
443
	 */
444
	protected boolean isIgnore(BerlinModelImportState state){
445
		return ! ((AlgaTerraImportState)state).getAlgaTerraConfigurator().isDoMorphology();
446
	}
447
	
448
}
(9-9/15)