Project

General

Profile

Download (34.5 KB) Statistics
| Branch: | Tag: | Revision:
1
/**
2
 * Copyright (C) 2016 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.specimen.gbif.in;
11

    
12
import java.io.IOException;
13
import java.net.URISyntaxException;
14
import java.util.Collection;
15
import java.util.HashMap;
16
import java.util.Iterator;
17
import java.util.List;
18
import java.util.Map;
19
import java.util.Set;
20

    
21
import org.apache.commons.lang.StringUtils;
22
import org.apache.http.client.ClientProtocolException;
23
import org.apache.log4j.Logger;
24
import org.springframework.stereotype.Component;
25

    
26
import eu.etaxonomy.cdm.api.application.ICdmRepository;
27
import eu.etaxonomy.cdm.api.facade.DerivedUnitFacade;
28
import eu.etaxonomy.cdm.ext.occurrence.gbif.GbifQueryServiceWrapper;
29
import eu.etaxonomy.cdm.ext.occurrence.gbif.GbifResponse;
30
import eu.etaxonomy.cdm.io.specimen.SpecimenImportBase;
31
import eu.etaxonomy.cdm.io.specimen.SpecimenImportConfiguratorBase;
32
import eu.etaxonomy.cdm.io.specimen.SpecimenImportStateBase;
33
import eu.etaxonomy.cdm.model.agent.Institution;
34
import eu.etaxonomy.cdm.model.common.Language;
35
import eu.etaxonomy.cdm.model.name.TaxonNameBase;
36
import eu.etaxonomy.cdm.model.occurrence.DerivationEvent;
37
import eu.etaxonomy.cdm.model.occurrence.DerivedUnit;
38
import eu.etaxonomy.cdm.model.occurrence.DeterminationEvent;
39
import eu.etaxonomy.cdm.model.occurrence.FieldUnit;
40
import eu.etaxonomy.cdm.model.reference.Reference;
41
import eu.etaxonomy.cdm.model.reference.ReferenceFactory;
42
import eu.etaxonomy.cdm.model.taxon.Classification;
43
import eu.etaxonomy.cdm.model.taxon.Taxon;
44
import eu.etaxonomy.cdm.persistence.query.MatchMode;
45

    
46
/**
47
 * @author k.luther
48
 * @date 15.07.2016
49
 *
50
 */
51
@Component
52
public class GbifImport extends SpecimenImportBase<GbifImportConfigurator, SpecimenImportStateBase<SpecimenImportConfiguratorBase, SpecimenImportStateBase>> {
53
    /**
54
     *
55
     */
56
    private static final long serialVersionUID = 1L;
57
    private static final Logger logger = Logger.getLogger(GbifImport.class);
58

    
59
    @Override
60
    protected boolean doCheck(SpecimenImportStateBase<SpecimenImportConfiguratorBase, SpecimenImportStateBase> state) {
61
        logger.warn("Checking not yet implemented for " + this.getClass().getSimpleName());
62
        return true;
63
    }
64

    
65

    
66

    
67

    
68

    
69

    
70
    /* (non-Javadoc)
71
     * @see eu.etaxonomy.cdm.io.specimen.SpecimenImportBase#doInvoke(eu.etaxonomy.cdm.io.common.ImportStateBase)
72
     */
73
    @Override
74
    protected void doInvoke(SpecimenImportStateBase state) {
75
       // GbifImportState gbifImportState = (GbifImportState)state;
76
        SpecimenImportConfiguratorBase config = state.getConfig();
77

    
78
            state.setTx(startTransaction());
79
            logger.info("INVOKE Specimen Import from Gbif webservice");
80
            Collection<GbifResponse> results = null;
81
            //init cd repository
82
            if(state.getCdmRepository()==null){
83
                state.setCdmRepository(this);
84
            }
85
            if (config.getOccurenceQuery() != null){
86
                 try {
87
                    results = new GbifQueryServiceWrapper().query(config.getOccurenceQuery());
88
                } catch (ClientProtocolException e) {
89
                    // TODO Auto-generated catch block
90
                    e.printStackTrace();
91
                } catch (IOException e) {
92
                    // TODO Auto-generated catch block
93
                    e.printStackTrace();
94
                } catch (URISyntaxException e) {
95
                    // TODO Auto-generated catch block
96
                    e.printStackTrace();
97
                }
98

    
99

    
100
            }
101
            if (results == null){
102
                logger.info("There were no results for the query: " + config.getOccurenceQuery().toString());
103
                return;
104
            }
105
            List<Reference> references = getReferenceService().listByReferenceTitle(Reference.class, state.getConfig().getSourceReferenceTitle(), MatchMode.LIKE, null, null, null, null, null);
106
            //List<Reference> references = new ArrayList<Reference>();
107
            if (state.getRef()==null){
108
                String name = NB(( state.getConfig()).getSourceReferenceTitle());
109
                for (Reference reference : references) {
110
                    if (! StringUtils.isBlank(reference.getTitleCache())) {
111
                        if (reference.getTitleCache().equalsIgnoreCase(name)) {
112
                            state.setRef(reference);
113
                        }
114
                    }
115
                }
116
                if (state.getRef() == null){
117
                    state.setRef(ReferenceFactory.newGeneric());
118
                    state.getRef().setTitle(state.getConfig().getSourceReferenceTitle() + " Test ");
119
                }
120
            }
121
        //}
122
        save(state.getRef(), state);
123
        state.getConfig().setSourceReference(state.getRef());
124
        if(state.getConfig().getClassificationUuid()!=null){
125
            //load classification from config if it exists
126
            state.setClassification(getClassificationService().load(state.getConfig().getClassificationUuid()));
127
        }
128
        if(state.getClassification()==null){//no existing classification was set in config
129
            List<Classification> classificationList = getClassificationService().list(Classification.class, null, null, null, null);
130
            //get classification via user interaction
131
            if (state.getConfig().isUseClassification() && state.getConfig().isInteractWithUser()){
132
                Map<String,Classification> classMap = new HashMap<String, Classification>();
133
                for (Classification tree : classificationList) {
134
                    if (! StringUtils.isBlank(tree.getTitleCache())) {
135
                        classMap.put(tree.getTitleCache(),tree);
136
                    }
137
                }
138

    
139
            }
140
            // use default classification as the classification to import into
141
            if (state.getClassification() == null) {
142
                String name = NB(state.getConfig().getClassificationName());
143
                for (Classification classif : classificationList){
144
                    if (classif.getTitleCache() != null && classif.getTitleCache().equalsIgnoreCase(name)) {
145
                        state.setClassification(classif);
146
                    }
147
                }
148
                if (state.getClassification() == null){
149
                    state.setClassification(Classification.NewInstance(name, state.getRef(), Language.DEFAULT()));
150
                    //we do not need a default classification when creating an empty new one
151
                    state.setDefaultClassification(state.getClassification());
152

    
153
                }
154

    
155
            }
156
        }
157
        String message = "nb units to insert: " + results.size();
158
        logger.info(message);
159
        state.getConfig().getProgressMonitor().beginTask("Importing ABCD file", results.size());
160
        updateProgress(state, message);
161

    
162
        state.setDataHolder(new GbifDataHolder());
163
        state.getDataHolder().reset();
164

    
165
        for (GbifResponse response:results) {
166
            if(state.getConfig().getProgressMonitor().isCanceled()){
167
                break;
168
            }
169

    
170

    
171

    
172

    
173
            //this.setUnitPropertiesXML( item, abcdFieldGetter, state);
174
        //   updateProgress(state, "Importing data for unit "+state.getDataHolder().unitID+" ("+i+"/"+unitsList.getLength()+")");
175

    
176
            //import unit + field unit data
177
            this.handleSingleUnit(state, response);
178

    
179
        }
180

    
181

    
182
        commitTransaction(state.getTx());
183

    
184

    
185

    
186
    }
187

    
188
    @Override
189
    protected void importAssociatedUnits(
190
            SpecimenImportStateBase<SpecimenImportConfiguratorBase, SpecimenImportStateBase> state, Object item,
191
            DerivedUnitFacade derivedUnitFacade) {
192

    
193
        //import associated units
194
        FieldUnit currentFieldUnit = derivedUnitFacade.innerFieldUnit();
195
        //TODO: push state (think of implementing stack architecture for state
196
        DerivedUnit currentUnit = state.getDerivedUnitBase();
197
        if (currentUnit != null){
198
        DerivationEvent currentDerivedFrom = currentUnit.getDerivedFrom();
199
        }
200
      /*  NodeList unitAssociationList = item.getElementsByTagName(currentPrefix+"UnitAssociation");
201
        for(int k=0;k<unitAssociationList.getLength();k++){
202
            if(unitAssociationList.item(k) instanceof Element){
203
                Element unitAssociation = (Element)unitAssociationList.item(k);
204
                UnitAssociationParser unitAssociationParser = new UnitAssociationParser(currentPrefix, state.getReport(), state.getCdmRepository());
205
                UnitAssociationWrapper associationWrapper = unitAssociationParser.parse(unitAssociation);
206
                if(associationWrapper!=null){
207
                    NodeList associatedUnits = associationWrapper.getAssociatedUnits();
208
                    if(associatedUnits!=null){
209
                        for(int m=0;m<associatedUnits.getLength();m++){
210
                            if(associatedUnits.item(m) instanceof Element){
211
                                state.reset();
212
                                state.setPrefix(associationWrapper.getPrefix());
213
                                this.setUnitPropertiesXML((Element) associatedUnits.item(m), new Abcd206XMLFieldGetter(state.getDataHolder(), state.getPrefix()), state);
214
                                handleSingleUnit(state, associatedUnits.item(m));
215

    
216
                                DerivedUnit associatedUnit = state.getDerivedUnitBase();
217
                                FieldUnit associatedFieldUnit = null;
218
                                java.util.Collection<FieldUnit> associatedFieldUnits = state.getCdmRepository().getOccurrenceService().getFieldUnits(associatedUnit.getUuid());
219
                                //ignore field unit if associated unit has more than one
220
                                if(associatedFieldUnits.size()>1){
221
                                    state.getReport().addInfoMessage(String.format("%s has more than one field unit.", associatedUnit));
222
                                }
223
                                else if(associatedFieldUnits.size()==1){
224
                                    associatedFieldUnit = associatedFieldUnits.iterator().next();
225
                                }
226

    
227
                                //attach current unit and associated unit depending on association type
228

    
229
                                //parent-child relation:
230
                                //copy derivation event and connect parent and sub derivative
231
                                if(associationWrapper.getAssociationType().contains("individual")){
232
                                    if(currentDerivedFrom==null){
233
                                        state.getReport().addInfoMessage(String.format("No derivation event found for unit %s. Defaulting to ACCESSIONING event.",AbcdImportUtility.getUnitID(currentUnit, config)));
234
                                        DerivationEvent.NewSimpleInstance(associatedUnit, currentUnit, DerivationEventType.ACCESSIONING());
235
                                    }
236
                                    else{
237
                                        DerivationEvent updatedDerivationEvent = DerivationEvent.NewSimpleInstance(associatedUnit, currentUnit, currentDerivedFrom.getType());
238
                                        updatedDerivationEvent.setActor(currentDerivedFrom.getActor());
239
                                        updatedDerivationEvent.setDescription(currentDerivedFrom.getDescription());
240
                                        updatedDerivationEvent.setInstitution(currentDerivedFrom.getInstitution());
241
                                        updatedDerivationEvent.setTimeperiod(currentDerivedFrom.getTimeperiod());
242
                                    }
243
                                    state.getReport().addDerivate(associatedUnit, currentUnit, config);
244
                                }
245
                                //siblings relation
246
                                //connect current unit to field unit of associated unit
247
                                else if(associationWrapper.getAssociationType().contains("population")){
248
                                    //no associated field unit -> using current one
249
                                    if(associatedFieldUnit==null){
250
                                        if(currentFieldUnit!=null){
251
                                            DerivationEvent.NewSimpleInstance(currentFieldUnit, associatedUnit, DerivationEventType.ACCESSIONING());
252
                                        }
253
                                    }
254
                                    else{
255
                                        if(currentDerivedFrom==null){
256
                                            state.getReport().addInfoMessage("No derivation event found for unit "+AbcdImportUtility.getUnitID(currentUnit, config)+". Defaulting to ACCESIONING event.");
257
                                            DerivationEvent.NewSimpleInstance(associatedFieldUnit, currentUnit, DerivationEventType.ACCESSIONING());
258
                                        }
259
                                        if(currentDerivedFrom!=null && associatedFieldUnit!=currentFieldUnit){
260
                                            DerivationEvent updatedDerivationEvent = DerivationEvent.NewSimpleInstance(associatedFieldUnit, currentUnit, currentDerivedFrom.getType());
261
                                            updatedDerivationEvent.setActor(currentDerivedFrom.getActor());
262
                                            updatedDerivationEvent.setDescription(currentDerivedFrom.getDescription());
263
                                            updatedDerivationEvent.setInstitution(currentDerivedFrom.getInstitution());
264
                                            updatedDerivationEvent.setTimeperiod(currentDerivedFrom.getTimeperiod());
265
                                        }
266
                                    }
267
                                }
268

    
269
                                //delete current field unit if replaced
270
                                if(currentFieldUnit!=null && currentDerivedFrom!=null
271
                                        && currentFieldUnit.getDerivationEvents().size()==1  && currentFieldUnit.getDerivationEvents().contains(currentDerivedFrom) //making sure that the field unit
272
                                        && currentDerivedFrom.getDerivatives().size()==1 && currentDerivedFrom.getDerivatives().contains(currentUnit) //is not attached to other derived units
273
                                        && currentDerivedFrom!=currentUnit.getDerivedFrom() // <- derivation has been replaced and can be deleted
274
                                        ){
275
                                    currentFieldUnit.removeDerivationEvent(currentDerivedFrom);
276
                                    state.getCdmRepository().getOccurrenceService().delete(currentFieldUnit);
277
                                }
278

    
279
                                save(associatedUnit, state);
280
                            }
281
                        }
282
                    }
283
                }
284
            }
285
        }*/
286
        //TODO: pop state
287
        state.reset();
288
        state.setDerivedUnitBase(currentUnit);
289

    
290
    }
291

    
292

    
293
@Override
294
protected void handleSingleUnit(SpecimenImportStateBase<SpecimenImportConfiguratorBase, SpecimenImportStateBase> state,
295
        Object itemObject){
296
    GbifResponse item;
297
    if (itemObject instanceof GbifResponse){
298
        item = (GbifResponse) itemObject;
299
    } else{
300
        logger.error("For Gbif Import the item has to be of type GbifResponse.");
301
        return;
302
    }
303
    if (logger.isDebugEnabled()) {
304
        logger.info("handleSingleUnit "+state.getRef());
305
    }
306

    
307
        ICdmRepository cdmAppController = state.getConfig().getCdmAppController();
308
        if(cdmAppController==null){
309
            cdmAppController = this;
310
        }
311
        //check if unit already exists
312
        DerivedUnitFacade derivedUnitFacade;
313
        derivedUnitFacade = item.getDerivedUnitFacade();
314
        state.setDerivedUnitBase(derivedUnitFacade.innerDerivedUnit());
315
        TaxonNameBase bestMatchingName =  findBestMatchingNames(item, state);
316
        if (bestMatchingName == null){
317
            bestMatchingName = item.getScientificName();
318
        }
319
        if (bestMatchingName != null){
320
            Taxon taxon = getOrCreateTaxonForName(bestMatchingName, state);
321
            if (state.getConfig().isAddIndividualsAssociationsSuchAsSpecimenAndObservations()) {
322
                //do not add IndividualsAssociation to non-preferred taxa
323
                if(logger.isDebugEnabled()){
324
                    logger.info("isDoCreateIndividualsAssociations");
325
                }
326
                for (DeterminationEvent determinationEvent:derivedUnitFacade.getDeterminations()){
327
                    makeIndividualsAssociation(state, taxon, determinationEvent);
328
                }
329

    
330
                save(state.getDerivedUnitBase(), state);
331
            }
332
        }
333

    
334

    
335

    
336
        // handle collection data
337
        handleCollectionData(state, derivedUnitFacade);
338
        save(item.getDerivedUnitFacade().baseUnit(), state);
339
        save(item.getDerivedUnitFacade().getFieldUnit(false), state);
340
        importAssociatedUnits(state, item, derivedUnitFacade);
341
        /*
342
        if(state.getConfig().isIgnoreImportOfExistingSpecimens()){
343
            String[] tripleId = item.getTripleID();
344
            SpecimenOrObservationBase<?> existingSpecimen = findExistingSpecimen(tripleId[0], state);
345
            DerivedUnitFacade derivedUnitFacade;
346
            if(existingSpecimen!=null && existingSpecimen.isInstanceOf(DerivedUnit.class)){
347
                DerivedUnit derivedUnit = HibernateProxyHelper.deproxy(existingSpecimen, DerivedUnit.class);
348
                state.setDerivedUnitBase(derivedUnit);
349
                derivedUnitFacade = item.getDerivedUnitFacade();
350
                List<NonViralName> names = findExistingNames(item.getScientificName().getNameCache(), state);
351
                if (!names.isEmpty()){
352
                    findBestMatchingName(names, item);
353
                }
354
                save(item.getDerivedUnitFacade().baseUnit(), state);
355
                importAssociatedUnits(state, item, derivedUnitFacade);
356
                state.getReport().addAlreadyExistingSpecimen(SpecimenImportUtility.getUnitID(derivedUnit, state.getConfig()), derivedUnit);
357
                return;
358
            }
359
        }
360

    
361
        //import new specimen
362

    
363
        // import DNA unit
364
        //TODO!!!!
365
        if(state.getDataHolder().getKindOfUnit()!=null && state.getDataHolder().getKindOfUnit().equalsIgnoreCase("dna")){
366
            GbifDnaParser dnaParser = new GbifDnaParser(state.getPrefix(), state.getReport(), state.getCdmRepository());
367
            DnaSample dnaSample = dnaParser.parse(item, state);
368
            save(dnaSample, state);
369
            //set dna as derived unit to avoid creating an extra specimen for this dna sample (instead just the field unit will be created)
370
            state.setDerivedUnitBase(dnaSample);
371
            derivedUnitFacade = DerivedUnitFacade.NewInstance(state.getDerivedUnitBase());
372
        }
373
        else{
374
            // create facade
375
            derivedUnitFacade = getFacade(state);
376
            state.setDerivedUnitBase(derivedUnitFacade.innerDerivedUnit());
377
     //   }
378

    
379
        /**
380
         * GATHERING EVENT
381

    
382
        // gathering event
383
        UnitsGatheringEvent<GbifImportConfigurator> unitsGatheringEvent =
384
               /* new UnitsGatheringEvent<GbifImportConfigurator>(cdmAppController.getTermService(),
385
                state.getDataHolder().locality, null, state.getDataHolder().decimalLongitude,
386
                state.getDataHolder().decimalLatitude, state.getDataHolder().getGatheringElevationText(),
387
                state.getDataHolder().getGatheringElevationMin(), state.getDataHolder().getGatheringElevationMax(),
388
                state.getDataHolder().getGatheringElevationUnit(), state.getDataHolder().getGatheringDateText(),
389
                state.getDataHolder().getGatheringNotes(), state.getTransformer().getReferenceSystemByKey(
390
                        state.getDataHolder().getGatheringSpatialDatum()), state.getDataHolder().gatheringAgentList,
391
                state.getDataHolder().gatheringTeamList, state.getConfig());
392

    
393
        // country
394
        UnitsGatheringArea unitsGatheringArea = new UnitsGatheringArea();
395
        //  unitsGatheringArea.setConfig(state.getConfig(),getOccurrenceService(), getTermService());
396
        unitsGatheringArea.setParams(state.getDataHolder().countryCode, state.getDataHolder().country, state.getConfig(), cdmAppController.getTermService(), cdmAppController.getOccurrenceService());
397

    
398
        DefinedTermBase<?> areaCountry =  unitsGatheringArea.getCountry();
399

    
400
        // other areas
401
        unitsGatheringArea = new UnitsGatheringArea();
402
        //            unitsGatheringArea.setConfig(state.getConfig(),getOccurrenceService(),getTermService());
403
        unitsGatheringArea.setAreas(state.getDataHolder().getNamedAreaList(),state.getConfig(), cdmAppController.getTermService(), cdmAppController.getVocabularyService());
404
        ArrayList<DefinedTermBase> nas = unitsGatheringArea.getAreas();
405
        for (DefinedTermBase namedArea : nas) {
406
            unitsGatheringEvent.addArea(namedArea);
407
        }
408

    
409
        // copy gathering event to facade
410
        GatheringEvent gatheringEvent = unitsGatheringEvent.getGatheringEvent();
411
        derivedUnitFacade.setLocality(gatheringEvent.getLocality());
412
        derivedUnitFacade.setExactLocation(gatheringEvent.getExactLocation());
413
        derivedUnitFacade.setCollector(gatheringEvent.getCollector());
414
        derivedUnitFacade.setCountry((NamedArea)areaCountry);
415
        derivedUnitFacade.setAbsoluteElevationText(gatheringEvent.getAbsoluteElevationText());
416
        derivedUnitFacade.setAbsoluteElevation(gatheringEvent.getAbsoluteElevation());
417
        derivedUnitFacade.setAbsoluteElevationMax(gatheringEvent.getAbsoluteElevationMax());
418
        derivedUnitFacade.setGatheringPeriod(gatheringEvent.getTimeperiod());
419

    
420
        for(DefinedTermBase<?> area:unitsGatheringArea.getAreas()){
421
            derivedUnitFacade.addCollectingArea((NamedArea) area);
422
        }
423
        //            derivedUnitFacade.addCollectingAreas(unitsGatheringArea.getAreas());
424
        // TODO exsiccatum
425

    
426
        // add fieldNumber
427
        derivedUnitFacade.setFieldNumber(NB(state.getDataHolder().getFieldNumber()));
428

    
429
        // add unitNotes
430
        derivedUnitFacade.addAnnotation(Annotation.NewDefaultLanguageInstance(NB(state.getDataHolder().getUnitNotes())));
431

    
432
        // //add Multimedia URLs
433
        if (state.getDataHolder().getMultimediaObjects().size() != -1) {
434
            for (String multimediaObject : state.getDataHolder().getMultimediaObjects()) {
435
                Media media;
436
                try {
437
                    media = getImageMedia(multimediaObject, READ_MEDIA_DATA);
438
                    derivedUnitFacade.addDerivedUnitMedia(media);
439
                    if(state.getConfig().isAddMediaAsMediaSpecimen()){
440
                        //add media also as specimen scan
441
                        MediaSpecimen mediaSpecimen = MediaSpecimen.NewInstance(SpecimenOrObservationType.Media);
442
                        mediaSpecimen.setMediaSpecimen(media);
443
                        DefinedTermBase specimenScanTerm = getTermService().load(SPECIMEN_SCAN_TERM);
444
                        if(specimenScanTerm instanceof DefinedTerm){
445
                            mediaSpecimen.setKindOfUnit((DefinedTerm) specimenScanTerm);
446
                        }
447
                        DerivationEvent derivationEvent = DerivationEvent.NewInstance(DerivationEventType.PREPARATION());
448
                        derivationEvent.addDerivative(mediaSpecimen);
449
                        derivedUnitFacade.innerDerivedUnit().addDerivationEvent(derivationEvent);
450
                    }
451

    
452
                } catch (MalformedURLException e) {
453
                    // TODO Auto-generated catch block
454
                    e.printStackTrace();
455
                }
456

    
457
            }
458
        }
459

    
460
        //          /*
461
        //           * merge AND STORE DATA
462
        //
463
        //          getTermService().saveOrUpdate(areaCountry);// TODO save area sooner
464
        //
465
        //          for (NamedArea area : otherAreas) {
466
        //              getTermService().saveOrUpdate(area);// merge it sooner (foreach area)
467
        //          }
468

    
469
        save(unitsGatheringEvent.getLocality(), state);
470

    
471
        // handle collection data
472
        setCollectionData(state, derivedUnitFacade);
473

    
474
        //Reference stuff
475
       // SpecimenUserInteraction sui = state.getConfig().getSpecimenUserInteraction();
476
        Map<String,OriginalSourceBase<?>> sourceMap = new HashMap<String, OriginalSourceBase<?>>();
477

    
478
        state.getDataHolder().docSources = new ArrayList<String>();
479
        for (String[] fullReference : state.getDataHolder().referenceList) {
480
            String strReference=fullReference[0];
481
            String citationDetail = fullReference[1];
482
            String citationURL = fullReference[2];
483

    
484
            if (!citationURL.isEmpty()) {
485
                citationDetail+=", "+citationURL;
486
            }
487

    
488
            Reference reference;
489
            if(strReference.equals(state.getRef().getTitleCache())){
490
                reference = state.getRef();
491
            }
492
            else{
493
                reference = ReferenceFactory.newGeneric();
494
                reference.setTitle(strReference);
495
            }
496

    
497
            IdentifiableSource sour = getIdentifiableSource(reference,citationDetail);
498

    
499
            try{
500
                if (sour.getCitation() != null){
501
                    if(StringUtils.isNotBlank(sour.getCitationMicroReference())) {
502
                        state.getDataHolder().docSources.add(sour.getCitation().getTitleCache()+ "---"+sour.getCitationMicroReference());
503
                    } else {
504
                        state.getDataHolder().docSources.add(sour.getCitation().getTitleCache());
505
                    }
506
                }
507
            }catch(Exception e){
508
                logger.warn("oups");
509
            }
510
            reference.addSource(sour);
511
            save(reference, state);
512
        }
513
        List<IdentifiableSource> issTmp = new ArrayList<IdentifiableSource>();//getCommonService().list(IdentifiableSource.class, null, null, null, null);
514
        List<DescriptionElementSource> issTmp2 = new ArrayList<DescriptionElementSource>();//getCommonService().list(DescriptionElementSource.class, null, null, null, null);
515

    
516
        Set<OriginalSourceBase> osbSet = new HashSet<OriginalSourceBase>();
517
        if(issTmp2!=null) {
518
            osbSet.addAll(issTmp2);
519
        }
520
        if(issTmp!=null) {
521
            osbSet.addAll(issTmp);
522
        }
523

    
524
        addToSourceMap(sourceMap, osbSet);
525

    
526
        if( state.getConfig().isInteractWithUser()){
527
            List<OriginalSourceBase<?>>sources=null;
528
            if(!state.isDerivedUnitSourcesSet()){
529
                sources= sui.askForSource(sourceMap, "the unit itself","",getReferenceService(), state.getDataHolder().docSources);
530
                state.setDerivedUnitSources(sources);
531
                state.setDerivedUnitSourcesSet(true);
532
            }
533
            else{
534
                sources=state.getDerivedUnitSources();
535
            }
536
//          System.out.println("nb sources: "+sources.size());
537
//          System.out.println("derivedunitfacade : "+derivedUnitFacade.getTitleCache());
538
            for (OriginalSourceBase<?> sour:sources){
539
                if(sour.isInstanceOf(IdentifiableSource.class)){
540
                    if(sourceNotLinkedToElement(derivedUnitFacade,sour)) {
541
//                      System.out.println("add source to derivedunitfacade1 "+derivedUnitFacade.getTitleCache());
542
                        derivedUnitFacade.addSource((IdentifiableSource)sour.clone());
543
                    }
544
                }else{
545
                    if(sourceNotLinkedToElement(derivedUnitFacade,sour)) {
546
//                      System.out.println("add source to derivedunitfacade2 "+derivedUnitFacade.getTitleCache());
547
                        derivedUnitFacade.addSource(OriginalSourceType.Import,sour.getCitation(),sour.getCitationMicroReference(), ioName);
548
                    }
549
                }
550
            }
551
        }else{
552
            for (OriginalSourceBase<?> sr : sourceMap.values()){
553
                if(sr.isInstanceOf(IdentifiableSource.class)){
554
                    if(sourceNotLinkedToElement(derivedUnitFacade,sr)) {
555
//                      System.out.println("add source to derivedunitfacade3 "+derivedUnitFacade.getTitleCache());
556
                        derivedUnitFacade.addSource((IdentifiableSource)sr.clone());
557
                    }
558
                }else{
559
                    if(sourceNotLinkedToElement(derivedUnitFacade,sr)) {
560
//                      System.out.println("add source to derivedunitfacade4 "+derivedUnitFacade.getTitleCache());
561
                        derivedUnitFacade.addSource(OriginalSourceType.Import,sr.getCitation(),sr.getCitationMicroReference(), ioName);
562
                    }
563
                }
564
            }
565
        }
566

    
567
        save(item, state);
568

    
569
        if(DEBUG) {
570
            logger.info("saved ABCD specimen ...");
571
        }
572

    
573
        // handle identifications
574
        handleIdentifications(state, derivedUnitFacade);
575

    
576
        //associatedUnits
577
        importAssociatedUnits(state, item, derivedUnitFacade);
578

    
579

    
580

    
581
    } catch (Exception e) {
582
        String message = "Error when reading record!";
583
        logger.warn(message);
584
        state.getReport().addException(message, e);
585
        e.printStackTrace();
586
        state.setUnsuccessfull();
587
    }
588
*/
589
    return;
590
}
591

    
592

    
593
/**
594
 * @param state
595
 * @param derivedUnitFacade
596
 */
597
private void handleCollectionData(
598
        SpecimenImportStateBase<SpecimenImportConfiguratorBase, SpecimenImportStateBase> state,
599
        DerivedUnitFacade derivedUnitFacade) {
600
   eu.etaxonomy.cdm.model.occurrence.Collection collection = derivedUnitFacade.getCollection();
601
   if (collection != null) {
602
       Institution institution = getInstitution(collection.getInstitute().getCode(), state);
603

    
604
       collection = getCollection(institution, collection.getCode(), state);
605
   }
606

    
607
}
608

    
609

    
610

    
611

    
612

    
613

    
614
/**
615
 * @param state
616
 * @param derivedUnitFacade
617
 */
618
private void handleDeterminations(
619
        SpecimenImportStateBase<SpecimenImportConfiguratorBase, SpecimenImportStateBase> state,
620
        DerivedUnitFacade derivedUnitFacade) {
621
    SpecimenImportConfiguratorBase config = state.getConfig();
622

    
623

    
624
    String scientificName = "";
625
    boolean preferredFlag = false;
626

    
627
    if (state.getDataHolder().getNomenclatureCode() == ""){
628
        state.getDataHolder().setNomenclatureCode(config.getNomenclaturalCode().toString());
629
    }
630
    Set<DeterminationEvent> determinations =  derivedUnitFacade.getDeterminations();
631
    Iterator<DeterminationEvent> determinationIterator = determinations.iterator();
632
    DeterminationEvent event;
633
    Taxon taxon;
634
    TaxonNameBase name ;
635
    while (determinationIterator.hasNext()) {
636
        event = determinationIterator.next();
637
        taxon = (Taxon)event.getTaxon();
638
        if (taxon == null){
639
            name = event.getTaxonName();
640
            if (!name.getTaxa().isEmpty()){
641
                taxon = (Taxon)name.getTaxa().iterator().next();
642
            }
643
        }
644
        if (taxon != null){
645
            addTaxonNode(taxon, state,preferredFlag);
646
            linkDeterminationEvent(state, taxon, preferredFlag, derivedUnitFacade, null, null);
647
        }
648
    }
649

    
650
}
651

    
652
/**
653
 * @param names
654
 * @param item
655
 */
656
private TaxonNameBase<?,?> findBestMatchingNames(GbifResponse item, SpecimenImportStateBase state) {
657
   //TODO
658
    if (item.getScientificName() != null){
659

    
660
       List<TaxonNameBase> names = findExistingNames(item.getScientificName().getNameCache(), state);
661
       if (!names.isEmpty()){
662
           TaxonNameBase<?,?> result = names.get(0);
663
           Set<DeterminationEvent> detEvents = item.getDerivedUnitFacade().baseUnit().getDeterminations();
664
           for (DeterminationEvent event:detEvents){
665
               if(event.getTaxonName().getNameCache().equals(result.getNameCache()) ){
666
                  event.setTaxonName(result);
667
               } else{
668
                   names = findExistingNames(event.getTaxonName().getNameCache(), state);
669
                   if (!names.isEmpty()){
670
                       event.setTaxonName(names.get(0));
671
                   }
672
               }
673
           }
674
           return result;
675
       }
676
    }
677
   return null;
678

    
679
}
680

    
681

    
682

    
683
/**
684
 * @param titleCache
685
 * @param state
686
 * @return
687
 */
688
private List<TaxonNameBase> findExistingNames(String nameCache, SpecimenImportStateBase state) {
689
    return getNameService().findNamesByNameCache(nameCache, MatchMode.LIKE, null);
690
}
691

    
692

    
693

    
694

    
695

    
696

    
697
/* (non-Javadoc)
698
 * @see eu.etaxonomy.cdm.io.common.CdmIoBase#isIgnore(eu.etaxonomy.cdm.io.common.IoStateBase)
699
 */
700
@Override
701
protected boolean isIgnore(SpecimenImportStateBase<SpecimenImportConfiguratorBase, SpecimenImportStateBase> state) {
702

    
703
    return false;
704
}
705

    
706

    
707

    
708

    
709

    
710

    
711
    /*
712
     * "key": 1257570425,
713
"datasetKey": "7bd65a7a-f762-11e1-a439-00145eb45e9a",
714
"publishingOrgKey": "90fd6680-349f-11d8-aa2d-b8a03c50a862",
715
"publishingCountry": "US",
716
"protocol": "DWC_ARCHIVE",
717
"lastCrawled": "2016-06-06T11:11:35.800+0000",
718
"lastParsed": "2016-03-21T14:11:42.224+0000",
719
"extensions": { },
720
"basisOfRecord": "PRESERVED_SPECIMEN",
721
"individualCount": 1,
722
"taxonKey": 5338762,
723
"kingdomKey": 6,
724
"phylumKey": 7707728,
725
"classKey": 220,
726
"orderKey": 412,
727
"familyKey": 8798,
728
"genusKey": 2907867,
729
"speciesKey": 5338762,
730
"scientificName": "Mitchella repens L.",
731
"kingdom": "Plantae",
732
"phylum": "Tracheophyta",
733
"order": "Gentianales",
734
"family": "Rubiaceae",
735
"genus": "Mitchella",
736
"species": "Mitchella repens",
737
"genericName": "Mitchella",
738
"specificEpithet": "repens",
739
"taxonRank": "SPECIES",
740
"dateIdentified": "2005-12-31T23:00:00.000+0000",
741
"decimalLongitude": -98.70693,
742
"decimalLatitude": 20.77805,
743
"elevation": 1524.0,
744
"continent": "NORTH_AMERICA",
745
"stateProvince": "Hidalgo",
746
"year": 2006,
747
"month": 6,
748
"day": 11,
749
"eventDate": "2006-06-10T22:00:00.000+0000",
750
"issues": [
751

    
752
    "COORDINATE_ROUNDED",
753
    "GEODETIC_DATUM_ASSUMED_WGS84"
754

    
755
],
756
"lastInterpreted": "2016-04-17T13:34:52.325+0000",
757
"identifiers": [ ],
758
"facts": [ ],
759
"relations": [ ],
760
"geodeticDatum": "WGS84",
761
"class": "Magnoliopsida",
762
"countryCode": "MX",
763
"country": "Mexico",
764
"nomenclaturalStatus": "No opinion",
765
"rightsHolder": "Missouri Botanical Garden",
766
"identifier": "urn:catalog:MO:Tropicos:100217973",
767
"recordNumber": "Oberle 274",
768
"nomenclaturalCode": "ICNafp",
769
"county": "Metztitlán",
770
"locality": "Along trail downslope of road between Molango and Zacualtipan.",
771
"datasetName": "Tropicos",
772
"gbifID": "1257570425",
773
"collectionCode": "MO",
774
"occurrenceID": "urn:catalog:MO:Tropicos:100217973",
775
"type": "PhysicalObject",
776
"taxonID": "27902971",
777
"license": "http://creativecommons.org/licenses/by/4.0/legalcode",
778
"catalogNumber": "100217973",
779
"recordedBy": "Brad Oberle",
780
"institutionCode": "MO",
781
"ownerInstitutionCode": "MOBOT",
782
"bibliographicCitation": "http://www.tropicos.org/Specimen/100217973",
783
"identifiedBy": "B. Oberle",
784
"collectionID": "http://biocol.org/urn:lsid:biocol.org:col:15859
785
     *
786
     */
787

    
788

    
789

    
790
}
(2-2/5)