Project

General

Profile

Download (41 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.pesi.faunaEuropaea;
11

    
12
import static eu.etaxonomy.cdm.io.pesi.faunaEuropaea.FaunaEuropaeaTransformer.P_PARENTHESIS;
13
import static eu.etaxonomy.cdm.io.pesi.faunaEuropaea.FaunaEuropaeaTransformer.R_GENUS;
14
import static eu.etaxonomy.cdm.io.pesi.faunaEuropaea.FaunaEuropaeaTransformer.R_SPECIES;
15
import static eu.etaxonomy.cdm.io.pesi.faunaEuropaea.FaunaEuropaeaTransformer.R_SUBGENUS;
16
import static eu.etaxonomy.cdm.io.pesi.faunaEuropaea.FaunaEuropaeaTransformer.R_SUBSPECIES;
17
import static eu.etaxonomy.cdm.io.pesi.faunaEuropaea.FaunaEuropaeaTransformer.T_STATUS_ACCEPTED;
18
import static eu.etaxonomy.cdm.io.pesi.faunaEuropaea.FaunaEuropaeaTransformer.T_STATUS_NOT_ACCEPTED;
19

    
20
import java.sql.ResultSet;
21
import java.sql.SQLException;
22
import java.sql.Timestamp;
23
import java.util.Collection;
24
import java.util.HashMap;
25
import java.util.HashSet;
26
import java.util.Map;
27
import java.util.Set;
28
import java.util.UUID;
29

    
30
import org.apache.commons.lang.StringUtils;
31
import org.apache.log4j.Logger;
32
import org.joda.time.DateTime;
33
import org.springframework.stereotype.Component;
34
import org.springframework.transaction.TransactionStatus;
35

    
36

    
37

    
38

    
39
import eu.etaxonomy.cdm.common.CdmUtils;
40
import eu.etaxonomy.cdm.io.common.ICdmIO;
41
import eu.etaxonomy.cdm.io.common.ImportHelper;
42
import eu.etaxonomy.cdm.io.common.MapWrapper;
43
import eu.etaxonomy.cdm.io.common.Source;
44
import eu.etaxonomy.cdm.io.pesi.out.PesiExportState;
45
import eu.etaxonomy.cdm.io.pesi.out.PesiTransformer;
46
import eu.etaxonomy.cdm.model.agent.TeamOrPersonBase;
47
import eu.etaxonomy.cdm.model.common.CdmBase;
48
import eu.etaxonomy.cdm.model.common.Extension;
49
import eu.etaxonomy.cdm.model.common.IdentifiableSource;
50
import eu.etaxonomy.cdm.model.common.LSID;
51
import eu.etaxonomy.cdm.model.common.Marker;
52
import eu.etaxonomy.cdm.model.common.MarkerType;
53
import eu.etaxonomy.cdm.model.name.NomenclaturalStatus;
54
import eu.etaxonomy.cdm.model.name.Rank;
55
import eu.etaxonomy.cdm.model.name.TaxonNameBase;
56
import eu.etaxonomy.cdm.model.name.ZoologicalName;
57
import eu.etaxonomy.cdm.model.reference.Reference;
58
import eu.etaxonomy.cdm.model.taxon.Synonym;
59
import eu.etaxonomy.cdm.model.taxon.Taxon;
60
import eu.etaxonomy.cdm.model.taxon.TaxonBase;
61
import eu.etaxonomy.cdm.strategy.exceptions.UnknownCdmTypeException;
62

    
63

    
64
/**
65
 * @author a.babadshanjan
66
 * @created 12.05.2009
67
 * @version 1.0
68
 */
69
@Component
70
public class FaunaEuropaeaTaxonNameImport extends FaunaEuropaeaImportBase  {
71
	
72
	public static final String OS_NAMESPACE_TAXON = "Taxon";
73
	
74
	private static final Logger logger = Logger.getLogger(FaunaEuropaeaTaxonNameImport.class);
75

    
76
	/* Max number of taxa to retrieve (for test purposes) */
77
	private int maxTaxa = 0;
78

    
79
	/* (non-Javadoc)
80
	 * @see eu.etaxonomy.cdm.io.common.CdmIoBase#doCheck(eu.etaxonomy.cdm.io.common.IImportConfigurator)
81
	 */
82
	@Override
83
	protected boolean doCheck(FaunaEuropaeaImportState state) {
84
		boolean result = true;
85
		FaunaEuropaeaImportConfigurator fauEuConfig = state.getConfig();
86
		logger.warn("Checking for Taxa not yet fully implemented");
87
//		result &= checkTaxonStatus(fauEuConfig);
88
		
89
		return result;
90
	}
91
	
92
	/* (non-Javadoc)
93
	 * @see eu.etaxonomy.cdm.io.common.CdmIoBase#isIgnore(eu.etaxonomy.cdm.io.common.IImportConfigurator)
94
	 */
95
	protected boolean isIgnore(FaunaEuropaeaImportState state) {
96
		return ! state.getConfig().isDoTaxa();
97
	}
98

    
99
	/** 
100
	 * Import taxa from FauEU DB
101
	 */
102
	protected void doInvoke(FaunaEuropaeaImportState state) {				
103
		if(logger.isInfoEnabled()) { logger.info("Start making taxa..."); }
104
		
105
		processTaxa(state);
106
		logger.info("End making taxa...");
107
		return;
108
	}
109

    
110

    
111
	/**
112
	 * Returns an empty string in case of a null string.
113
	 * This avoids having the string "null" when using StringBuilder.append(null);
114
	 * @param string
115
	 * @return
116
	 */
117
	private String NullToEmpty(String string) {
118
		if (string == null) {
119
			return "";
120
		} else {
121
			return string;
122
		}
123
	}
124

    
125
	/** Retrieve taxa from FauEu DB, process in blocks */
126
	private void processTaxa(FaunaEuropaeaImportState state) {
127

    
128
		int limit = state.getConfig().getLimitSave();
129

    
130
		TransactionStatus txStatus = null;
131

    
132
		Map<String, MapWrapper<? extends CdmBase>> stores = state.getStores();
133
		MapWrapper<TeamOrPersonBase> authorStore = (MapWrapper<TeamOrPersonBase>)stores.get(ICdmIO.TEAM_STORE);
134
		
135
		Map<Integer, TaxonBase<?>> taxonMap = null;
136
		Map<Integer, FaunaEuropaeaTaxon> fauEuTaxonMap = null;
137
		/* Store for heterotypic synonyms to be save separately */
138
		Set<Synonym> synonymSet = null;
139

    
140
		FaunaEuropaeaImportConfigurator fauEuConfig = state.getConfig();
141
		Reference<?> sourceRef = fauEuConfig.getSourceReference();
142

    
143
		Source source = fauEuConfig.getSource();
144
		int i = 0;
145
		
146
		String selectCount = 
147
			" SELECT count(*) ";
148

    
149
		String selectColumns = 
150
			" SELECT Parent.TAX_NAME AS P2Name, Parent.TAX_RNK_ID AS P2RankId, " +
151
			" GrandParent.TAX_ID AS GP3Id, GrandParent.TAX_NAME AS GP3Name, GrandParent.TAX_RNK_ID AS GP3RankId, " +
152
			" GreatGrandParent.TAX_ID AS GGP4Id, GreatGrandParent.TAX_NAME AS GGP4Name, GreatGrandParent.TAX_RNK_ID AS GGP4RankId, " +
153
			" GreatGreatGrandParent.TAX_ID AS GGGP5Id, GreatGreatGrandParent.TAX_NAME AS GGGP5Name, GreatGreatGrandParent.TAX_RNK_ID AS GGGP5RankId, " +
154
			" OriginalGenusTaxon.TAX_NAME AS OGenusName, " +
155
			" GreatGreatGreatGrandParent.TAX_ID AS GGGGP6Id, GreatGreatGreatGrandParent.TAX_NAME AS GGGGP6Name, GreatGreatGreatGrandParent.TAX_RNK_ID AS GGGGP6RankId," +
156
			" expertUsers.usr_id AS expertUserId, expertUsers.usr_title AS ExpertUsrTitle, expertUsers.usr_firstname AS ExpertUsrFirstname, expertUsers.usr_lastname AS ExpertUsrLastname," +
157
			" speciesExpertUsers.usr_id AS speciesExpertUserId, speciesExpertUsers.usr_title AS SpeciesUsrTitle, speciesExpertUsers.usr_firstname AS SpeciesUsrFirstname, speciesExpertUsers.usr_lastname AS SpeciesUsrLastname," +
158
			" Taxon.*, rank.*, author.* ";
159
		
160
		String fromClause = 
161
			" FROM Taxon LEFT OUTER JOIN " +
162
			" Taxon AS Parent ON Taxon.TAX_TAX_IDPARENT = Parent.TAX_ID LEFT OUTER JOIN " +
163
			" Taxon AS GrandParent ON Parent.TAX_TAX_IDPARENT = GrandParent.TAX_ID LEFT OUTER JOIN " +
164
			" Taxon AS GreatGrandParent ON GrandParent.TAX_TAX_IDPARENT = GreatGrandParent.TAX_ID LEFT OUTER JOIN " +
165
			" Taxon AS GreatGreatGrandParent ON GreatGrandParent.TAX_TAX_IDPARENT = GreatGreatGrandParent.TAX_ID LEFT OUTER JOIN " +
166
			" Taxon AS GreatGreatGreatGrandParent ON GreatGreatGrandParent.TAX_TAX_IDPARENT = GreatGreatGreatGrandParent.TAX_ID LEFT OUTER JOIN " +
167
			" Taxon AS OriginalGenusTaxon ON Taxon.TAX_TAX_IDGENUS = OriginalGenusTaxon.TAX_ID LEFT OUTER JOIN " +
168
			" author ON Taxon.TAX_AUT_ID = author.aut_id LEFT OUTER JOIN " +
169
			" users AS expertUsers ON Taxon.TAX_USR_IDGC = expertUsers.usr_id LEFT OUTER JOIN " +
170
			" users AS speciesExpertUsers ON Taxon.TAX_USR_IDSP = speciesExpertUsers.usr_id LEFT OUTER JOIN " +
171
			" rank ON Taxon.TAX_RNK_ID = rank.rnk_id ";
172

    
173
		String countQuery = 
174
			selectCount + fromClause;
175

    
176
		String selectQuery = 
177
			selectColumns + fromClause;
178
		
179

    
180
        try {
181

    
182
			ResultSet rs = source.getResultSet(countQuery);
183
			rs.next();
184
			int count = rs.getInt(1);
185
			
186
			rs = source.getResultSet(selectQuery);
187

    
188
	        if (logger.isInfoEnabled()) {
189
				logger.info("Number of rows: " + count);
190
				logger.info("Count Query: " + countQuery);
191
				logger.info("Select Query: " + selectQuery);
192
			}
193
	        
194
			while (rs.next()) {
195

    
196
				if ((i++ % limit) == 0) {
197
					
198
					txStatus = startTransaction();
199
					taxonMap = new HashMap<Integer, TaxonBase<?>>(limit);
200
					fauEuTaxonMap = new HashMap<Integer, FaunaEuropaeaTaxon>(limit);
201
					synonymSet = new HashSet<Synonym>();
202
					
203
					if(logger.isInfoEnabled()) {
204
						logger.info("i = " + i + " - Transaction started"); 
205
					}
206
				}
207

    
208
				String localName = rs.getString("TAX_NAME");
209
				String parentName = rs.getString("P2Name");
210
				int grandParentId = rs.getInt("GP3Id");
211
				String grandParentName = rs.getString("GP3Name");
212
				int greatGrandParentId = rs.getInt("GGP4Id");
213
				String greatGrandParentName = rs.getString("GGP4Name");
214
				int greatGreatGrandParentId = rs.getInt("GGGP5Id");
215
				String greatGreatGrandParentName = rs.getString("GGGP5Name");
216
				String greatGreatGreatGrandParentName = rs.getString("GGGGP6Name");
217
				String originalGenusName = rs.getString("OGenusName");
218
				String autName = rs.getString("aut_name");
219
				int taxonId = rs.getInt("TAX_ID");
220
				int rankId = rs.getInt("TAX_RNK_ID");
221
				int parentId = rs.getInt("TAX_TAX_IDPARENT");
222
				int parentRankId = rs.getInt("P2RankId");
223
				int grandParentRankId = rs.getInt("GP3RankId");
224
				int greatGrandParentRankId = rs.getInt("GGP4RankId");
225
				int greatGreatGrandParentRankId = rs.getInt("GGGP5RankId");
226
				int greatGreatGreatGrandParentRankId = rs.getInt("GGGGP6RankId");
227
				int originalGenusId = rs.getInt("TAX_TAX_IDGENUS");
228
				int autId = rs.getInt("TAX_AUT_ID");
229
				int status = rs.getInt("TAX_VALID");
230
				
231

    
232
				// user related
233
				String expertUsrTitle = rs.getString("ExpertUsrTitle");
234
				String expertUsrFirstname = rs.getString("ExpertUsrFirstname");
235
				String expertUsrLastname = rs.getString("ExpertUsrLastname");
236
				String speciesUsrTitle = rs.getString("SpeciesUsrTitle");
237
				String speciesUsrFirstname = rs.getString("SpeciesUsrFirstname");
238
				String speciesUsrLastname = rs.getString("SpeciesUsrLastname");
239
				String expertUserId = "" + rs.getInt("expertUserId");
240
				String speciesExpertUserId = "" + rs.getInt("speciesExpertUserId");
241

    
242
				String expertName = "";
243
				if (expertUsrTitle != null) {
244
					expertName = expertUsrTitle;
245
					if (! expertUsrTitle.endsWith(".")) {
246
						expertName += ".";
247
					}
248
				}
249
				expertName += expertUsrTitle == null ? NullToEmpty(expertUsrFirstname) : " " + NullToEmpty(expertUsrFirstname);
250
				if ((expertUsrTitle != null || expertUsrFirstname != null) && expertUsrLastname != null) {
251
					expertName += " " + expertUsrLastname;
252
				}
253
				
254
				String speciesExpertName = speciesUsrTitle == null ? "" : speciesUsrTitle + ".";
255
				if (speciesUsrTitle != null) {
256
					speciesExpertName = speciesUsrTitle;
257
					if (! speciesUsrTitle.endsWith(".")) {
258
						speciesExpertName += ".";
259
					}
260
				}
261
				speciesExpertName += speciesUsrTitle == null ? NullToEmpty(speciesUsrFirstname) : " " + NullToEmpty(speciesUsrFirstname);
262
				if ((speciesUsrTitle != null || speciesUsrFirstname != null) && speciesUsrLastname != null) {
263
					speciesExpertName += " " + speciesUsrLastname;
264
				}
265
				
266
				// date related
267
				Timestamp createdTimeStamp = rs.getTimestamp("TAX_CREATEDAT");
268
				Timestamp modifiedTimeStamp = rs.getTimestamp("TAX_MODIFIEDAT");
269
				boolean isCreated = createdTimeStamp.equals(modifiedTimeStamp);
270
				String lastAction = isCreated ? "created" : "modified";
271
				DateTime created = new DateTime(createdTimeStamp);
272
				DateTime modified = isCreated ? null : new DateTime(modifiedTimeStamp);
273
				DateTime lastActionDate = isCreated ?  created : modified;
274
				String lastActionDateStr = isCreated ? createdTimeStamp.toString() : modifiedTimeStamp.toString();
275
				
276
				
277
				// note related
278
				String taxComment = rs.getString("TAX_TAXCOMMENT");
279
				String fauComment = rs.getString("TAX_FAUCOMMENT");
280
				String fauExtraCodes = rs.getString("TAX_FAUEXTRACODES");
281

    
282
				// Avoid publication year 0 for NULL values in database.
283
				Integer year = rs.getInt("TAX_YEAR");
284
				if (year != null && year.intValue() == 0) {
285
					year = null;
286
				}
287
				
288
				//int familyId = rs.getInt("TAX_TAX_IDFAMILY");
289

    
290
				Rank rank = null;
291
				int parenthesis = rs.getInt("TAX_PARENTHESIS");
292
				UUID taxonBaseUuid = null;
293
				if (resultSetHasColumn(rs,"UUID")){
294
					String uuid = rs.getString("UUID");
295
					taxonBaseUuid = UUID.fromString(uuid);
296
				} else {
297
					taxonBaseUuid = UUID.randomUUID();
298
				}
299

    
300
				FaunaEuropaeaTaxon fauEuTaxon = new FaunaEuropaeaTaxon();
301
				fauEuTaxon.setUuid(taxonBaseUuid);
302
				fauEuTaxon.setId(taxonId);
303
				fauEuTaxon.setRankId(rankId);
304
				fauEuTaxon.setLocalName(localName);
305
				
306
				fauEuTaxon.setParentId(parentId);
307
				fauEuTaxon.setParentRankId(parentRankId);
308
				fauEuTaxon.setParentName(parentName);
309
				
310
				fauEuTaxon.setGrandParentId(grandParentId);
311
				fauEuTaxon.setGrandParentRankId(grandParentRankId);
312
				fauEuTaxon.setGrandParentName(grandParentName);
313
				
314
				fauEuTaxon.setGreatGrandParentId(greatGrandParentId);
315
				fauEuTaxon.setGreatGrandParentRankId(greatGrandParentRankId);
316
				fauEuTaxon.setGreatGrandParentName(greatGrandParentName);
317
				
318
				fauEuTaxon.setGreatGreatGrandParentId(greatGreatGrandParentId);
319
				fauEuTaxon.setGreatGreatGrandParentRankId(greatGreatGrandParentRankId);
320
				fauEuTaxon.setGreatGreatGrandParentName(greatGreatGrandParentName);
321
				
322
				fauEuTaxon.setGreatGreatGreatGrandParentRankId(greatGreatGreatGrandParentRankId);
323
				fauEuTaxon.setGreatGreatGreatGrandParentName(greatGreatGreatGrandParentName);
324
				
325
				fauEuTaxon.setOriginalGenusId(originalGenusId);
326
				fauEuTaxon.setYear(year);
327
				fauEuTaxon.setOriginalGenusName(originalGenusName);
328
				fauEuTaxon.setAuthorName(autName);
329
				if (parenthesis == P_PARENTHESIS) {
330
					fauEuTaxon.setParenthesis(true);
331
				} else {
332
					fauEuTaxon.setParenthesis(false);
333
				}
334
				if (status == T_STATUS_ACCEPTED) {
335
					fauEuTaxon.setValid(true);
336
				} else {
337
					fauEuTaxon.setValid(false);
338
				}
339

    
340
//				fauEuTaxon.setAuthorId(autId);
341

    
342
				try {
343
					rank = FaunaEuropaeaTransformer.rankId2Rank(rs, false);
344
				} catch (UnknownCdmTypeException e) {
345
					logger.warn("Taxon (" + taxonId + ") has unknown rank (" + rankId + ") and could not be saved.");
346
					continue;
347
				} catch (NullPointerException e) {
348
					logger.warn("Taxon (" + taxonId + ") has rank null and can not be saved.");
349
					continue;
350
				}
351

    
352
				Reference<?> sourceReference = fauEuConfig.getSourceReference();
353
				Reference<?> auctReference = fauEuConfig.getAuctReference();
354

    
355
				ZoologicalName zooName = ZoologicalName.NewInstance(rank);
356
				TeamOrPersonBase<?> author = authorStore.get(autId);
357
				
358
				zooName.setCombinationAuthorTeam(author);
359
				zooName.setPublicationYear(year);
360
				
361
				
362
				// Add Date extensions to this zooName
363
				Extension.NewInstance(zooName, lastAction, getExtensionType(state, PesiTransformer.lastActionUuid, "LastAction", "LastAction", "LA"));
364
//				Extension.NewInstance(zooName, lastActionDateStr, getExtensionType(state, PesiTransformer.lastActionDateUuid, "LastActionDate", "LastActionDate", "LAD"));
365
				zooName.setCreated(created);
366
				zooName.setUpdated(modified);
367
				
368
				/* Add Note extensions to this zooName
369
				Extension.NewInstance(zooName, taxComment, getExtensionType(PesiTransformer.taxCommentUuid, "TaxComment", "TaxComment", "TC"));
370
				Extension.NewInstance(zooName, fauComment, getExtensionType(PesiTransformer.fauCommentUuid, "FauComment", "FauComment", "FC"));
371
				Extension.NewInstance(zooName, fauExtraCodes, getExtensionType(PesiTransformer.fauExtraCodesUuid, "FauExtraCodes", "FauExtraCodes", "FEC"));
372
				*/
373
				TaxonBase<?> taxonBase;
374

    
375
				Synonym synonym = null;
376
				Taxon taxon;
377
				try {
378
					// check for occurrence of the auct string in auctName
379
					String auctRegEx = "\\bauct\\b\\.?"; // The word "auct" with or without "."
380
					
381
					String auctWithNecRegEx = "\\bauct\\b\\.?.*\\bnec\\b\\.?.*";
382
					String necAuctRegEx = ".*\\bnec\\b\\.?.*\\bauct\\b\\.?";
383
					
384
					boolean auctNecFound = expressionMatches(auctWithNecRegEx, autName);
385
					boolean necAuctFound = expressionMatches(necAuctRegEx, autName);
386
					boolean auctWordFound = expressionMatches(auctRegEx, autName);
387
					
388
						
389
					
390
					if (status == T_STATUS_ACCEPTED ) {
391
						
392
							taxon = Taxon.NewInstance(zooName, sourceReference);
393
							if (logger.isDebugEnabled()) {
394
								logger.debug("Taxon created (" + taxonId + ")");
395
							}
396
							
397
						
398
						taxonBase = taxon;
399
					} else if ((status == T_STATUS_NOT_ACCEPTED) && ! auctWordFound) { // synonym
400
						synonym = Synonym.NewInstance(zooName, sourceReference);
401
						//logger.info("Synonym created: " + synonym.getTitleCache() + " taxonName: " + zooName.getTitleCache());
402
						if (logger.isDebugEnabled()) {
403
							logger.debug("Synonym created (" + taxonId + ")");
404
						}
405
						taxonBase = synonym;
406
					} else if (status == T_STATUS_NOT_ACCEPTED && (necAuctFound || auctNecFound)){
407
						synonym = Synonym.NewInstance(zooName, sourceReference);
408
						NomenclaturalStatus tempNameNomStatus = NomenclaturalStatus.NewInstance(FaunaEuropaeaTransformer.getNomStatusTempNamed(getTermService()));
409
						zooName.addStatus(tempNameNomStatus);
410
						taxonBase = synonym;
411
						logger.info("temporary named name created ("+ taxonId + ") " + zooName.getTitleCache()+ zooName.getStatus().toString());
412
					}else if (status == T_STATUS_NOT_ACCEPTED && auctWordFound){
413
							// misapplied name
414
								zooName.setCombinationAuthorTeam(null);
415
								zooName.setPublicationYear(null);
416
								
417
								taxon = Taxon.NewInstance(zooName, auctReference);
418
								taxonBase = taxon;
419
								//logger.info("Misapplied name created ("+ taxonId + ") " + autName);
420
								if (logger.isDebugEnabled()) {
421
									logger.debug("Misapplied name created (" + taxonId + ")");
422
									}
423
					}else{
424
						
425
						logger.warn("Unknown taxon status " + status + ". Taxon (" + taxonId + ") ignored.");
426
						continue;
427
					}
428

    
429
					taxonBase.setUuid(taxonBaseUuid);
430
					taxonBase.setLsid(new LSID( "urn:lsid:faunaeur.org:taxname:"+taxonId));
431
					taxonBase.setCreated(created);
432
					taxonBase.setUpdated(modified);
433
					
434
					// Add Note extensions to this taxon
435
					
436
					if (!StringUtils.isBlank(taxComment)){
437
						Extension.NewInstance(taxonBase, taxComment, getExtensionType(state, PesiTransformer.taxCommentUuid, "TaxComment", "TaxComment", "TC"));
438
					}
439
					if (!StringUtils.isBlank(fauComment)){
440
						Extension.NewInstance(taxonBase, fauComment, getExtensionType(state, PesiTransformer.fauCommentUuid, "FauComment", "FauComment", "FC"));
441
					}
442
					if (!StringUtils.isBlank(fauExtraCodes)){
443
						Extension.NewInstance(taxonBase, fauExtraCodes, getExtensionType(state, PesiTransformer.fauExtraCodesUuid, "FauExtraCodes", "FauExtraCodes", "FEC"));
444
					}
445
					// Add UserId extensions to this zooName
446
					//Extension.NewInstance(zooName, expertUserId, getExtensionType(state, PesiTransformer.expertUserIdUuid, "expertUserId", "expertUserId", "EUID"));
447
					//Extension.NewInstance(zooName, speciesExpertUserId, getExtensionType(state, PesiTransformer.speciesExpertUserIdUuid, "speciesExpertUserId", "speciesExpertUserId", "SEUID"));
448
					
449
					// Add Expert extensions to this zooName
450
					Extension.NewInstance(taxonBase, expertName, getExtensionType(state, PesiTransformer.expertNameUuid, "ExpertName", "ExpertName", "EN"));
451
					Extension.NewInstance(taxonBase, speciesExpertName, getExtensionType(state, PesiTransformer.speciesExpertNameUuid, "SpeciesExpertName", "SpeciesExpertName", "SEN"));
452

    
453
					
454
					ImportHelper.setOriginalSource(taxonBase, fauEuConfig.getSourceReference(), taxonId, OS_NAMESPACE_TAXON);
455
					ImportHelper.setOriginalSource(zooName, fauEuConfig.getSourceReference(), taxonId, "TaxonName");
456

    
457
					if (!taxonMap.containsKey(taxonId)) {
458
						
459
						taxonMap.put(taxonId, taxonBase);
460
						fauEuTaxonMap.put(taxonId, fauEuTaxon);
461
						
462
					} else {
463
						logger.warn("Not imported taxon base with duplicated TAX_ID (" + taxonId + 
464
								") " + localName);
465
					}
466
				} catch (Exception e) {
467
					logger.warn("An exception occurred when creating taxon base with id " + taxonId + 
468
					". Taxon base could not be saved.");
469
					e.printStackTrace();
470
				}
471

    
472
				if (((i % limit) == 0 && i != 1 )) { 
473

    
474
					commitTaxa(state, txStatus, taxonMap, fauEuTaxonMap,
475
							synonymSet);
476
					
477
					taxonMap = null;
478
					synonymSet = null;
479
					fauEuTaxonMap = null;
480
					
481
					
482
					if(logger.isInfoEnabled()) {
483
						logger.info("i = " + i + " - Transaction committed"); 
484
					}
485
				}
486

    
487
			}
488
			rs = null;
489
			if (taxonMap != null){
490
				commitTaxa(state, txStatus, taxonMap, fauEuTaxonMap,
491
						synonymSet);
492
				taxonMap = null;
493
				synonymSet = null;
494
				fauEuTaxonMap = null;
495
			}
496
		} catch (SQLException e) {
497
			logger.error("SQLException:" +  e);
498
			state.setUnsuccessfull();
499
		}
500
        taxonMap = null;
501
		synonymSet = null;
502
		fauEuTaxonMap = null;
503
		return;
504
	}
505

    
506
	private void commitTaxa(FaunaEuropaeaImportState state,
507
			TransactionStatus txStatus, Map<Integer, TaxonBase<?>> taxonMap,
508
			Map<Integer, FaunaEuropaeaTaxon> fauEuTaxonMap,
509
			Set<Synonym> synonymSet) {
510
		processTaxaSecondPass(state, taxonMap, fauEuTaxonMap, synonymSet);
511
		if(logger.isDebugEnabled()) { logger.debug("Saving taxa ... " + taxonMap.size()); }
512
		getTaxonService().save((Collection)taxonMap.values());
513
		
514
		commitTransaction(txStatus);
515
	}
516

    
517
	
518
	
519
	/**
520
	 * Processes taxa from complete taxon store
521
	 */
522
	private void processTaxaSecondPass(FaunaEuropaeaImportState state, Map<Integer, TaxonBase<?>> taxonMap,
523
			Map<Integer, FaunaEuropaeaTaxon> fauEuTaxonMap, Set<Synonym> synonymSet) {
524
		if(logger.isDebugEnabled()) { logger.debug("Processing taxa second pass..."); }
525

    
526
		FaunaEuropaeaImportConfigurator fauEuConfig = state.getConfig();
527
		
528
		for (int id : taxonMap.keySet())
529
		{
530
			if (logger.isDebugEnabled()) { logger.debug("Taxon # " + id); }
531
			
532
			TaxonBase<?> taxonBase = taxonMap.get(id);
533
			TaxonNameBase<?,?> taxonName = taxonBase.getName();
534
			FaunaEuropaeaTaxon fauEuTaxon = fauEuTaxonMap.get(id);
535
			boolean useOriginalGenus = false;
536
			//if (taxonBase instanceof Synonym){
537
			if (!fauEuTaxon.isValid() ){
538
				useOriginalGenus = true;
539
			}
540
			
541
			String nameString = 
542
				buildTaxonName(fauEuTaxon, taxonBase, taxonName, useOriginalGenus, fauEuConfig);
543
			
544
			if (taxonBase instanceof Synonym){
545
				logger.debug("Name of Synonym: " + nameString);
546
			}
547
			
548
			if (fauEuConfig.isDoBasionyms() 
549
					&& fauEuTaxon.getRankId() > R_SUBGENUS
550
					&& (fauEuTaxon.getOriginalGenusId() != 0)) {
551
				
552
				Integer originalGenusId = fauEuTaxon.getOriginalGenusId();
553
				Integer actualGenusId = getActualGenusId(fauEuTaxon);
554
				
555
				if (logger.isDebugEnabled()) {
556
					logger.debug("actual genus id = " + actualGenusId + ", original genus id = " + originalGenusId);
557
				}
558
				
559
				if (actualGenusId.intValue() != originalGenusId.intValue() && taxonBase.isInstanceOf(Taxon.class)) {
560
					createBasionym(fauEuTaxon, taxonBase, taxonName, fauEuConfig, synonymSet, state);
561
				} else if (fauEuTaxon.isParenthesis()) {
562
					//the authorteam should be set in parenthesis because there should be a basionym, but we do not know it?
563
					ZoologicalName zooName = taxonName.deproxy(taxonName, ZoologicalName.class);
564
					zooName.setBasionymAuthorTeam(zooName.getCombinationAuthorTeam());
565
					zooName.setCombinationAuthorTeam(null);
566
					zooName.setOriginalPublicationYear(zooName.getPublicationYear());
567
					zooName.setPublicationYear(null);
568
				}
569
				
570
			}
571
		}
572
		return;	
573
	}
574

    
575
	
576
	private void createBasionym(FaunaEuropaeaTaxon fauEuTaxon, TaxonBase<?> taxonBase, 
577
			TaxonNameBase<?,?>taxonName, FaunaEuropaeaImportConfigurator fauEuConfig,
578
			Set<Synonym> synonymSet, FaunaEuropaeaImportState state) {
579

    
580
		try {
581
			ZoologicalName zooName = taxonName.deproxy(taxonName, ZoologicalName.class);
582
			
583
			// create basionym
584
			ZoologicalName basionym = ZoologicalName.NewInstance(taxonName.getRank());
585
			basionym.setCombinationAuthorTeam(zooName.getCombinationAuthorTeam());
586
			basionym.setPublicationYear(zooName.getPublicationYear());
587

    
588
			
589
			zooName.addBasionym(basionym, fauEuConfig.getSourceReference(), null, null);
590
			//TODO:this is a workaround for fauna europaea, this should be fixed in cdm model. this should be not a basionym but an orthographic variant (original spelling)
591
			if (fauEuTaxon.isParenthesis()){
592
				zooName.setOriginalPublicationYear(zooName.getPublicationYear());
593
				zooName.setBasionymAuthorTeam(zooName.getCombinationAuthorTeam());
594
				zooName.setCombinationAuthorTeam(null);
595
			} else{
596
				zooName.setBasionymAuthorTeam(null);
597
				zooName.setAuthorshipCache(zooName.getAuthorshipCache(), true);
598
				zooName.setCombinationAuthorTeam(null);
599
			}
600
			zooName.setPublicationYear(null);
601
			zooName.setTitleCache(null); // This should (re)generate the titleCache automatically
602
			if (logger.isDebugEnabled()) {
603
				logger.debug("Basionym created (" + fauEuTaxon.getId() + ")");
604
			}
605

    
606
			// create synonym
607
			Synonym synonym = Synonym.NewInstance(basionym, fauEuConfig.getSourceReference());
608
			MarkerType markerType =getMarkerType(state, PesiTransformer.uuidMarkerGuidIsMissing, "Uuid is missing", "Uuid is missing", null);
609
			synonym.addMarker(Marker.NewInstance(markerType, true));
610
			
611
			if (fauEuTaxon.isValid()) { // Taxon
612

    
613
				// homotypic synonym
614
				Taxon taxon = taxonBase.deproxy(taxonBase, Taxon.class);
615
				taxon.addHomotypicSynonym(synonym, fauEuConfig.getSourceReference(), null);
616
				
617
				if (logger.isDebugEnabled()) {
618
					logger.debug("Homotypic synonym created (" + fauEuTaxon.getId() + ")");
619
				}
620

    
621
			} else { // Synonym
622
				
623
				// heterotypic synonym
624
				// synonym relationship to the accepted taxon is created later
625
				synonymSet.add(synonym);
626
				
627
				if (logger.isDebugEnabled()) {
628
					logger.debug("Heterotypic synonym stored (" + fauEuTaxon.getId() + ")");
629
				}
630
			}
631
			
632
			
633
			buildTaxonName(fauEuTaxon, synonym, basionym, true, fauEuConfig);
634
			
635
			//originalSources zufügen
636
			
637
			ImportHelper.setOriginalSource(synonym, fauEuConfig.getSourceReference(), fauEuTaxon.getId(), PesiTransformer.STR_NAMESPACE_NOMINAL_TAXON);
638
			ImportHelper.setOriginalSource(synonym.getName(), fauEuConfig.getSourceReference(), fauEuTaxon.getId(), PesiTransformer.STR_NAMESPACE_NOMINAL_TAXON);
639

    
640
			// add originalGenusId as source
641
//			String originalGenusIdString = String.valueOf(fauEuTaxon.getId());
642
//			IdentifiableSource basionymSource = IdentifiableSource.NewInstance(originalGenusIdString, "originalGenusId");
643
//			basionym.addSource(basionymSource);
644
//			
645
//			// add original database reference
646
//			ImportHelper.setOriginalSource(basionym, fauEuConfig.getSourceReference(), fauEuTaxon.getId(), "TaxonName");
647
			
648
			
649
		} catch (Exception e) {
650
			logger.warn("Exception occurred when creating basionym for " + fauEuTaxon.getId());
651
			e.printStackTrace();
652
		}
653
		
654
		
655
		return;
656
	}
657
	
658
	
659
	/* Build name title cache */
660
	private String buildNameTitleCache(String nameString, boolean useOriginalGenus, FaunaEuropaeaTaxon fauEuTaxon) {
661
		
662
		StringBuilder titleCacheStringBuilder = new StringBuilder(nameString);
663
		Integer year = fauEuTaxon.getYear();
664
		if (year != null) { // TODO: Ignore authors like xp, xf, etc?
665
			titleCacheStringBuilder.append(" ");
666
			if ((fauEuTaxon.isParenthesis() == true) && !useOriginalGenus) {
667
				titleCacheStringBuilder.append("(");
668
			}
669
			titleCacheStringBuilder.append(fauEuTaxon.getAuthor());
670
			titleCacheStringBuilder.append(" ");
671
			titleCacheStringBuilder.append(year);
672
			if ((fauEuTaxon.isParenthesis() == true) && !useOriginalGenus) {
673
				titleCacheStringBuilder.append(")");
674
			}
675
		}
676
		return titleCacheStringBuilder.toString();
677
	}
678

    
679

    
680
	/* Build taxon title cache */
681
	private String buildTaxonTitleCache(String nameCache, Reference<?> reference) {
682
		
683
		StringBuilder titleCacheStringBuilder = new StringBuilder(nameCache);
684
		titleCacheStringBuilder.append(" sec. ");
685
		titleCacheStringBuilder.append(reference.getTitleCache());
686
		return titleCacheStringBuilder.toString();
687
	}
688

    
689
	
690
	/* Build name full title cache */
691
	private String buildNameFullTitleCache(String titleCache, FaunaEuropaeaImportConfigurator fauEuConfig) {
692
		
693
		StringBuilder fullTitleCacheStringBuilder = new StringBuilder(titleCache);
694
		fullTitleCacheStringBuilder.append(" ");
695
		fullTitleCacheStringBuilder.append(fauEuConfig.getSourceReferenceTitle());
696
		return fullTitleCacheStringBuilder.toString();
697
	}
698
	
699
	
700
	private String genusPart(StringBuilder originalGenusName, boolean useOriginalGenus, 
701
			StringBuilder genusOrUninomial) {
702

    
703
		StringBuilder stringBuilder = new StringBuilder();
704
		
705
		if(useOriginalGenus) {
706
			stringBuilder.append(originalGenusName);
707
			genusOrUninomial.delete(0, genusOrUninomial.length());
708
			genusOrUninomial.append(originalGenusName);
709
		} else {
710
			stringBuilder.append(genusOrUninomial);
711
		}
712
		stringBuilder.append(" ");
713

    
714
		return stringBuilder.toString();
715
	}
716

    
717
	
718
	private String genusSubGenusPart(StringBuilder originalGenusName, boolean useOriginalGenus, 
719
			StringBuilder genusOrUninomial,
720
			StringBuilder infraGenericEpithet,
721
			FaunaEuropaeaTaxon fauEuTaxon) {
722

    
723
		StringBuilder stringBuilder = new StringBuilder();
724
		
725
		stringBuilder.append(genusPart(originalGenusName, useOriginalGenus, genusOrUninomial));
726

    
727
		// The infraGenericEpithet is set to empty only if the original genus should be used and
728
		// the actualGenusId is not the originalGenusId.
729
		// This differentiation is relevant for synonyms and for basionyms.
730
		// InfraGenericEpithets of accepted taxa are not touched at all.
731
		Integer originalGenusId = fauEuTaxon.getOriginalGenusId();
732
		Integer actualGenusId = getActualGenusId(fauEuTaxon);
733
		if (useOriginalGenus && 
734
				originalGenusId.intValue() != actualGenusId.intValue() && 
735
				originalGenusId.intValue() > 0 &&
736
				actualGenusId.intValue() > 0) {
737
			infraGenericEpithet.delete(0, infraGenericEpithet.length());
738
			stringBuilder.append(" ");
739
			return stringBuilder.toString();
740
		}
741

    
742
		stringBuilder.append("(");
743
		stringBuilder.append(infraGenericEpithet);
744
		stringBuilder.append(")");
745
		stringBuilder.append(" ");
746
		
747
		return stringBuilder.toString();
748
	}
749

    
750
	/** Get actual genus id **/
751
	private Integer getActualGenusId(FaunaEuropaeaTaxon fauEuTaxon) {
752
		Integer actualGenusId = null;
753
		HashMap<Integer, Integer> ranks = new HashMap<Integer, Integer>();
754
		ranks.put(fauEuTaxon.getParentRankId(), fauEuTaxon.getParentId());
755
		ranks.put(fauEuTaxon.getGrandParentRankId(), fauEuTaxon.getGrandParentId());
756
		ranks.put(fauEuTaxon.getGreatGrandParentRankId(), fauEuTaxon.getGreatGrandParentId());
757
		ranks.put(fauEuTaxon.getGreatGreatGrandParentRankId(), fauEuTaxon.getGreatGreatGrandParentId());
758
		ranks.put(fauEuTaxon.getGreatGreatGreatGrandParentRankId(), fauEuTaxon.getGreatGreatGreatGrandParentId());
759
		
760
		actualGenusId = ranks.get(R_GENUS);
761

    
762
		return actualGenusId;
763
	}
764
	
765
	
766
	/** Build species and subspecies names */
767
	private String buildLowerTaxonName(StringBuilder originalGenus, boolean useOriginalGenus, 
768
			StringBuilder genusOrUninomial, StringBuilder infraGenericEpithet, 
769
			StringBuilder specificEpithet, StringBuilder infraSpecificEpithet,
770
			FaunaEuropaeaTaxon fauEuTaxon) {
771
		
772
		// species or subspecies name
773
		String localName = fauEuTaxon.getLocalName();
774
		int taxonId = fauEuTaxon.getId();
775
		int parentId = fauEuTaxon.getParentId();
776
		StringBuilder nameCacheStringBuilder = new StringBuilder();
777

    
778
//		FaunaEuropaeaTaxon parent = fauEuTaxonMap.get(parentId);
779
		if (parentId == 0) {
780
			nameCacheStringBuilder.append(localName);
781
			if (logger.isInfoEnabled()) {
782
				logger.info("Parent of (" + taxonId + ") is null");
783
			}
784
			return nameCacheStringBuilder.toString();
785
		}
786
		
787
		String parentName = fauEuTaxon.getParentName();
788
		String grandParentName = fauEuTaxon.getGrandParentName();
789
		String greatGrandParentName = fauEuTaxon.getGreatGrandParentName();
790
		int rank = fauEuTaxon.getRankId();
791
		int parentRankId = fauEuTaxon.getParentRankId();
792
		int grandParentRankId = fauEuTaxon.getGrandParentRankId();
793
		int greatGrandParentRankId = fauEuTaxon.getGreatGrandParentRankId();
794
//		int grandParentId = fauEuTaxon.getGrandParentId();
795
//		int greatGrandParentId = grandParent.getParentId();
796

    
797
		
798
		if (fauEuTaxon.isValid()) { // Taxon
799
			
800
			if (rank == R_SPECIES) {
801

    
802
				if(parentRankId == R_SUBGENUS) {
803
					//differ between isParanthesis= true and false
804
					String genusSubGenusPart = genusSubGenusPart(originalGenus, useOriginalGenus, 
805
							genusOrUninomial.append(grandParentName), 
806
							infraGenericEpithet.append(parentName),
807
							fauEuTaxon);
808
						nameCacheStringBuilder.append(genusSubGenusPart);
809
					
810

    
811
				} else if(parentRankId == R_GENUS) {
812

    
813
					String genusPart = genusPart(originalGenus, useOriginalGenus, 
814
							genusOrUninomial.append(parentName));
815
					nameCacheStringBuilder.append(genusPart);
816
				}
817
				nameCacheStringBuilder.append(localName);
818
				specificEpithet.append(localName);
819

    
820
			} else if (rank == R_SUBSPECIES) {
821

    
822
				if(grandParentRankId == R_SUBGENUS) {
823

    
824
					String genusSubGenusPart = genusSubGenusPart(originalGenus, useOriginalGenus, 
825
							genusOrUninomial.append(greatGrandParentName), 
826
							infraGenericEpithet.append(grandParentName),
827
							fauEuTaxon);
828
					nameCacheStringBuilder.append(genusSubGenusPart);
829

    
830
				} else if (grandParentRankId == R_GENUS) {
831

    
832
					String genusPart = genusPart(originalGenus, useOriginalGenus, 
833
							genusOrUninomial.append(grandParentName));
834
					nameCacheStringBuilder.append(genusPart);
835

    
836
				}
837
				nameCacheStringBuilder.append(parentName);
838
				nameCacheStringBuilder.append(" ");
839
				nameCacheStringBuilder.append(localName);
840
				specificEpithet.append(parentName);
841
				infraSpecificEpithet.append(localName);
842
			}
843
		} else { // Synonym or misapplied name
844
			
845
			if (rank == R_SPECIES) {
846

    
847
				if(grandParentRankId == R_SUBGENUS) {
848
					
849
					String genusSubGenusPart = genusSubGenusPart(originalGenus, useOriginalGenus, 
850
							genusOrUninomial.append(greatGrandParentName), 
851
							infraGenericEpithet.append(grandParentName),
852
							fauEuTaxon);
853
					nameCacheStringBuilder.append(genusSubGenusPart);
854

    
855
				} else if (grandParentRankId == R_GENUS) {
856
					
857
					String genusPart = genusPart(originalGenus, useOriginalGenus, 
858
							genusOrUninomial.append(grandParentName));
859
					nameCacheStringBuilder.append(genusPart);
860

    
861
				}
862
				nameCacheStringBuilder.append(localName);
863
				specificEpithet.append(localName);
864

    
865
			} else if (rank == R_SUBSPECIES) {
866
				
867
				String greatGreatGrandParentName = fauEuTaxon.getGreatGreatGrandParentName();
868
				
869
				if(greatGrandParentRankId == R_SUBGENUS) {
870
					
871
					String genusSubGenusPart = genusSubGenusPart(originalGenus, useOriginalGenus, 
872
							genusOrUninomial.append(greatGreatGrandParentName), 
873
							infraGenericEpithet.append(greatGrandParentName),
874
							fauEuTaxon);
875
					nameCacheStringBuilder.append(genusSubGenusPart);
876
					
877
				} else if (greatGrandParentRankId == R_GENUS) {
878
					
879
					String genusPart = genusPart(originalGenus, useOriginalGenus, 
880
							genusOrUninomial.append(greatGreatGrandParentName));
881
					nameCacheStringBuilder.append(genusPart);
882
				}
883
				
884
				nameCacheStringBuilder.append(grandParentName);
885
				nameCacheStringBuilder.append(" ");
886
				specificEpithet.append(grandParentName);
887
				nameCacheStringBuilder.append(localName);
888
				infraSpecificEpithet.append(localName);
889
			}
890
			
891
			
892
			
893
		}
894
		
895
		return nameCacheStringBuilder.toString();
896
	}
897
	
898
	
899
	/** Build taxon's name parts and caches */
900
	private String buildTaxonName(FaunaEuropaeaTaxon fauEuTaxon, TaxonBase<?> taxonBase, TaxonNameBase<?,?>taxonName,
901
			boolean useOriginalGenus, FaunaEuropaeaImportConfigurator fauEuConfig) {
902

    
903
		/* Local taxon name string */
904
		String localString = "";
905
		/* Concatenated taxon name string */
906
		String completeString = "";
907

    
908
		StringBuilder acceptedGenus = new StringBuilder("");
909
		
910
		StringBuilder genusOrUninomial = new StringBuilder();
911
		StringBuilder infraGenericEpithet = new StringBuilder(); 
912
		StringBuilder specificEpithet = new StringBuilder();
913
		StringBuilder infraSpecificEpithet = new StringBuilder();
914

    
915
		localString = fauEuTaxon.getLocalName();
916
		int rank = fauEuTaxon.getRankId();
917
		
918
		// determine genus: this also works for cases of synonyms since the accepted taxon is its parent
919
		String acceptedGenusString = null;
920
		String tempAcceptedGenusString = determineAcceptedGenus(fauEuTaxon);
921
		if (useOriginalGenus && ! "".equals(fauEuTaxon.getOriginalGenusName()) && !fauEuTaxon.getOriginalGenusName().equals(tempAcceptedGenusString) ) {
922
			acceptedGenusString  = fauEuTaxon.getOriginalGenusName();
923
		} else {
924
			acceptedGenusString = tempAcceptedGenusString;
925
		}
926

    
927
		if (acceptedGenusString != null) {
928
			acceptedGenus = new StringBuilder(acceptedGenusString);
929
		}
930

    
931
		if(logger.isDebugEnabled()) { 
932
			logger.debug("Local taxon name (rank = " + rank + "): " + localString); 
933
		}
934

    
935
		if (rank < R_SPECIES) {
936
			// subgenus or above
937

    
938
			completeString = localString;
939
			if (rank == R_SUBGENUS) {
940
				// subgenus part
941
				infraGenericEpithet.append(localString);
942
				
943
				// genus part
944
				genusOrUninomial.append(acceptedGenus);
945
				
946
				completeString = acceptedGenus + " ("+ localString + ")";
947
			} else {
948
				// genus or above
949
				genusOrUninomial.append(localString);
950
			}
951
			
952
		} else {
953
			// species or below
954

    
955
			taxonBase = taxonBase.deproxy(taxonBase, TaxonBase.class);
956

    
957
			completeString = 
958
				buildLowerTaxonName(acceptedGenus, useOriginalGenus, 
959
						genusOrUninomial, infraGenericEpithet, specificEpithet, infraSpecificEpithet,
960
						fauEuTaxon);
961
			
962
			completeString = (String) CdmUtils.removeDuplicateWhitespace(completeString.trim());
963

    
964
		}
965
		return setCompleteTaxonName(completeString, useOriginalGenus,
966
				genusOrUninomial.toString(), infraGenericEpithet.toString(), 
967
				specificEpithet.toString(), infraSpecificEpithet.toString(),
968
				fauEuTaxon, taxonBase, fauEuConfig);
969
		 
970
	}
971
	
972
	
973
	/**
974
	 * Determines the original genus name by searching the taxon with rank Genus.
975
	 * @param fauEuTaxon
976
	 * @return
977
	 */
978
	private String determineAcceptedGenus(FaunaEuropaeaTaxon fauEuTaxon) {
979
		String originalGenus = null;
980

    
981
		HashMap<Integer, String> ranks = new HashMap<Integer, String>();
982
		ranks.put(fauEuTaxon.getParentRankId(), fauEuTaxon.getParentName());
983
		ranks.put(fauEuTaxon.getGrandParentRankId(), fauEuTaxon.getGrandParentName());
984
		ranks.put(fauEuTaxon.getGreatGrandParentRankId(), fauEuTaxon.getGreatGrandParentName());
985
		ranks.put(fauEuTaxon.getGreatGreatGrandParentRankId(), fauEuTaxon.getGreatGreatGrandParentName());
986
		ranks.put(fauEuTaxon.getGreatGreatGreatGrandParentRankId(), fauEuTaxon.getGreatGreatGreatGrandParentName());
987
		
988
		originalGenus = ranks.get(R_GENUS);
989

    
990
		return originalGenus;
991
	}
992

    
993
	/** Sets name parts and caches */
994
	private String setCompleteTaxonName(String concatString, boolean useOriginalGenus,
995
			String genusOrUninomial, String infraGenericEpithet, String specificEpithet, String infraSpecificEpithet, 
996
			FaunaEuropaeaTaxon fauEuTaxon, TaxonBase<?> taxonBase, FaunaEuropaeaImportConfigurator fauEuConfig) {
997

    
998
		boolean success = true;
999
		
1000
		TaxonNameBase<?,?> taxonName = taxonBase.getName();
1001
		ZoologicalName zooName = (ZoologicalName)taxonName;
1002
		
1003
		if (!genusOrUninomial.equals("")) {
1004
			zooName.setGenusOrUninomial(emptyToNull(genusOrUninomial));
1005
			if (logger.isDebugEnabled()) { 
1006
				logger.debug("genusOrUninomial: " + genusOrUninomial); 
1007
			}
1008
		}
1009
		
1010
		//if ((!infraGenericEpithet.equals("") && fauEuTaxon.isParenthesis()) || (!infraGenericEpithet.equals("") && fauEuTaxon.)) {
1011
		if (fauEuTaxon.getParentRankId() == R_SUBGENUS || fauEuTaxon.getRankId() == R_SUBGENUS ||
1012
				fauEuTaxon.getGrandParentRankId() == R_SUBGENUS || fauEuTaxon.getGreatGrandParentRankId() == R_SUBGENUS) {
1013
			zooName.setInfraGenericEpithet(emptyToNull(infraGenericEpithet));
1014
			if (logger.isDebugEnabled()) { 
1015
				logger.debug("infraGenericEpithet: " + infraGenericEpithet); 
1016
			}
1017
		}
1018
		if ((fauEuTaxon.getRankId() == R_SPECIES || fauEuTaxon.getRankId() == R_SUBSPECIES)) {
1019
			zooName.setSpecificEpithet(emptyToNull(specificEpithet));
1020
			if (logger.isDebugEnabled()) { 
1021
				logger.debug("specificEpithet: " + specificEpithet); 
1022
			}
1023
		}
1024
		if (fauEuTaxon.getRankId() == R_SUBSPECIES) {
1025
			zooName.setInfraSpecificEpithet(emptyToNull(infraSpecificEpithet));
1026
			if (logger.isDebugEnabled()) { 
1027
				logger.debug("infraSpecificEpithet: " + infraSpecificEpithet); 
1028
			}
1029
		}
1030
		//TODO: use generate NameCache
1031
		//zooName.setNameCache(concatString);
1032
		String result = zooName.getNameCache();
1033
//		zooName.generateTitle();
1034
		//String titleCache = buildNameTitleCache(concatString, useOriginalGenus, fauEuTaxon);
1035
		//zooName.setTitleCache(titleCache);
1036
		//titleCache = buildNameFullTitleCache(concatString, fauEuConfig);
1037
//		zooName.generateFullTitle();
1038
		//zooName.setFullTitleCache(titleCache); // TODO: Add reference, NC status
1039
		
1040
//		ImportHelper.setOriginalSource(taxonName, fauEuConfig.getSourceReference(), 
1041
//				fauEuTaxon.getId(), "TaxonName");
1042
//		taxonBase.setSec(fauEuConfig.getSourceReference());
1043
//		taxonBase.generateTitle();
1044
		//titleCache = buildTaxonTitleCache(concatString, fauEuConfig.getSourceReference());
1045
		//taxonBase.setTitleCache(titleCache);
1046
		
1047
		if (logger.isDebugEnabled()) { 
1048
			logger.debug("Name stored: " + result); 
1049
		}
1050
		return result;
1051
	}
1052

    
1053
	/**
1054
	 * Ensures that empty strings are translated to null.
1055
	 * @param genusOrUninomial
1056
	 * @return
1057
	 */
1058
	private String emptyToNull(String text) {
1059
		if (CdmUtils.isEmpty(text)) {
1060
			return null;
1061
		} else {
1062
			return text;
1063
		}
1064
	}
1065
	
1066
	
1067

    
1068
}
(15-15/17)