Project

General

Profile

Download (40.5 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
import eu.etaxonomy.cdm.common.CdmUtils;
37
import eu.etaxonomy.cdm.io.common.ICdmIO;
38
import eu.etaxonomy.cdm.io.common.ImportHelper;
39
import eu.etaxonomy.cdm.io.common.MapWrapper;
40
import eu.etaxonomy.cdm.io.common.Source;
41
import eu.etaxonomy.cdm.io.pesi.out.PesiTransformer;
42
import eu.etaxonomy.cdm.model.agent.TeamOrPersonBase;
43
import eu.etaxonomy.cdm.model.common.CdmBase;
44
import eu.etaxonomy.cdm.model.common.Extension;
45
import eu.etaxonomy.cdm.model.common.LSID;
46
import eu.etaxonomy.cdm.model.common.Marker;
47
import eu.etaxonomy.cdm.model.common.MarkerType;
48
import eu.etaxonomy.cdm.model.name.NomenclaturalStatus;
49
import eu.etaxonomy.cdm.model.name.Rank;
50
import eu.etaxonomy.cdm.model.name.TaxonNameBase;
51
import eu.etaxonomy.cdm.model.name.ZoologicalName;
52
import eu.etaxonomy.cdm.model.reference.Reference;
53
import eu.etaxonomy.cdm.model.taxon.Synonym;
54
import eu.etaxonomy.cdm.model.taxon.Taxon;
55
import eu.etaxonomy.cdm.model.taxon.TaxonBase;
56
import eu.etaxonomy.cdm.strategy.exceptions.UnknownCdmTypeException;
57

    
58

    
59
/**
60
 * @author a.babadshanjan
61
 * @created 12.05.2009
62
 * @version 1.0
63
 */
64
@Component
65
public class FaunaEuropaeaTaxonNameImport extends FaunaEuropaeaImportBase  {
66

    
67
	public static final String OS_NAMESPACE_TAXON = "Taxon";
68

    
69
	private static final Logger logger = Logger.getLogger(FaunaEuropaeaTaxonNameImport.class);
70

    
71
	/* Max number of taxa to retrieve (for test purposes) */
72
	private final int maxTaxa = 0;
73

    
74
	/* (non-Javadoc)
75
	 * @see eu.etaxonomy.cdm.io.common.CdmIoBase#doCheck(eu.etaxonomy.cdm.io.common.IImportConfigurator)
76
	 */
77
	@Override
78
	protected boolean doCheck(FaunaEuropaeaImportState state) {
79
		boolean result = true;
80
		FaunaEuropaeaImportConfigurator fauEuConfig = state.getConfig();
81
		logger.warn("Checking for Taxa not yet fully implemented");
82
//		result &= checkTaxonStatus(fauEuConfig);
83

    
84
		return result;
85
	}
86

    
87
	/* (non-Javadoc)
88
	 * @see eu.etaxonomy.cdm.io.common.CdmIoBase#isIgnore(eu.etaxonomy.cdm.io.common.IImportConfigurator)
89
	 */
90
	@Override
91
    protected boolean isIgnore(FaunaEuropaeaImportState state) {
92
		return ! state.getConfig().isDoTaxa();
93
	}
94

    
95
	/**
96
	 * Import taxa from FauEU DB
97
	 */
98
	@Override
99
    protected void doInvoke(FaunaEuropaeaImportState state) {
100
		if(logger.isInfoEnabled()) { logger.info("Start making taxa..."); }
101

    
102
		processTaxa(state);
103
		logger.info("End making taxa...");
104
		return;
105
	}
106

    
107

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

    
122
	/** Retrieve taxa from FauEu DB, process in blocks */
123
	private void processTaxa(FaunaEuropaeaImportState state) {
124

    
125
		int limit = state.getConfig().getLimitSave();
126

    
127
		TransactionStatus txStatus = null;
128

    
129
		Map<String, MapWrapper<? extends CdmBase>> stores = state.getStores();
130
		MapWrapper<TeamOrPersonBase> authorStore = (MapWrapper<TeamOrPersonBase>)stores.get(ICdmIO.TEAM_STORE);
131

    
132
		Map<Integer, TaxonBase<?>> taxonMap = null;
133
		Map<Integer, FaunaEuropaeaTaxon> fauEuTaxonMap = null;
134
		/* Store for heterotypic synonyms to be save separately */
135
		Set<Synonym> synonymSet = null;
136

    
137
		FaunaEuropaeaImportConfigurator fauEuConfig = state.getConfig();
138
		Reference<?> sourceRef = fauEuConfig.getSourceReference();
139

    
140
		Source source = fauEuConfig.getSource();
141
		int i = 0;
142

    
143
		String selectCount =
144
			" SELECT count(*) ";
145

    
146
		String selectColumns =
147
			" SELECT Parent.TAX_NAME AS P2Name, Parent.TAX_RNK_ID AS P2RankId, " +
148
			" GrandParent.TAX_ID AS GP3Id, GrandParent.TAX_NAME AS GP3Name, GrandParent.TAX_RNK_ID AS GP3RankId, " +
149
			" GreatGrandParent.TAX_ID AS GGP4Id, GreatGrandParent.TAX_NAME AS GGP4Name, GreatGrandParent.TAX_RNK_ID AS GGP4RankId, " +
150
			" GreatGreatGrandParent.TAX_ID AS GGGP5Id, GreatGreatGrandParent.TAX_NAME AS GGGP5Name, GreatGreatGrandParent.TAX_RNK_ID AS GGGP5RankId, " +
151
			" OriginalGenusTaxon.TAX_NAME AS OGenusName, " +
152
			" GreatGreatGreatGrandParent.TAX_ID AS GGGGP6Id, GreatGreatGreatGrandParent.TAX_NAME AS GGGGP6Name, GreatGreatGreatGrandParent.TAX_RNK_ID AS GGGGP6RankId," +
153
			" expertUsers.usr_id AS expertUserId, expertUsers.usr_title AS ExpertUsrTitle, expertUsers.usr_firstname AS ExpertUsrFirstname, expertUsers.usr_lastname AS ExpertUsrLastname," +
154
			" speciesExpertUsers.usr_id AS speciesExpertUserId, speciesExpertUsers.usr_title AS SpeciesUsrTitle, speciesExpertUsers.usr_firstname AS SpeciesUsrFirstname, speciesExpertUsers.usr_lastname AS SpeciesUsrLastname," +
155
			" Taxon.*, rank.*, author.* ";
156

    
157
		String fromClause =
158
			" FROM Taxon LEFT OUTER JOIN " +
159
			" Taxon AS Parent ON Taxon.TAX_TAX_IDPARENT = Parent.TAX_ID LEFT OUTER JOIN " +
160
			" Taxon AS GrandParent ON Parent.TAX_TAX_IDPARENT = GrandParent.TAX_ID LEFT OUTER JOIN " +
161
			" Taxon AS GreatGrandParent ON GrandParent.TAX_TAX_IDPARENT = GreatGrandParent.TAX_ID LEFT OUTER JOIN " +
162
			" Taxon AS GreatGreatGrandParent ON GreatGrandParent.TAX_TAX_IDPARENT = GreatGreatGrandParent.TAX_ID LEFT OUTER JOIN " +
163
			" Taxon AS GreatGreatGreatGrandParent ON GreatGreatGrandParent.TAX_TAX_IDPARENT = GreatGreatGreatGrandParent.TAX_ID LEFT OUTER JOIN " +
164
			" Taxon AS OriginalGenusTaxon ON Taxon.TAX_TAX_IDGENUS = OriginalGenusTaxon.TAX_ID LEFT OUTER JOIN " +
165
			" author ON Taxon.TAX_AUT_ID = author.aut_id LEFT OUTER JOIN " +
166
			" users AS expertUsers ON Taxon.TAX_USR_IDGC = expertUsers.usr_id LEFT OUTER JOIN " +
167
			" users AS speciesExpertUsers ON Taxon.TAX_USR_IDSP = speciesExpertUsers.usr_id LEFT OUTER JOIN " +
168
			" rank ON Taxon.TAX_RNK_ID = rank.rnk_id ";
169

    
170
		String countQuery =
171
			selectCount + fromClause;
172

    
173
		String selectQuery =
174
			selectColumns + fromClause;
175

    
176

    
177
        try {
178

    
179
			ResultSet rs = source.getResultSet(countQuery);
180
			rs.next();
181
			int count = rs.getInt(1);
182

    
183
			rs = source.getResultSet(selectQuery);
184

    
185
	        if (logger.isInfoEnabled()) {
186
				logger.info("Number of rows: " + count);
187
				logger.info("Count Query: " + countQuery);
188
				logger.info("Select Query: " + selectQuery);
189
			}
190

    
191
			while (rs.next()) {
192

    
193
				if ((i++ % limit) == 0) {
194

    
195
					txStatus = startTransaction();
196
					taxonMap = new HashMap<Integer, TaxonBase<?>>(limit);
197
					fauEuTaxonMap = new HashMap<Integer, FaunaEuropaeaTaxon>(limit);
198
					synonymSet = new HashSet<Synonym>();
199

    
200
					if(logger.isInfoEnabled()) {
201
						logger.info("i = " + i + " - Transaction started");
202
					}
203
				}
204

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

    
228

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

    
239
				String expertName = "";
240
				if (expertUsrTitle != null) {
241
					expertName = expertUsrTitle;
242
					if (! expertUsrTitle.endsWith(".")) {
243
						expertName += ".";
244
					}
245
				}
246
				expertName += expertUsrTitle == null ? NullToEmpty(expertUsrFirstname) : " " + NullToEmpty(expertUsrFirstname);
247
				if ((expertUsrTitle != null || expertUsrFirstname != null) && expertUsrLastname != null) {
248
					expertName += " " + expertUsrLastname;
249
				}
250

    
251
				String speciesExpertName = speciesUsrTitle == null ? "" : speciesUsrTitle + ".";
252
				if (speciesUsrTitle != null) {
253
					speciesExpertName = speciesUsrTitle;
254
					if (! speciesUsrTitle.endsWith(".")) {
255
						speciesExpertName += ".";
256
					}
257
				}
258
				speciesExpertName += speciesUsrTitle == null ? NullToEmpty(speciesUsrFirstname) : " " + NullToEmpty(speciesUsrFirstname);
259
				if ((speciesUsrTitle != null || speciesUsrFirstname != null) && speciesUsrLastname != null) {
260
					speciesExpertName += " " + speciesUsrLastname;
261
				}
262

    
263
				// date related
264
				Timestamp createdTimeStamp = rs.getTimestamp("TAX_CREATEDAT");
265
				Timestamp modifiedTimeStamp = rs.getTimestamp("TAX_MODIFIEDAT");
266
				boolean isCreated = createdTimeStamp.equals(modifiedTimeStamp);
267
				String lastAction = isCreated ? "created" : "modified";
268
				DateTime created = new DateTime(createdTimeStamp);
269
				DateTime modified = isCreated ? null : new DateTime(modifiedTimeStamp);
270
				DateTime lastActionDate = isCreated ?  created : modified;
271
				String lastActionDateStr = isCreated ? createdTimeStamp.toString() : modifiedTimeStamp.toString();
272

    
273

    
274
				// note related
275
				String taxComment = rs.getString("TAX_TAXCOMMENT");
276
				String fauComment = rs.getString("TAX_FAUCOMMENT");
277
				String fauExtraCodes = rs.getString("TAX_FAUEXTRACODES");
278

    
279
				// Avoid publication year 0 for NULL values in database.
280
				Integer year = rs.getInt("TAX_YEAR");
281
				if (year != null && year.intValue() == 0) {
282
					year = null;
283
				}
284

    
285
				//int familyId = rs.getInt("TAX_TAX_IDFAMILY");
286

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

    
297
				FaunaEuropaeaTaxon fauEuTaxon = new FaunaEuropaeaTaxon();
298
				fauEuTaxon.setUuid(taxonBaseUuid);
299
				fauEuTaxon.setId(taxonId);
300
				fauEuTaxon.setRankId(rankId);
301
				fauEuTaxon.setLocalName(localName);
302

    
303
				fauEuTaxon.setParentId(parentId);
304
				fauEuTaxon.setParentRankId(parentRankId);
305
				fauEuTaxon.setParentName(parentName);
306

    
307
				fauEuTaxon.setGrandParentId(grandParentId);
308
				fauEuTaxon.setGrandParentRankId(grandParentRankId);
309
				fauEuTaxon.setGrandParentName(grandParentName);
310

    
311
				fauEuTaxon.setGreatGrandParentId(greatGrandParentId);
312
				fauEuTaxon.setGreatGrandParentRankId(greatGrandParentRankId);
313
				fauEuTaxon.setGreatGrandParentName(greatGrandParentName);
314

    
315
				fauEuTaxon.setGreatGreatGrandParentId(greatGreatGrandParentId);
316
				fauEuTaxon.setGreatGreatGrandParentRankId(greatGreatGrandParentRankId);
317
				fauEuTaxon.setGreatGreatGrandParentName(greatGreatGrandParentName);
318

    
319
				fauEuTaxon.setGreatGreatGreatGrandParentRankId(greatGreatGreatGrandParentRankId);
320
				fauEuTaxon.setGreatGreatGreatGrandParentName(greatGreatGreatGrandParentName);
321

    
322
				fauEuTaxon.setOriginalGenusId(originalGenusId);
323
				fauEuTaxon.setYear(year);
324
				fauEuTaxon.setOriginalGenusName(originalGenusName);
325
				fauEuTaxon.setAuthorName(autName);
326
				if (parenthesis == P_PARENTHESIS) {
327
					fauEuTaxon.setParenthesis(true);
328
				} else {
329
					fauEuTaxon.setParenthesis(false);
330
				}
331
				if (status == T_STATUS_ACCEPTED) {
332
					fauEuTaxon.setValid(true);
333
				} else {
334
					fauEuTaxon.setValid(false);
335
				}
336

    
337
//				fauEuTaxon.setAuthorId(autId);
338

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

    
349
				Reference<?> sourceReference = fauEuConfig.getSourceReference();
350
				Reference<?> auctReference = fauEuConfig.getAuctReference();
351

    
352
				ZoologicalName zooName = ZoologicalName.NewInstance(rank);
353
				TeamOrPersonBase<?> author = authorStore.get(autId);
354

    
355
				zooName.setCombinationAuthorship(author);
356
				zooName.setPublicationYear(year);
357

    
358

    
359
				// Add Date extensions to this zooName
360
				Extension.NewInstance(zooName, lastAction, getExtensionType(state, PesiTransformer.lastActionUuid, "LastAction", "LastAction", "LA"));
361
//				Extension.NewInstance(zooName, lastActionDateStr, getExtensionType(state, PesiTransformer.lastActionDateUuid, "LastActionDate", "LastActionDate", "LAD"));
362
				zooName.setCreated(created);
363
				zooName.setUpdated(modified);
364

    
365
				/* Add Note extensions to this zooName
366
				Extension.NewInstance(zooName, taxComment, getExtensionType(PesiTransformer.taxCommentUuid, "TaxComment", "TaxComment", "TC"));
367
				Extension.NewInstance(zooName, fauComment, getExtensionType(PesiTransformer.fauCommentUuid, "FauComment", "FauComment", "FC"));
368
				Extension.NewInstance(zooName, fauExtraCodes, getExtensionType(PesiTransformer.fauExtraCodesUuid, "FauExtraCodes", "FauExtraCodes", "FEC"));
369
				*/
370
				TaxonBase<?> taxonBase;
371

    
372
				Synonym synonym = null;
373
				Taxon taxon;
374
				try {
375
					// check for occurrence of the auct string in auctName
376
					String auctRegEx = "\\bauct\\b\\.?"; // The word "auct" with or without "."
377

    
378
					String auctWithNecRegEx = "\\bauct\\b\\.?.*\\bnec\\b\\.?.*";
379
					String necAuctRegEx = ".*\\bnec\\b\\.?.*\\bauct\\b\\.?";
380

    
381
					boolean auctNecFound = expressionMatches(auctWithNecRegEx, autName);
382
					boolean necAuctFound = expressionMatches(necAuctRegEx, autName);
383
					boolean auctWordFound = expressionMatches(auctRegEx, autName);
384

    
385

    
386

    
387
					if (status == T_STATUS_ACCEPTED ) {
388

    
389
							taxon = Taxon.NewInstance(zooName, sourceReference);
390
							if (logger.isDebugEnabled()) {
391
								logger.debug("Taxon created (" + taxonId + ")");
392
							}
393

    
394

    
395
						taxonBase = taxon;
396
					} else if ((status == T_STATUS_NOT_ACCEPTED) && ! auctWordFound) { // synonym
397
						synonym = Synonym.NewInstance(zooName, sourceReference);
398
						//logger.info("Synonym created: " + synonym.getTitleCache() + " taxonName: " + zooName.getTitleCache());
399
						if (logger.isDebugEnabled()) {
400
							logger.debug("Synonym created (" + taxonId + ")");
401
						}
402
						taxonBase = synonym;
403
					} else if (status == T_STATUS_NOT_ACCEPTED && (necAuctFound || auctNecFound)){
404
						synonym = Synonym.NewInstance(zooName, sourceReference);
405
						NomenclaturalStatus tempNameNomStatus = NomenclaturalStatus.NewInstance(FaunaEuropaeaTransformer.getNomStatusTempNamed(getTermService()));
406
						zooName.addStatus(tempNameNomStatus);
407
						taxonBase = synonym;
408
						logger.info("temporary named name created ("+ taxonId + ") " + zooName.getTitleCache()+ zooName.getStatus().toString());
409
					}else if (status == T_STATUS_NOT_ACCEPTED && auctWordFound){
410
							// misapplied name
411
								zooName.setCombinationAuthorship(null);
412
								zooName.setPublicationYear(null);
413

    
414
								taxon = Taxon.NewInstance(zooName, auctReference);
415
								taxonBase = taxon;
416
								//logger.info("Misapplied name created ("+ taxonId + ") " + autName);
417
								if (logger.isDebugEnabled()) {
418
									logger.debug("Misapplied name created (" + taxonId + ")");
419
									}
420
					}else{
421

    
422
						logger.warn("Unknown taxon status " + status + ". Taxon (" + taxonId + ") ignored.");
423
						continue;
424
					}
425

    
426
					taxonBase.setUuid(taxonBaseUuid);
427
					taxonBase.setLsid(new LSID( "urn:lsid:faunaeur.org:taxname:"+taxonId));
428
					taxonBase.setCreated(created);
429
					taxonBase.setUpdated(modified);
430

    
431
					// Add Note extensions to this taxon
432

    
433
					if (!StringUtils.isBlank(taxComment)){
434
						Extension.NewInstance(taxonBase, taxComment, getExtensionType(state, PesiTransformer.taxCommentUuid, "TaxComment", "TaxComment", "TC"));
435
					}
436
					if (!StringUtils.isBlank(fauComment)){
437
						Extension.NewInstance(taxonBase, fauComment, getExtensionType(state, PesiTransformer.fauCommentUuid, "FauComment", "FauComment", "FC"));
438
					}
439
					if (!StringUtils.isBlank(fauExtraCodes)){
440
						Extension.NewInstance(taxonBase, fauExtraCodes, getExtensionType(state, PesiTransformer.fauExtraCodesUuid, "FauExtraCodes", "FauExtraCodes", "FEC"));
441
					}
442
					// Add UserId extensions to this zooName
443
					//Extension.NewInstance(zooName, expertUserId, getExtensionType(state, PesiTransformer.expertUserIdUuid, "expertUserId", "expertUserId", "EUID"));
444
					//Extension.NewInstance(zooName, speciesExpertUserId, getExtensionType(state, PesiTransformer.speciesExpertUserIdUuid, "speciesExpertUserId", "speciesExpertUserId", "SEUID"));
445

    
446
					// Add Expert extensions to this zooName
447
					Extension.NewInstance(taxonBase, expertName, getExtensionType(state, PesiTransformer.expertNameUuid, "ExpertName", "ExpertName", "EN"));
448
					Extension.NewInstance(taxonBase, speciesExpertName, getExtensionType(state, PesiTransformer.speciesExpertNameUuid, "SpeciesExpertName", "SpeciesExpertName", "SEN"));
449

    
450

    
451
					ImportHelper.setOriginalSource(taxonBase, fauEuConfig.getSourceReference(), taxonId, OS_NAMESPACE_TAXON);
452
					ImportHelper.setOriginalSource(zooName, fauEuConfig.getSourceReference(), taxonId, "TaxonName");
453

    
454
					if (!taxonMap.containsKey(taxonId)) {
455

    
456
						taxonMap.put(taxonId, taxonBase);
457
						fauEuTaxonMap.put(taxonId, fauEuTaxon);
458

    
459
					} else {
460
						logger.warn("Not imported taxon base with duplicated TAX_ID (" + taxonId +
461
								") " + localName);
462
					}
463
				} catch (Exception e) {
464
					logger.warn("An exception occurred when creating taxon base with id " + taxonId +
465
					". Taxon base could not be saved.");
466
					e.printStackTrace();
467
				}
468

    
469
				if (((i % limit) == 0 && i != 1 )) {
470

    
471
					commitTaxa(state, txStatus, taxonMap, fauEuTaxonMap,
472
							synonymSet);
473

    
474
					taxonMap = null;
475
					synonymSet = null;
476
					fauEuTaxonMap = null;
477

    
478

    
479
					if(logger.isInfoEnabled()) {
480
						logger.info("i = " + i + " - Transaction committed");
481
					}
482
				}
483

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

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

    
511
		commitTransaction(txStatus);
512
	}
513

    
514

    
515

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

    
523
		FaunaEuropaeaImportConfigurator fauEuConfig = state.getConfig();
524

    
525
		for (int id : taxonMap.keySet())
526
		{
527
			if (logger.isDebugEnabled()) { logger.debug("Taxon # " + id); }
528

    
529
			TaxonBase<?> taxonBase = taxonMap.get(id);
530
			TaxonNameBase<?,?> taxonName = taxonBase.getName();
531
			FaunaEuropaeaTaxon fauEuTaxon = fauEuTaxonMap.get(id);
532
			boolean useOriginalGenus = false;
533
			//if (taxonBase instanceof Synonym){
534
			if (!fauEuTaxon.isValid() ){
535
				useOriginalGenus = true;
536
			}
537

    
538
			String nameString =
539
				buildTaxonName(fauEuTaxon, taxonBase, taxonName, useOriginalGenus, fauEuConfig);
540

    
541
			if (taxonBase instanceof Synonym){
542
				logger.debug("Name of Synonym: " + nameString);
543
			}
544

    
545
			if (fauEuConfig.isDoBasionyms()
546
					&& fauEuTaxon.getRankId() > R_SUBGENUS
547
					&& (fauEuTaxon.getOriginalGenusId() != 0)) {
548

    
549
				Integer originalGenusId = fauEuTaxon.getOriginalGenusId();
550
				Integer actualGenusId = getActualGenusId(fauEuTaxon);
551

    
552
				if (logger.isDebugEnabled()) {
553
					logger.debug("actual genus id = " + actualGenusId + ", original genus id = " + originalGenusId);
554
				}
555

    
556
				if (actualGenusId.intValue() != originalGenusId.intValue() && taxonBase.isInstanceOf(Taxon.class)) {
557
					createBasionym(fauEuTaxon, taxonBase, taxonName, fauEuConfig, synonymSet, state);
558
				} else if (fauEuTaxon.isParenthesis()) {
559
					//the Authorship should be set in parenthesis because there should be a basionym, but we do not know it?
560
					ZoologicalName zooName = taxonName.deproxy(taxonName, ZoologicalName.class);
561
					zooName.setBasionymAuthorship(zooName.getCombinationAuthorship());
562
					zooName.setCombinationAuthorship(null);
563
					zooName.setOriginalPublicationYear(zooName.getPublicationYear());
564
					zooName.setPublicationYear(null);
565
				}
566

    
567
			}
568
		}
569
		return;
570
	}
571

    
572

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

    
577
		try {
578
			ZoologicalName zooName = taxonName.deproxy(taxonName, ZoologicalName.class);
579

    
580
			// create basionym
581
			ZoologicalName basionym = ZoologicalName.NewInstance(taxonName.getRank());
582
			basionym.setCombinationAuthorship(zooName.getCombinationAuthorship());
583
			basionym.setPublicationYear(zooName.getPublicationYear());
584

    
585

    
586
			zooName.addBasionym(basionym, fauEuConfig.getSourceReference(), null, null);
587
			//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)
588
			if (fauEuTaxon.isParenthesis()){
589
				zooName.setOriginalPublicationYear(zooName.getPublicationYear());
590
				zooName.setBasionymAuthorship(zooName.getCombinationAuthorship());
591
				zooName.setCombinationAuthorship(null);
592
			} else{
593
				zooName.setBasionymAuthorship(null);
594
				zooName.setAuthorshipCache(zooName.getAuthorshipCache(), true);
595
				zooName.setCombinationAuthorship(null);
596
			}
597
			zooName.setPublicationYear(null);
598
			zooName.setTitleCache(null); // This should (re)generate the titleCache automatically
599
			if (logger.isDebugEnabled()) {
600
				logger.debug("Basionym created (" + fauEuTaxon.getId() + ")");
601
			}
602

    
603
			// create synonym
604
			Synonym synonym = Synonym.NewInstance(basionym, fauEuConfig.getSourceReference());
605
			MarkerType markerType =getMarkerType(state, PesiTransformer.uuidMarkerGuidIsMissing, "Uuid is missing", "Uuid is missing", null);
606
			synonym.addMarker(Marker.NewInstance(markerType, true));
607

    
608
			if (fauEuTaxon.isValid()) { // Taxon
609

    
610
				// homotypic synonym
611
				Taxon taxon = taxonBase.deproxy(taxonBase, Taxon.class);
612
				taxon.addHomotypicSynonym(synonym, fauEuConfig.getSourceReference(), null);
613

    
614
				if (logger.isDebugEnabled()) {
615
					logger.debug("Homotypic synonym created (" + fauEuTaxon.getId() + ")");
616
				}
617

    
618
			} else { // Synonym
619

    
620
				// heterotypic synonym
621
				// synonym relationship to the accepted taxon is created later
622
				synonymSet.add(synonym);
623

    
624
				if (logger.isDebugEnabled()) {
625
					logger.debug("Heterotypic synonym stored (" + fauEuTaxon.getId() + ")");
626
				}
627
			}
628

    
629

    
630
			buildTaxonName(fauEuTaxon, synonym, basionym, true, fauEuConfig);
631

    
632
			//originalSources zufügen
633

    
634
			ImportHelper.setOriginalSource(synonym, fauEuConfig.getSourceReference(), fauEuTaxon.getId(), PesiTransformer.STR_NAMESPACE_NOMINAL_TAXON);
635
			ImportHelper.setOriginalSource(synonym.getName(), fauEuConfig.getSourceReference(), fauEuTaxon.getId(), PesiTransformer.STR_NAMESPACE_NOMINAL_TAXON);
636

    
637
			// add originalGenusId as source
638
//			String originalGenusIdString = String.valueOf(fauEuTaxon.getId());
639
//			IdentifiableSource basionymSource = IdentifiableSource.NewInstance(originalGenusIdString, "originalGenusId");
640
//			basionym.addSource(basionymSource);
641
//
642
//			// add original database reference
643
//			ImportHelper.setOriginalSource(basionym, fauEuConfig.getSourceReference(), fauEuTaxon.getId(), "TaxonName");
644

    
645

    
646
		} catch (Exception e) {
647
			logger.warn("Exception occurred when creating basionym for " + fauEuTaxon.getId());
648
			e.printStackTrace();
649
		}
650

    
651

    
652
		return;
653
	}
654

    
655

    
656
	/* Build name title cache */
657
	private String buildNameTitleCache(String nameString, boolean useOriginalGenus, FaunaEuropaeaTaxon fauEuTaxon) {
658

    
659
		StringBuilder titleCacheStringBuilder = new StringBuilder(nameString);
660
		Integer year = fauEuTaxon.getYear();
661
		if (year != null) { // TODO: Ignore authors like xp, xf, etc?
662
			titleCacheStringBuilder.append(" ");
663
			if ((fauEuTaxon.isParenthesis() == true) && !useOriginalGenus) {
664
				titleCacheStringBuilder.append("(");
665
			}
666
			titleCacheStringBuilder.append(fauEuTaxon.getAuthor());
667
			titleCacheStringBuilder.append(" ");
668
			titleCacheStringBuilder.append(year);
669
			if ((fauEuTaxon.isParenthesis() == true) && !useOriginalGenus) {
670
				titleCacheStringBuilder.append(")");
671
			}
672
		}
673
		return titleCacheStringBuilder.toString();
674
	}
675

    
676

    
677
	/* Build taxon title cache */
678
	private String buildTaxonTitleCache(String nameCache, Reference<?> reference) {
679

    
680
		StringBuilder titleCacheStringBuilder = new StringBuilder(nameCache);
681
		titleCacheStringBuilder.append(" sec. ");
682
		titleCacheStringBuilder.append(reference.getTitleCache());
683
		return titleCacheStringBuilder.toString();
684
	}
685

    
686

    
687
	/* Build name full title cache */
688
	private String buildNameFullTitleCache(String titleCache, FaunaEuropaeaImportConfigurator fauEuConfig) {
689

    
690
		StringBuilder fullTitleCacheStringBuilder = new StringBuilder(titleCache);
691
		fullTitleCacheStringBuilder.append(" ");
692
		fullTitleCacheStringBuilder.append(fauEuConfig.getSourceReferenceTitle());
693
		return fullTitleCacheStringBuilder.toString();
694
	}
695

    
696

    
697
	private String genusPart(StringBuilder originalGenusName, boolean useOriginalGenus,
698
			StringBuilder genusOrUninomial) {
699

    
700
		StringBuilder stringBuilder = new StringBuilder();
701

    
702
		if(useOriginalGenus) {
703
			stringBuilder.append(originalGenusName);
704
			genusOrUninomial.delete(0, genusOrUninomial.length());
705
			genusOrUninomial.append(originalGenusName);
706
		} else {
707
			stringBuilder.append(genusOrUninomial);
708
		}
709
		stringBuilder.append(" ");
710

    
711
		return stringBuilder.toString();
712
	}
713

    
714

    
715
	private String genusSubGenusPart(StringBuilder originalGenusName, boolean useOriginalGenus,
716
			StringBuilder genusOrUninomial,
717
			StringBuilder infraGenericEpithet,
718
			FaunaEuropaeaTaxon fauEuTaxon) {
719

    
720
		StringBuilder stringBuilder = new StringBuilder();
721

    
722
		stringBuilder.append(genusPart(originalGenusName, useOriginalGenus, genusOrUninomial));
723

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

    
739
		stringBuilder.append("(");
740
		stringBuilder.append(infraGenericEpithet);
741
		stringBuilder.append(")");
742
		stringBuilder.append(" ");
743

    
744
		return stringBuilder.toString();
745
	}
746

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

    
757
		actualGenusId = ranks.get(R_GENUS);
758

    
759
		return actualGenusId;
760
	}
761

    
762

    
763
	/** Build species and subspecies names */
764
	private String buildLowerTaxonName(StringBuilder originalGenus, boolean useOriginalGenus,
765
			StringBuilder genusOrUninomial, StringBuilder infraGenericEpithet,
766
			StringBuilder specificEpithet, StringBuilder infraSpecificEpithet,
767
			FaunaEuropaeaTaxon fauEuTaxon) {
768

    
769
		// species or subspecies name
770
		String localName = fauEuTaxon.getLocalName();
771
		int taxonId = fauEuTaxon.getId();
772
		int parentId = fauEuTaxon.getParentId();
773
		StringBuilder nameCacheStringBuilder = new StringBuilder();
774

    
775
//		FaunaEuropaeaTaxon parent = fauEuTaxonMap.get(parentId);
776
		if (parentId == 0) {
777
			nameCacheStringBuilder.append(localName);
778
			if (logger.isInfoEnabled()) {
779
				logger.info("Parent of (" + taxonId + ") is null");
780
			}
781
			return nameCacheStringBuilder.toString();
782
		}
783

    
784
		String parentName = fauEuTaxon.getParentName();
785
		String grandParentName = fauEuTaxon.getGrandParentName();
786
		String greatGrandParentName = fauEuTaxon.getGreatGrandParentName();
787
		int rank = fauEuTaxon.getRankId();
788
		int parentRankId = fauEuTaxon.getParentRankId();
789
		int grandParentRankId = fauEuTaxon.getGrandParentRankId();
790
		int greatGrandParentRankId = fauEuTaxon.getGreatGrandParentRankId();
791
//		int grandParentId = fauEuTaxon.getGrandParentId();
792
//		int greatGrandParentId = grandParent.getParentId();
793

    
794

    
795
		if (fauEuTaxon.isValid()) { // Taxon
796

    
797
			if (rank == R_SPECIES) {
798

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

    
807

    
808
				} else if(parentRankId == R_GENUS) {
809

    
810
					String genusPart = genusPart(originalGenus, useOriginalGenus,
811
							genusOrUninomial.append(parentName));
812
					nameCacheStringBuilder.append(genusPart);
813
				}
814
				nameCacheStringBuilder.append(localName);
815
				specificEpithet.append(localName);
816

    
817
			} else if (rank == R_SUBSPECIES) {
818

    
819
				if(grandParentRankId == R_SUBGENUS) {
820

    
821
					String genusSubGenusPart = genusSubGenusPart(originalGenus, useOriginalGenus,
822
							genusOrUninomial.append(greatGrandParentName),
823
							infraGenericEpithet.append(grandParentName),
824
							fauEuTaxon);
825
					nameCacheStringBuilder.append(genusSubGenusPart);
826

    
827
				} else if (grandParentRankId == R_GENUS) {
828

    
829
					String genusPart = genusPart(originalGenus, useOriginalGenus,
830
							genusOrUninomial.append(grandParentName));
831
					nameCacheStringBuilder.append(genusPart);
832

    
833
				}
834
				nameCacheStringBuilder.append(parentName);
835
				nameCacheStringBuilder.append(" ");
836
				nameCacheStringBuilder.append(localName);
837
				specificEpithet.append(parentName);
838
				infraSpecificEpithet.append(localName);
839
			}
840
		} else { // Synonym or misapplied name
841

    
842
			if (rank == R_SPECIES) {
843

    
844
				if(grandParentRankId == R_SUBGENUS) {
845

    
846
					String genusSubGenusPart = genusSubGenusPart(originalGenus, useOriginalGenus,
847
							genusOrUninomial.append(greatGrandParentName),
848
							infraGenericEpithet.append(grandParentName),
849
							fauEuTaxon);
850
					nameCacheStringBuilder.append(genusSubGenusPart);
851

    
852
				} else if (grandParentRankId == R_GENUS) {
853

    
854
					String genusPart = genusPart(originalGenus, useOriginalGenus,
855
							genusOrUninomial.append(grandParentName));
856
					nameCacheStringBuilder.append(genusPart);
857

    
858
				}
859
				nameCacheStringBuilder.append(localName);
860
				specificEpithet.append(localName);
861

    
862
			} else if (rank == R_SUBSPECIES) {
863

    
864
				String greatGreatGrandParentName = fauEuTaxon.getGreatGreatGrandParentName();
865

    
866
				if(greatGrandParentRankId == R_SUBGENUS) {
867

    
868
					String genusSubGenusPart = genusSubGenusPart(originalGenus, useOriginalGenus,
869
							genusOrUninomial.append(greatGreatGrandParentName),
870
							infraGenericEpithet.append(greatGrandParentName),
871
							fauEuTaxon);
872
					nameCacheStringBuilder.append(genusSubGenusPart);
873

    
874
				} else if (greatGrandParentRankId == R_GENUS) {
875

    
876
					String genusPart = genusPart(originalGenus, useOriginalGenus,
877
							genusOrUninomial.append(greatGreatGrandParentName));
878
					nameCacheStringBuilder.append(genusPart);
879
				}
880

    
881
				nameCacheStringBuilder.append(grandParentName);
882
				nameCacheStringBuilder.append(" ");
883
				specificEpithet.append(grandParentName);
884
				nameCacheStringBuilder.append(localName);
885
				infraSpecificEpithet.append(localName);
886
			}
887

    
888

    
889

    
890
		}
891

    
892
		return nameCacheStringBuilder.toString();
893
	}
894

    
895

    
896
	/** Build taxon's name parts and caches */
897
	private String buildTaxonName(FaunaEuropaeaTaxon fauEuTaxon, TaxonBase<?> taxonBase, TaxonNameBase<?,?>taxonName,
898
			boolean useOriginalGenus, FaunaEuropaeaImportConfigurator fauEuConfig) {
899

    
900
		/* Local taxon name string */
901
		String localString = "";
902
		/* Concatenated taxon name string */
903
		String completeString = "";
904

    
905
		StringBuilder acceptedGenus = new StringBuilder("");
906

    
907
		StringBuilder genusOrUninomial = new StringBuilder();
908
		StringBuilder infraGenericEpithet = new StringBuilder();
909
		StringBuilder specificEpithet = new StringBuilder();
910
		StringBuilder infraSpecificEpithet = new StringBuilder();
911

    
912
		localString = fauEuTaxon.getLocalName();
913
		int rank = fauEuTaxon.getRankId();
914

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

    
924
		if (acceptedGenusString != null) {
925
			acceptedGenus = new StringBuilder(acceptedGenusString);
926
		}
927

    
928
		if(logger.isDebugEnabled()) {
929
			logger.debug("Local taxon name (rank = " + rank + "): " + localString);
930
		}
931

    
932
		if (rank < R_SPECIES) {
933
			// subgenus or above
934

    
935
			completeString = localString;
936
			if (rank == R_SUBGENUS) {
937
				// subgenus part
938
				infraGenericEpithet.append(localString);
939

    
940
				// genus part
941
				genusOrUninomial.append(acceptedGenus);
942

    
943
				completeString = acceptedGenus + " ("+ localString + ")";
944
			} else {
945
				// genus or above
946
				genusOrUninomial.append(localString);
947
			}
948

    
949
		} else {
950
			// species or below
951

    
952
			taxonBase = taxonBase.deproxy(taxonBase, TaxonBase.class);
953

    
954
			completeString =
955
				buildLowerTaxonName(acceptedGenus, useOriginalGenus,
956
						genusOrUninomial, infraGenericEpithet, specificEpithet, infraSpecificEpithet,
957
						fauEuTaxon);
958

    
959
			completeString = (String) CdmUtils.removeDuplicateWhitespace(completeString.trim());
960

    
961
		}
962
		return setCompleteTaxonName(completeString, useOriginalGenus,
963
				genusOrUninomial.toString(), infraGenericEpithet.toString(),
964
				specificEpithet.toString(), infraSpecificEpithet.toString(),
965
				fauEuTaxon, taxonBase, fauEuConfig);
966

    
967
	}
968

    
969

    
970
	/**
971
	 * Determines the original genus name by searching the taxon with rank Genus.
972
	 * @param fauEuTaxon
973
	 * @return
974
	 */
975
	private String determineAcceptedGenus(FaunaEuropaeaTaxon fauEuTaxon) {
976
		String originalGenus = null;
977

    
978
		HashMap<Integer, String> ranks = new HashMap<Integer, String>();
979
		ranks.put(fauEuTaxon.getParentRankId(), fauEuTaxon.getParentName());
980
		ranks.put(fauEuTaxon.getGrandParentRankId(), fauEuTaxon.getGrandParentName());
981
		ranks.put(fauEuTaxon.getGreatGrandParentRankId(), fauEuTaxon.getGreatGrandParentName());
982
		ranks.put(fauEuTaxon.getGreatGreatGrandParentRankId(), fauEuTaxon.getGreatGreatGrandParentName());
983
		ranks.put(fauEuTaxon.getGreatGreatGreatGrandParentRankId(), fauEuTaxon.getGreatGreatGreatGrandParentName());
984

    
985
		originalGenus = ranks.get(R_GENUS);
986

    
987
		return originalGenus;
988
	}
989

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

    
995
		boolean success = true;
996

    
997
		TaxonNameBase<?,?> taxonName = taxonBase.getName();
998
		ZoologicalName zooName = (ZoologicalName)taxonName;
999

    
1000
		if (!genusOrUninomial.equals("")) {
1001
			zooName.setGenusOrUninomial(emptyToNull(genusOrUninomial));
1002
			if (logger.isDebugEnabled()) {
1003
				logger.debug("genusOrUninomial: " + genusOrUninomial);
1004
			}
1005
		}
1006

    
1007
		//if ((!infraGenericEpithet.equals("") && fauEuTaxon.isParenthesis()) || (!infraGenericEpithet.equals("") && fauEuTaxon.)) {
1008
		if (fauEuTaxon.getParentRankId() == R_SUBGENUS || fauEuTaxon.getRankId() == R_SUBGENUS ||
1009
				fauEuTaxon.getGrandParentRankId() == R_SUBGENUS || fauEuTaxon.getGreatGrandParentRankId() == R_SUBGENUS) {
1010
			zooName.setInfraGenericEpithet(emptyToNull(infraGenericEpithet));
1011
			if (logger.isDebugEnabled()) {
1012
				logger.debug("infraGenericEpithet: " + infraGenericEpithet);
1013
			}
1014
		}
1015
		if ((fauEuTaxon.getRankId() == R_SPECIES || fauEuTaxon.getRankId() == R_SUBSPECIES)) {
1016
			zooName.setSpecificEpithet(emptyToNull(specificEpithet));
1017
			if (logger.isDebugEnabled()) {
1018
				logger.debug("specificEpithet: " + specificEpithet);
1019
			}
1020
		}
1021
		if (fauEuTaxon.getRankId() == R_SUBSPECIES) {
1022
			zooName.setInfraSpecificEpithet(emptyToNull(infraSpecificEpithet));
1023
			if (logger.isDebugEnabled()) {
1024
				logger.debug("infraSpecificEpithet: " + infraSpecificEpithet);
1025
			}
1026
		}
1027
		//TODO: use generate NameCache
1028
		//zooName.setNameCache(concatString);
1029
		String result = zooName.getNameCache();
1030
//		zooName.generateTitle();
1031
		//String titleCache = buildNameTitleCache(concatString, useOriginalGenus, fauEuTaxon);
1032
		//zooName.setTitleCache(titleCache);
1033
		//titleCache = buildNameFullTitleCache(concatString, fauEuConfig);
1034
//		zooName.generateFullTitle();
1035
		//zooName.setFullTitleCache(titleCache); // TODO: Add reference, NC status
1036

    
1037
//		ImportHelper.setOriginalSource(taxonName, fauEuConfig.getSourceReference(),
1038
//				fauEuTaxon.getId(), "TaxonName");
1039
//		taxonBase.setSec(fauEuConfig.getSourceReference());
1040
//		taxonBase.generateTitle();
1041
		//titleCache = buildTaxonTitleCache(concatString, fauEuConfig.getSourceReference());
1042
		//taxonBase.setTitleCache(titleCache);
1043

    
1044
		if (logger.isDebugEnabled()) {
1045
			logger.debug("Name stored: " + result);
1046
		}
1047
		return result;
1048
	}
1049

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

    
1063

    
1064

    
1065
}
(15-15/17)