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
		if (state.getConfig().isDoTaxa()){
102
			return;
103
		}
104
		processTaxa(state);
105
		logger.info("End making taxa...");
106
		return;
107
	}
108

    
109

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

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

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

    
129
		TransactionStatus txStatus = null;
130

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

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

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

    
142
		Source source = fauEuConfig.getSource();
143
		int i = 0;
144

    
145
		String selectCount =
146
			" SELECT count(*) ";
147

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

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

    
172
		String countQuery =
173
			selectCount + fromClause;
174

    
175
		String selectQuery =
176
			selectColumns + fromClause;
177

    
178

    
179
        try {
180

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

    
185
			rs = source.getResultSet(selectQuery);
186

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

    
193
			while (rs.next()) {
194

    
195
				if ((i++ % limit) == 0) {
196

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

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

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

    
230

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

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

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

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

    
275

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

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

    
287
				//int familyId = rs.getInt("TAX_TAX_IDFAMILY");
288

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

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

    
305
				fauEuTaxon.setParentId(parentId);
306
				fauEuTaxon.setParentRankId(parentRankId);
307
				fauEuTaxon.setParentName(parentName);
308

    
309
				fauEuTaxon.setGrandParentId(grandParentId);
310
				fauEuTaxon.setGrandParentRankId(grandParentRankId);
311
				fauEuTaxon.setGrandParentName(grandParentName);
312

    
313
				fauEuTaxon.setGreatGrandParentId(greatGrandParentId);
314
				fauEuTaxon.setGreatGrandParentRankId(greatGrandParentRankId);
315
				fauEuTaxon.setGreatGrandParentName(greatGrandParentName);
316

    
317
				fauEuTaxon.setGreatGreatGrandParentId(greatGreatGrandParentId);
318
				fauEuTaxon.setGreatGreatGrandParentRankId(greatGreatGrandParentRankId);
319
				fauEuTaxon.setGreatGreatGrandParentName(greatGreatGrandParentName);
320

    
321
				fauEuTaxon.setGreatGreatGreatGrandParentRankId(greatGreatGreatGrandParentRankId);
322
				fauEuTaxon.setGreatGreatGreatGrandParentName(greatGreatGreatGrandParentName);
323

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

    
339
//				fauEuTaxon.setAuthorId(autId);
340

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

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

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

    
357
				zooName.setCombinationAuthorship(author);
358
				zooName.setPublicationYear(year);
359

    
360

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

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

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

    
380
					String auctWithNecRegEx = "\\bauct\\b\\.?.*\\bnec\\b\\.?.*";
381
					String necAuctRegEx = ".*\\bnec\\b\\.?.*\\bauct\\b\\.?";
382

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

    
387

    
388

    
389
					if (status == T_STATUS_ACCEPTED ) {
390

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

    
396

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

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

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

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

    
433
					// Add Note extensions to this taxon
434

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

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

    
452

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

    
456
					if (!taxonMap.containsKey(taxonId)) {
457

    
458
						taxonMap.put(taxonId, taxonBase);
459
						fauEuTaxonMap.put(taxonId, fauEuTaxon);
460

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

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

    
473
					commitTaxa(state, txStatus, taxonMap, fauEuTaxonMap,
474
							synonymSet);
475

    
476
					taxonMap = null;
477
					synonymSet = null;
478
					fauEuTaxonMap = null;
479

    
480

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

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

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

    
513
		commitTransaction(txStatus);
514
	}
515

    
516

    
517

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

    
525
		FaunaEuropaeaImportConfigurator fauEuConfig = state.getConfig();
526

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

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

    
540
			String nameString =
541
				buildTaxonName(fauEuTaxon, taxonBase, taxonName, useOriginalGenus, fauEuConfig);
542

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

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

    
551
				Integer originalGenusId = fauEuTaxon.getOriginalGenusId();
552
				Integer actualGenusId = getActualGenusId(fauEuTaxon);
553

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

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

    
569
			}
570
		}
571
		return;
572
	}
573

    
574

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

    
579
		try {
580
			ZoologicalName zooName = taxonName.deproxy(taxonName, ZoologicalName.class);
581

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

    
587

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

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

    
610
			if (fauEuTaxon.isValid()) { // Taxon
611

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

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

    
620
			} else { // Synonym
621

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

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

    
631

    
632
			buildTaxonName(fauEuTaxon, synonym, basionym, true, fauEuConfig);
633

    
634
			//originalSources zufügen
635

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

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

    
647

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

    
653

    
654
		return;
655
	}
656

    
657

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

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

    
678

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

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

    
688

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

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

    
698

    
699
	private String genusPart(StringBuilder originalGenusName, boolean useOriginalGenus,
700
			StringBuilder genusOrUninomial) {
701

    
702
		StringBuilder stringBuilder = new StringBuilder();
703

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

    
713
		return stringBuilder.toString();
714
	}
715

    
716

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

    
722
		StringBuilder stringBuilder = new StringBuilder();
723

    
724
		stringBuilder.append(genusPart(originalGenusName, useOriginalGenus, genusOrUninomial));
725

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

    
741
		stringBuilder.append("(");
742
		stringBuilder.append(infraGenericEpithet);
743
		stringBuilder.append(")");
744
		stringBuilder.append(" ");
745

    
746
		return stringBuilder.toString();
747
	}
748

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

    
759
		actualGenusId = ranks.get(R_GENUS);
760

    
761
		return actualGenusId;
762
	}
763

    
764

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

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

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

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

    
796

    
797
		if (fauEuTaxon.isValid()) { // Taxon
798

    
799
			if (rank == R_SPECIES) {
800

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

    
809

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

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

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

    
821
				if(grandParentRankId == R_SUBGENUS) {
822

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

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

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

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

    
844
			if (rank == R_SPECIES) {
845

    
846
				if(grandParentRankId == R_SUBGENUS) {
847

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

    
854
				} else if (grandParentRankId == R_GENUS) {
855

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

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

    
864
			} else if (rank == R_SUBSPECIES) {
865

    
866
				String greatGreatGrandParentName = fauEuTaxon.getGreatGreatGrandParentName();
867

    
868
				if(greatGrandParentRankId == R_SUBGENUS) {
869

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

    
876
				} else if (greatGrandParentRankId == R_GENUS) {
877

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

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

    
890

    
891

    
892
		}
893

    
894
		return nameCacheStringBuilder.toString();
895
	}
896

    
897

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

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

    
907
		StringBuilder acceptedGenus = new StringBuilder("");
908

    
909
		StringBuilder genusOrUninomial = new StringBuilder();
910
		StringBuilder infraGenericEpithet = new StringBuilder();
911
		StringBuilder specificEpithet = new StringBuilder();
912
		StringBuilder infraSpecificEpithet = new StringBuilder();
913

    
914
		localString = fauEuTaxon.getLocalName();
915
		int rank = fauEuTaxon.getRankId();
916

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

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

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

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

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

    
942
				// genus part
943
				genusOrUninomial.append(acceptedGenus);
944

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

    
951
		} else {
952
			// species or below
953

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

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

    
961
			completeString = (String) CdmUtils.removeDuplicateWhitespace(completeString.trim());
962

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

    
969
	}
970

    
971

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

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

    
987
		originalGenus = ranks.get(R_GENUS);
988

    
989
		return originalGenus;
990
	}
991

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

    
997
		boolean success = true;
998

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

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

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

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

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

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

    
1065

    
1066

    
1067
}
(15-15/20)