Project

General

Profile

Download (14.9 KB) Statistics
| Branch: | Tag: | 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.csv.redlist.out;
11

    
12
import java.io.ByteArrayOutputStream;
13
import java.io.PrintWriter;
14
import java.util.ArrayList;
15
import java.util.Collections;
16
import java.util.Comparator;
17
import java.util.HashSet;
18
import java.util.List;
19
import java.util.Set;
20
import java.util.UUID;
21

    
22
import org.apache.log4j.Logger;
23
import org.springframework.stereotype.Component;
24
import org.springframework.transaction.TransactionStatus;
25

    
26
import eu.etaxonomy.cdm.model.common.CdmBase;
27
import eu.etaxonomy.cdm.model.common.Language;
28
import eu.etaxonomy.cdm.model.common.RelationshipTermBase;
29
import eu.etaxonomy.cdm.model.description.CategoricalData;
30
import eu.etaxonomy.cdm.model.description.DescriptionElementBase;
31
import eu.etaxonomy.cdm.model.description.Distribution;
32
import eu.etaxonomy.cdm.model.description.Feature;
33
import eu.etaxonomy.cdm.model.description.State;
34
import eu.etaxonomy.cdm.model.description.TaxonDescription;
35
import eu.etaxonomy.cdm.model.description.TextData;
36
import eu.etaxonomy.cdm.model.location.NamedArea;
37
import eu.etaxonomy.cdm.model.name.NonViralName;
38
import eu.etaxonomy.cdm.model.taxon.Classification;
39
import eu.etaxonomy.cdm.model.taxon.Synonym;
40
import eu.etaxonomy.cdm.model.taxon.SynonymRelationship;
41
import eu.etaxonomy.cdm.model.taxon.SynonymRelationshipType;
42
import eu.etaxonomy.cdm.model.taxon.Taxon;
43
import eu.etaxonomy.cdm.model.taxon.TaxonBase;
44
import eu.etaxonomy.cdm.model.taxon.TaxonNode;
45
import eu.etaxonomy.cdm.model.taxon.TaxonRelationship;
46
import eu.etaxonomy.cdm.model.taxon.TaxonRelationshipType;
47

    
48

    
49
/**
50
 * @author a.oppermann
51
 * @created 18.10.2012
52
 */
53

    
54
@Component
55
public class CsvTaxExportRedlist extends CsvExportBaseRedlist {
56
	private static final Logger logger = Logger.getLogger(CsvTaxExportRedlist.class);
57

    
58
	private static final String ROW_TYPE = "http://rs.tdwg.org/dwc/terms/Taxon";
59
	private static final String fileName = "RedlistCoreTax.csv";
60

    
61
	public CsvTaxExportRedlist() {
62
		super();
63
		this.ioName = this.getClass().getSimpleName();
64
	}
65
	
66

    
67
	/** Retrieves data from a CDM DB and serializes them CDM to CSV.
68
	 * Starts with root taxa and traverses the classification to retrieve 
69
	 * children taxa, synonyms, relationships, descriptive data, red list 
70
	 * status (features). 
71
	 * Taxa that are not part of the classification are not found.
72
	 * 
73
	 * @param exImpConfig
74
	 * @param dbname
75
	 * @param filename
76
	 */
77
	@Override
78
	protected void doInvoke(CsvTaxExportStateRedlist state){
79
		CsvTaxExportConfiguratorRedlist config = state.getConfig();
80
		TransactionStatus txStatus = startTransaction(true);
81
		List<NamedArea> selectedAreas = config.getNamedAreas();
82
		Set<Classification> classificationSet = assembleClassificationSet(config);
83
		
84
		PrintWriter writer = null;
85
		ByteArrayOutputStream byteArrayOutputStream;
86
		try {
87
			byteArrayOutputStream = config.getByteArrayOutputStream();
88
			writer = new PrintWriter(byteArrayOutputStream); 
89
			//geographical Filter
90
			List<TaxonNode> filteredNodes = handleGeographicalFilter(selectedAreas, classificationSet);
91
			
92
			//sorting List
93
			Collections.sort(filteredNodes, new Comparator<TaxonNode>() {
94

    
95
				@Override
96
				public int compare(TaxonNode tn1, TaxonNode tn2) {
97
					Taxon taxon1 = tn1.getTaxon();
98
					Taxon taxon2 = tn2.getTaxon();
99
					if(taxon1 != null && taxon2 != null){
100
						return taxon1.getTitleCache().compareTo(taxon2.getTitleCache());
101
					}
102
					else{
103
						return 0;
104
					}
105
				}
106
			});
107
			for (TaxonNode node : filteredNodes){
108
				Taxon taxon = CdmBase.deproxy(node.getTaxon(), Taxon.class);
109
				CsvTaxRecordRedlist record = assembleRecord(state);
110
				NonViralName<?> name = CdmBase.deproxy(taxon.getName(), NonViralName.class);
111
				Classification classification = node.getClassification();
112
				config.setClassificationTitleCache(classification.getTitleCache());	
113
				if (! this.recordExists(taxon)){
114
					handleTaxonBase(record, taxon, name, taxon, classification, null, false, false, config);
115
					record.write(writer);
116
					this.addExistingRecord(taxon);
117
				}
118
				//misapplied names
119
				handleMisapplication(taxon, writer, classification, record, config);
120
				writer.flush();
121
			}
122
		} catch (ClassCastException e) {
123
			e.printStackTrace();
124
		}
125
		finally{
126
			writer.close();
127
			this.clearExistingRecordIds();
128
		}
129
		commitTransaction(txStatus);
130
		return;
131

    
132
	}
133
	
134
	
135
	//TODO: Exception handling
136
	/**
137
	 * 
138
	 * @param config
139
	 * @return
140
	 */
141
	protected Set<Classification> assembleClassificationSet(CsvTaxExportConfiguratorRedlist config){
142
		if(config != null){
143
			Set<UUID> taxonNodeUuidSet = config.getTaxonNodeUuids();
144
			List<Classification> classificationList = getClassificationService().find(taxonNodeUuidSet);
145
			Set<Classification> classificationSet = new HashSet<Classification>();
146
			classificationSet.addAll(classificationList);
147
			return classificationSet;
148
		}
149
		return null;
150
	}
151

    
152
//	
153
//	private Collections sort(List<Classification> classificationList, new Comparator<TaxonNode>() {
154
//		public int compare(TaxonNode tn1, TaxonNode tn2){
155
//			int i = 0;
156
//			return i;
157
//		}
158
//	});
159
	//TODO: Exception handling
160
	/**
161
	 * 
162
	 * @param state
163
	 * @return
164
	 */
165
	private CsvTaxRecordRedlist assembleRecord(CsvTaxExportStateRedlist state) {
166
		if(state!=null){
167
			CsvTaxExportConfiguratorRedlist config = state.getConfig();
168
			CsvMetaDataRecordRedlist metaRecord = new CsvMetaDataRecordRedlist(true, fileName, ROW_TYPE);
169
			state.addMetaRecord(metaRecord);
170
			CsvTaxRecordRedlist record = new CsvTaxRecordRedlist(metaRecord, config);
171
			return record;
172
		}
173
		return null;
174
	}
175

    
176
	/**
177
	 * Takes positive List of areas and iterates over a given classification 
178
	 * and their {@link Taxon} to return all {@link Taxon} with the desired 
179
	 * geographical attribute.
180
	 * 
181
	 * <p><p>
182
	 *
183
	 * If selectedAreas is null all {@link TaxonNode}s of the given {@link Classification} will be returned.
184
	 * 
185
	 * @param selectedAreas 
186
	 * @param classificationSet
187
	 * @return
188
	 */
189
	protected List<TaxonNode> handleGeographicalFilter(List<NamedArea> selectedAreas,
190
			Set<Classification> classificationSet) {
191
		List<TaxonNode> filteredNodes = new ArrayList<TaxonNode>();
192
		List<TaxonNode> allNodes =  getAllNodes(classificationSet);
193
		//Geographical filter
194
		logger.info(selectedAreas.size());
195
		if(selectedAreas != null && !selectedAreas.isEmpty() && selectedAreas.size() < 16){
196
//				if(selectedAreas.size() == 16){
197
//					//Germany TDWG Level 3
198
//					String germany="uu7b7c2db5-aa44-4302-bdec-6556fd74b0b9id";
199
//					selectedAreas.add((NamedArea) getTermService().find(UUID.fromString(germany)));
200
//				}
201
			for (TaxonNode node : allNodes){
202
				Taxon taxon = CdmBase.deproxy(node.getTaxon(), Taxon.class);
203
				Set<TaxonDescription> descriptions = taxon.getDescriptions();
204
				for (TaxonDescription description : descriptions){
205
					for (DescriptionElementBase el : description.getElements()){
206
						if (el.isInstanceOf(Distribution.class) ){
207
							Distribution distribution = CdmBase.deproxy(el, Distribution.class);
208
							NamedArea area = distribution.getArea();
209
							for(NamedArea selectedArea:selectedAreas){
210
								if(selectedArea.getUuid().equals(area.getUuid())){
211
									filteredNodes.add(node);
212
								}
213
							}
214
						}
215
					}
216
				}
217
			}
218
		}else{
219
			filteredNodes = allNodes;
220
		}
221
		return filteredNodes;
222
	}
223

    
224
	/**
225
	 * handles misapplied {@link Taxon}
226
	 * @param taxon
227
	 * @param writer
228
	 * @param classification
229
	 * @param metaRecord
230
	 * @param config
231
	 */
232
	private void handleMisapplication(Taxon taxon, PrintWriter writer, Classification classification, CsvTaxRecordRedlist record, CsvTaxExportConfiguratorRedlist config) {
233
		Set<Taxon> misappliedNames = taxon.getMisappliedNames();
234
		for (Taxon misappliedName : misappliedNames ){
235
//			CsvTaxRecordRedlist record = new CsvTaxRecordRedlist(metaRecord, config);
236
			TaxonRelationshipType relType = TaxonRelationshipType.MISAPPLIED_NAME_FOR();
237
			NonViralName<?> name = CdmBase.deproxy(misappliedName.getName(), NonViralName.class);
238
		
239
			if (! this.recordExists(misappliedName)){
240
				handleTaxonBase(record, misappliedName, name, taxon, classification, relType, false, false, config);
241
				record.write(writer);
242
				this.addExistingRecord(misappliedName);
243
			}
244
		}	
245
	}
246

    
247
	/**
248
	 * handles the information record for the actual {@link Taxon} including {@link Classification classification}, Taxon Name, Taxon ID,
249
	 * Taxon Status, Synonyms, {@link Feature features} data 
250
	 * @param record the concrete information record
251
	 * @param taxonBase {@link Taxon}
252
	 * @param name
253
	 * @param acceptedTaxon
254
	 * @param parent
255
	 * @param basionym
256
	 * @param isPartial 
257
	 * @param isProParte 
258
	 * @param config 
259
	 * @param type
260
	 */
261
	private void handleTaxonBase(CsvTaxRecordRedlist record,TaxonBase<?> taxonBase,
262
			NonViralName<?> name, Taxon acceptedTaxon, Classification classification, 
263
			RelationshipTermBase<?> relType, boolean isProParte, boolean isPartial, 
264
			CsvTaxExportConfiguratorRedlist config) {
265
		
266
		List<Feature> features = config.getFeatures();
267
		record.setHeadLinePrinted(config.isHasHeaderLines());
268
		if(features != null)record.setPrintFeatures(features);
269
		config.setHasHeaderLines(false);
270

    
271
		record.setDatasetName(classification.getTitleCache());
272
		record.setScientificName(name.getTitleCache());
273
		record.setScientificNameId(name.getUuid().toString());
274
		handleTaxonomicStatus(record, name, relType, isProParte, isPartial);
275
		//synonyms
276
		handleSynonyms(record,(Taxon) taxonBase);
277
		//distribution
278
		handleDiscriptionData(record, (Taxon) taxonBase);
279
		if(features!= null) {
280
			
281
			List<List<String>> featureCells = new ArrayList<List<String>>(features.size());
282
			for(int i = 0; i < features.size(); i++) {
283
				featureCells.add(new ArrayList<String>());
284
			}
285
			handleRelatedRedlistStatus(record, (Taxon)taxonBase, false, featureCells, features);
286
			handleRelatedRedlistStatus(record, (Taxon)taxonBase, true, featureCells, features);
287

    
288
		}
289
		return;
290
	}
291

    
292
	/**
293
	 * @param record
294
	 * @param name
295
	 * @param type
296
	 * @param isPartial 
297
	 * @param isProParte 
298
	 */
299
	private void handleTaxonomicStatus(
300
			CsvTaxRecordRedlist record,
301
			NonViralName<?> name, 
302
			RelationshipTermBase<?> type,
303
			boolean isProParte,
304
			boolean isPartial) {
305
		if (type == null){
306
			record.setTaxonomicStatus(name.getNomenclaturalCode().acceptedTaxonStatusLabel());
307
		}else{
308
			String status = name.getNomenclaturalCode().synonymStatusLabel();
309
			if (type.equals(SynonymRelationshipType.HETEROTYPIC_SYNONYM_OF())){
310
				status = "heterotypicSynonym";
311
			}else if(type.equals(SynonymRelationshipType.HOMOTYPIC_SYNONYM_OF())){
312
				status = "homotypicSynonym";
313
			}else if(type.equals(TaxonRelationshipType.MISAPPLIED_NAME_FOR())){
314
				status = "misapplied";
315
			}
316
			if (isProParte){
317
				status = "proParteSynonym";
318
			}else if (isPartial){
319
				String message = "Partial synonym is not part of the gbif toxonomic status vocabulary";
320
				logger.warn(message);
321
				status = "partialSynonym";
322
			}
323
			
324
			record.setTaxonomicStatus(status);
325
		}
326
	}
327

    
328
	/**
329
	 * 
330
	 * @param record
331
	 * @param taxon
332
	 */
333
	private void handleSynonyms(CsvTaxRecordRedlist record, Taxon taxon) {
334
		
335
		Set<SynonymRelationship> synRels = taxon.getSynonymRelations();
336
		ArrayList<String> synonyms = new ArrayList<String>(); 
337
		for (SynonymRelationship synRel :synRels ){
338
			Synonym synonym = synRel.getSynonym();
339
			SynonymRelationshipType type = synRel.getType();
340
			if (type == null){ // should not happen
341
				type = SynonymRelationshipType.SYNONYM_OF();
342
			}
343
			NonViralName<?> name = CdmBase.deproxy(synonym.getName(), NonViralName.class);
344
			synonyms.add(name.getTitleCache());
345
		}
346
		record.setSynonyms(synonyms);
347
	}
348

    
349
	/**
350
	 * 
351
	 * @param record
352
	 * @param taxon
353
	 */
354
	private void handleDiscriptionData(CsvTaxRecordRedlist record, Taxon taxon) {
355
		
356
		Set<TaxonDescription> descriptions = taxon.getDescriptions();
357
		ArrayList<String> distributions = new ArrayList<String>();
358
		for (TaxonDescription description : descriptions){
359
			for (DescriptionElementBase el : description.getElements()){
360
				if (el.isInstanceOf(Distribution.class) ){
361
						Distribution distribution = CdmBase.deproxy(el, Distribution.class);
362
						NamedArea area = distribution.getArea();
363
						distributions.add(area.getTitleCache());
364
				}
365

    
366
			}
367
		}
368
		record.setCountryCode(distributions);
369
	}
370
	/**
371
	 * 
372
	 * @param record
373
	 * @param taxon
374
	 * @param featureCells
375
	 * @param features 
376
	 */
377
	private void handleRedlistStatus(CsvTaxRecordRedlist record, Taxon taxon, List<List<String>> featureCells, List<Feature> features){
378
		Set<TaxonDescription> descriptions = taxon.getDescriptions();
379

    
380
		for (TaxonDescription description : descriptions){
381
			for (DescriptionElementBase el : description.getElements()){
382
				if(el.isInstanceOf(CategoricalData.class)){
383
					CategoricalData categoricalData = CdmBase.deproxy(el, CategoricalData.class);
384
					for(State state:categoricalData.getStatesOnly()){
385
						Feature stateFeature = categoricalData.getFeature();
386
						// find matching feature and put data into according cell
387
						for(int i = 0; i < features.size(); i++) {
388
							if(features.get(i).equals(stateFeature)){
389
								List<String> cell = featureCells.get(i);
390
								cell.add(state.toString());
391
							}
392
						}
393
					}
394
				}else if(el.isInstanceOf(TextData.class)){
395
					TextData textData = CdmBase.deproxy(el, TextData.class);
396
					Feature textFeature = textData.getFeature();
397
					// find matching feature and put data into according cell
398
					for(int i = 0; i < features.size(); i++) {
399
						if(features.get(i).equals(textFeature)){
400
							List<String> cell = featureCells.get(i);
401
							String text = textData.getText(Language.GERMAN());
402
							text = text.replaceAll(System.getProperty("line.separator"), "");
403
							text = text.replaceAll("                            ", " ");
404
							cell.add(text);
405
							
406
						}
407
					}
408
				}
409
			}
410
		}
411
		record.setFeatures(featureCells);
412
	}
413

    
414
	/**
415
	 * 
416
	 * @param record
417
	 * @param taxon
418
	 * @param relationFrom
419
	 * @param featureCells
420
	 * @param features 
421
	 */
422
	private void handleRelatedRedlistStatus(CsvTaxRecordRedlist record, Taxon taxon, boolean relationFrom, List<List<String>> featureCells, List<Feature> features) {
423

    
424
		if (relationFrom)handleRedlistStatus(record, taxon, featureCells, features);
425
		
426
		
427
		Set<TaxonRelationship> taxRels;
428
		if(relationFrom){
429
			taxRels = taxon.getRelationsFromThisTaxon();
430
		}else{
431
			taxRels = taxon.getRelationsToThisTaxon();
432
		}
433
		for (TaxonRelationship taxRel:taxRels){
434
			if(taxRel.getType().equals(TaxonRelationshipType.CONGRUENT_TO())){
435
				Taxon relatedTaxon;
436
				if(relationFrom){
437
					relatedTaxon = taxRel.getToTaxon();
438
				}else{
439
					relatedTaxon = taxRel.getFromTaxon();
440
				}
441
				handleRedlistStatus(record, relatedTaxon, featureCells, features);
442
			}
443
		}
444
	}
445

    
446
	@Override
447
	protected boolean doCheck(CsvTaxExportStateRedlist state) {
448
		boolean result = true;
449
		logger.warn("No check implemented for " + this.ioName);
450
		return result;
451
	}
452

    
453
	@Override
454
	protected boolean isIgnore(CsvTaxExportStateRedlist state) {
455
		return ! state.getConfig().isDoTaxa();
456
	}
457
	
458
}
(6-6/10)