Project

General

Profile

« Previous | Next » 

Revision d5301da6

Added by Andreas Müller over 11 years ago

AlgaTerra categorical data and flat classifications

View differences:

app-import/src/main/java/eu/etaxonomy/cdm/io/algaterra/AlgaTerraSpecimenImport.java
9 9

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

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

  
19 22
import org.apache.commons.lang.StringUtils;
20 23
import org.apache.log4j.Logger;
21 24
import org.springframework.stereotype.Component;
25
import org.springframework.transaction.TransactionStatus;
22 26

  
23 27
import eu.etaxonomy.cdm.api.facade.DerivedUnitFacade;
24 28
import eu.etaxonomy.cdm.api.facade.DerivedUnitFacade.DerivedUnitType;
......
29 33
import eu.etaxonomy.cdm.io.berlinModel.in.BerlinModelTaxonImport;
30 34
import eu.etaxonomy.cdm.io.common.IOValidator;
31 35
import eu.etaxonomy.cdm.io.common.ResultSetPartitioner;
36
import eu.etaxonomy.cdm.io.common.Source;
37
import eu.etaxonomy.cdm.model.agent.Team;
32 38
import eu.etaxonomy.cdm.model.common.CdmBase;
39
import eu.etaxonomy.cdm.model.common.DefinedTermBase;
40
import eu.etaxonomy.cdm.model.common.Language;
41
import eu.etaxonomy.cdm.model.common.Marker;
42
import eu.etaxonomy.cdm.model.common.MarkerType;
43
import eu.etaxonomy.cdm.model.common.OrderedTermVocabulary;
44
import eu.etaxonomy.cdm.model.common.TimePeriod;
45
import eu.etaxonomy.cdm.model.description.CategoricalData;
46
import eu.etaxonomy.cdm.model.description.DescriptionBase;
33 47
import eu.etaxonomy.cdm.model.description.Feature;
34 48
import eu.etaxonomy.cdm.model.description.IndividualsAssociation;
49
import eu.etaxonomy.cdm.model.description.SpecimenDescription;
50
import eu.etaxonomy.cdm.model.description.State;
35 51
import eu.etaxonomy.cdm.model.description.TaxonDescription;
52
import eu.etaxonomy.cdm.model.description.TextData;
53
import eu.etaxonomy.cdm.model.location.NamedArea;
36 54
import eu.etaxonomy.cdm.model.location.Point;
37 55
import eu.etaxonomy.cdm.model.location.ReferenceSystem;
56
import eu.etaxonomy.cdm.model.location.TdwgArea;
57
import eu.etaxonomy.cdm.model.location.WaterbodyOrCountry;
58
import eu.etaxonomy.cdm.model.name.BotanicalName;
59
import eu.etaxonomy.cdm.model.name.Rank;
60
import eu.etaxonomy.cdm.model.occurrence.FieldObservation;
38 61
import eu.etaxonomy.cdm.model.reference.Reference;
39 62
import eu.etaxonomy.cdm.model.taxon.Taxon;
40 63
import eu.etaxonomy.cdm.model.taxon.TaxonBase;
......
49 72
public class AlgaTerraSpecimenImport  extends BerlinModelImportBase {
50 73
	private static final Logger logger = Logger.getLogger(AlgaTerraSpecimenImport.class);
51 74

  
52
	public static final String NAMESPACE = "Occurrence";
75
	public static final String FIELD_OBSERVATION_NAMESPACE = "FieldObservation";
76
	public static final String TERMS_NAMESPACE = "ALGA_TERRA_TERMS";
77
	
78
	//move to transformrer
79
	final static UUID uuidMarkerAlkalinity = UUID.fromString("e52d0ea2-0c1f-4d95-ae6d-e21ab317c594");  
80
	final static UUID uuidRefSystemGps = UUID.fromString("c23e4928-c137-4e4a-b6ab-b430da3d0b94");  
81
	final static UUID uuidFeatureSpecimenCommunity = UUID.fromString("3ff5b1ab-3999-4b5a-b8f7-01fd2f6c12c7");
82
	final static UUID uuidFeatureAdditionalData = UUID.fromString("0ac82ab8-2c2b-4953-98eb-a9f718eb9c57");
83
	
84
	final static UUID uuidVocAlgaTerraClimate = UUID.fromString("b0a677c6-8bb6-43f4-b1b8-fc377a10feb5");
85
	final static UUID uuidVocAlgaTerraHabitat = UUID.fromString("06f30114-e19c-4e7d-a8e5-5488c41fcbc5");
86
	final static UUID uuidVocAlgaTerraLifeForm = UUID.fromString("3c0b194e-809c-4b42-9498-6ff034066ed7");
87
	
88
	final static UUID uuidFeatureAlgaTerraClimate = UUID.fromString("8754674c-9ab9-4f28-95f1-91eeee2314ee");
89
	final static UUID uuidFeatureAlgaTerraHabitat = UUID.fromString("7def3fc2-cdc5-4739-8e13-62edbd053415");
90
	final static UUID uuidFeatureAlgaTerraLifeForm = UUID.fromString("9b657901-1b0d-4a2a-8d21-dd8c1413e2e6");
91
	
53 92
	
54 93
	
55 94
	private static int modCount = 5000;
......
61 100
		super();
62 101
	}
63 102
	
103
	
104
	
64 105
	/* (non-Javadoc)
65 106
	 * @see eu.etaxonomy.cdm.io.berlinModel.in.BerlinModelImportBase#getIdQuery()
66 107
	 */
67 108
	@Override
68 109
	protected String getIdQuery(BerlinModelImportState state) {
69 110
		String result = " SELECT factId " + 
70
				" FROM " + getTableName() + " INNER JOIN PTaxon ON Fact.PTNameFk = PTaxon.PTNameFk AND Fact.PTRefFk = PTaxon.PTRefFk "
111
				" FROM Fact " +
112
					" INNER JOIN EcoFact ON Fact.ExtensionFk = EcoFact.EcoFactId " +
113
					"INNER JOIN PTaxon ON Fact.PTNameFk = PTaxon.PTNameFk AND Fact.PTRefFk = PTaxon.PTRefFk "
71 114
				+ " WHERE FactCategoryFk = 202 "
72
				+ " ORDER BY PTaxon.RIdentifier, Fact.FactId ";
115
				+ " ORDER BY EcoFact.EcoFactId, PTaxon.RIdentifier, Fact.FactId ";
73 116
		return result;
74 117
	}
75 118

  
......
79 122
	@Override
80 123
	protected String getRecordQuery(BerlinModelImportConfigurator config) {
81 124
			String strQuery =   //DISTINCT because otherwise emOccurrenceSource creates multiple records for a single distribution 
82
            " SELECT PTaxon.RIdentifier as taxonId, Fact.FactId, Fact.RecordBasis, EcoFact.* " + 
125
            " SELECT PTaxon.RIdentifier as taxonId, Fact.FactId, Fact.RecordBasis, EcoFact.*, " + 
126
               " tg.ID AS GazetteerId, tg.L2Code, tg.L3Code, tg.L4Code, tg.Country, tg.ISOCountry, " +
127
               " ec.UUID as climateUuid, eh.UUID as habitatUuid, elf.UUID as lifeFormUuid" +
83 128
            " FROM Fact " + 
84 129
                 " INNER JOIN EcoFact ON Fact.ExtensionFk = EcoFact.EcoFactId " +
85 130
                 " INNER JOIN PTaxon ON dbo.Fact.PTNameFk = dbo.PTaxon.PTNameFk AND dbo.Fact.PTRefFk = dbo.PTaxon.PTRefFk " +
86
            " WHERE Fact.FactCategoryFk = 202 AND (Fact.FactId IN (" + ID_LIST_TOKEN + ")  )"  
87
            + " ORDER BY PTaxon.RIdentifier, Fact.FactId "
131
                 " LEFT OUTER JOIN TDWGGazetteer tg ON EcoFact.TDWGGazetteerFk = tg.ID " +
132
                 " LEFT OUTER JOIN EcoClimate  ec  ON EcoFact.ClimateFk  = ec.ClimateId " +
133
                 " LEFT OUTER JOIN EcoHabitat  eh  ON EcoFact.HabitatFk  = eh.HabitatId " +
134
                 " LEFT OUTER JOIN EcoLifeForm elf ON EcoFact.LifeFormFk = elf.LifeFormId " +
135
              " WHERE Fact.FactCategoryFk = 202 AND (Fact.FactId IN (" + ID_LIST_TOKEN + ")  )"  
136
            + " ORDER BY EcoFact.EcoFactId, PTaxon.RIdentifier, Fact.FactId "
88 137
            ;
89 138
		return strQuery;
90 139
	}
......
92 141
	/* (non-Javadoc)
93 142
	 * @see eu.etaxonomy.cdm.io.berlinModel.in.IPartitionedIO#doPartition(eu.etaxonomy.cdm.io.berlinModel.in.ResultSetPartitioner, eu.etaxonomy.cdm.io.berlinModel.in.BerlinModelImportState)
94 143
	 */
95
	public boolean doPartition(ResultSetPartitioner partitioner, BerlinModelImportState state) {
144
	public boolean doPartition(ResultSetPartitioner partitioner, BerlinModelImportState bmState) {
96 145
		boolean success = true;
146
		
147
		AlgaTerraImportState state = (AlgaTerraImportState)bmState;
148
		try {
149
			makeVocabulariesAndFeatures(state);
150
		} catch (SQLException e1) {
151
			logger.warn("Exception occurred when trying to create Ecofact vocabularies: " + e1.getMessage());
152
			e1.printStackTrace();
153
		}
97 154
		Set<TaxonBase> taxaToSave = new HashSet<TaxonBase>();
98 155
		
99 156
		Map<String, TaxonBase> taxonMap = (Map<String, TaxonBase>) partitioner.getObjectMap(BerlinModelTaxonImport.NAMESPACE);
100
			
157
		Map<String, FieldObservation> fieldObservationMap = (Map<String, FieldObservation>) partitioner.getObjectMap(FIELD_OBSERVATION_NAMESPACE);
158
		
101 159
		ResultSet rs = partitioner.getResultSet();
102 160

  
103 161
		try {
104
			int oldTaxonId = -1;
105
			TaxonDescription oldDescription = null;
162
			
106 163
			int i = 0;
107
			int countDescriptions = 0;
108
			int countSpecimen = 0;
164

  
109 165
			//for each reference
110 166
            while (rs.next()){
111 167
                
......
113 169
				
114 170
				int newTaxonId = rs.getInt("taxonId");
115 171
				int factId = rs.getInt("FactId");
172
				int ecoFactId = rs.getInt("EcoFactId");
173
				String recordBasis = rs.getString("RecordBasis");
174
				
116 175
				try {
117
							
118
					String recordBasis = rs.getString("RecordBasis");
119 176
					
177
					//source ref
120 178
					Reference<?> sourceRef = state.getTransactionalSourceReference();
121
					//create description(elements)
122
					TaxonDescription taxonDescription = getTaxonDescription(newTaxonId, oldTaxonId, oldDescription, taxonMap, factId, sourceRef);
123

  
179
				
180
					//facade
181
					FieldObservation fieldObservation = getFieldObservation(ecoFactId, fieldObservationMap);
124 182
					DerivedUnitType type = makeDerivedUnitType(recordBasis);
125
					DerivedUnitFacade facade = DerivedUnitFacade.NewInstance(type);
126
					
127
					handleSingleSpecimen(rs, facade);
183
					DerivedUnitFacade facade = DerivedUnitFacade.NewInstance(type, fieldObservation);
184

  
185
					//field observation
186
					handleSingleSpecimen(rs, facade, state);
128 187
					
188
					//description element
189
					TaxonDescription taxonDescription = getTaxonDescription(state, newTaxonId, taxonMap, factId, sourceRef);
129 190
					IndividualsAssociation indAssociation = IndividualsAssociation.NewInstance();
130 191
					Feature feature = makeFeature(type);
131 192
					indAssociation.setAssociatedSpecimenOrObservation(facade.innerDerivedUnit());
132 193
					indAssociation.setFeature(feature);
133 194
					taxonDescription.addElement(indAssociation);
134 195
					
135
					if (taxonDescription != oldDescription){ 
136
						taxaToSave.add(taxonDescription.getTaxon()); 
137
						oldDescription = taxonDescription; 
138
						countDescriptions++; 
139
					}
196
					taxaToSave.add(taxonDescription.getTaxon()); 
197
					
198

  
140 199
				} catch (Exception e) {
141 200
					logger.warn("Exception in ecoFact: FactId " + factId + ". " + e.getMessage());
142 201
//					e.printStackTrace();
......
144 203
                
145 204
            }
146 205
           
147
            logger.warn("Specimen: " + countSpecimen + ", Descriptions: " + countDescriptions );
206
//            logger.warn("Specimen: " + countSpecimen + ", Descriptions: " + countDescriptions );
148 207

  
149 208
			logger.warn("Taxa to save: " + taxaToSave.size());
150 209
			getTaxonService().save(taxaToSave);	
......
157 216
	}
158 217

  
159 218

  
160
	private void handleSingleSpecimen(ResultSet rs, DerivedUnitFacade facade) throws SQLException {
161
       	//TDWGGazetteerFK, CollectionFk, Collector, GeoCodeMethod, Prec, AltitudeMethod, Depth,
162
    	//ISOCountrySub, CollectionDate/End, WaterBody, 
163
    	//CreatedWhen/Who/Updated/who
164
    	
165
    	//P1-10Value/Unit/Parameter/Method
166 219

  
167
//		int factId = rs.getInt("factId");
168
        String locality = rs.getString("Locality");
169
        Double latitude = rs.getDouble("Latitude");
170
        Double longitude = rs.getDouble("Longitude");
171
        int errorRadius = rs.getInt("Prec");
172
    	Integer altitude = rs.getInt("Altitude");
173
    	String altitudeUnit = rs.getString("AltitudeUnit");
174
    	String collectorsNumber = rs.getString("CollectorsNumber");
175
    	
176
    	//location
177
    	facade.setLocality(locality);
178
    	    	
179
    	//exact location
180
    	ReferenceSystem referenceSystem = null;
181
    	Point exactLocation = Point.NewInstance(longitude, latitude, referenceSystem, errorRadius);
182
    	facade.setExactLocation(exactLocation);
220

  
221
	/**
222
	 * Creates the vocabularies and the features for Climate, Habitat and Lifeform
223
	 * @param state
224
	 * @throws SQLException
225
	 */
226
	private void makeVocabulariesAndFeatures(AlgaTerraImportState state) throws SQLException {
227
		String abbrevLabel = null;
228
		URI uri = null;
229
		
230
		if (! state.isSpecimenVocabulariesCreated()){
231
			
232
			TransactionStatus txStatus = this.startTransaction();
233
		
234
			boolean isOrdered = true;
235
			OrderedTermVocabulary<State> climateVoc = (OrderedTermVocabulary)getVocabulary(uuidVocAlgaTerraClimate, "Climate", "Climate", abbrevLabel, uri, isOrdered, null);
236
			OrderedTermVocabulary<State> habitatVoc = (OrderedTermVocabulary)getVocabulary(uuidVocAlgaTerraHabitat, "Habitat", "Habitat", abbrevLabel, uri, isOrdered, null);
237
			OrderedTermVocabulary<State> lifeformVoc = (OrderedTermVocabulary)getVocabulary(uuidVocAlgaTerraLifeForm, "Lifeform", "Lifeform", abbrevLabel, uri, isOrdered, null);
238
			
239
			
240
			Feature feature = getFeature(state, uuidFeatureAlgaTerraClimate, "Climate","Climate", null, null);
241
			feature.setSupportsCategoricalData(true);
242
			
243
			feature = getFeature(state, uuidFeatureAlgaTerraLifeForm, "LifeForm","LifeForm", null, null);
244
			feature.setSupportsCategoricalData(true);
245
			
246
			feature = Feature.HABITAT();
247
			feature.setSupportsCategoricalData(true);
248
			getTermService().saveOrUpdate(feature);
249
			
250
			Source source = state.getAlgaTerraConfigurator().getSource();
251
			
252
			String climateSql = "SELECT * FROM EcoClimate";
253
			ResultSet rs = source.getResultSet(climateSql);
254
			while (rs.next()){
255
				String climate = rs.getString("Climate");
256
				String description = rs.getString("Description");
257
				Integer id = rs.getInt("ClimateId");
258
				UUID uuid = UUID.fromString(rs.getString("UUID"));
259
				State stateTerm = getStateTerm(state, uuid, climate, description, null, climateVoc);
260
				addOriginalSource(stateTerm, id.toString(), "EcoClimate", state.getConfig().getSourceReference());
261
				getTermService().saveOrUpdate(stateTerm);
262
			}
263
			
264
			String habitatSql = "SELECT * FROM EcoHabitat";
265
			rs = source.getResultSet(habitatSql);
266
			while (rs.next()){
267
				String habitat = rs.getString("Habitat");
268
				String description = rs.getString("Description");
269
				Integer id = rs.getInt("HabitatId");
270
				UUID uuid = UUID.fromString(rs.getString("UUID"));
271
				State stateTerm = getStateTerm(state, uuid, habitat, description, null, habitatVoc);
272
				addOriginalSource(stateTerm, id.toString(), "EcoHabitat", state.getConfig().getSourceReference());
273
				getTermService().saveOrUpdate(stateTerm);
274
			}
275
			
276
			String lifeformSql = "SELECT * FROM EcoLifeForm";
277
			rs = source.getResultSet(lifeformSql);
278
			while (rs.next()){
279
				String lifeform = rs.getString("LifeForm");
280
				String description = rs.getString("Description");
281
				Integer id = rs.getInt("LifeFormId");
282
				UUID uuid = UUID.fromString(rs.getString("UUID"));
283
				State stateTerm = getStateTerm(state, uuid, lifeform, description, null, lifeformVoc);
284
				addOriginalSource(stateTerm, id.toString(), "EcoLifeForm", state.getConfig().getSourceReference());
285
				getTermService().saveOrUpdate(stateTerm);
286
			}
287
			
288
			this.commitTransaction(txStatus);
289
			
290
			state.setSpecimenVocabulariesCreated(true);
291
		}
292
		
293
	}
294

  
295

  
296

  
297
	private void handleSingleSpecimen(ResultSet rs, DerivedUnitFacade facade, AlgaTerraImportState state) throws SQLException {
298
       	//CollectionFk, Collector, AltitudeMethod, 
299
    	//ISOCountrySub, CreatedWhen/Who/Updated/who
183 300
    	
184
    	//altitude
185
    	if (StringUtils.isNotBlank(altitudeUnit) && ! altitudeUnit.trim().equalsIgnoreCase("m")){
186
    		logger.warn("Altitude unit is not [m] but: " +  altitudeUnit);
187
    	}
188
    	facade.setAbsoluteElevationRange(altitude, altitude);  //TODO
301
    	//P1-10Value/Unit/Parameter/Method
302
		
303
		try {
304
			Object alkalinityFlag = rs.getBoolean("AlkalinityFlag");
305
			
306
			String locality = rs.getString("Locality");
307
			Double latitude = nullSafeDouble(rs, "Latitude");
308
			Double longitude = nullSafeDouble(rs, "Longitude");
309
			Integer errorRadius = nullSafeInt(rs,"Prec");
310
			String geoCodeMethod = rs.getString("GeoCodeMethod");
311
			
312
			Integer altitude = nullSafeInt(rs, "Altitude");
313
			Integer lowerAltitude = nullSafeInt(rs,"AltitudeLowerValue");
314
			String altitudeUnit = rs.getString("AltitudeUnit");
315
			Double depth = nullSafeDouble(rs, "Depth");
316
			Double depthLow = nullSafeDouble(rs, "DepthLow");
317
			   	
318
			String collectorsNumber = rs.getString("CollectorsNumber");
319
			Date collectionDateStart = rs.getDate("CollectionDate");
320
			Date collectionDateEnd = rs.getDate("CollectionDateEnd");
321
			
322
			String climateUuid = rs.getString("climateUuid");
323
			String habitatUuid = rs.getString("habitatUuid");
324
			String lifeFormUuid = rs.getString("lifeFormUuid");
325
			
326
			String habitat = rs.getString("HabitatExplanation");
327
			String community = rs.getString("Comunity");
328
			String additionalData = rs.getString("AdditionalData");
329
			
330
			
331
			
332
			FieldObservation fieldObservation = facade.innerFieldObservation();
333
			
334
			//alkalinity marker
335
			if (alkalinityFlag != null){
336
				MarkerType alkalinityMarkerType = getMarkerType(state, uuidMarkerAlkalinity, "Alkalinity", "Alkalinity", null);
337
				boolean alkFlag = Boolean.valueOf(alkalinityFlag.toString());
338
				Marker alkalinityMarker = Marker.NewInstance(alkalinityMarkerType, alkFlag);
339
				fieldObservation.addMarker(alkalinityMarker);
340
			}
341
			
342
			//location
343
			facade.setLocality(locality);
344
			    	
345
			//exact location
346
			ReferenceSystem referenceSystem = makeRefrenceSystem(geoCodeMethod, state);
347
			Point exactLocation = Point.NewInstance(longitude, latitude, referenceSystem, errorRadius);
348
			facade.setExactLocation(exactLocation);
349
			
350
			//altitude, depth
351
			if (StringUtils.isNotBlank(altitudeUnit) && ! altitudeUnit.trim().equalsIgnoreCase("m")){
352
				logger.warn("Altitude unit is not [m] but: " +  altitudeUnit);
353
			}
354
			if ( altitude != null){
355
				if (lowerAltitude == null){
356
					facade.setAbsoluteElevation(altitude);
357
				}else{
358
			   		if (! facade.isEvenDistance(lowerAltitude, altitude)){
359
			   			//FIXME there is a ticket for this
360
			   			altitude = altitude + 1;
361
			   			logger.warn("Current implementation of altitude does not allow uneven distances");
362
			   		}
363
					facade.setAbsoluteElevationRange(lowerAltitude,altitude);
364
			   	}
365
			}
366
			if ( depth != null){
367
				//FIXME needs model change to accept double #3072
368
				Integer intDepth = depth.intValue();
369
				if (depthLow == null){
370
					facade.setDistanceToWaterSurface(intDepth);
371
				}else{
372
					//FIXME range not yet in model #3074
373
			   		facade.setDistanceToWaterSurface(intDepth);
374
			   	}
375
			}
376
			
377
			//habitat, ecology, community, etc.
378
			DescriptionBase<?> fieldDescription = getFieldObservationDescription(facade);
379
			addCategoricalValue(state, fieldDescription, climateUuid, uuidFeatureAlgaTerraClimate);
380
			addCategoricalValue(state, fieldDescription, habitatUuid, Feature.HABITAT().getUuid());
381
			addCategoricalValue(state, fieldDescription, lifeFormUuid, uuidFeatureAlgaTerraLifeForm);
382
			
383
			if (isNotBlank(habitat)){
384
				//FIXME
385
				facade.setEcology(habitat);  //or use an own feature ??
386
			}
387
			if (isNotBlank(community)){
388
				Feature communityFeature = getFeature(state, uuidFeatureSpecimenCommunity, "Community", "The community of a specimen (e.g. other algae in the same sample)", null, null);
389
				TextData textData = TextData.NewInstance(communityFeature);
390
				textData.putText(Language.DEFAULT(), community);
391
				getFieldObservationDescription(facade).addElement(textData);
392
			}
393
			if (isNotBlank(additionalData)){  //or handle it as Annotation ??
394
				Feature additionalDataFeature = getFeature(state, uuidFeatureAdditionalData, "Additional Data", "Additional Data", null, null);
395
				TextData textData = TextData.NewInstance(additionalDataFeature);
396
				textData.putText(Language.DEFAULT(), additionalData);
397
				getFieldObservationDescription(facade).addElement(textData);
398
			}
399
			
400
			//field
401
			facade.setFieldNumber(collectorsNumber);
402
			TimePeriod gatheringPeriod = TimePeriod.NewInstance(collectionDateStart, collectionDateEnd);
403
			facade.setGatheringPeriod(gatheringPeriod);
404
			handleCollectorTeam(state, facade, rs);
405
			
406
			//areas
407
			makeAreas(state, rs, facade);
408
			
409
			//parameters
410
			//TODO
411
			
412
			//notes
413
			//TODO is this an annotation on field observation or on the derived unit?
414
			
415
			//TODO id, created for fact +  ecoFact
416
			//    	this.doIdCreatedUpdatedNotes(state, descriptionElement, rs, id, namespace);
417
		
418
		} catch (IllegalArgumentException e) {
419
			throw e;
420
		}
189 421
    	
190
    	//field
191
    	facade.setFieldNumber(collectorsNumber);
192
     	
422
	}
423

  
424

  
425
	private void addCategoricalValue(AlgaTerraImportState importState, DescriptionBase description, String uuidTerm, UUID featureUuid) {
426
		if (uuidTerm != null){
427
			State state = this.getStateTerm(importState, UUID.fromString(uuidTerm));
428
			Feature feature = getFeature(importState, featureUuid);
429
			CategoricalData categoricalData = CategoricalData.NewInstance(state, feature);
430
			description.addElement(categoricalData);
431
		}
432
	}
433

  
434

  
435
	private void handleCollectorTeam(AlgaTerraImportState state, DerivedUnitFacade facade, ResultSet rs) throws SQLException {
436
		// FIXME parsen
437
		String collector = rs.getString("Collector");
438
		Team team = Team.NewTitledInstance(collector, collector);
439
		facade.setCollector(team);
440
		
441
		
442
		
443
	}
444

  
445
	private void makeAreas(AlgaTerraImportState state, ResultSet rs, DerivedUnitFacade facade) throws SQLException {
446
	   	Object gazetteerId = rs.getObject("GazetteerId");
447
	   	if (gazetteerId != null){
448
	   		//TDWG
449
	   		NamedArea tdwgArea;
450
	   		String tdwg4 = rs.getString("L4Code");
451
	   		if (isNotBlank(tdwg4)){
452
	   			tdwgArea = TdwgArea.getAreaByTdwgAbbreviation(tdwg4);
453
	   		}else{
454
	   			String tdwg3 = rs.getString("L3Code");
455
	   			if (isNotBlank(tdwg3)){
456
	   				tdwgArea = TdwgArea.getAreaByTdwgAbbreviation(tdwg3);
457
	   			}else{
458
	   				Integer tdwg2 = rs.getInt("L2Code");   				
459
	   				tdwgArea = TdwgArea.getAreaByTdwgAbbreviation(String.valueOf(tdwg2));
460
		   		}
461
	   		}
462
	   		if (tdwgArea == null){
463
	   			logger.warn("TDWG area could not be defined for gazetterId: " + gazetteerId);
464
	   		}else{
465
	   			facade.addCollectingArea(tdwgArea);
466
	   		}
467
	   		
468
	   		//Countries
469
	   		WaterbodyOrCountry country = null;
470
	   		String isoCountry = rs.getString("ISOCountry");
471
	   		String countryStr = rs.getString("Country");
472
	   		if (isNotBlank(isoCountry)){
473
		   		country = WaterbodyOrCountry.getWaterbodyOrCountryByIso3166A2(isoCountry);
474
	   		}else if (isNotBlank(countryStr)){
475
	   			logger.warn("Country exists but no ISO code");
476
	   		}
477
	   		if (country == null){
478
	   			logger.warn("Country does not exist for GazetteerID " + gazetteerId);
479
	   		}else{
480
	   			facade.setCountry(country);
481
	   		}
482
	   		
483
	   	}
484
	    
485
	   	//Waterbody
486
	   	WaterbodyOrCountry waterbody = null;
487
	   	String waterbodyStr = rs.getString("WaterBody");
488
	   	if (isNotBlank(waterbodyStr)){
489
	   		if (waterbodyStr.equals("Atlantic Ocean")){
490
	   			waterbody = WaterbodyOrCountry.ATLANTICOCEAN();
491
	   		}else{
492
	   			logger.warn("Waterbody not recognized: " + waterbody);
493
	   		}
494
	   		if (waterbody != null){
495
	   			facade.addCollectingArea(waterbody);
496
	   		}
497
	   	}
498

  
499
		
500
	   	//countries sub
501
	   	//TODO
502
	}
503

  
504
	private DescriptionBase getFieldObservationDescription(DerivedUnitFacade facade) {
505
		Set<DescriptionBase> descriptions = facade.innerFieldObservation().getDescriptions();
506
		for (DescriptionBase desc : descriptions){
507
			if (desc.isImageGallery() == false){
508
				return desc;
509
			}
510
		}
511
		SpecimenDescription specDesc = SpecimenDescription.NewInstance(facade.innerFieldObservation());
512
		descriptions.add(specDesc);
513
		return specDesc;
514
	}
515

  
516
	private ReferenceSystem makeRefrenceSystem(String geoCodeMethod, AlgaTerraImportState state) {
517
		if (StringUtils.isBlank(geoCodeMethod)){
518
			return null;
519
		}else if(geoCodeMethod.startsWith("GPS")){
520
			getReferenceSystem(state, uuidRefSystemGps, "GPS", "GPS", "GPS", ReferenceSystem.GOOGLE_EARTH().getVocabulary());
521
			return ReferenceSystem.WGS84(); 
522
		}else if(geoCodeMethod.startsWith("Google")){
523
			return ReferenceSystem.GOOGLE_EARTH();
524
		}else if(geoCodeMethod.startsWith("Map")){
525
			logger.warn("Reference system " +  geoCodeMethod +  " not yet supported.");
526
			return null;
527
		}else if(geoCodeMethod.startsWith("WikiProjekt Georeferenzierung") || geoCodeMethod.startsWith("http://toolserver.org/~geohack/geohack.php") ){
528
			return ReferenceSystem.WGS84();
529
		}else {
530
			logger.warn("Reference system " +  geoCodeMethod +  " not yet supported.");
531
			return null;
532
		}
533
	}
534

  
535
	private FieldObservation getFieldObservation(int ecoFactId, Map<String, FieldObservation> fieldObservationMap) {
536
		String key = String.valueOf(ecoFactId);
537
		FieldObservation fieldObservation = fieldObservationMap.get(key);
538
		if (fieldObservation == null){
539
			fieldObservation = FieldObservation.NewInstance();
540
			
541
			fieldObservationMap.put(key, fieldObservation);
542
		}
543
		
544
		return fieldObservation;
193 545
	}
194 546
	
195 547
	private Feature makeFeature(DerivedUnitType type) {
......
238 590
		
239 591
		try{
240 592
			Set<String> taxonIdSet = new HashSet<String>();
593
			Set<String> fieldObservationIdSet = new HashSet<String>();
594
			Set<String> termsIdSet = new HashSet<String>();
595
			
241 596
			while (rs.next()){
242 597
				handleForeignKey(rs, taxonIdSet, "taxonId");
598
				handleForeignKey(rs, fieldObservationIdSet, "ecoFactId");
599
				handleForeignKey(rs, termsIdSet, "ClimateFk");
600
				handleForeignKey(rs, termsIdSet, "HabitatFk");
601
				handleForeignKey(rs, termsIdSet, "LifeFormFk");
243 602
			}
244 603
			
245 604
			//taxon map
......
249 608
			Map<String, TaxonBase> objectMap = (Map<String, TaxonBase>)getCommonService().getSourcedObjectsByIdInSource(cdmClass, idSet, nameSpace);
250 609
			result.put(nameSpace, objectMap);
251 610

  
611
			//field observation map map
612
			nameSpace = AlgaTerraSpecimenImport.FIELD_OBSERVATION_NAMESPACE;
613
			cdmClass = FieldObservation.class;
614
			idSet = taxonIdSet;
615
			Map<String, FieldObservation> fieldObservationMap = (Map<String, FieldObservation>)getCommonService().getSourcedObjectsByIdInSource(cdmClass, idSet, nameSpace);
616
			result.put(nameSpace, fieldObservationMap);
617

  
618
			//terms
619
			nameSpace = AlgaTerraSpecimenImport.TERMS_NAMESPACE;
620
			cdmClass = FieldObservation.class;
621
			idSet = taxonIdSet;
622
			Map<String, DefinedTermBase> termMap = (Map<String, DefinedTermBase>)getCommonService().getSourcedObjectsByIdInSource(cdmClass, idSet, nameSpace);
623
			result.put(nameSpace, termMap);
624

  
625
		
626
			
627
			
252 628
		} catch (SQLException e) {
253 629
			throw new RuntimeException(e);
254 630
		}
......
258 634

  
259 635
	/**
260 636
	 * Use same TaxonDescription if two records belong to the same taxon 
637
	 * @param state 
261 638
	 * @param newTaxonId
262 639
	 * @param oldTaxonId
263 640
	 * @param oldDescription
264 641
	 * @param taxonMap
265 642
	 * @return
266 643
	 */
267
	private TaxonDescription getTaxonDescription(int newTaxonId, int oldTaxonId, TaxonDescription oldDescription, Map<String, TaxonBase> taxonMap, int factId, Reference<?> sourceSec){
644
	private TaxonDescription getTaxonDescription(AlgaTerraImportState state, int newTaxonId, Map<String, TaxonBase> taxonMap, int factId, Reference<?> sourceSec){
268 645
		TaxonDescription result = null;
269
		if (oldDescription == null || newTaxonId != oldTaxonId){
270
			TaxonBase<?> taxonBase = taxonMap.get(String.valueOf(newTaxonId));
271
			//TODO for testing
272
			//TaxonBase taxonBase = Taxon.NewInstance(BotanicalName.NewInstance(Rank.SPECIES()), null);
273
			Taxon taxon;
274
			if ( taxonBase instanceof Taxon ) {
275
				taxon = (Taxon) taxonBase;
276
			} else if (taxonBase != null) {
277
				logger.warn("TaxonBase for Fact(Specimen) with factId" + factId + " was not of type Taxon but: " + taxonBase.getClass().getSimpleName());
278
				return null;
279
			} else {
280
				logger.warn("TaxonBase for Fact(Specimen) " + factId + " is null.");
281
				return null;
282
			}		
283
			Set<TaxonDescription> descriptionSet= taxon.getDescriptions();
284
			if (descriptionSet.size() > 0) {
285
				result = descriptionSet.iterator().next(); 
286
			}else{
287
				result = TaxonDescription.NewInstance();
288
				result.setTitleCache(sourceSec.getTitleCache(), true);
289
				taxon.addDescription(result);
290
			}
646
		TaxonBase<?> taxonBase = taxonMap.get(String.valueOf(newTaxonId));
647
		
648
		//TODO for testing
649
		if (taxonBase == null && ! state.getConfig().isDoTaxa()){
650
			taxonBase = Taxon.NewInstance(BotanicalName.NewInstance(Rank.SPECIES()), null);
651
		}
652
		
653
		Taxon taxon;
654
		if ( taxonBase instanceof Taxon ) {
655
			taxon = (Taxon) taxonBase;
656
		} else if (taxonBase != null) {
657
			logger.warn("TaxonBase for Fact(Specimen) with factId" + factId + " was not of type Taxon but: " + taxonBase.getClass().getSimpleName());
658
			return null;
659
		} else {
660
			logger.warn("TaxonBase for Fact(Specimen) " + factId + " is null.");
661
			return null;
662
		}		
663
		Set<TaxonDescription> descriptionSet= taxon.getDescriptions();
664
		if (descriptionSet.size() > 0) {
665
			result = descriptionSet.iterator().next(); 
291 666
		}else{
292
			result = oldDescription;
667
			result = TaxonDescription.NewInstance();
668
			result.setTitleCache(sourceSec.getTitleCache(), true);
669
			taxon.addDescription(result);
293 670
		}
294 671
		return result;
295 672
	}

Also available in: Unified diff