Project

General

Profile

Download (14.9 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.ss.usermodel.Workbook;
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.Country;
37
import eu.etaxonomy.cdm.model.location.NamedArea;
38
import eu.etaxonomy.cdm.model.location.Point;
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

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

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

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

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

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

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

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

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

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

    
225

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

    
232

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

    
238

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

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

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

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

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

    
320
			NamedArea area = NamedArea.NewInstance();
321
			
322

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

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

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

    
376
			//join gatheringEvent to fieldObservation
377
			fieldUnit.setGatheringEvent(gatheringEvent);
378

    
379

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

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

    
402

    
403
			logger.info("saved new specimen ...");
404

    
405

    
406

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

    
420

    
421

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

    
431

    
432

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

    
459

    
460

    
461
}
(2-2/3)