Project

General

Profile

Download (15.3 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.berlinModel.in;
11

    
12
import static eu.etaxonomy.cdm.io.berlinModel.BerlinModelTransformer.T_STATUS_ACCEPTED;
13
import static eu.etaxonomy.cdm.io.berlinModel.BerlinModelTransformer.T_STATUS_PARTIAL_SYN;
14
import static eu.etaxonomy.cdm.io.berlinModel.BerlinModelTransformer.T_STATUS_PRO_PARTE_SYN;
15
import static eu.etaxonomy.cdm.io.berlinModel.BerlinModelTransformer.T_STATUS_SYNONYM;
16
import static eu.etaxonomy.cdm.io.berlinModel.BerlinModelTransformer.T_STATUS_UNRESOLVED;
17

    
18
import java.lang.reflect.Method;
19
import java.sql.ResultSet;
20
import java.sql.SQLException;
21
import java.util.HashMap;
22
import java.util.HashSet;
23
import java.util.Map;
24
import java.util.Set;
25
import java.util.UUID;
26

    
27
import org.apache.commons.lang.StringUtils;
28
import org.apache.log4j.Logger;
29
import org.springframework.stereotype.Component;
30

    
31
import eu.etaxonomy.cdm.database.update.DatabaseTypeNotSupportedException;
32
import eu.etaxonomy.cdm.io.berlinModel.BerlinModelTransformer;
33
import eu.etaxonomy.cdm.io.berlinModel.in.validation.BerlinModelTaxonImportValidator;
34
import eu.etaxonomy.cdm.io.common.IOValidator;
35
import eu.etaxonomy.cdm.io.common.ResultSetPartitioner;
36
import eu.etaxonomy.cdm.model.agent.Person;
37
import eu.etaxonomy.cdm.model.common.CdmBase;
38
import eu.etaxonomy.cdm.model.common.Extension;
39
import eu.etaxonomy.cdm.model.common.ExtensionType;
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.description.Feature;
44
import eu.etaxonomy.cdm.model.description.TaxonDescription;
45
import eu.etaxonomy.cdm.model.description.TextData;
46
import eu.etaxonomy.cdm.model.name.TaxonName;
47
import eu.etaxonomy.cdm.model.reference.Reference;
48
import eu.etaxonomy.cdm.model.taxon.Synonym;
49
import eu.etaxonomy.cdm.model.taxon.Taxon;
50
import eu.etaxonomy.cdm.model.taxon.TaxonBase;
51

    
52

    
53
/**
54
 * @author a.mueller
55
 * @since 20.03.2008
56
 */
57
@Component
58
public class BerlinModelTaxonImport  extends BerlinModelImportBase {
59
    /**
60
     *
61
     */
62
    private static final String LAST_SCRUTINY_FK = "lastScrutinyFk";
63

    
64
    private static final long serialVersionUID = -1186364983750790695L;
65

    
66
    private static final Logger logger = Logger.getLogger(BerlinModelTaxonImport.class);
67

    
68
	public static final String NAMESPACE = "Taxon";
69

    
70
	private static final String pluralString = "Taxa";
71
	private static final String dbTableName = "PTaxon";
72

    
73
	/**
74
	 * How should the publish flag in table PTaxon be interpreted
75
	 * NO_MARKER: No marker is set
76
	 * ONLY_FALSE:
77
	 */
78
	public enum PublishMarkerChooser{
79
		NO_MARKER,
80
		ONLY_FALSE,
81
		ONLY_TRUE,
82
		ALL;
83

    
84
		boolean doMark(boolean value){
85
			if (value == true){
86
				return this == ALL || this == ONLY_TRUE;
87
			}else{
88
				return this == ALL || this == ONLY_FALSE;
89
			}
90
		}
91
	}
92

    
93
	public BerlinModelTaxonImport(){
94
		super(dbTableName, pluralString);
95
	}
96

    
97
	@Override
98
	protected String getIdQuery(BerlinModelImportState state) {
99
		String sqlSelect = " SELECT RIdentifier";
100
		String taxonTable = state.getConfig().getTaxonTable();
101
		String sqlFrom = String.format(" FROM %s ", taxonTable);
102
		String sqlWhere = "";
103

    
104
		String sql = sqlSelect + " " + sqlFrom + " " + sqlWhere ;
105
		return sql;
106
	}
107

    
108
	@Override
109
	protected String getRecordQuery(BerlinModelImportConfigurator config) {
110
		String sqlSelect = " SELECT pt.*  ";
111
		String sqlFrom = " FROM PTaxon pt ";
112
		if (config.isEuroMed()){
113
			sqlFrom = " FROM PTaxon AS pt " +
114
							" INNER JOIN v_cdm_exp_taxaAll AS em ON pt.RIdentifier = em.RIdentifier ";
115
			if (!config.isUseLastScrutinyAsSec()){
116
			    sqlFrom += " LEFT OUTER JOIN Reference r ON pt.LastScrutinyFk = r.RefId ";
117
			}
118
			sqlSelect += " , em.MA ";
119
			if (!config.isUseLastScrutinyAsSec()){
120
			    sqlSelect += ", r.RefCache as LastScrutiny ";
121
            }
122
		}
123

    
124

    
125
		String sqlWhere = " WHERE ( pt.RIdentifier IN (" + ID_LIST_TOKEN + ") )";
126

    
127
		String strRecordQuery =sqlSelect + " " + sqlFrom + " " + sqlWhere ;
128
//			" SELECT * " +
129
//			" FROM PTaxon " + state.getConfig().getTaxonTable();
130
//			" WHERE ( RIdentifier IN (" + ID_LIST_TOKEN + ") )";
131
		return strRecordQuery;
132
	}
133

    
134
	@Override
135
	protected boolean doCheck(BerlinModelImportState state){
136
		IOValidator<BerlinModelImportState> validator = new BerlinModelTaxonImportValidator();
137
		return validator.validate(state);
138
	}
139

    
140
	@Override
141
	public boolean doPartition(ResultSetPartitioner partitioner, BerlinModelImportState state) {
142
		boolean success = true ;
143

    
144
		BerlinModelImportConfigurator config = state.getConfig();
145
		Set<TaxonBase> taxaToSave = new HashSet<>();
146
		Map<String, TaxonName> taxonNameMap = partitioner.getObjectMap(BerlinModelTaxonNameImport.NAMESPACE);
147
		Map<String, Reference> refMap = partitioner.getObjectMap(BerlinModelReferenceImport.REFERENCE_NAMESPACE);
148

    
149
		ResultSet rs = partitioner.getResultSet();
150
		try{
151
			boolean publishFlagExists = state.getConfig().getSource().checkColumnExists("PTaxon", "PublishFlag");
152
			boolean isEuroMed = config.isEuroMed();
153
			while (rs.next()){
154

    
155
			//	if ((i++ % modCount) == 0 && i!= 1 ){ logger.info("PTaxa handled: " + (i-1));}
156

    
157
				//create TaxonName element
158
				int taxonId = rs.getInt("RIdentifier");
159
				int statusFk = rs.getInt("statusFk");
160

    
161
				int nameFk = rs.getInt("PTNameFk");
162
				int refFkInt = rs.getInt("PTRefFk");
163
				String doubtful = rs.getString("DoubtfulFlag");
164
				String uuid = null;
165
				if (resultSetHasColumn(rs,"UUID")){
166
					uuid = rs.getString("UUID");
167
				}
168

    
169

    
170
				TaxonName taxonName = null;
171
				taxonName  = taxonNameMap.get(String.valueOf(nameFk));
172

    
173
				Reference reference = null;
174
				String refFkStr = String.valueOf(refFkInt);
175
				reference = refMap.get(refFkStr);
176

    
177
				Reference lastScrutinyRef = null;
178
                if (state.getConfig().isUseLastScrutinyAsSec() && resultSetHasColumn(rs,LAST_SCRUTINY_FK)){
179
                    Integer lastScrutinyFk = nullSafeInt(rs,LAST_SCRUTINY_FK);
180
                    if (lastScrutinyFk != null){
181
                        String lastScrutinyFkStr = String.valueOf(lastScrutinyFk);
182
                        if (lastScrutinyFkStr != null){
183
                            lastScrutinyRef = refMap.get(lastScrutinyFkStr);
184
                            if (lastScrutinyRef == null){
185
                                logger.warn("Last scrutiny reference "+lastScrutinyFkStr+" could not be found "
186
                                        + "for taxon " + taxonId);
187
                            }
188
                            if(!StringUtils.right(refFkStr, 5).equals("00000")){
189
                                logger.warn("Unexpected secFk " + refFkStr + " for taxon with last scrutiny. Taxon id " + taxonId);
190
                            }
191
                        }
192
                    }
193
                }
194

    
195
				if(! config.isIgnoreNull()){
196
					if (taxonName == null ){
197
						logger.warn("TaxonName belonging to taxon (RIdentifier = " + taxonId + ") could not be found in store. Taxon will not be imported");
198
						success = false;
199
						continue; //next taxon
200
					}else if (reference == null ){
201
						logger.warn("Sec Reference belonging to taxon could not be found in store. Taxon will not be imported");
202
						success = false;
203
						continue; //next taxon
204
					}
205
				}
206
				TaxonBase<?> taxonBase;
207
				Synonym synonym;
208
				Taxon taxon;
209
				Reference sec = lastScrutinyRef != null? lastScrutinyRef: reference;
210
				try {
211
					logger.debug(statusFk);
212
					if (statusFk == T_STATUS_ACCEPTED || statusFk == T_STATUS_UNRESOLVED
213
					        || statusFk == T_STATUS_PRO_PARTE_SYN || statusFk == T_STATUS_PARTIAL_SYN ){
214
						taxon = Taxon.NewInstance(taxonName, sec);
215
						taxonBase = taxon;
216
						if (statusFk == T_STATUS_UNRESOLVED){
217
							taxon.setTaxonStatusUnknown(true);
218
						}
219
						//TODO marker for pp and partial?
220
					}else if (statusFk == T_STATUS_SYNONYM ){
221
						synonym = Synonym.NewInstance(taxonName, sec);
222
						taxonBase = synonym;
223
//						if (statusFk == T_STATUS_PRO_PARTE_SYN){
224
//						    synonym.setProParte(true);
225
//						}
226
//						if (statusFk == T_STATUS_PARTIAL_SYN){
227
//							synonym.setPartial(true);
228
//						}
229
					}else{
230
						logger.warn("TaxonStatus " + statusFk + " not yet implemented. Taxon (RIdentifier = " + taxonId + ") left out.");
231
						success = false;
232
						continue;
233
					}
234
					if (uuid != null){
235
						taxonBase.setUuid(UUID.fromString(uuid));
236
					}
237

    
238
					//doubtful
239
					if (doubtful.equals("a")){
240
						taxonBase.setDoubtful(false);
241
					}else if(doubtful.equals("d")){
242
						taxonBase.setDoubtful(true);
243
					}else if(doubtful.equals("i")){
244
						taxonBase.setDoubtful(false);
245
						logger.warn("Doubtful = i (inactivated) does not exist in CDM. Doubtful set to false. RIdentifier: " + taxonId);
246
					}
247

    
248
					//detail
249
					String detail = rs.getString("Detail");
250
					if (isNotBlank(detail)){
251
						ExtensionType detailExtensionType = getExtensionType(state, BerlinModelTransformer.DETAIL_EXT_UUID, "micro reference","micro reference","micro ref.");
252
						Extension.NewInstance(taxonBase, detail, detailExtensionType);
253
					}
254
					//idInSource
255
					String idInSource = rs.getString("IdInSource");
256
					if (isNotBlank(idInSource)){
257
						ExtensionType detailExtensionType = getExtensionType(state, BerlinModelTransformer.ID_IN_SOURCE_EXT_UUID, "Berlin Model IdInSource","Berlin Model IdInSource","BM source id");
258
						Extension.NewInstance(taxonBase, idInSource, detailExtensionType);
259
					}
260
					//namePhrase
261
					String namePhrase = rs.getString("NamePhrase");
262
					if (StringUtils.isNotBlank(namePhrase)){
263
						taxonBase.setAppendedPhrase(namePhrase);
264
					}
265
					//useNameCache
266
					Boolean useNameCacheFlag = rs.getBoolean("UseNameCacheFlag");
267
					if (useNameCacheFlag){
268
						taxonBase.setUseNameCache(true);
269
					}
270
					//publisheFlag
271
					if (publishFlagExists){
272
						Boolean publishFlag = rs.getBoolean("PublishFlag");
273
						Boolean misapplied = false;
274
						if (isEuroMed){
275
							misapplied = rs.getBoolean("MA");
276
						}
277

    
278
						if ( ! misapplied){
279
							taxonBase.setPublish(publishFlag);
280
						}
281
					}
282

    
283
					//  does not exist anymore as we use last scrutiny now as sec ref
284
					if (!state.getConfig().isUseLastScrutinyAsSec() && resultSetHasColumn(rs, "LastScrutiny")){
285
						String lastScrutiny = rs.getString("LastScrutiny");
286
						//TODO strange, why not Extension last scrutiny? To match PESI? Is there a difference
287
						//to LastScrutinyFK and SpeciesExpertFK?
288
						if (isNotBlank(lastScrutiny)){
289
						    ExtensionType extensionTypeSpeciesExpert = getExtensionType(state, BerlinModelTransformer.uuidSpeciesExpertName, "Species Expert", "Species Expert", "Species Expert");
290
						    taxonBase.addExtension(lastScrutiny, extensionTypeSpeciesExpert);
291
						    ExtensionType extensionTypeExpert = getExtensionType(state, BerlinModelTransformer.uuidExpertName, "Expert", "Expert for a taxonomic group", "Expert");
292
						    taxonBase.addExtension(lastScrutiny, extensionTypeExpert);
293
						}
294
					}
295
					//
296
					if (resultSetHasColumn(rs, "IsExcludedMarker")){
297
					    boolean isExcluded = rs.getBoolean("IsExcludedMarker");
298
					    if (isExcluded){
299
					        String extension = rs.getString("IsExcludedExtension");
300
					        String valueless = "not accepted: taxonomically valueless local or singular biotype";
301
					        String provisional = "provisional: probably a taxonomically valueless local or singular biotype";
302

    
303
					        MarkerType markerType = null;
304
					        if (valueless.equals(extension)){
305
					            markerType = getMarkerType(state, BerlinModelTransformer.uuidTaxonomicallyValueless, "taxonomically valueless", valueless, "valueless", getEuroMedMarkerTypeVoc());
306
					        }else if (provisional.equals(extension)){
307
                                markerType = getMarkerType(state, BerlinModelTransformer.uuidProbablyTaxonomicallyValueless, "probably taxonomically valueless", provisional, "provisional", getEuroMedMarkerTypeVoc());
308
                            }
309
					        if (markerType != null){
310
					            taxonBase.addMarker(Marker.NewInstance(markerType, true));
311
					        }else{
312
					            logger.warn("IsExcludedExtension not regonized for taxon " + taxonId + "; " + extension);
313
					        }
314
					    }
315
					}
316

    
317
					//Notes
318
					boolean excludeNotes = state.getConfig().isTaxonNoteAsFeature() && taxonBase.isInstanceOf(Taxon.class);
319
					doIdCreatedUpdatedNotes(state, taxonBase, rs, taxonId, NAMESPACE, false, excludeNotes);
320
					if (excludeNotes){
321
					    makeTaxonomicNote(state, CdmBase.deproxy(taxonBase, Taxon.class), rs.getString("Notes"));
322
					}
323

    
324
					//external url
325
					if (config.getMakeUrlForTaxon() != null){
326
						Method urlMethod = config.getMakeUrlForTaxon();
327
						urlMethod.invoke(null, taxonBase, rs);
328
					}
329

    
330
					partitioner.startDoSave();
331
					taxaToSave.add(taxonBase);
332
				} catch (Exception e) {
333
					logger.warn("An exception (" +e.getMessage()+") occurred when creating taxon with id " + taxonId + ". Taxon could not be saved.");
334
					success = false;
335
				}
336
			}
337
		} catch (DatabaseTypeNotSupportedException e) {
338
			logger.error("MethodNotSupportedException:" +  e);
339
			return false;
340
		} catch (Exception e) {
341
			logger.error("SQLException:" +  e);
342
			return false;
343
		}
344

    
345

    
346
		//	logger.info( i + " names handled");
347
		getTaxonService().save(taxaToSave);
348
		return success;
349
	}
350

    
351
	/**
352
     * @param state
353
     * @param taxonBase
354
	 * @param notes
355
     */
356
    private void makeTaxonomicNote(BerlinModelImportState state, Taxon taxon, String notes) {
357
        if (isNotBlank(notes)){
358
            TaxonDescription desc = getTaxonDescription(taxon, false, true);
359
            desc.setDefault(true);  //hard coded for Salvador, not used elsewhere as far as I can see
360
            TextData textData = TextData.NewInstance(Feature.NOTES() , notes, Language.SPANISH_CASTILIAN(), null);
361
            desc.addElement(textData);
362
        }
363
    }
364

    
365
    @Override
366
	public Map<Object, Map<String, ? extends CdmBase>> getRelatedObjectsForPartition(ResultSet rs, BerlinModelImportState state) {
367
		String nameSpace;
368
		Class<?> cdmClass;
369
		Set<String> idSet;
370
		Map<Object, Map<String, ? extends CdmBase>> result = new HashMap<>();
371

    
372
		try{
373
			Set<String> nameIdSet = new HashSet<>();
374
			Set<String> referenceIdSet = new HashSet<>();
375
			while (rs.next()){
376
				handleForeignKey(rs, nameIdSet, "PTNameFk");
377
				handleForeignKey(rs, referenceIdSet, "PTRefFk");
378
				if (state.getConfig().isUseLastScrutinyAsSec() && resultSetHasColumn(rs, LAST_SCRUTINY_FK)){
379
				    handleForeignKey(rs, referenceIdSet, LAST_SCRUTINY_FK);
380
				}
381
			}
382

    
383
			//name map
384
			nameSpace = BerlinModelTaxonNameImport.NAMESPACE;
385
			cdmClass = TaxonName.class;
386
			idSet = nameIdSet;
387
			Map<String, Person> nameMap = (Map<String, Person>)getCommonService().getSourcedObjectsByIdInSource(cdmClass, idSet, nameSpace);
388
			result.put(nameSpace, nameMap);
389

    
390
			//reference map
391
			nameSpace = BerlinModelReferenceImport.REFERENCE_NAMESPACE;
392
			cdmClass = Reference.class;
393
			idSet = referenceIdSet;
394
			Map<String, Reference> referenceMap = (Map<String, Reference>)getCommonService().getSourcedObjectsByIdInSource(cdmClass, idSet, nameSpace);
395
			result.put(nameSpace, referenceMap);
396

    
397
		} catch (SQLException e) {
398
			throw new RuntimeException(e);
399
		}
400
		return result;
401
	}
402

    
403
	@Override
404
	protected String getTableName() {
405
		return dbTableName;
406
	}
407

    
408
	@Override
409
	public String getPluralString() {
410
		return pluralString;
411
	}
412

    
413
	@Override
414
	protected boolean isIgnore(BerlinModelImportState state){
415
		return ! state.getConfig().isDoTaxa();
416
	}
417

    
418
}
(14-14/21)