Project

General

Profile

Download (44.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.A_AUCT;
13

    
14
import java.sql.ResultSet;
15
import java.sql.SQLException;
16
import java.util.ArrayList;
17
import java.util.HashMap;
18
import java.util.HashSet;
19
import java.util.List;
20
import java.util.Map;
21
import java.util.Set;
22
import java.util.UUID;
23

    
24
import org.apache.commons.lang.StringUtils;
25
import org.apache.log4j.Logger;
26
import org.springframework.stereotype.Component;
27
import org.springframework.transaction.TransactionStatus;
28

    
29
import eu.etaxonomy.cdm.hibernate.HibernateProxyHelper;
30
import eu.etaxonomy.cdm.io.common.ICdmIO;
31
import eu.etaxonomy.cdm.io.common.MapWrapper;
32
import eu.etaxonomy.cdm.io.common.Source;
33
import eu.etaxonomy.cdm.io.pesi.out.PesiTransformer;
34
import eu.etaxonomy.cdm.model.agent.TeamOrPersonBase;
35
import eu.etaxonomy.cdm.model.common.Annotation;
36
import eu.etaxonomy.cdm.model.common.CdmBase;
37
import eu.etaxonomy.cdm.model.common.IdentifiableSource;
38
import eu.etaxonomy.cdm.model.common.Language;
39
import eu.etaxonomy.cdm.model.common.Marker;
40
import eu.etaxonomy.cdm.model.common.MarkerType;
41
import eu.etaxonomy.cdm.model.name.Rank;
42
import eu.etaxonomy.cdm.model.name.TaxonNameBase;
43
import eu.etaxonomy.cdm.model.name.ZoologicalName;
44
import eu.etaxonomy.cdm.model.reference.Reference;
45
import eu.etaxonomy.cdm.model.taxon.Classification;
46
import eu.etaxonomy.cdm.model.taxon.Synonym;
47
import eu.etaxonomy.cdm.model.taxon.SynonymRelationship;
48
import eu.etaxonomy.cdm.model.taxon.SynonymRelationshipType;
49
import eu.etaxonomy.cdm.model.taxon.Taxon;
50
import eu.etaxonomy.cdm.model.taxon.TaxonBase;
51
import eu.etaxonomy.cdm.model.taxon.TaxonNode;
52
//import eu.etaxonomy.cdm.profiler.ProfilerController;
53
import eu.etaxonomy.cdm.model.taxon.TaxonNodeAgentRelation;
54

    
55

    
56

    
57
/**
58
 * @author a.babadshanjan
59
 * @created 12.05.2009
60
 */
61
@Component
62
public class FaunaEuropaeaRelTaxonIncludeImport extends FaunaEuropaeaImportBase  {
63

    
64
	public static final String OS_NAMESPACE_TAXON = "Taxon";
65
	private static final Logger logger = Logger.getLogger(FaunaEuropaeaRelTaxonIncludeImport.class);
66
	//private static final String acceptedTaxonUUID = "A9C24E42-69F5-4681-9399-041E652CF338"; // any accepted taxon uuid, taken from original fauna europaea database
67
	//private static final String acceptedTaxonUUID = "E23E6295-836A-4332-BF72-7D29949C7C60"; //faunaEu_1_3
68
	//private static final String acceptedTaxonUUID = "bab7642e-f733-4a21-848d-a15250d2f4ed"; //for faunEu (2.4)
69
	private static final String acceptedTaxonUUID = "DADA6F44-B7B5-4C0A-9F32-980F54B02C36"; // for MfNFaunaEuropaea
70

    
71

    
72
	private Reference<?> sourceRef;
73
    private final String parentPluralString = "Taxa";
74
	private static String ALL_SYNONYM_FROM_CLAUSE = " FROM Taxon INNER JOIN Taxon AS Parent " +
75
	" ON Taxon.TAX_TAX_IDPARENT = Parent.TAX_ID " +
76
	" WHERE (Taxon.TAX_VALID = 0) " +
77
	" AND (Taxon.TAX_AUT_ID <> " + A_AUCT + " OR Taxon.TAX_AUT_ID IS NULL)";
78

    
79
	@Override
80
	protected boolean doCheck(FaunaEuropaeaImportState state) {
81
		boolean result = true;
82
		FaunaEuropaeaImportConfigurator fauEuConfig = state.getConfig();
83
		logger.warn("Checking for Taxa not yet fully implemented");
84
		result &= checkTaxonStatus(fauEuConfig);
85

    
86
		return result;
87
	}
88

    
89
	@Override
90
	protected boolean isIgnore(FaunaEuropaeaImportState state) {
91
		return ! (state.getConfig().isDoTaxonomicallyIncluded() ||
92
		state.getConfig().isDoMisappliedNames() || state.getConfig().isDoHeterotypicSynonyms() || state.getConfig().isDoInferredSynonyms());
93
	}
94

    
95
	private boolean checkTaxonStatus(FaunaEuropaeaImportConfigurator fauEuConfig) {
96
		boolean result = true;
97
//		try {
98
			Source source = fauEuConfig.getSource();
99
			String sqlStr = "";
100
			ResultSet rs = source.getResultSet(sqlStr);
101
			return result;
102
//		} catch (SQLException e) {
103
//			e.printStackTrace();
104
//			return false;
105
//		}
106
	}
107

    
108
	@Override
109
	protected void doInvoke(FaunaEuropaeaImportState state) {
110

    
111
		/*logger.warn("Start RelTaxon doInvoke");
112
		ProfilerController.memorySnapshot();
113
		*/
114

    
115

    
116
		Map<String, MapWrapper<? extends CdmBase>> stores = state.getStores();
117

    
118
		MapWrapper<TeamOrPersonBase> authorStore = (MapWrapper<TeamOrPersonBase>)stores.get(ICdmIO.TEAM_STORE);
119
		authorStore.makeEmpty();
120

    
121
		if(logger.isInfoEnabled()) { logger.info("Start making relationships..."); }
122

    
123
		TransactionStatus txStatus = startTransaction();
124

    
125
		// the uuid of an accepted taxon is needed here. any accepted taxon will do.
126
		TaxonBase taxon = getTaxonService().find(UUID.fromString(acceptedTaxonUUID));
127
		sourceRef = taxon.getSec();
128

    
129
		Classification tree = getClassificationFor(state, sourceRef);
130
		commitTransaction(txStatus);
131

    
132
		logger.warn("Before processParentsChildren" + state.getConfig().isDoTaxonomicallyIncluded());
133

    
134
		//ProfilerController.memorySnapshot();
135

    
136
		if (state.getConfig().isDoTaxonomicallyIncluded())  {
137
			processParentsChildren(state);
138

    
139
		}
140
		if (state.getConfig().isDoAssociatedSpecialists()){
141
			processAssociatedSpecialists(state);
142
		}
143

    
144
		logger.warn("Before processMissappliedNames" + state.getConfig().isDoMisappliedNames());
145

    
146
		//ProfilerController.memorySnapshot();
147

    
148
		if (state.getConfig().isDoMisappliedNames()) {
149
			processMisappliedNames(state);
150
		}
151
		/*
152
		logger.warn("Before heterotypic synonyms");
153
		ProfilerController.memorySnapshot();
154
		*/
155
		if (state.getConfig().isDoHeterotypicSynonyms()) {
156
			if(logger.isInfoEnabled()) {
157
				logger.info("Start making heterotypic synonym relationships...");
158
			}
159
			processHeterotypicSynonyms(state, ALL_SYNONYM_FROM_CLAUSE);
160
		}
161

    
162
		if (state.getConfig().isDoInferredSynonyms()){
163
		    processInferredSynonyms(state);
164
		}
165
		/*
166
		logger.warn("End RelTaxon doInvoke");
167
		ProfilerController.memorySnapshot();
168
		*/
169
		logger.info("End making relationships......");
170

    
171
		return;
172
	}
173

    
174
	/** Retrieve child-parent uuid map from CDM DB */
175
	private void processParentsChildren(FaunaEuropaeaImportState state) {
176

    
177
		int limit = state.getConfig().getLimitSave();
178

    
179
		TransactionStatus txStatus = null;
180

    
181
		Map<UUID, UUID> childParentMap = null;
182

    
183
		Map<UUID, UUID> taxonSpecialistMap = null;
184
		Map<UUID, UUID> taxonGroupCoordinatorMap = null;
185
		FaunaEuropaeaImportConfigurator fauEuConfig = state.getConfig();
186
		Source source = fauEuConfig.getSource();
187
		int i = 0;
188

    
189
		String selectCount =
190
			" SELECT count(*) ";
191

    
192
		String selectColumns = " SELECT Taxon.UUID AS ChildUuid, Taxon.tax_usr_idgc as group_coordinator, Taxon.tax_usr_idsp as specialist, Parent.UUID AS ParentUuid, Parent.tax_usr_idgc as parent_group_coordinator, Parent.tax_usr_idsp as parent_specialist";
193

    
194
		String fromClause = " FROM Taxon INNER JOIN Taxon AS Parent " +
195
		" ON Taxon.TAX_TAX_IDPARENT = Parent.TAX_ID " +
196
		" WHERE (Taxon.TAX_VALID <> 0) AND (Taxon.TAX_AUT_ID <> " + A_AUCT + " OR Taxon.TAX_AUT_ID IS NULL )";
197

    
198
		String orderClause = " ORDER BY Taxon.TAX_RNK_ID ASC";
199

    
200
		String countQuery =
201
			selectCount + fromClause;
202

    
203
		String selectQuery =
204
			selectColumns + fromClause + orderClause;
205

    
206
		if(logger.isInfoEnabled()) { logger.info("Start making taxonomically included relationships..."); }
207

    
208
		try {
209

    
210
			ResultSet rs = source.getResultSet(countQuery);
211
			rs.next();
212
			int count = rs.getInt(1);
213

    
214
			rs = source.getResultSet(selectQuery);
215

    
216
	        if (logger.isInfoEnabled()) {
217
				logger.info("Number of rows: " + count);
218
				logger.info("Count Query: " + countQuery);
219
				logger.info("Select Query: " + selectQuery);
220
			}
221

    
222
	        while (rs.next()) {
223

    
224
				if ((i++ % limit) == 0) {
225

    
226
					txStatus = startTransaction();
227
					childParentMap = new HashMap<UUID, UUID>(limit);
228
					taxonSpecialistMap = new HashMap<UUID,UUID>(limit);
229
					taxonGroupCoordinatorMap = new HashMap<UUID, UUID>(limit);
230
					if(logger.isInfoEnabled()) {
231
						logger.info("Taxonomically included retrieved: " + (i-1));
232
					}
233
				}
234

    
235
				String childUuidStr = rs.getString("ChildUuid");
236
				String parentUuidStr = rs.getString("ParentUuid");
237

    
238
				int group_coordinator_id = rs.getInt("group_coordinator");
239
				int specialist_id = rs.getInt("specialist");
240
				int parent_group_coordinator_id = rs.getInt("parent_group_coordinator");
241
                int parent_specialist_id = rs.getInt("parent_specialist");
242
				UUID childUuid = UUID.fromString(childUuidStr);
243
				UUID parentUuid = UUID.fromString(parentUuidStr);
244

    
245
				if (!childParentMap.containsKey(childUuid)) {
246

    
247
						childParentMap.put(childUuid, parentUuid);
248

    
249

    
250
				} else {
251
					if(logger.isDebugEnabled()) {
252
						logger.debug("Duplicated child UUID (" + childUuid + ")");
253
					}
254
				}
255
				if (!taxonSpecialistMap.containsKey(childUuid)) {
256

    
257
				    taxonSpecialistMap.put(childUuid, state.getAgentMap().get(specialist_id));
258
				}
259
				if (!taxonSpecialistMap.containsKey(parentUuid)) {
260

    
261
                    taxonSpecialistMap.put(parentUuid, state.getAgentMap().get(parent_specialist_id));
262
                }
263
				if (taxonGroupCoordinatorMap.containsKey(childUuid)) {
264

    
265
				    taxonGroupCoordinatorMap.put(childUuid, state.getAgentMap().get(group_coordinator_id));
266
                }
267
                if (!taxonGroupCoordinatorMap.containsKey(parentUuid)) {
268

    
269
                    taxonGroupCoordinatorMap.put(parentUuid, state.getAgentMap().get(parent_group_coordinator_id));
270
                }
271

    
272

    
273
				if (((i % limit) == 0 && i != 1 ) || i == count ) {
274

    
275
					createAndCommitParentChildRelationships(
276
							state, txStatus, childParentMap, taxonSpecialistMap, taxonGroupCoordinatorMap);
277
					childParentMap = null;
278

    
279
					if(logger.isInfoEnabled()) {
280
						logger.info("i = " + i + " - Transaction committed");
281
					}
282
				}
283
			}
284
	        rs = null;
285
	        if (childParentMap != null){
286
	        	logger.info("processParentsChildren... last commit");
287
	        	createAndCommitParentChildRelationships(
288
						state, txStatus, childParentMap,taxonSpecialistMap, taxonGroupCoordinatorMap);
289
	        	childParentMap = null;
290
	        }
291

    
292
		} catch (SQLException e) {
293
			logger.error("SQLException:" +  e);
294
			state.setUnsuccessfull();
295
		}
296
		childParentMap = null;
297
		return;
298
	}
299

    
300
	private Map<UUID, UUID> createAndCommitParentChildRelationships(
301
			FaunaEuropaeaImportState state, TransactionStatus txStatus,
302
			Map<UUID, UUID> childParentMap, Map<UUID, UUID> taxonSpecialistMap, Map<UUID, UUID> taxonGroupCoordinatorMap) {
303
		createParentChildRelationships(state, childParentMap, taxonSpecialistMap, taxonGroupCoordinatorMap);
304

    
305

    
306
		commitTransaction(txStatus);
307
		return childParentMap;
308
	}
309

    
310

    
311
	/** Retrieve misapplied name / accepted taxon uuid map from CDM DB */
312
	private void processMisappliedNames(FaunaEuropaeaImportState state) {
313

    
314
		int limit = state.getConfig().getLimitSave();
315

    
316
		TransactionStatus txStatus = null;
317

    
318
		Map<UUID, UUID> childParentMap = null;
319
		FaunaEuropaeaImportConfigurator fauEuConfig = state.getConfig();
320
		Source source = fauEuConfig.getSource();
321
		int i = 0;
322

    
323
		String selectCount =
324
			" SELECT count(*) ";
325

    
326
		String selectColumns = " SELECT Taxon.UUID AS MisappliedUuid, Parent.UUID AS AcceptedUuid ";
327

    
328
		String fromClause = " FROM Taxon INNER JOIN Taxon AS Parent " +
329
		" ON Taxon.TAX_TAX_IDPARENT = Parent.TAX_ID " +
330
		" WHERE (Taxon.TAX_VALID = 0) AND (Taxon.TAX_AUT_ID = " + A_AUCT + ")";
331
		String orderClause = " ORDER BY dbo.Taxon.TAX_RNK_ID ASC ";
332

    
333

    
334

    
335

    
336
		String countQuery =
337
			selectCount + fromClause;
338

    
339
		String selectQuery =
340
			selectColumns + fromClause + orderClause;
341

    
342
		if(logger.isInfoEnabled()) { logger.info("Start making misapplied name relationships..."); }
343

    
344
		try {
345

    
346
			ResultSet rs = source.getResultSet(countQuery);
347
			rs.next();
348
			int count = rs.getInt(1);
349

    
350
			rs = source.getResultSet(selectQuery);
351

    
352
	        if (logger.isInfoEnabled()) {
353
				logger.info("Number of rows: " + count);
354
				logger.info("Count Query: " + countQuery);
355
				logger.info("Select Query: " + selectQuery);
356
			}
357

    
358
			while (rs.next()) {
359

    
360
				if ((i++ % limit) == 0) {
361

    
362
					txStatus = startTransaction();
363
					childParentMap = new HashMap<UUID, UUID>(limit);
364

    
365
					if(logger.isInfoEnabled()) {
366
						logger.info("Misapplied names retrieved: " + (i-1) );
367
					}
368
				}
369

    
370
				String childUuidStr = rs.getString("MisappliedUuid");
371
				String parentUuidStr = rs.getString("AcceptedUuid");
372
				UUID childUuid = UUID.fromString(childUuidStr);
373
				UUID parentUuid = UUID.fromString(parentUuidStr);
374

    
375
				if (!childParentMap.containsKey(childUuid)) {
376

    
377
						childParentMap.put(childUuid, parentUuid);
378

    
379
				} else {
380
					if(logger.isDebugEnabled()) {
381
						logger.debug("Duplicated child UUID (" + childUuid + ")");
382
					}
383
				}
384

    
385
				if (((i % limit) == 0 && i != 1 ) || i == count) {
386

    
387
					createAndCommitMisappliedNameRelationships(state, txStatus,
388
							childParentMap);
389
					childParentMap = null;
390

    
391

    
392
					if(logger.isInfoEnabled()) {
393
						logger.info("i = " + i + " - Transaction committed");
394
					}
395
				}
396
			}
397
			if (childParentMap != null){
398
				logger.info("processMisappliedNames... last commit");
399
				createAndCommitMisappliedNameRelationships(state, txStatus,
400
						childParentMap);
401
				childParentMap = null;
402
			}
403

    
404
		} catch (SQLException e) {
405
			logger.error("SQLException:" +  e);
406
			state.setUnsuccessfull();
407
		}
408
		return;
409
	}
410

    
411
	private void createAndCommitMisappliedNameRelationships(
412
			FaunaEuropaeaImportState state, TransactionStatus txStatus,
413
			Map<UUID, UUID> childParentMap) {
414
		createMisappliedNameRelationships(state, childParentMap);
415
		commitTransaction(txStatus);
416
	}
417

    
418

    
419

    
420
	/** Retrieve synonyms from FauEuDB DB */
421
	private void processHeterotypicSynonyms(FaunaEuropaeaImportState state, String fromClause) {
422

    
423
		FaunaEuropaeaImportConfigurator fauEuConfig = state.getConfig();
424
		Source source = fauEuConfig.getSource();
425

    
426
		String selectCount =
427
			" SELECT count(*) ";
428

    
429
		String selectColumns = " SELECT Taxon.UUID AS SynonymUuid, Parent.UUID AS AcceptedUuid ";
430

    
431
		String orderClause = " ORDER BY dbo.Taxon.TAX_RNK_ID ASC ";
432

    
433
		String countQuery =
434
			selectCount + fromClause;
435

    
436
		String selectQuery =
437
			selectColumns + fromClause + orderClause;
438
		logger.debug(selectQuery);
439

    
440
		try {
441

    
442
			ResultSet rs = source.getResultSet(countQuery);
443
			rs.next();
444
			int count = rs.getInt(1);
445

    
446
			rs = source.getResultSet(selectQuery);
447

    
448
	        if (logger.isInfoEnabled()) {
449
				logger.info("Number of rows: " + count);
450
				logger.info("Count Query: " + countQuery);
451
				logger.info("Select Query: " + selectQuery);
452
			}
453

    
454
	        storeSynonymRelationships(rs, count, state);
455
	        rs = null;
456
		} catch (SQLException e) {
457
			logger.error("SQLException:" +  e);
458
			state.setUnsuccessfull();
459
		}
460
		return;
461
	}
462

    
463

    
464

    
465

    
466
	private void storeSynonymRelationships(ResultSet rs, int count, FaunaEuropaeaImportState state)
467
	throws SQLException {
468

    
469
		TransactionStatus txStatus = null;
470
		Map<UUID, UUID> synonymAcceptedMap = null;
471
		int i = 0;
472
		int limit = state.getConfig().getLimitSave();
473

    
474
		while (rs.next()) {
475

    
476
			if ((i++ % limit) == 0) {
477

    
478
				txStatus = startTransaction();
479
				synonymAcceptedMap = new HashMap<UUID, UUID>(limit);
480

    
481
				if(logger.isInfoEnabled()) {
482
					logger.info("Synonyms retrieved: " + (i-1));
483
				}
484
			}
485

    
486
			String synonymUuidStr = rs.getString("SynonymUuid");
487
			String acceptedUuidStr = rs.getString("AcceptedUuid");
488
			UUID synonymUuid = UUID.fromString(synonymUuidStr);
489
			UUID acceptedUuid = UUID.fromString(acceptedUuidStr);
490

    
491
			if (!synonymAcceptedMap.containsKey(synonymUuid)) {
492

    
493
				synonymAcceptedMap.put(synonymUuid, acceptedUuid);
494

    
495
			} else {
496
				if(logger.isDebugEnabled()) {
497
					logger.debug("Duplicated synonym UUID (" + synonymUuid + ")");
498
				}
499
			}
500

    
501
			if (((i % limit) == 0 && i != 1 ) || i == count ) {
502

    
503
				synonymAcceptedMap = createAndCommitHeterotypicSynonyms(state,
504
						txStatus, synonymAcceptedMap);
505

    
506
				if(logger.isInfoEnabled()) {
507
					logger.info("i = " + i + " - Transaction committed");
508
				}
509
			}
510
		}
511
		if (synonymAcceptedMap != null){
512
			logger.info("processHeterotypicSynonyms... last commit");
513
			synonymAcceptedMap = createAndCommitHeterotypicSynonyms(state,
514
					txStatus, synonymAcceptedMap);
515
		}
516
		return;
517
	}
518

    
519
	private Map<UUID, UUID> createAndCommitHeterotypicSynonyms(
520
			FaunaEuropaeaImportState state, TransactionStatus txStatus,
521
			Map<UUID, UUID> synonymAcceptedMap) {
522
		createHeterotypicSynonyms(state, synonymAcceptedMap);
523

    
524
		synonymAcceptedMap = null;
525
		commitTransaction(txStatus);
526
		return synonymAcceptedMap;
527
	}
528

    
529

    
530

    
531

    
532

    
533
	/* Creates parent-child relationships.
534
	 * Parent-child pairs are retrieved in blocks via findByUUID(Set<UUID>) from CDM DB.
535
	 */
536
	private void createParentChildRelationships(FaunaEuropaeaImportState state, Map<UUID, UUID> childParentMap, Map<UUID, UUID> taxonSpecialistMap, Map<UUID, UUID> taxonGroupCoordinatorMap) {
537
		//gets the taxon "Hydroscaphidae"(family)
538
		TaxonBase taxon = getTaxonService().find(UUID.fromString(acceptedTaxonUUID));
539
		sourceRef = taxon.getSec();
540
		int limit = state.getConfig().getLimitSave();
541

    
542
		Classification tree = getClassificationFor(state, sourceRef);
543

    
544
		Set<TaxonBase> childSet = new HashSet<TaxonBase>(limit);
545

    
546
		Set<UUID> childKeysSet = childParentMap.keySet();
547
		Set<UUID> parentValuesSet = new HashSet<UUID>(childParentMap.values());
548

    
549
		if (logger.isTraceEnabled()) {
550
			logger.trace("Start reading children and parents");
551
		}
552
		List<TaxonBase> children = getTaxonService().find(childKeysSet);
553
		List<TaxonBase> parents = getTaxonService().find(parentValuesSet);
554
		Map<UUID, TaxonBase> parentsMap = new HashMap<UUID, TaxonBase>(parents.size());
555

    
556
		for (TaxonBase taxonBase : parents){
557
			parentsMap.put(taxonBase.getUuid(), taxonBase);
558
		}
559

    
560
		if (logger.isTraceEnabled()) {
561
			logger.debug("End reading children and parents");
562
			for (UUID uuid : childKeysSet) {
563
				logger.trace("child uuid query: " + uuid);
564
			}
565
			for (UUID uuid : parentValuesSet) {
566
				logger.trace("parent uuid query: " + uuid);
567
			}
568
			for (TaxonBase tb : children) {
569
				logger.trace("child uuid result: " + tb.getUuid());
570
			}
571
			for (TaxonBase tb : parents) {
572
				logger.trace("parent uuid result: " + tb.getUuid());
573
			}
574
		}
575

    
576
		UUID mappedParentUuid = null;
577
		UUID childUuid = null;
578
		TaxonNode childNode;
579
		TeamOrPersonBase taxonomicSpecialist = null;
580
		TeamOrPersonBase groupCoordinator = null;
581
		UUID agentUuid = null;
582
		for (TaxonBase child : children) {
583

    
584
			try {
585
				Taxon childTaxon = child.deproxy(child, Taxon.class);
586
				childUuid = childTaxon.getUuid();
587
				mappedParentUuid = childParentMap.get(childUuid);
588
				TaxonBase parent = null;
589

    
590
				TaxonBase potentialParent = parentsMap.get(mappedParentUuid);
591
//					for (TaxonBase potentialParent : parents ) {
592
//						parentUuid = potentialParent.getUuid();
593
//						if(parentUuid.equals(mappedParentUuid)) {
594
						parent = potentialParent;
595
						if (logger.isDebugEnabled()) {
596
							logger.debug("Parent (" + mappedParentUuid + ") found for child (" + childUuid + ")");
597
						}
598
//							break;
599
//						}
600
//					}
601

    
602
				Taxon parentTaxon = parent.deproxy(parent, Taxon.class);
603

    
604
				if (childTaxon != null && parentTaxon != null) {
605

    
606
					childNode = tree.addParentChild(parentTaxon, childTaxon, sourceRef, null);
607
					agentUuid = taxonSpecialistMap.get(childTaxon.getUuid());
608
					taxonomicSpecialist = null;
609
					if (agentUuid != null){
610
					    taxonomicSpecialist = (TeamOrPersonBase) getAgentService().find(agentUuid);
611

    
612
    					if (taxonomicSpecialist != null){
613
    					    childNode.addAgentRelation(FaunaEuropaeaTransformer.getTaxonomicSpecialistType(getTermService()),  taxonomicSpecialist);
614
    					}
615
    				}
616

    
617
					agentUuid = taxonGroupCoordinatorMap.get(childTaxon.getUuid());
618
					groupCoordinator = (TeamOrPersonBase) getAgentService().find(agentUuid);
619
					if (groupCoordinator != null){
620
                        childNode.addAgentRelation(FaunaEuropaeaTransformer.getGroupCoordinatorType(getTermService()),  groupCoordinator);
621
                    }
622

    
623
					//TODO: add the specialist and the group coordinator to the node!!
624
					if (logger.isDebugEnabled()) {
625
						logger.debug("Parent-child (" + mappedParentUuid + "-" + childUuid +
626
						") relationship created");
627
					}
628
					if (childTaxon != null && !childSet.contains(childTaxon)) {
629

    
630
						childSet.add(childTaxon);
631

    
632
						if (logger.isTraceEnabled()) {
633
							logger.trace("Child taxon (" + childUuid + ") added to Set");
634
						}
635

    
636
					} else {
637
						if (logger.isDebugEnabled()) {
638
							logger.debug("Duplicated child taxon (" + childUuid + ")");
639
						}
640
					}
641
				} else {
642
					if (logger.isDebugEnabled()) {
643
						logger.debug("Parent(" + mappedParentUuid + ") or child (" + childUuid + " is null");
644
					}
645
				}
646

    
647
			} catch (Exception e) {
648
				logger.error("Error creating taxonomically included relationship parent-child (" +
649
					mappedParentUuid + " <----> " + childUuid + ")", e);
650
			}
651

    
652
		}
653
		if (logger.isTraceEnabled()) {
654
			logger.trace("Start saving childSet");
655
		}
656
		getTaxonService().save(childSet);
657
		if (logger.isTraceEnabled()) {
658
			logger.trace("End saving childSet");
659
		}
660

    
661
		parentValuesSet = null;
662
		childSet = null;
663
		children = null;
664
		parents = null;
665
		tree = null;
666

    
667
		return;
668
	}
669

    
670
	/* Creates misapplied name relationships.
671
	 * Misapplied name-accepted taxon pairs are retrieved in blocks via findByUUID(Set<UUID>) from CDM DB.
672
	 */
673
	private void createMisappliedNameRelationships(FaunaEuropaeaImportState state, Map<UUID, UUID> fromToMap) {
674

    
675
		//gets the taxon "Hydroscaphidae" (family)
676

    
677
		TaxonBase taxon = getTaxonService().find(UUID.fromString(acceptedTaxonUUID));
678
		sourceRef = taxon.getSec();
679
		int limit = state.getConfig().getLimitSave();
680

    
681
			Set<TaxonBase> misappliedNameSet = new HashSet<TaxonBase>(limit);
682

    
683
			Set<UUID> misappliedNamesSet = fromToMap.keySet();
684
			Set<UUID> acceptedTaxaSet = new HashSet<UUID>(fromToMap.values());
685

    
686
			if (logger.isTraceEnabled()) {
687
				logger.trace("Start reading misapplied names and accepted taxa");
688
			}
689
			List<TaxonBase> misappliedNames = getTaxonService().find(misappliedNamesSet);
690
			List<TaxonBase> acceptedTaxa = getTaxonService().find(acceptedTaxaSet);
691
			Map<UUID, TaxonBase> acceptedTaxaMap = new HashMap<UUID, TaxonBase>(acceptedTaxa.size());
692
			for (TaxonBase taxonBase : acceptedTaxa){
693
				acceptedTaxaMap.put(taxonBase.getUuid(), taxonBase);
694
			}
695

    
696
			if (logger.isTraceEnabled()) {
697
				logger.info("End reading misapplied names and accepted taxa");
698
				for (UUID uuid : misappliedNamesSet) {
699
					logger.trace("misapplied name uuid query: " + uuid);
700
				}
701
				for (UUID uuid : acceptedTaxaSet) {
702
					logger.trace("accepted taxon uuid query: " + uuid);
703
				}
704
				for (TaxonBase tb : misappliedNames) {
705
					logger.trace("misapplied name uuid result: " + tb.getUuid());
706
				}
707
				for (TaxonBase tb : acceptedTaxa) {
708
					logger.trace("accepted taxon uuid result: " + tb.getUuid());
709
				}
710
			}
711

    
712
			UUID mappedAcceptedTaxonUuid = null;
713
			UUID misappliedNameUuid = null;
714
			Taxon misappliedNameTaxon = null;
715
			TaxonBase acceptedTaxonBase = null;
716
			Taxon acceptedTaxon = null;
717

    
718
			for (TaxonBase misappliedName : misappliedNames) {
719

    
720
				try {
721
					misappliedNameTaxon = misappliedName.deproxy(misappliedName, Taxon.class);
722
					misappliedNameUuid = misappliedNameTaxon.getUuid();
723
					mappedAcceptedTaxonUuid = fromToMap.get(misappliedNameUuid);
724
					acceptedTaxonBase = null;
725

    
726
					acceptedTaxonBase = acceptedTaxaMap.get(mappedAcceptedTaxonUuid);
727
							if (logger.isDebugEnabled()) {
728
								logger.debug("Parent (" + mappedAcceptedTaxonUuid + ") found for child (" + misappliedNameUuid + ")");
729
							}
730

    
731
							acceptedTaxon = acceptedTaxonBase.deproxy(acceptedTaxonBase, Taxon.class);
732

    
733
					if (misappliedNameTaxon != null && acceptedTaxon != null) {
734

    
735
						acceptedTaxon.addMisappliedName(misappliedNameTaxon, sourceRef, null);
736

    
737
						if (logger.isDebugEnabled()) {
738
							logger.debug("Accepted taxon / misapplied name (" + mappedAcceptedTaxonUuid + "-" + misappliedNameUuid +
739
							") relationship created");
740
						}
741
						if (!misappliedNameSet.contains(misappliedNameTaxon)) {
742

    
743
							misappliedNameSet.add(misappliedNameTaxon);
744

    
745
							if (logger.isTraceEnabled()) {
746
								logger.trace("Misapplied name taxon (" + misappliedNameUuid + ") added to Set");
747
							}
748

    
749
						} else {
750
							if (logger.isDebugEnabled()) {
751
								logger.debug("Duplicated misapplied name taxon (" + misappliedNameUuid + ")");
752
							}
753
						}
754
					} else {
755
						if (logger.isDebugEnabled()) {
756
							logger.debug("Accepted taxon (" + mappedAcceptedTaxonUuid + ") or misapplied name (" + misappliedNameUuid + " is null");
757
						}
758
					}
759

    
760
					if (misappliedNameTaxon != null && !misappliedNameSet.contains(misappliedNameTaxon)) {
761
						misappliedNameSet.add(misappliedNameTaxon);
762
						if (logger.isTraceEnabled()) {
763
							logger.trace("Misapplied name taxon (" + misappliedNameUuid + ") added to Set");
764
						}
765
					} else {
766
						if (logger.isDebugEnabled()) {
767
							logger.debug("Duplicated misapplied name taxon (" + misappliedNameUuid + ")");
768
						}
769
					}
770

    
771
				} catch (Exception e) {
772
					logger.error("Error creating misapplied name relationship accepted taxon-misapplied name (" +
773
						mappedAcceptedTaxonUuid + "-" + misappliedNameUuid + ")", e);
774
				}
775

    
776
			}
777
			if (logger.isTraceEnabled()) {
778
				logger.trace("Start saving misappliedNameSet");
779
			}
780
			getTaxonService().save(misappliedNameSet);
781
			if (logger.isTraceEnabled()) {
782
				logger.trace("End saving misappliedNameSet");
783
			}
784

    
785
			acceptedTaxaSet = null;
786
			misappliedNameSet = null;
787
			misappliedNames = null;
788
			acceptedTaxa = null;
789

    
790
		return;
791
	}
792

    
793

    
794
	/* Creates heterotypic synonym relationships.
795
	 * Synonym-accepted taxon pairs are retrieved in blocks via findByUUID(Set<UUID>) from CDM DB.
796
	 */
797
	private void createHeterotypicSynonyms(FaunaEuropaeaImportState state, Map<UUID, UUID> fromToMap) {
798

    
799
		int limit = state.getConfig().getLimitSave();
800

    
801
		Set<TaxonBase> synonymSet = new HashSet<TaxonBase>(limit);
802

    
803
		Set<UUID> synonymUuidSet = fromToMap.keySet();
804
		Set<UUID> acceptedTaxaUuidSet = new HashSet<UUID>(fromToMap.values());
805

    
806
		if (logger.isTraceEnabled()) {
807
			logger.trace("Reading synonym names and accepted taxa...");
808
		}
809
		List<TaxonBase> synonyms = getTaxonService().find(synonymUuidSet);
810
		List<TaxonBase> acceptedTaxa = getTaxonService().find(acceptedTaxaUuidSet);
811
		Map<UUID, TaxonBase> acceptedTaxaMap = new HashMap<UUID, TaxonBase>(acceptedTaxa.size());
812
		for (TaxonBase taxonBase : acceptedTaxa){
813
			acceptedTaxaMap.put(taxonBase.getUuid(), taxonBase);
814
		}
815

    
816
		if (logger.isTraceEnabled()) {
817
			logger.trace("End reading synonyms names and accepted taxa");
818
			for (UUID uuid : synonymUuidSet) {
819
				logger.trace("synonym uuid query: " + uuid);
820
			}
821
			for (UUID uuid : acceptedTaxaUuidSet) {
822
				logger.trace("accepted taxon uuid query: " + uuid);
823
			}
824
			for (TaxonBase tb : synonyms) {
825
				logger.trace("synonym uuid result: " + tb.getUuid());
826
			}
827
			for (TaxonBase tb : acceptedTaxa) {
828
				logger.trace("accepted taxon uuid result: " + tb.getUuid());
829
			}
830
		}
831

    
832
		UUID mappedAcceptedTaxonUuid = null;
833
		UUID synonymUuid = null;
834
		Synonym synonym = null;
835
		TaxonBase acceptedTaxonBase = null;
836
		Taxon acceptedTaxon = null;
837

    
838
		for (TaxonBase synonymTaxonBase : synonyms) {
839

    
840
			try {
841
				//check for misapplied names with nec (in Fauna Europaea they have a synonym relationship to the accepted taxon)
842
				if (synonymTaxonBase instanceof Taxon ){
843
					if (((Taxon)synonymTaxonBase).isMisapplication()){
844
						if (logger.isDebugEnabled()) {
845
							logger.debug("misapplied name with exclusion" +  synonymTaxonBase.getTitleCache());
846
						}
847
					}
848
					continue;
849
				}
850
				synonym = HibernateProxyHelper.deproxy(synonymTaxonBase, Synonym.class);
851
				synonymUuid = synonym.getUuid();
852
				mappedAcceptedTaxonUuid = fromToMap.get(synonymUuid);
853
				acceptedTaxonBase = null;
854

    
855
				acceptedTaxonBase = acceptedTaxaMap.get(mappedAcceptedTaxonUuid);
856
				if (logger.isDebugEnabled()) {
857
					logger.debug("Parent (" + mappedAcceptedTaxonUuid + ") found for child (" + synonymUuid + ")");
858
				}
859
				acceptedTaxon = CdmBase.deproxy(acceptedTaxonBase, Taxon.class);
860

    
861
				if (synonym != null && acceptedTaxon != null) {
862

    
863
					//TODO: in case original genus exists must add synonym to original genus instead of to accepted taxon
864
					acceptedTaxon.addSynonym(synonym, SynonymRelationshipType.HETEROTYPIC_SYNONYM_OF());
865

    
866
					if (logger.isDebugEnabled()) {
867
						logger.debug("Accepted taxon - synonym (" + mappedAcceptedTaxonUuid + " - " + synonymUuid +
868
						") relationship created");
869
					}
870
					if (synonym != null && !synonymSet.contains(synonym)) {
871

    
872
						synonymSet.add(synonym);
873

    
874
						if (logger.isTraceEnabled()) {
875
							logger.trace("Synonym (" + synonymUuid + ") added to Set");
876
						}
877

    
878
					} else {
879
						if (logger.isDebugEnabled()) {
880
							logger.debug("Duplicated synonym (" + synonymUuid + ")");
881
						}
882
					}
883
				} else {
884
					if (logger.isDebugEnabled()) {
885
						logger.debug("Accepted taxon (" + mappedAcceptedTaxonUuid + ") or misapplied name (" + synonymUuid + " is null");
886
					}
887
				}
888
			} catch (Exception e) {
889
				logger.error("Error creating synonym relationship: accepted taxon-synonym (" +
890
						mappedAcceptedTaxonUuid + "-" + synonymUuid + ": "+ synonymTaxonBase.getTitleCache() +")", e);
891
			}
892
		}
893
		if (logger.isTraceEnabled()) {
894
			logger.trace("Start saving synonymSet");
895
		}
896
		getTaxonService().save(synonymSet);
897
		if (logger.isTraceEnabled()) {
898
			logger.trace("End saving synonymSet");
899
		}
900

    
901
		acceptedTaxaUuidSet = null;
902
		synonymSet = null;
903
		synonyms = null;
904
		acceptedTaxa = null;
905

    
906
		return;
907
	}
908

    
909
	private void processAssociatedSpecialists(FaunaEuropaeaImportState state){
910
		int limit = state.getConfig().getLimitSave();
911

    
912
		TransactionStatus txStatus = null;
913

    
914
		Map<UUID, UUID> childParentMap = null;
915

    
916

    
917
		TaxonNode taxonNode = null;
918
		TeamOrPersonBase associatedSpecialist = null;
919
		TaxonNodeAgentRelation agentRel = null;
920
		UUID agentUuid = null;
921
		FaunaEuropaeaImportConfigurator fauEuConfig = state.getConfig();
922
		Source source = fauEuConfig.getSource();
923
		int i = 0;
924

    
925
		String selectCount =
926
			" SELECT count(*) ";
927

    
928

    
929

    
930
		String selectColumns = "SELECT  u.USR_GROUPNAME as groupName, u.USR_GROUPNOTE groupNote, u.USR_USR_ID as user_user_id, "
931
				+ "		u.usr_id user_id, user2.USR_ID as user2_id, taxon.UUID as tax_uuid ";
932

    
933
		String fromClause = " FROM USERROLE as userrole left join USERS u on userrole.URL_USR_ID = u.USR_ID left join USERS user2 on user2.USR_ID = u.USR_USR_ID "
934
						+ " left join TAXON taxon on (taxon.TAX_USR_IDSP= user2.USR_ID or taxon.TAX_USR_IDGC= user2.USR_ID) "
935
						+ " where USERROLE.URL_ROL_ID = 7 order by taxon.TAX_ID";
936
		String orderClause = " ORDER BY taxon.TAX_ID";
937

    
938
		String countQuery =
939
			selectCount + fromClause;
940

    
941
		String selectQuery =
942
			selectColumns + fromClause + orderClause;
943

    
944
		if(logger.isInfoEnabled()) { logger.info("Start making associated specialists..."); }
945

    
946
		try {
947

    
948
			ResultSet rs = source.getResultSet(countQuery);
949
			rs.next();
950
			int count = rs.getInt(1);
951

    
952
			rs = source.getResultSet(selectQuery);
953

    
954
	        if (logger.isInfoEnabled()) {
955
				logger.info("Number of rows: " + count);
956
				logger.info("Count Query: " + countQuery);
957
				logger.info("Select Query: " + selectQuery);
958
			}
959

    
960
	        while (rs.next()) {
961
				String taxonUUID = rs.getString("taxUuid");
962
				String oldTaxonUuidString = null;
963
				int userId = rs.getInt("user_id");
964
				int user2Id = rs.getInt("user2_id");
965
				String groupName = rs.getString("groupName");
966
				Taxon taxon = null;
967
				if (!taxonUUID.equals(oldTaxonUuidString)){
968
					if (taxonNode != null){
969
						getTaxonNodeService().saveOrUpdate(taxonNode);
970
					}
971
					commitTransaction(txStatus);
972
					txStatus = startTransaction();
973
					taxon = HibernateProxyHelper.deproxy(getTaxonService().find(UUID.fromString(taxonUUID)), Taxon.class);
974
					oldTaxonUuidString = taxonUUID;
975
					if (!taxon.getTaxonNodes().isEmpty()){
976
						taxonNode = taxon.getTaxonNodes().iterator().next();
977
					} else {
978
						taxonNode = null;
979
						logger.info("There is an associated specialist for a taxon which has no taxonnode.");
980
					}
981
 				}
982

    
983
				agentUuid = state.getAgentMap().get(userId);
984

    
985

    
986
				associatedSpecialist = (TeamOrPersonBase) getAgentService().find(agentUuid);
987
				if (associatedSpecialist != null && taxonNode != null){
988
					agentRel =taxonNode.addAgentRelation(FaunaEuropaeaTransformer.getAssociateSpecialistType(getTermService()), associatedSpecialist);
989
					if (!StringUtils.isBlank(groupName)) {
990
                        agentRel.addAnnotation(Annotation.NewInstance(groupName, Language.DEFAULT()));
991
                    }
992
				}
993

    
994

    
995
	        }
996
	        getTaxonNodeService().saveOrUpdate(taxonNode);
997
			commitTransaction(txStatus);
998
		}catch(SQLException e){
999
			logger.info("Problems during creating associated specialists.", e);
1000
		}
1001
	}
1002

    
1003
	private void processInferredSynonyms(FaunaEuropaeaImportState state){
1004

    
1005
	        int count;
1006
	        int pastCount;
1007
	        boolean success = true;
1008
	        // Get the limit for objects to save within a single transaction.
1009
	        if (! state.getConfig().isDoInferredSynonyms()){
1010
	            logger.info ("Ignore Creating Inferred Synonyms...");
1011
	            return;
1012
	        }
1013

    
1014
	        int limit = state.getConfig().getLimitSave();
1015
	        // Create inferred synonyms for accepted taxa
1016
	        logger.info("Creating Inferred Synonyms...");
1017

    
1018

    
1019
	        count = 0;
1020
	        pastCount = 0;
1021
	        int pageSize = limit/10;
1022
	        int pageNumber = 1;
1023
	        String inferredSynonymPluralString = "Inferred Synonyms";
1024

    
1025
	        // Start transaction
1026
	        TransactionStatus txStatus = startTransaction(true);
1027
	        logger.info("Started new transaction. Fetching some " + parentPluralString + " first (max: " + limit + ") ...");
1028
	        List<TaxonBase> taxonList = null;
1029
	        Set<TaxonBase> synonymList = new HashSet<TaxonBase>();
1030

    
1031

    
1032
	        while ((taxonList  = getTaxonService().listTaxaByName(Taxon.class, "*", "*", "*", "*", Rank.SPECIES(), pageSize, pageNumber)).size() > 0) {
1033
	            HashMap<Integer, TaxonNameBase<?,?>> inferredSynonymsDataToBeSaved = new HashMap<Integer, TaxonNameBase<?,?>>();
1034

    
1035
	            logger.info("Fetched " + taxonList.size() + " " + parentPluralString + ". Importing...");
1036
	            synonymList = createInferredSynonymsForTaxonList(state,  taxonList);
1037
	            getTaxonService().save(synonymList);
1038

    
1039
	          //  getTaxonService().saveOrUpdate(taxonList);
1040
	            // Commit transaction
1041
	            commitTransaction(txStatus);
1042
	            logger.debug("Committed transaction.");
1043
	            logger.info("Imported " + (taxonList.size()) + " " + inferredSynonymPluralString + ". Total: " + count);
1044
	            //pastCount = count;
1045

    
1046

    
1047

    
1048
	            // Start transaction
1049
	            txStatus = startTransaction(true);
1050
	            logger.info("Started new transaction. Fetching some " + parentPluralString + " first (max: " + limit + ") ...");
1051

    
1052
	            // Increment pageNumber
1053
	            pageNumber++;
1054
	        }
1055
	        taxonList = null;
1056
	        while ((taxonList  = getTaxonService().listTaxaByName(Taxon.class, "*", "*", "*", "*", Rank.SUBSPECIES(), pageSize, pageNumber)).size() > 0) {
1057
	            HashMap<Integer, TaxonNameBase<?,?>> inferredSynonymsDataToBeSaved = new HashMap<Integer, TaxonNameBase<?,?>>();
1058

    
1059
	            logger.info("Fetched " + taxonList.size() + " " + parentPluralString  + ". Exporting...");
1060
	            synonymList = createInferredSynonymsForTaxonList(state, taxonList);
1061

    
1062
	            getTaxonService().save(synonymList);
1063
	            // Commit transaction
1064
	            commitTransaction(txStatus);
1065
	            logger.debug("Committed transaction.");
1066
	            logger.info("Exported " + taxonList.size()+ " " + inferredSynonymPluralString + ". Total: " + count);
1067
	            //pastCount = count;
1068

    
1069

    
1070

    
1071
	            // Start transaction
1072
	            txStatus = startTransaction(true);
1073
	            logger.info("Started new transaction. Fetching some " + parentPluralString + " first (max: " + limit + ") ...");
1074

    
1075
	            // Increment pageNumber
1076
	            pageNumber++;
1077
	            inferredSynonymsDataToBeSaved = null;
1078
	        }
1079
	        if (taxonList.size() == 0) {
1080
	            logger.info("No " + parentPluralString + " left to fetch.");
1081
	        }
1082

    
1083
	        taxonList = null;
1084

    
1085
	        // Commit transaction
1086
	        commitTransaction(txStatus);
1087
	        System.gc();
1088

    
1089
	        //ProfilerController.memorySnapshot();
1090
	        logger.debug("Committed transaction.");
1091

    
1092

    
1093
	}
1094

    
1095
	/**
1096
    * @param state
1097
    * @param mapping
1098
    * @param synRelMapping
1099
    * @param currentTaxonId
1100
    * @param taxonList
1101
    * @param inferredSynonymsDataToBeSaved
1102
    * @return
1103
    */
1104
   private Set<TaxonBase> createInferredSynonymsForTaxonList(FaunaEuropaeaImportState state,
1105
            List<TaxonBase> taxonList) {
1106

    
1107
       Taxon acceptedTaxon;
1108
       Classification classification = null;
1109
       Set<TaxonBase> inferredSynonyms = new HashSet<TaxonBase>();
1110
       List<Synonym> inferredSynonymsLocal= new ArrayList<Synonym>();
1111
       boolean localSuccess = true;
1112

    
1113
       HashMap<Integer, TaxonNameBase<?,?>> inferredSynonymsDataToBeSaved = new HashMap<Integer, TaxonNameBase<?,?>>();
1114

    
1115
       for (TaxonBase<?> taxonBase : taxonList) {
1116

    
1117
           if (taxonBase.isInstanceOf(Taxon.class)) { // this should always be the case since we should have fetched accepted taxon only, but you never know...
1118
               acceptedTaxon = CdmBase.deproxy(taxonBase, Taxon.class);
1119
               TaxonNameBase<?,?> taxonName = acceptedTaxon.getName();
1120

    
1121
               if (taxonName.isInstanceOf(ZoologicalName.class)) {
1122
                   Set<TaxonNode> taxonNodes = acceptedTaxon.getTaxonNodes();
1123
                   TaxonNode singleNode = null;
1124

    
1125
                   if (taxonNodes.size() > 0) {
1126
                       // Determine the classification of the current TaxonNode
1127

    
1128
                       singleNode = taxonNodes.iterator().next();
1129
                       if (singleNode != null) {
1130
                           classification = singleNode.getClassification();
1131
                       } else {
1132
                           logger.error("A TaxonNode belonging to this accepted Taxon is NULL: " + acceptedTaxon.getUuid() + " (" + acceptedTaxon.getTitleCache() +")");
1133
                       }
1134
                   } else {
1135
                       // Classification could not be determined directly from this TaxonNode
1136
                       // The stored classification from another TaxonNode is used. It's a simple, but not a failsafe fallback solution.
1137
                       if (taxonNodes.size() == 0) {
1138
                           //logger.error("Classification could not be determined directly from this Taxon: " + acceptedTaxon.getUuid() + " is misapplication? "+acceptedTaxon.isMisapplication()+ "). The classification of the last taxon is used");
1139

    
1140
                       }
1141
                   }
1142

    
1143
                   if (classification != null) {
1144
                       try{
1145
                           TaxonNameBase name = acceptedTaxon.getName();
1146

    
1147
                            //if (name.isSpecies() || name.isInfraSpecific()){
1148
                               inferredSynonymsLocal = getTaxonService().createAllInferredSynonyms(acceptedTaxon, classification, true);
1149
                              // logger.info("number of inferred synonyms: " + inferredSynonyms.size());
1150
                           //}
1151
//                             inferredSynonyms = getTaxonService().createInferredSynonyms(classification, acceptedTaxon, SynonymRelationshipType.INFERRED_GENUS_OF());
1152
                           if (inferredSynonymsLocal != null) {
1153
                               for (TaxonBase synonym : inferredSynonymsLocal) {
1154
//                                 TaxonNameBase<?,?> synonymName = synonym.getName();
1155
                                   MarkerType markerType =getUuidMarkerType(PesiTransformer.uuidMarkerGuidIsMissing, state);
1156

    
1157
                                   synonym.addMarker(Marker.NewInstance(markerType, true));
1158

    
1159

    
1160
                                   //get SynonymRelationship and export
1161
                                   if (((Synonym)synonym).getSynonymRelations().isEmpty() ){
1162
                                       SynonymRelationship synRel;
1163
                                       IdentifiableSource source = ((Synonym)synonym).getSources().iterator().next();
1164
                                       if (source.getIdNamespace().contains("Potential combination")){
1165
                                           synRel = acceptedTaxon.addSynonym((Synonym)synonym, SynonymRelationshipType.POTENTIAL_COMBINATION_OF());
1166
                                           logger.error(synonym.getTitleCache() + " has no synonym relationship to " + acceptedTaxon.getTitleCache() + " type is set to potential combination");
1167
                                       } else if (source.getIdNamespace().contains("Inferred Genus")){
1168
                                           synRel = acceptedTaxon.addSynonym((Synonym)synonym, SynonymRelationshipType.INFERRED_GENUS_OF());
1169
                                           logger.error(synonym.getTitleCache() + " has no synonym relationship to " + acceptedTaxon.getTitleCache() + " type is set to inferred genus");
1170
                                       } else if (source.getIdNamespace().contains("Inferred Epithet")){
1171
                                           synRel = acceptedTaxon.addSynonym((Synonym)synonym, SynonymRelationshipType.INFERRED_EPITHET_OF());
1172
                                           logger.error(synonym.getTitleCache() + " has no synonym relationship to " + acceptedTaxon.getTitleCache() + " type is set to inferred epithet");
1173
                                       } else{
1174
                                           synRel = acceptedTaxon.addSynonym((Synonym)synonym, SynonymRelationshipType.INFERRED_SYNONYM_OF());
1175
                                           logger.error(synonym.getTitleCache() + " has no synonym relationship to " + acceptedTaxon.getTitleCache() + " type is set to inferred synonym");
1176
                                       }
1177

    
1178

    
1179

    
1180
                                       synRel = null;
1181
                                   } else {
1182
                                       for (SynonymRelationship synRel: ((Synonym)synonym).getSynonymRelations()){
1183
                                           if (!localSuccess) {
1184
                                               logger.error("Synonym relationship export failed " + synonym.getTitleCache() + " accepted taxon: " + acceptedTaxon.getUuid() + " (" + acceptedTaxon.getTitleCache()+")");
1185
                                           } else {
1186
                                              // logger.info("Synonym relationship successfully exported: " + synonym.getTitleCache() + "  " +acceptedTaxon.getUuid() + " (" + acceptedTaxon.getTitleCache()+")");
1187
                                           }
1188
                                           synRel = null;
1189
                                       }
1190
                                   }
1191

    
1192
                                   inferredSynonymsDataToBeSaved.put(synonym.getId(), synonym.getName());
1193
                               }
1194

    
1195
                               inferredSynonyms.addAll(inferredSynonymsLocal);
1196
                              //logger.info("inferredSet: " + inferredSet.size());
1197
                               //getTaxonService().save(inferredSynonyms);
1198
                               //commitTransaction(txStatus);
1199

    
1200
                               inferredSynonymsLocal = null;
1201

    
1202
                           }
1203

    
1204

    
1205
                       }catch(Exception e){
1206
                           logger.error(e.getMessage());
1207
                           e.printStackTrace();
1208
                       }
1209
                   } else {
1210
                       logger.error("Classification is NULL. Inferred Synonyms could not be created for this Taxon: " + acceptedTaxon.getUuid() + " (" + acceptedTaxon.getTitleCache() + ")");
1211
                   }
1212
               } else {
1213
//                         logger.error("TaxonName is not a ZoologicalName: " + taxonName.getUuid() + " (" + taxonName.getTitleCache() + ")");
1214
               }
1215
           } else {
1216
               logger.error("This TaxonBase is not a Taxon even though it should be: " + taxonBase.getUuid() + " (" + taxonBase.getTitleCache() + ")");
1217
           }
1218
       }
1219
       //getTaxonService().saveOrUpdate(taxonList);
1220
       taxonList = null;
1221
       return inferredSynonyms;
1222
   }
1223

    
1224

    
1225
}
(13-13/20)