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.TaxonName;
51
import eu.etaxonomy.cdm.model.name.TaxonNameFactory;
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
 * @since 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
				TaxonName zooName = TaxonNameFactory.NewZoologicalInstance(rank);
355
				TeamOrPersonBase<?> author = authorStore.get(autId);
356

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

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

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

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

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

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

    
386
					if (status == T_STATUS_ACCEPTED ) {
387

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

    
393

    
394
						taxonBase = taxon;
395
					} else if ((status == T_STATUS_NOT_ACCEPTED) && ! auctWordFound) { // synonym
396
						synonym = Synonym.NewInstance(zooName, sourceReference);
397
						//logger.info("Synonym created: " + synonym.getTitleCache() + " taxonName: " + zooName.getTitleCache());
398
						if (logger.isDebugEnabled()) {
399
							logger.debug("Synonym created (" + taxonId + ")");
400
						}
401
						taxonBase = synonym;
402
					} else if (status == T_STATUS_NOT_ACCEPTED && (necAuctFound || auctNecFound)){
403
						synonym = Synonym.NewInstance(zooName, sourceReference);
404
						NomenclaturalStatus tempNameNomStatus = NomenclaturalStatus.NewInstance(FaunaEuropaeaTransformer.getNomStatusTempNamed(getTermService()));
405
						zooName.addStatus(tempNameNomStatus);
406
						taxonBase = synonym;
407
						logger.info("temporary named name created ("+ taxonId + ") " + zooName.getTitleCache()+ zooName.getStatus().toString());
408
					}else if (status == T_STATUS_NOT_ACCEPTED && auctWordFound){
409
							// misapplied name
410
								zooName.setCombinationAuthorship(null);
411
								zooName.setPublicationYear(null);
412
								// now we do it with appended phrase and without auct reference
413
								taxon = Taxon.NewInstance(zooName, null);
414
								taxonBase = taxon;
415
								//logger.info("Misapplied name created ("+ taxonId + ") " + autName);
416
								if (logger.isDebugEnabled()) {
417
									logger.debug("Misapplied name created (" + taxonId + ")");
418
									}
419
					}else{
420

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

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

    
430
					// Add Note extensions to this taxon
431

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

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

    
449

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

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

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

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

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

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

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

    
477

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

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

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

    
510
		commitTransaction(txStatus);
511
	}
512

    
513

    
514

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

    
522
		FaunaEuropaeaImportConfigurator fauEuConfig = state.getConfig();
523

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

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

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

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

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

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

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

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

    
565
			}
566
		}
567
		return;
568
	}
569

    
570

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

    
575
		try {
576
//			fIZoologicalName zooName = CdmBase.deproxy(taxonName);
577

    
578
			// create basionym
579
			TaxonName basionym =TaxonNameFactory.NewZoologicalInstance(taxonName.getRank());
580
			basionym.setCombinationAuthorship(taxonName.getCombinationAuthorship());
581
			basionym.setPublicationYear(taxonName.getPublicationYear());
582

    
583

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

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

    
606
			if (fauEuTaxon.isValid()) { // Taxon
607

    
608
				// homotypic synonym
609
				Taxon taxon = CdmBase.deproxy(taxonBase, Taxon.class);
610
				taxon.addHomotypicSynonym(synonym);
611

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

    
616
			} else { // Synonym
617

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

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

    
627

    
628
			buildTaxonName(fauEuTaxon, synonym, basionym, true, fauEuConfig);
629

    
630
			//originalSources zufügen
631

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

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

    
643

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

    
649

    
650
		return;
651
	}
652

    
653

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

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

    
674

    
675
	/* Build taxon title cache */
676
	private String buildTaxonTitleCache(String nameCache, Reference reference) {
677

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

    
684

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

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

    
694

    
695
	private String genusPart(StringBuilder originalGenusName, boolean useOriginalGenus,
696
			StringBuilder genusOrUninomial) {
697

    
698
		StringBuilder stringBuilder = new StringBuilder();
699

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

    
709
		return stringBuilder.toString();
710
	}
711

    
712

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

    
718
		StringBuilder stringBuilder = new StringBuilder();
719

    
720
		stringBuilder.append(genusPart(originalGenusName, useOriginalGenus, genusOrUninomial));
721

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

    
737
		stringBuilder.append("(");
738
		stringBuilder.append(infraGenericEpithet);
739
		stringBuilder.append(")");
740
		stringBuilder.append(" ");
741

    
742
		return stringBuilder.toString();
743
	}
744

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

    
755
		actualGenusId = ranks.get(R_GENUS);
756

    
757
		return actualGenusId;
758
	}
759

    
760

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

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

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

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

    
792

    
793
		if (fauEuTaxon.isValid()) { // Taxon
794

    
795
			if (rank == R_SPECIES) {
796

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

    
805

    
806
				} else if(parentRankId == R_GENUS) {
807

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

    
815
			} else if (rank == R_SUBSPECIES) {
816

    
817
				if(grandParentRankId == R_SUBGENUS) {
818

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

    
825
				} else if (grandParentRankId == R_GENUS) {
826

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

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

    
840
			if (rank == R_SPECIES) {
841

    
842
				if(grandParentRankId == R_SUBGENUS) {
843

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

    
850
				} else if (grandParentRankId == R_GENUS) {
851

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

    
856
				}
857
				nameCacheStringBuilder.append(localName);
858
				specificEpithet.append(localName);
859

    
860
			} else if (rank == R_SUBSPECIES) {
861

    
862
				String greatGreatGrandParentName = fauEuTaxon.getGreatGreatGrandParentName();
863

    
864
				if(greatGrandParentRankId == R_SUBGENUS) {
865

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

    
872
				} else if (greatGrandParentRankId == R_GENUS) {
873

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

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

    
886

    
887

    
888
		}
889

    
890
		return nameCacheStringBuilder.toString();
891
	}
892

    
893

    
894
	/** Build taxon's name parts and caches */
895
	private String buildTaxonName(FaunaEuropaeaTaxon fauEuTaxon, TaxonBase taxonBase, TaxonName taxonName,
896
			boolean useOriginalGenus, FaunaEuropaeaImportConfigurator fauEuConfig) {
897

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

    
903
		StringBuilder acceptedGenus = new StringBuilder("");
904

    
905
		StringBuilder genusOrUninomial = new StringBuilder();
906
		StringBuilder infraGenericEpithet = new StringBuilder();
907
		StringBuilder specificEpithet = new StringBuilder();
908
		StringBuilder infraSpecificEpithet = new StringBuilder();
909

    
910
		localString = fauEuTaxon.getLocalName();
911
		int rank = fauEuTaxon.getRankId();
912

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

    
922
		if (acceptedGenusString != null) {
923
			acceptedGenus = new StringBuilder(acceptedGenusString);
924
		}
925

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

    
930
		if (rank < R_SPECIES) {
931
			// subgenus or above
932

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

    
938
				// genus part
939
				genusOrUninomial.append(acceptedGenus);
940

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

    
947
		} else {
948
			// species or below
949

    
950
			taxonBase = taxonBase.deproxy(taxonBase, TaxonBase.class);
951

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

    
957
			completeString = (String) CdmUtils.removeDuplicateWhitespace(completeString.trim());
958

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

    
965
	}
966

    
967

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

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

    
983
		originalGenus = ranks.get(R_GENUS);
984

    
985
		return originalGenus;
986
	}
987

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

    
993
		boolean success = true;
994

    
995
		TaxonName taxonName = taxonBase.getName();
996

    
997
		if (!genusOrUninomial.equals("")) {
998
			taxonName.setGenusOrUninomial(emptyToNull(genusOrUninomial));
999
			if (logger.isDebugEnabled()) {
1000
				logger.debug("genusOrUninomial: " + genusOrUninomial);
1001
			}
1002
		}
1003

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

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

    
1041
		if (logger.isDebugEnabled()) {
1042
			logger.debug("Name stored: " + result);
1043
		}
1044
		return result;
1045
	}
1046

    
1047
	/**
1048
	 * Ensures that empty strings are translated to null.
1049
	 * @param genusOrUninomial
1050
	 * @return
1051
	 */
1052
	private String emptyToNull(String text) {
1053
		if (StringUtils.isBlank(text)) {
1054
			return null;
1055
		} else {
1056
			return text;
1057
		}
1058
	}
1059

    
1060

    
1061

    
1062
}
(15-15/20)