Project

General

Profile

Download (15 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.app.synthesysImport;
11

    
12
import java.io.FileNotFoundException;
13
import java.net.URI;
14
import java.net.URISyntaxException;
15
import java.util.ArrayList;
16
import java.util.HashMap;
17
import java.util.List;
18
import java.util.ListIterator;
19

    
20
import org.apache.log4j.Logger;
21
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
22
import org.springframework.transaction.TransactionStatus;
23

    
24
import eu.etaxonomy.cdm.api.application.CdmApplicationController;
25
import eu.etaxonomy.cdm.api.service.pager.Pager;
26
import eu.etaxonomy.cdm.app.common.CdmDestinations;
27
import eu.etaxonomy.cdm.app.common.CdmImportSources;
28
import eu.etaxonomy.cdm.common.ExcelUtils;
29
import eu.etaxonomy.cdm.database.DbSchemaValidation;
30
import eu.etaxonomy.cdm.database.ICdmDataSource;
31
import eu.etaxonomy.cdm.model.agent.AgentBase;
32
import eu.etaxonomy.cdm.model.agent.Institution;
33
import eu.etaxonomy.cdm.model.agent.Person;
34
import eu.etaxonomy.cdm.model.common.Language;
35
import eu.etaxonomy.cdm.model.common.LanguageString;
36
import eu.etaxonomy.cdm.model.location.NamedArea;
37
import eu.etaxonomy.cdm.model.location.Point;
38
import eu.etaxonomy.cdm.model.location.Country;
39
import eu.etaxonomy.cdm.model.name.TaxonNameBase;
40
import eu.etaxonomy.cdm.model.occurrence.Collection;
41
import eu.etaxonomy.cdm.model.occurrence.DerivationEvent;
42
import eu.etaxonomy.cdm.model.occurrence.DerivedUnit;
43
import eu.etaxonomy.cdm.model.occurrence.DeterminationEvent;
44
import eu.etaxonomy.cdm.model.occurrence.FieldUnit;
45
import eu.etaxonomy.cdm.model.occurrence.GatheringEvent;
46
import eu.etaxonomy.cdm.model.occurrence.SpecimenOrObservationType;
47
import eu.etaxonomy.cdm.model.reference.Reference;
48
import eu.etaxonomy.cdm.model.reference.ReferenceFactory;
49
import eu.etaxonomy.cdm.model.taxon.Taxon;
50
import eu.etaxonomy.cdm.strategy.parser.NonViralNameParserImpl;
51

    
52
/**
53
 * @author PK
54
 * @created 19.09.2008
55
 * @version 1.0
56
 */
57
public class SynthesysCacheActivator {
58
	private static final Logger logger = Logger.getLogger(SynthesysCacheActivator.class);
59

    
60
	protected String fullScientificNameString = null;
61
	protected String institutionCode = null;
62
	protected String collectionCode = null;
63
	protected String unitID = null;
64
	protected String recordBasis = null;
65
	protected String accessionNumber = null;
66
	protected String collectorsNumber = null;
67
	protected String fieldNumber = null;
68
	protected Double longitude = null;
69
	protected Double latitude = null;
70
	protected String locality = null;
71
	protected String country = null;
72
	protected String isocountry = null;
73
	protected ArrayList<String> gatheringAgentList = new ArrayList<String>();
74
	protected ArrayList<String> identificationList = new ArrayList<String>();
75

    
76
	static DbSchemaValidation hbm2dll = DbSchemaValidation.CREATE;
77
	
78
	static ICdmDataSource desitination = CdmDestinations.localH2();
79
	
80
	protected HSSFWorkbook hssfworkbook = null;
81

    
82

    
83
	public void saveUnit(HashMap<String,String> unit){
84
		String author = unit.get("author");
85
		author=author.replaceAll("None","");
86
		String taxonName = unit.get("taxonName");
87
		taxonName = taxonName.replaceAll("None", "");
88

    
89
		try {
90
			this.institutionCode = unit.get("institution").replaceAll("None", null);
91
		} catch (Exception e) {
92
		}
93

    
94
		try {this.collectionCode = unit.get("collection").replaceAll("None", null);
95
		} catch (Exception e) {
96
		}
97
		try {this.unitID = unit.get("unitID").replaceAll("None", null);
98
		} catch (Exception e) {
99
		}
100
		try {this.recordBasis = unit.get("recordBasis").replaceAll("None", null);
101
		} catch (Exception e) {
102
		}
103
		try {this.accessionNumber = null;
104
		} catch (Exception e) {
105
		}
106
		try {this.locality = unit.get("locality").replaceAll("None", null);
107
		} catch (Exception e) {
108
		}
109
		try {this.longitude = Double.valueOf(unit.get("longitude"));
110
		} catch (Exception e) {
111
		}
112
		try {this.latitude = Double.valueOf(unit.get("latitude"));
113
		} catch (Exception e) {
114
		}
115
		try {this.country = unit.get("country").replaceAll("None", null);
116
		} catch (Exception e) {
117
		}
118
		try {this.isocountry = unit.get("isoCountry").replaceAll("None", null);
119
		} catch (Exception e) {
120
		}
121
		try {this.fieldNumber = unit.get("field number").replaceAll("None", null);
122
		} catch (Exception e) {
123
		}
124
		try {this.collectorsNumber = unit.get("collector number").replaceAll("None", null);
125
		} catch (Exception e) {
126
		}
127
		try {String coll =unit.get("collector");
128
			coll=coll.replaceAll("None", null);
129
			this.gatheringAgentList.add(coll);
130
		} catch (Exception e) {
131
		}
132
		try {this.identificationList.add(taxonName+" "+author);
133
		} catch (Exception e) {System.out.println(e);
134
		}
135
	}
136

    
137
	public boolean invoke(){
138
		boolean result = true;
139
		boolean withCdm = true;
140
		CdmApplicationController app = null;
141
		TransactionStatus tx = null;
142

    
143
		app = CdmApplicationController.NewInstance(desitination, hbm2dll);
144
		
145
		tx = app.startTransaction();
146
		try {
147
			Reference<?> sec = ReferenceFactory.newDatabase();
148
			sec.setTitleCache("SYNTHESYS CACHE DATA", true);
149

    
150
			/**
151
			 * SPECIMEN OR OBSERVATION OR LIVING
152
			 */
153
			DerivedUnit derivedThing = null;
154
			//create specimen
155
			if (this.recordBasis != null){
156
				if (this.recordBasis.toLowerCase().startsWith("s")) {//specimen
157
					derivedThing = DerivedUnit.NewPreservedSpecimenInstance();				
158
				}
159
				else if (this.recordBasis.toLowerCase().startsWith("o")) {//observation
160
					derivedThing = DerivedUnit.NewInstance(SpecimenOrObservationType.Observation);				
161
				}
162
				else if (this.recordBasis.toLowerCase().startsWith("l")) {//living -> fossil, herbarium sheet....???
163
					derivedThing = DerivedUnit.NewInstance(SpecimenOrObservationType.LivingSpecimen);	
164
				}
165
			}
166
			if (derivedThing == null){
167
				derivedThing =  DerivedUnit.NewInstance(SpecimenOrObservationType.Observation);
168
			}
169

    
170
			TaxonNameBase<?,?> taxonName = null;
171
			Taxon taxon = null;
172
			DeterminationEvent determinationEvent = null;
173
			List<TaxonNameBase> names = null;
174
			NonViralNameParserImpl nvnpi = NonViralNameParserImpl.NewInstance();
175
			String scientificName="";
176
			boolean preferredFlag=false;
177
			System.out.println(this.identificationList);
178
			for (int i = 0; i < this.identificationList.size(); i++) {
179
				this.fullScientificNameString = this.identificationList.get(i);
180
				this.fullScientificNameString = this.fullScientificNameString.replaceAll(" et ", " & ");
181
				if (this.fullScientificNameString.indexOf("_preferred_") != -1){
182
					scientificName = this.fullScientificNameString.split("_preferred_")[0];
183
					String pTmp = this.fullScientificNameString.split("_preferred_")[1];
184
					if (pTmp == "1" || pTmp.toLowerCase().indexOf("true") != -1)
185
						preferredFlag=true;
186
					else
187
						preferredFlag=false;
188
				}
189
				else scientificName = this.fullScientificNameString;
190

    
191
//				taxonName = nvnpi.parseFullName(this.fullScientificNameString,NomenclaturalCode.ICZN(),null);
192
//				if (taxonName.hasProblem()){
193
//				System.out.println("pb ICZN");
194
//				taxonName  = nvnpi.parseFullName(this.fullScientificNameString,NomenclaturalCode.ICBN(),null);
195
//				if (taxonName.hasProblem()){
196
//				System.out.println("pb ICBN");
197
//				taxonName = nvnpi.parseFullName(this.fullScientificNameString,NomenclaturalCode.ICNB(), null);
198
//				if (taxonName.hasProblem()){
199
//				System.out.println("pb ICNB");
200
//				taxonName = nvnpi.parseFullName(this.fullScientificNameString,NomenclaturalCode.ICNCP(), null);
201
//				if (taxonName.hasProblem()){
202
//				System.out.println("pb ICNCP");
203
//				}
204
//				}
205
//				}				
206
//				}
207
				taxonName = nvnpi.parseFullName(scientificName);
208
				if (withCdm){
209
					names = app.getNameService().getNamesByName(scientificName);
210
					if (names.size() == 0){
211
						System.out.println("Name not found: " + scientificName);
212
					}else{
213
						if (names.size() > 1){
214
							System.out.println("More then 1 name found: " + scientificName);
215
						}
216
						System.out.println("Name found");
217
						taxonName = names.get(0);
218
					}
219
				}
220

    
221
				
222
//				tx = app.startTransaction();
223
				app.getNameService().saveOrUpdate(taxonName);
224
				taxon = Taxon.NewInstance(taxonName, sec); //TODO use real reference for sec
225
//				app.commitTransaction(tx);
226

    
227

    
228
				determinationEvent = DeterminationEvent.NewInstance();
229
				determinationEvent.setTaxon(taxon);
230
				determinationEvent.setPreferredFlag(preferredFlag);
231
				derivedThing.addDetermination(determinationEvent);
232
			}
233

    
234

    
235
			//set catalogue number (unitID)
236
			derivedThing.setCatalogNumber(this.unitID);
237
			derivedThing.setAccessionNumber(this.accessionNumber);
238
			derivedThing.setCollectorsNumber(this.collectorsNumber);
239

    
240

    
241
			/**
242
			 * INSTITUTION & COLLECTION
243
			 */
244
			//manage institution
245
			Institution institution;
246
			List<Institution> institutions;
247
			try{
248
				System.out.println(this.institutionCode);
249
				institutions= app.getAgentService().searchInstitutionByCode(this.institutionCode);
250
			}catch(Exception e){
251
				System.out.println("BLI "+e);
252
				institutions=new ArrayList<Institution>();
253
			}
254
			if (institutions.size() ==0){
255
				System.out.println("Institution (agent) unknown");
256
				//create institution
257
				institution = Institution.NewInstance();
258
				institution.setCode(this.institutionCode);				
259
			}
260
			else{
261
				System.out.println("Institution (agent) already in the db");
262
				institution = institutions.get(0);
263
			}
264

    
265
			//manage collection
266
			Collection collection = Collection.NewInstance();
267
			List<Collection> collections;
268
			try{
269
				collections = app.getCollectionService().searchByCode(this.collectionCode);
270
				//.searchCollectionByCode(this.collectionCode);
271
			}catch(Exception e){
272
				System.out.println("BLA"+e);
273
				collections=new ArrayList<Collection>();
274
			}
275
			if (collections.size() ==0){
276
				System.out.println("Collection not found "+this.collectionCode);
277
				//create new collection
278
				collection.setCode(this.collectionCode);
279
				collection.setCodeStandard("GBIF");
280
				collection.setInstitute(institution);
281
			}
282
			else{
283
				boolean collectionFound=false;
284
				for (int i=0; i<collections.size(); i++){
285
					collection = collections.get(i);
286
					try {
287
						if (collection.getInstitute().getCode().equalsIgnoreCase(institution.getCode())){ 
288
							//found a collection with the same code and the same institution
289
							collectionFound=true;
290
						}
291
					} catch (NullPointerException e) {}
292
				}
293
				System.out.println("a trouvé la collection avec la meme institution? "+collectionFound);
294
				if (!collectionFound){ //need to add a new collection with the pre-configured institution
295
					collection.setCode(this.collectionCode);
296
					collection.setCodeStandard("GBIF");
297
					collection.setInstitute(institution);
298
				}
299

    
300
			}
301
			System.out.println("collection inserted");
302
			//link specimen & collection
303
			derivedThing.setCollection(collection);
304

    
305
			/**
306
			 * GATHERING EVENT
307
			 */
308
			//create gathering event
309
			GatheringEvent gatheringEvent = GatheringEvent.NewInstance();
310
			//add locality
311
			Language language = Language.DEFAULT();
312
			LanguageString loc = LanguageString.NewInstance(this.locality,language);
313
			gatheringEvent.setLocality(loc);
314

    
315
			//create coordinates point
316
			Point coordinates = Point.NewInstance();
317
			//add coordinates
318
			coordinates.setLatitude(this.latitude);
319
			coordinates.setLongitude(this.longitude);
320
			gatheringEvent.setExactLocation(coordinates);
321

    
322
			NamedArea area = NamedArea.NewInstance();
323
			
324

    
325
			Country country = null;
326
//			System.out.println("isocountry "+this.isocountry);
327
			if (this.isocountry != null)
328
				country = app.getOccurrenceService().getCountryByIso(this.isocountry);
329
			
330
//			System.out.println(country.getLabel());
331
//			Set<Continent> cont = country.getContinents();
332
//			
333
//			System.out.println(cont.size());
334
//			Iterator<Continent> iter = cont.iterator();
335
//			while (iter.hasNext())
336
//				System.out.println(iter.next().toString());
337
			
338
			if (country != null){
339
				area.addCountry(country);
340
				System.out.println("country not null!");
341
			}
342
//			else{
343
//				if (this.country != null){
344
//					List<Country>countries = app.getOccurrenceService().getCountryByName(this.country);
345
//					if (countries.size() >0)
346
//						area.addCountry(countries.get(0));
347
//					else
348
//						System.out.println("NO COUNTRY");//TODO need to add a new country!
349
//				}
350
//			}
351
//			app.getTermService().saveTerm(area);
352
			gatheringEvent.addCollectingArea(area);
353

    
354
			//create collector
355
			AgentBase collector;
356
			ListIterator<String> collectors = this.gatheringAgentList.listIterator();
357
			//add the collectors
358
			String collName;
359
			while (collectors.hasNext()){
360
				collName = collectors.next();
361
				/*check if the collector does already exist*/
362
				try{
363
					Pager<AgentBase> col = app.getAgentService().findByTitle(null, collName, null, null, null, null, null, null);
364
					collector=col.getRecords().get(0);
365
					System.out.println("a trouve l'agent");
366
				}catch (Exception e) {
367
					collector = Person.NewInstance();
368
					collector.setTitleCache(collName, true);
369
				}
370
				gatheringEvent.setCollector(collector);
371
			}
372

    
373
			//create field/observation
374
			FieldUnit fieldUnit = FieldUnit.NewInstance();
375
			//add fieldNumber
376
			fieldUnit.setFieldNumber(this.fieldNumber);
377

    
378
			//join gatheringEvent to fieldObservation
379
			fieldUnit.setGatheringEvent(gatheringEvent);
380

    
381

    
382
//			//link fieldObservation and specimen
383
			DerivationEvent derivationEvent = DerivationEvent.NewInstance();
384
			derivationEvent.addOriginal(fieldUnit);
385
			derivedThing.addDerivationEvent(derivationEvent);
386
//			derivationEvent.addDerivative(derivedThing);
387

    
388
			/**
389
			 * SAVE AND STORE DATA
390
			 */			
391
			//save the specimen data
392
			//	app.getOccurrenceService().saveSpecimenOrObservationBase(fieldObservation);
393
			try {
394
//				tx = app.startTransaction();
395
				app.getTermService().saveOrUpdate(area);//save it sooner
396
				app.getOccurrenceService().saveOrUpdate(derivedThing);
397
//				app.commitTransaction(tx);
398
//				app.close();
399
			} catch (Exception e) {
400
				// TODO Auto-generated catch block
401
				System.out.println("PATATE "+e);
402
			}
403

    
404

    
405
			logger.info("saved new specimen ...");
406

    
407

    
408

    
409
		} catch (Exception e) {
410
			logger.warn("Error when reading record!!");
411
			e.printStackTrace();
412
			result = false;
413
		}
414
//		
415
		app.commitTransaction(tx);
416
		System.out.println("commit done");
417
		app.close();
418
		
419
		return result;
420
	}
421

    
422

    
423

    
424
	private DeterminationEvent getDetermination(Taxon taxon, String actor){
425
		logger.info("Create determination event");
426
		DeterminationEvent determinationEvent = DeterminationEvent.NewInstance();
427
		determinationEvent.setTaxon(taxon);
428
		Person person = Person.NewTitledInstance(actor);
429
		determinationEvent.setActor(person);
430
		return determinationEvent;
431
	}
432

    
433

    
434

    
435
	/**
436
	 * @param args
437
	 * @throws URISyntaxException 
438
	 */
439
	public static void main(String[] args) throws URISyntaxException {
440
		URI uri = CdmImportSources.SYNTHESYS_SPECIMEN();		
441
		logger.info("main method");
442
		SynthesysCacheActivator abcdAct = new SynthesysCacheActivator();
443
		
444
		ArrayList<HashMap<String, String>> units;
445
		try {
446
			units = ExcelUtils.parseXLS(uri);
447
		} catch (FileNotFoundException e) {
448
			logger.error("FileNotFound: " + uri);
449
			return;
450
		}
451
		HashMap<String,String> unit=null;
452
		for (int i=0; i<units.size();i++){
453
			unit = units.get(i);
454
			logger.info(unit);
455
			abcdAct.saveUnit(unit);//and then invoke
456
			abcdAct.invoke();
457
			
458
		}
459
	}
460

    
461

    
462

    
463
}
(2-2/3)