Project

General

Profile

Download (40.4 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
 * @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
				TaxonName zooName = TaxonNameFactory.NewZoologicalInstance(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
								// now we do it with appended phrase and without auct reference
416
								taxon = Taxon.NewInstance(zooName, null);
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
			TaxonName taxonName = CdmBase.deproxy(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
					taxonName.setBasionymAuthorship(taxonName.getCombinationAuthorship());
563
					taxonName.setCombinationAuthorship(null);
564
					taxonName.setOriginalPublicationYear(taxonName.getPublicationYear());
565
					taxonName.setPublicationYear(null);
566
				}
567

    
568
			}
569
		}
570
		return;
571
	}
572

    
573

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

    
578
		try {
579
//			fIZoologicalName zooName = CdmBase.deproxy(taxonName);
580

    
581
			// create basionym
582
			TaxonName basionym =TaxonNameFactory.NewZoologicalInstance(taxonName.getRank());
583
			basionym.setCombinationAuthorship(taxonName.getCombinationAuthorship());
584
			basionym.setPublicationYear(taxonName.getPublicationYear());
585

    
586

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

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

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

    
611
				// homotypic synonym
612
				Taxon taxon = CdmBase.deproxy(taxonBase, Taxon.class);
613
				taxon.addHomotypicSynonym(synonym);
614

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

    
619
			} else { // Synonym
620

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

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

    
630

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

    
633
			//originalSources zufügen
634

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

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

    
646

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

    
652

    
653
		return;
654
	}
655

    
656

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

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

    
677

    
678
	/* Build taxon title cache */
679
	private String buildTaxonTitleCache(String nameCache, Reference reference) {
680

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

    
687

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

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

    
697

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

    
701
		StringBuilder stringBuilder = new StringBuilder();
702

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

    
712
		return stringBuilder.toString();
713
	}
714

    
715

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

    
721
		StringBuilder stringBuilder = new StringBuilder();
722

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

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

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

    
745
		return stringBuilder.toString();
746
	}
747

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

    
758
		actualGenusId = ranks.get(R_GENUS);
759

    
760
		return actualGenusId;
761
	}
762

    
763

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

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

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

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

    
795

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

    
798
			if (rank == R_SPECIES) {
799

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

    
808

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

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

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

    
820
				if(grandParentRankId == R_SUBGENUS) {
821

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

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

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

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

    
843
			if (rank == R_SPECIES) {
844

    
845
				if(grandParentRankId == R_SUBGENUS) {
846

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

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

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

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

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

    
865
				String greatGreatGrandParentName = fauEuTaxon.getGreatGreatGrandParentName();
866

    
867
				if(greatGrandParentRankId == R_SUBGENUS) {
868

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

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

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

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

    
889

    
890

    
891
		}
892

    
893
		return nameCacheStringBuilder.toString();
894
	}
895

    
896

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

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

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

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

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

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

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

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

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

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

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

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

    
950
		} else {
951
			// species or below
952

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

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

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

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

    
968
	}
969

    
970

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

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

    
986
		originalGenus = ranks.get(R_GENUS);
987

    
988
		return originalGenus;
989
	}
990

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

    
996
		boolean success = true;
997

    
998
		TaxonName taxonName = taxonBase.getName();
999

    
1000
		if (!genusOrUninomial.equals("")) {
1001
			taxonName.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
			taxonName.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
			taxonName.setSpecificEpithet(emptyToNull(specificEpithet));
1017
			if (logger.isDebugEnabled()) {
1018
				logger.debug("specificEpithet: " + specificEpithet);
1019
			}
1020
		}
1021
		if (fauEuTaxon.getRankId() == R_SUBSPECIES) {
1022
			taxonName.setInfraSpecificEpithet(emptyToNull(infraSpecificEpithet));
1023
			if (logger.isDebugEnabled()) {
1024
				logger.debug("infraSpecificEpithet: " + infraSpecificEpithet);
1025
			}
1026
		}
1027
		//TODO: use generate NameCache
1028
		//taxonName.setNameCache(concatString);
1029
		String result = taxonName.getNameCache();
1030
//		taxonName.generateTitle();
1031
		//String titleCache = buildNameTitleCache(concatString, useOriginalGenus, fauEuTaxon);
1032
		//taxonName.setTitleCache(titleCache);
1033
		//titleCache = buildNameFullTitleCache(concatString, fauEuConfig);
1034
//		taxonName.generateFullTitle();
1035
		//taxonName.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 (StringUtils.isBlank(text)) {
1057
			return null;
1058
		} else {
1059
			return text;
1060
		}
1061
	}
1062

    
1063

    
1064

    
1065
}
(15-15/20)