Project

General

Profile

Download (23.7 KB) Statistics
| Branch: | Revision:
1
/**
2
* Copyright (C) 2009 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
package eu.etaxonomy.cdm.io.pesi.out;
10

    
11
import java.util.ArrayList;
12
import java.util.EnumSet;
13
import java.util.HashSet;
14
import java.util.Iterator;
15
import java.util.List;
16
import java.util.Set;
17
import java.util.UUID;
18

    
19
import org.apache.log4j.Logger;
20

    
21
import eu.etaxonomy.cdm.api.service.pager.Pager;
22
import eu.etaxonomy.cdm.hibernate.HibernateProxyHelper;
23
import eu.etaxonomy.cdm.io.berlinModel.BerlinModelTransformer;
24
import eu.etaxonomy.cdm.io.common.DbExportBase;
25
import eu.etaxonomy.cdm.io.common.mapping.out.DbLastActionMapper;
26
import eu.etaxonomy.cdm.io.pesi.erms.ErmsTransformer;
27
import eu.etaxonomy.cdm.model.common.AnnotationType;
28
import eu.etaxonomy.cdm.model.common.CdmBase;
29
import eu.etaxonomy.cdm.model.common.IdentifiableEntity;
30
import eu.etaxonomy.cdm.model.common.IdentifiableSource;
31
import eu.etaxonomy.cdm.model.common.Marker;
32
import eu.etaxonomy.cdm.model.common.MarkerType;
33
import eu.etaxonomy.cdm.model.common.RelationshipBase;
34
import eu.etaxonomy.cdm.model.description.Feature;
35
import eu.etaxonomy.cdm.model.description.TaxonNameDescription;
36
import eu.etaxonomy.cdm.model.description.TextData;
37
import eu.etaxonomy.cdm.model.name.HybridRelationship;
38
import eu.etaxonomy.cdm.model.name.INonViralName;
39
import eu.etaxonomy.cdm.model.name.NameRelationship;
40
import eu.etaxonomy.cdm.model.name.NameRelationshipType;
41
import eu.etaxonomy.cdm.model.name.TaxonName;
42
import eu.etaxonomy.cdm.model.reference.Reference;
43
import eu.etaxonomy.cdm.model.taxon.Synonym;
44
import eu.etaxonomy.cdm.model.taxon.Taxon;
45
import eu.etaxonomy.cdm.model.taxon.TaxonBase;
46
import eu.etaxonomy.cdm.model.taxon.TaxonNode;
47
import eu.etaxonomy.cdm.model.taxon.TaxonRelationship;
48
import eu.etaxonomy.cdm.model.taxon.TaxonRelationshipType;
49
import eu.etaxonomy.cdm.persistence.query.OrderHint;
50
import eu.etaxonomy.cdm.strategy.cache.name.TaxonNameDefaultCacheStrategy;
51
import eu.etaxonomy.cdm.strategy.cache.name.ZooNameNoMarkerCacheStrategy;
52

    
53
/**
54
 * @author e.-m.lee
55
 * @since 12.02.2010
56
 */
57
public abstract class PesiExportBase
58
              extends DbExportBase<PesiExportConfigurator, PesiExportState, PesiTransformer> {
59

    
60
    private static final long serialVersionUID = 6226747017958138156L;
61
    private static final Logger logger = Logger.getLogger(PesiExportBase.class);
62

    
63
	protected static final boolean IS_CACHE = true;
64

    
65
	private static Set<NameRelationshipType> excludedRelTypes = new HashSet<>();
66

    
67
	private static TaxonNameDefaultCacheStrategy zooNameStrategy = ZooNameNoMarkerCacheStrategy.NewInstance();
68
	private static TaxonNameDefaultCacheStrategy botanicalNameStrategy = TaxonNameDefaultCacheStrategy.NewInstance();
69

    
70
	public PesiExportBase() {
71
		super();
72
	}
73

    
74
	protected <CLASS extends TaxonBase> List<CLASS> getNextTaxonPartition(Class<CLASS> clazz, int limit,
75
	        int partitionCount, List<String> propertyPath) {
76

    
77
	    List<OrderHint> orderHints = new ArrayList<>();
78
		orderHints.add(new OrderHint("id", OrderHint.SortOrder.ASCENDING ));
79

    
80
		List<CLASS> list = getTaxonService().list(clazz, limit, partitionCount * limit, orderHints, propertyPath);
81

    
82
		if (list.isEmpty()){
83
			return null;
84
		}
85

    
86
		Iterator<CLASS> it = list.iterator();
87
		while (it.hasNext()){
88
			TaxonBase<?> taxonBase = it.next();
89
			if (! isPesiTaxon(taxonBase)){
90
				it.remove();
91
			}
92
			taxonBase = null;
93
		}
94
		it = null;
95
		return list;
96
	}
97

    
98
	protected List<TaxonNameDescription> getNextNameDescriptionPartition(int limit, int partitionCount, List<String> propertyPath) {
99
		List<OrderHint> orderHints = new ArrayList<>();
100
		orderHints.add(new OrderHint("id", OrderHint.SortOrder.ASCENDING ));
101
		Pager<TaxonNameDescription> l = getDescriptionService().getTaxonNameDescriptions(null, limit, partitionCount, propertyPath);
102
		List<TaxonNameDescription> list = l.getRecords();
103
		if (list.isEmpty()){
104
			return null;
105
		}
106

    
107
		Iterator<TaxonNameDescription> it = list.iterator();
108
		while (it.hasNext()){
109
			TaxonNameDescription nameDescription = it.next();
110
			if (! isPesiNameDescriptionTaxon(nameDescription)){
111
				it.remove();
112
			}
113
		}
114
		return list;
115
	}
116

    
117
	private boolean isPesiNameDescriptionTaxon(TaxonNameDescription nameDescription) {
118
		TaxonName name = nameDescription.getTaxonName();
119
		if (isPurePesiName(name)){
120
			return true;
121
		}else{
122
			Set<TaxonBase> taxa = name.getTaxonBases();
123
			for (TaxonBase<?> taxonBase : taxa){
124
				if (isPesiTaxon(taxonBase)){
125
					return true;
126
				}
127
			}
128
		}
129
		return false;
130
	}
131

    
132
	/**
133
	 * Returns the next list of pure names. If finished result will be null. If list is empty there may be result in further partitions.
134
	 */
135
	protected List<TaxonName> getNextPureNamePartition(Class<TaxonName> clazz,int limit, int partitionCount) {
136
		List<OrderHint> orderHints = new ArrayList<>();
137
		orderHints.add(new OrderHint("id", OrderHint.SortOrder.ASCENDING ));
138
//		List<String> propPath = Arrays.asList(new String[]{"taxonBases"});
139

    
140
		List<TaxonName> list = getNameService().list(clazz, limit, partitionCount * limit, orderHints, null);
141
		if (list.isEmpty()){
142
			return null;
143
		}
144
		Iterator<TaxonName> it = list.iterator();
145
		while (it.hasNext()){
146
		    TaxonName taxonName = HibernateProxyHelper.deproxy(it.next());
147
			if (! isPurePesiName(taxonName)){
148
				it.remove();
149
			}
150
		}
151
		return list;
152
	}
153

    
154
	protected <CLASS extends RelationshipBase> List<CLASS> getNextNameRelationshipPartition(
155
	                Class<CLASS> clazz, int pageSize, int partitionCount, List<String> propertyPaths) {
156

    
157
	    List<CLASS> result = new ArrayList<>();
158
		List<OrderHint> orderHints = null;
159
		List<CLASS> list;
160
		if (NameRelationship.class.isAssignableFrom(clazz)){
161
            list = (List<CLASS>)getNameService().listNameRelationships(null, pageSize, partitionCount, orderHints, propertyPaths);
162
        }else if (HybridRelationship.class.isAssignableFrom(clazz)){
163
            list = (List<CLASS>)getNameService().listHybridRelationships(null, pageSize, partitionCount, orderHints, propertyPaths);
164
        }else{
165
            throw new RuntimeException("Only NameRelationship or HybridRelationship allowed here");
166
        }
167
		if (list.isEmpty()){
168
			return null;
169
		}
170
		for (CLASS rel : list){
171
			if (isPesiNameRelationship(rel)){
172
				result.add(rel);
173
			}
174
		}
175
		return result;
176
	}
177

    
178
	protected <CLASS extends RelationshipBase> List<CLASS> getNextTaxonRelationshipPartition( int limit, int partitionCount, List<String> propertyPaths) {
179

    
180
	    List<CLASS> result = new ArrayList<>();
181

    
182
	    List<OrderHint> orderHints = null;
183
		@SuppressWarnings("unchecked")
184
        List<CLASS> list = (List<CLASS>)this.getTaxonService()
185
		        .listTaxonRelationships(null, limit, partitionCount, orderHints, propertyPaths);
186

    
187
		if (list.isEmpty()){
188
			return null;
189
		}
190

    
191
		for (CLASS rel : list){
192
			if (isPesiTaxonOrSynonymRelationship(rel)){
193
				result.add(rel);
194
			}
195
		}
196
		return result;
197
	}
198

    
199
    protected List<TaxonNode> getNextTaxonNodePartition( int limit, int partitionCount, List<String> propertyPaths) {
200

    
201
        List<TaxonNode> result = new ArrayList<>();
202

    
203
        List<OrderHint> orderHints = null;
204
        List<TaxonNode> list = this.getTaxonNodeService()
205
            .list(TaxonNode.class, limit, limit * partitionCount, orderHints, propertyPaths);
206

    
207
        if (list.isEmpty()){
208
            return null;
209
        }
210

    
211
        for (TaxonNode tn : list){
212
            if (isPesiTaxonNode(tn)){
213
                result.add(tn);
214
            }
215
        }
216
        return result;
217
    }
218

    
219
    protected boolean isPesiTaxonNode(TaxonNode tn){
220
        TaxonBase<?> fromTaxon;
221
        Taxon toTaxon;
222

    
223
        fromTaxon = tn.getTaxon();
224
        toTaxon = tn.getParent()== null? null: tn.getParent().getTaxon();
225

    
226
        return (isPesiTaxon(fromTaxon, true) && isPesiTaxon(toTaxon, true));
227
    }
228

    
229
	protected boolean isPesiNameRelationship(RelationshipBase<?,?,?> rel){
230
		TaxonName name1;
231
		TaxonName name2;
232
		if (rel.isInstanceOf(HybridRelationship.class)){
233
			HybridRelationship hybridRel = CdmBase.deproxy(rel, HybridRelationship.class);
234
			name1 = hybridRel.getParentName();
235
			name2 = hybridRel.getHybridName();
236
		}else if (rel.isInstanceOf(NameRelationship.class)){
237
			NameRelationship nameRel = CdmBase.deproxy(rel, NameRelationship.class);
238
			name1 = nameRel.getFromName();
239
			name2 = nameRel.getToName();
240
		}else{
241
			logger.warn ("Only hybrid- and name-relationships alowed here");
242
			return false;
243
		}
244
		return (isPesiName(name1) && isPesiName(name2));
245
	}
246

    
247
	private boolean isPesiName(TaxonName name) {
248
		return hasPesiTaxon(name) || isPurePesiName(name);
249
	}
250

    
251
	protected boolean isPesiTaxonOrSynonymRelationship(RelationshipBase rel){
252
		TaxonBase<?> fromTaxon;
253
		Taxon toTaxon;
254
		// TODO:fix!!!
255
//		if (rel.isInstanceOf(SynonymRelationship.class)){
256
//			SynonymRelationship synRel = CdmBase.deproxy(rel, SynonymRelationship.class);
257
//			fromTaxon = synRel.getSynonym();
258
//			toTaxon = synRel.getAcceptedTaxon();
259
//			synRel = null;
260
//		}else
261
		if (rel.isInstanceOf(TaxonRelationship.class)){
262
			TaxonRelationship taxRel = CdmBase.deproxy(rel, TaxonRelationship.class);
263
			fromTaxon = taxRel.getFromTaxon();
264
			toTaxon = taxRel.getToTaxon();
265
			taxRel = null;
266
		}else{
267
			logger.warn ("Only synonym - and taxon-relationships allowed here");
268
			return false;
269
		}
270
		return (isPesiTaxon(fromTaxon, false) && isPesiTaxon(toTaxon, true));
271
	}
272

    
273
	/**
274
	 * Decides if a name is not used as the name part of a PESI taxon (and therefore is
275
	 * exported to PESI as taxon already) but is related to a name used as a PESI taxon
276
	 * (e.g. as basionym, orthographic variant, etc.) and therefore should be exported
277
	 * to PESI as part of the name relationship.
278
	 * @param taxonName
279
	 * @return
280
	 */
281
	protected boolean isPurePesiName(TaxonName taxonName){
282
		if (hasPesiTaxon(taxonName)){
283
			return false;
284
		}
285

    
286
		//from names
287
		for (NameRelationship rel :taxonName.getRelationsFromThisName()){
288
			TaxonName relatedName = rel.getToName();
289
			if (hasPesiTaxon(relatedName)){
290
				return true;
291
			}
292
		}
293

    
294
		//excluded relationships on to-side
295
		initExcludedRelTypes();
296

    
297
		//to names
298
		for (NameRelationship rel :taxonName.getRelationsToThisName()){
299
			//exclude certain types
300
			if (excludedRelTypes.contains(rel.getType())){
301
				continue;
302
			}
303
			TaxonName relatedName = rel.getFromName();
304
			if (hasPesiTaxon(relatedName)){
305
				return true;
306
			}
307
		}
308

    
309
		//include hybrid parents, but no childs
310

    
311
		for (HybridRelationship rel : taxonName.getHybridParentRelations()){
312
			INonViralName child = rel.getHybridName();
313
			if (hasPesiTaxon(child)){
314
				return true;
315
			}
316
		}
317

    
318
		return false;
319
	}
320

    
321

    
322
	private void initExcludedRelTypes() {
323
		if (excludedRelTypes.isEmpty()){
324
			excludedRelTypes.add(NameRelationshipType.BASIONYM());
325
			excludedRelTypes.add(NameRelationshipType.REPLACED_SYNONYM());
326
			excludedRelTypes.add(NameRelationshipType.ORTHOGRAPHIC_VARIANT());
327
		}
328
	}
329

    
330

    
331
	/**
332
	 * Decides if a given name has "PESI taxa" attached.
333
	 *
334
	 * @see #getPesiTaxa(TaxonNameBase)
335
	 * @see #isPesiTaxon(TaxonBase)
336
	 * @param taxonName
337
	 * @return
338
	 */
339
	protected boolean hasPesiTaxon(INonViralName taxonName) {
340
		for (TaxonBase<?> taxon : taxonName.getTaxonBases()){
341
			if (isPesiTaxon(taxon)){
342
				return true;
343
			}
344
		}
345
		return false;
346
	}
347

    
348
	/**
349
	 * Returns those concepts (taxon bases) for the given name that
350
	 * are pesi taxa.
351
	 *
352
	 *  @see #isPesiTaxon(TaxonBase)
353
	 * @param name
354
	 * @return
355
	 */
356
	protected Set<TaxonBase<?>> getPesiTaxa(TaxonName name){
357
		Set<TaxonBase<?>> result = new HashSet<>();
358
		for (TaxonBase<?> taxonBase : name.getTaxonBases()){
359
			if (isPesiTaxon(taxonBase)){
360
				result.add(taxonBase);
361
			}
362
		}
363
		return result;
364
	}
365

    
366
	/**
367
	 * @see #isPesiTaxon(TaxonBase, boolean)
368
	 * @return
369
	 */
370
	protected static boolean isPesiTaxon(TaxonBase taxonBase) {
371
		return isPesiTaxon(taxonBase, false);
372
	}
373

    
374
	/**
375
	 * Checks if this taxon base is a taxon that is to be exported to PESI. This is generally the case
376
	 * but not for taxa that are marked as "unpublish". Synonyms and misapplied names are exported if they are
377
	 * related at least to one accepted taxon that is also exported, except for those misapplied names
378
	 * marked as misapplied names created by Euro+Med common names ({@linkplain http://dev.e-taxonomy.eu/trac/ticket/2786} ).
379
	 * The list of conditions may change in future.
380
	 * @param taxonBase
381
	 * @return
382
	 */
383
	protected static boolean isPesiTaxon(TaxonBase taxonBase, boolean excludeMisappliedNames) {
384
		if (taxonBase == null){
385
		    return false;
386
		}
387
	    //handle accepted taxa
388
		if (taxonBase.isInstanceOf(Taxon.class)){
389
			Taxon taxon = CdmBase.deproxy(taxonBase, Taxon.class);
390
			return isPesiAcceptedTaxon(excludeMisappliedNames, taxon);
391
		//handle synonyms
392
		}else if (taxonBase.isInstanceOf(Synonym.class)){
393
			Synonym synonym = CdmBase.deproxy(taxonBase, Synonym.class);
394
			return isPesiSynonym(synonym);
395
		}else {
396
			throw new RuntimeException("Unknown taxon base type: " + taxonBase.getClass());
397
		}
398
	}
399

    
400
    private static boolean isPesiSynonym(Synonym synonym) {
401
        boolean hasAcceptedPesiTaxon = false;
402
        hasAcceptedPesiTaxon = isPesiTaxon(synonym.getAcceptedTaxon());
403

    
404
        if (!hasAcceptedPesiTaxon) {if (logger.isDebugEnabled()){logger.debug("Synonym has no accepted PESI taxon: " +  synonym.getUuid() + ", (" +  synonym.getTitleCache() + ")");}}
405
        synonym = null;
406
        return hasAcceptedPesiTaxon;
407
    }
408

    
409
    private static boolean isPesiAcceptedTaxon(boolean excludeMisappliedNames, Taxon taxon) {
410
        if (! taxon.isPublish()){
411
        	taxon = null;
412
        	return false;
413
        }
414
        for (Marker marker : taxon.getMarkers()){
415
        	//probably not needed anymore after #1780 was fixed, also #4046 interesting
416
        	if (marker.getValue() == false && marker.getMarkerType().equals(MarkerType.PUBLISH())){
417
        		taxon = null;
418
        		return false;
419
        	//probably not needed any more after #2786 was fixed
420
        	}else if (marker.getValue() == true && marker.getMarkerType().getUuid().equals(BerlinModelTransformer.uuidMisappliedCommonName)){
421
        		logger.warn("Misapplied common name still exists");
422
        		taxon = null;
423
        		return false;
424
        	}
425
        }
426

    
427
        //handle PESI accepted taxa
428
        if (! taxon.isMisapplication()){
429
        	for (Marker marker : taxon.getMarkers()){
430
        		if (marker.getValue() == false && marker.getMarkerType().equals(MarkerType.PUBLISH())){
431
        			taxon = null;
432
        			return false;
433
        		}
434
        	}
435
        	return true;
436
        //handle misapplied names
437
        }else{
438
        	if (excludeMisappliedNames){
439
        		taxon = null;
440
        		return false;
441
        	}
442
        	for (Marker marker : taxon.getMarkers()){
443
        		//probably not needed any more after #2786 was fixed
444
        		if (marker.getValue() == true && marker.getMarkerType().getUuid().equals(BerlinModelTransformer.uuidMisappliedCommonName)){
445
        			logger.warn("Misapplied common name still exists");
446
        			taxon = null;
447
        			return false;
448
        		}
449
        	}
450
        	for (TaxonRelationship taxRel : taxon.getRelationsFromThisTaxon()){
451
        		if (taxRel.getType().equals(TaxonRelationshipType.MISAPPLIED_NAME_FOR())){
452
//						logger.warn(taxRel.getUuid() + "; " + taxRel.getToTaxon().getUuid() + " + " + taxRel.getToTaxon().getTitleCache());
453
        			if (isPesiTaxon(taxRel.getToTaxon(), true)){
454
        				taxon = null;
455
        				return true;
456
        			}
457
        		}
458
        	}
459
        	if (logger.isDebugEnabled()){ logger.debug("Misapplied name has no accepted PESI taxon: " +  taxon.getUuid() + ", (" +  taxon.getTitleCache() + ")");}
460
        	taxon = null;
461
        	return false;
462
        }
463
    }
464

    
465
	@Override
466
    protected Object getDbIdCdmWithExceptions(CdmBase cdmBase, PesiExportState state) {
467
		if (cdmBase.isInstanceOf(TaxonName.class)){
468
		    TaxonName name = CdmBase.deproxy(cdmBase, TaxonName.class);
469
		    if (name.getTaxonBases().size()>1){
470
		        logger.warn("Name has multiple taxa. Can't define correct ID. Use first one." + name.getUuid());
471
		    }
472
		    if (!name.getTaxonBases().isEmpty()){
473
		        TaxonBase<?> tb = name.getTaxonBases().iterator().next();
474
		        return this.getDbId(tb, state);
475
            }else{
476
                return ( cdmBase.getId() + state.getConfig().getNameIdStart() );
477
            }
478
		}else if (isAdditionalSource(cdmBase) ){
479
			return ( cdmBase.getId() + 2 * state.getConfig().getNameIdStart() );  //make it a separate variable if conflicts occur.
480
		}else{
481
			return super.getDbIdCdmWithExceptions(cdmBase, state);
482
		}
483
	}
484

    
485
	private boolean isAdditionalSource(CdmBase cdmBase) {
486
		if (cdmBase.isInstanceOf(TextData.class)){
487
			TextData textData = CdmBase.deproxy(cdmBase, TextData.class);
488
			if (textData.getFeature().equals(Feature.ADDITIONAL_PUBLICATION()) ||
489
					textData.getFeature().equals(Feature.CITATION())){
490
				return true;
491
			}
492
		}
493
		return false;
494
	}
495

    
496
	protected MarkerType getUuidMarkerType(UUID uuid, PesiExportState state){
497
		if (uuid == null){
498
			uuid = UUID.randomUUID();
499
		}
500

    
501
		MarkerType markerType = state.getMarkerType(uuid);
502
		if (markerType == null){
503
			if (uuid.equals(PesiTransformer.uuidMarkerGuidIsMissing)){
504
				markerType = MarkerType.NewInstance("Uuid is Missing", "Uuid is missing", null);
505
				markerType.setUuid(uuid);
506
			} else if (uuid.equals(PesiTransformer.uuidMarkerTypeHasNoLastAction)){
507
				markerType = MarkerType.NewInstance("Has no last Action", "Has no last action", null);
508
				markerType.setUuid(uuid);
509
			}
510
		}
511

    
512
		state.putMarkerType(markerType);
513
		return markerType;
514
	}
515

    
516
	protected static TaxonNameDefaultCacheStrategy getCacheStrategy(TaxonName taxonName) {
517
	    TaxonNameDefaultCacheStrategy cacheStrategy;
518
		if (taxonName.isZoological()){
519
			cacheStrategy = zooNameStrategy;
520
		}else if (taxonName.isBotanical()) {
521
			cacheStrategy = botanicalNameStrategy;
522
		}else{
523
			logger.error("Unhandled taxon name type. Can't define strategy class");
524
			cacheStrategy = botanicalNameStrategy;
525
		}
526
		return cacheStrategy;
527
	}
528

    
529
	/**
530
	 * Checks whether a given taxon is a misapplied name.
531
	 * @param taxon The {@link TaxonBase Taxon}.
532
	 * @return Whether the given TaxonName is a misapplied name or not.
533
	 */
534
	protected static boolean isMisappliedName(TaxonBase<?> taxon) {
535
		return getAcceptedTaxonForMisappliedName(taxon) != null;
536
	}
537

    
538
	/**
539
	 * Returns the first accepted taxon for this misapplied name.
540
	 * If this misapplied name is not a misapplied name, <code>null</code> is returned.
541
	 * @param taxon The {@link TaxonBase Taxon}.
542
	 */
543
	private static Taxon getAcceptedTaxonForMisappliedName(TaxonBase<?> taxon) {
544
		if (! taxon.isInstanceOf(Taxon.class)){
545
			return null;
546
		}
547
		Set<TaxonRelationship> taxonRelations = CdmBase.deproxy(taxon, Taxon.class).getRelationsFromThisTaxon();
548
		for (TaxonRelationship taxonRelationship : taxonRelations) {
549
			TaxonRelationshipType taxonRelationshipType = taxonRelationship.getType();
550
			if (taxonRelationshipType.equals(TaxonRelationshipType.MISAPPLIED_NAME_FOR())) {
551
				return taxonRelationship.getToTaxon();
552
			}
553
		}
554
		return null;
555
	}
556

    
557
    protected List<AnnotationType> getLastActionAnnotationTypes() {
558
        Set<UUID> uuidSet = new HashSet<>();
559
        uuidSet.add(DbLastActionMapper.uuidAnnotationTypeLastActionDate);
560
        uuidSet.add(DbLastActionMapper.uuidAnnotationTypeLastAction);
561
        uuidSet.add(ErmsTransformer.uuidAnnSpeciesExpertName);
562
        @SuppressWarnings({"unchecked","rawtypes"})
563
        List<AnnotationType> result = (List)getTermService().find(uuidSet);
564
        return result;
565
    }
566

    
567
    protected enum PesiSource{
568
        EM,
569
        FE,
570
        ERMS,
571
        IF;
572

    
573
        private PesiSource(){
574

    
575
        }
576
    }
577

    
578
    /**
579
     * Returns the source (E+M, Fauna Europaea, Index Fungorum, ERMS) of a given
580
     * Identifiable Entity as an {@link EnumSet enum set}
581
     */
582
    protected static EnumSet<PesiSource> getSources(IdentifiableEntity<?> entity){
583
        EnumSet<PesiSource> result = EnumSet.noneOf(PesiSource.class);
584

    
585
        Set<IdentifiableSource> sources = getPesiSources(entity);
586
        for (IdentifiableSource source : sources) {
587
            Reference ref = source.getCitation();
588
            UUID refUuid = ref.getUuid();
589
            if (refUuid.equals(BerlinModelTransformer.uuidSourceRefEuroMed)){
590
                result.add(PesiSource.EM);
591
            }else if (refUuid.equals(PesiTransformer.uuidSourceRefFaunaEuropaea)){
592
                result.add(PesiSource.FE);
593
            }else if (refUuid.equals(PesiTransformer.uuidSourceRefErms)){
594
                result.add(PesiSource.ERMS);
595
            }else if (refUuid.equals(PesiTransformer.uuidSourceRefIndexFungorum)){
596
                result.add(PesiSource.IF);
597
            }else{
598
                if (logger.isDebugEnabled()){logger.debug("Not a PESI source");};
599
            }
600
        }
601
        return result;
602
    }
603

    
604
    /**
605
     * Returns the Sources for a given TaxonName only.
606
     * @param identifiableEntity
607
     * @return The Sources.
608
     */
609
    protected static Set<IdentifiableSource> getPesiSources(IdentifiableEntity<?> identifiableEntity) {
610
        Set<IdentifiableSource> sources = new HashSet<>();
611

    
612
        //Taxon Names
613
        if (identifiableEntity.isInstanceOf(TaxonName.class)){
614
            // Sources from TaxonName
615
            TaxonName taxonName = CdmBase.deproxy(identifiableEntity, TaxonName.class);
616
            Set<IdentifiableSource> testSources = identifiableEntity.getSources();
617
            sources = filterPesiSources(identifiableEntity.getSources());
618

    
619
            if (sources.size() == 0 && testSources.size()>0){
620
                IdentifiableSource source = testSources.iterator().next();
621
                logger.warn("There are sources, but they are no pesi sources!!!" + source.getIdInSource() + " - " + source.getIdNamespace() + " - " + source.getCitation().getTitleCache());
622
            }
623
            if (sources.size() > 1) {
624
                logger.warn("This TaxonName has more than one Source: " + identifiableEntity.getUuid() + " (" + identifiableEntity.getTitleCache() + ")");
625
            }
626

    
627
            // name has no PESI source, take sources from TaxonBase
628
            if (sources == null || sources.isEmpty()) {
629
                Set<TaxonBase> taxa = taxonName.getTaxonBases();
630
                for (TaxonBase taxonBase: taxa){
631
                    sources.addAll(filterPesiSources(taxonBase.getSources()));
632
                }
633
            }
634

    
635
        //for TaxonBases
636
        }else if (identifiableEntity.isInstanceOf(TaxonBase.class)){
637
            sources = filterPesiSources(identifiableEntity.getSources());
638
        } else {
639
            sources = filterPesiSources(identifiableEntity.getSources());
640
        }
641

    
642
        return sources;
643
    }
644

    
645
    // return all sources with a PESI reference
646
    private static Set<IdentifiableSource> filterPesiSources(Set<? extends IdentifiableSource> sources) {
647
        Set<IdentifiableSource> result = new HashSet<>();
648
        for (IdentifiableSource source : sources){
649
            Reference ref = source.getCitation();
650
            UUID refUuid = ref.getUuid();
651
            if (refUuid.equals(BerlinModelTransformer.uuidSourceRefEuroMed) ||
652
                refUuid.equals(PesiTransformer.uuidSourceRefFaunaEuropaea)||
653
                refUuid.equals(PesiTransformer.uuidSourceRefErms)||
654
                refUuid.equals(PesiTransformer.uuidSourceRefIndexFungorum) ||
655
                refUuid.equals(PesiTransformer.uuidSourceRefAuct)){
656
                result.add(source);
657
            }
658
        }
659
        return result;
660
    }
661

    
662
}
(6-6/14)