Project

General

Profile

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

    
12
import java.io.FileNotFoundException;
13
import java.util.ArrayList;
14
import java.util.HashMap;
15
import java.util.List;
16
import java.util.ListIterator;
17

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

    
22
import eu.etaxonomy.cdm.api.application.CdmApplicationController;
23
import eu.etaxonomy.cdm.api.service.pager.Pager;
24
import eu.etaxonomy.cdm.app.common.CdmDestinations;
25
import eu.etaxonomy.cdm.common.ExcelUtils;
26
import eu.etaxonomy.cdm.database.DataSourceNotFoundException;
27
import eu.etaxonomy.cdm.database.DbSchemaValidation;
28
import eu.etaxonomy.cdm.model.agent.AgentBase;
29
import eu.etaxonomy.cdm.model.agent.Institution;
30
import eu.etaxonomy.cdm.model.agent.Person;
31
import eu.etaxonomy.cdm.model.common.Language;
32
import eu.etaxonomy.cdm.model.common.LanguageString;
33
import eu.etaxonomy.cdm.model.common.init.TermNotFoundException;
34
import eu.etaxonomy.cdm.model.location.NamedArea;
35
import eu.etaxonomy.cdm.model.location.Point;
36
import eu.etaxonomy.cdm.model.location.WaterbodyOrCountry;
37
import eu.etaxonomy.cdm.model.name.TaxonNameBase;
38
import eu.etaxonomy.cdm.model.occurrence.Collection;
39
import eu.etaxonomy.cdm.model.occurrence.DerivationEvent;
40
import eu.etaxonomy.cdm.model.occurrence.DerivedUnitBase;
41
import eu.etaxonomy.cdm.model.occurrence.DeterminationEvent;
42
import eu.etaxonomy.cdm.model.occurrence.FieldObservation;
43
import eu.etaxonomy.cdm.model.occurrence.GatheringEvent;
44
import eu.etaxonomy.cdm.model.occurrence.LivingBeing;
45
import eu.etaxonomy.cdm.model.occurrence.Observation;
46
import eu.etaxonomy.cdm.model.occurrence.Specimen;
47
import eu.etaxonomy.cdm.model.reference.ReferenceBase;
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.UPDATE;
77

    
78
	protected HSSFWorkbook hssfworkbook = null;
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
	@SuppressWarnings("unchecked")
136
	public boolean invoke(){
137
		boolean result = true;
138
		boolean withCdm = true;
139
		CdmApplicationController app = null;
140
		TransactionStatus tx = null;
141

    
142

    
143
		try {
144
			app = CdmApplicationController.NewInstance(CdmDestinations.cdm_test_patricia(), hbm2dll);
145
		} catch (DataSourceNotFoundException e1) {
146
			e1.printStackTrace();
147
			System.out.println("DataSourceNotFoundException "+e1);
148
		} catch (TermNotFoundException e1) {
149
			e1.printStackTrace();
150
			System.out.println("TermNotFoundException " +e1);
151
		}
152
		tx = app.startTransaction();
153
		try {
154
			ReferenceFactory refFactory = ReferenceFactory.newInstance();
155
			ReferenceBase sec = refFactory.newDatabase();
156
			sec.setTitleCache("SYNTHESYS CACHE DATA", true);
157

    
158
			/**
159
			 * SPECIMEN OR OBSERVATION OR LIVING
160
			 */
161
			DerivedUnitBase derivedThing = null;
162
			//create specimen
163
			if (this.recordBasis != null){
164
				if (this.recordBasis.toLowerCase().startsWith("s")) {//specimen
165
					derivedThing = Specimen.NewInstance();				
166
				}
167
				else if (this.recordBasis.toLowerCase().startsWith("o")) {//observation
168
					derivedThing = Observation.NewInstance();				
169
				}
170
				else if (this.recordBasis.toLowerCase().startsWith("l")) {//living -> fossil, herbarium sheet....???
171
					derivedThing = LivingBeing.NewInstance();
172
				}
173
			}
174
			if (derivedThing == null) derivedThing = Observation.NewInstance();
175

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

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

    
227
				
228
//				tx = app.startTransaction();
229
				app.getNameService().saveOrUpdate(taxonName);
230
				taxon = Taxon.NewInstance(taxonName, sec); //TODO use real reference for sec
231
//				app.commitTransaction(tx);
232

    
233

    
234
				determinationEvent = DeterminationEvent.NewInstance();
235
				determinationEvent.setTaxon(taxon);
236
				determinationEvent.setPreferredFlag(preferredFlag);
237
				derivedThing.addDetermination(determinationEvent);
238
			}
239

    
240

    
241
			//set catalogue number (unitID)
242
			derivedThing.setCatalogNumber(this.unitID);
243
			derivedThing.setAccessionNumber(this.accessionNumber);
244
			derivedThing.setCollectorsNumber(this.collectorsNumber);
245

    
246

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

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

    
306
			}
307
			System.out.println("collection inserted");
308
			//link specimen & collection
309
			derivedThing.setCollection(collection);
310

    
311
			/**
312
			 * GATHERING EVENT
313
			 */
314
			//create gathering event
315
			GatheringEvent gatheringEvent = GatheringEvent.NewInstance();
316
			//add locality
317
			Language language = Language.DEFAULT();
318
			LanguageString loc = LanguageString.NewInstance(this.locality,language);
319
			gatheringEvent.setLocality(loc);
320

    
321
			//create coordinates point
322
			Point coordinates = Point.NewInstance();
323
			//add coordinates
324
			coordinates.setLatitude(this.latitude);
325
			coordinates.setLongitude(this.longitude);
326
			gatheringEvent.setExactLocation(coordinates);
327

    
328
			NamedArea area = NamedArea.NewInstance();
329
			
330

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

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

    
379
			//create field/observation
380
			FieldObservation fieldObservation = FieldObservation.NewInstance();
381
			//add fieldNumber
382
			fieldObservation.setFieldNumber(this.fieldNumber);
383

    
384
			//join gatheringEvent to fieldObservation
385
			fieldObservation.setGatheringEvent(gatheringEvent);
386

    
387

    
388
//			//link fieldObservation and specimen
389
			DerivationEvent derivationEvent = DerivationEvent.NewInstance();
390
			derivationEvent.addOriginal(fieldObservation);
391
			derivedThing.addDerivationEvent(derivationEvent);
392
//			derivationEvent.addDerivative(derivedThing);
393

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

    
410

    
411
			logger.info("saved new specimen ...");
412

    
413

    
414

    
415
		} catch (Exception e) {
416
			logger.warn("Error when reading record!!");
417
			e.printStackTrace();
418
			result = false;
419
		}
420
//		
421
		app.commitTransaction(tx);
422
		System.out.println("commit done");
423
		app.close();
424
		
425
		return result;
426
	}
427

    
428

    
429

    
430
	private DeterminationEvent getDetermination(Taxon taxon, String actor){
431
		logger.info("Create determination event");
432
		DeterminationEvent determinationEvent = DeterminationEvent.NewInstance();
433
		determinationEvent.setTaxon(taxon);
434
		Person person = Person.NewTitledInstance(actor);
435
		determinationEvent.setActor(person);
436
		return determinationEvent;
437
	}
438

    
439

    
440

    
441
	/**
442
	 * @param args
443
	 */
444
	public static void main(String[] args) {
445
		String filename = "/home/patricia/Desktop/CDMtabular9c04a474e2_23_09_08.xls";
446
		
447
		logger.info("main method");
448
		SynthesysCacheActivator abcdAct = new SynthesysCacheActivator();
449
		ArrayList<HashMap<String, String>> units;
450
		try {
451
			units = ExcelUtils.parseXLS(filename);
452
		} catch (FileNotFoundException e) {
453
			logger.error("FileNotFound: " + filename);
454
			return;
455
		}
456
		HashMap<String,String> unit=null;
457
		for (int i=0; i<units.size();i++){
458
			unit = units.get(i);
459
			logger.info(unit);
460
			abcdAct.saveUnit(unit);//and then invoke
461
			abcdAct.invoke();
462
			
463
		}
464
	}
465

    
466

    
467

    
468
}
(2-2/2)