Project

General

Profile

Download (35.7 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.TaxonName;
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
 * @since 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
            TaxonName 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
     * @param state
612
     * @param derivedUnitFacade
613
     */
614
    private void handleDeterminations(
615
            SpecimenImportStateBase<SpecimenImportConfiguratorBase, SpecimenImportStateBase> state,
616
            DerivedUnitFacade derivedUnitFacade) {
617
        SpecimenImportConfiguratorBase config = state.getConfig();
618

    
619

    
620
        String scientificName = "";
621
        boolean preferredFlag = false;
622

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

    
646
    }
647

    
648
    /**
649
     * @param names
650
     * @param item
651
     */
652
    private TaxonName findBestMatchingNames(GbifResponse item, SpecimenImportStateBase state) {
653
       //TODO
654
        if (item.getScientificName() != null){
655

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

    
675
    }
676

    
677

    
678

    
679
    /**
680
     * @param titleCache
681
     * @param state
682
     * @return
683
     */
684
    private List<TaxonName> findExistingNames(String nameCache, SpecimenImportStateBase state) {
685
        return getNameService().findNamesByNameCache(nameCache, MatchMode.LIKE, null);
686
    }
687

    
688

    
689

    
690
    @Override
691
    protected boolean isIgnore(SpecimenImportStateBase<SpecimenImportConfiguratorBase, SpecimenImportStateBase> state) {
692
        return false;
693
    }
694

    
695

    
696

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

    
738
    "COORDINATE_ROUNDED",
739
    "GEODETIC_DATUM_ASSUMED_WGS84"
740

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

    
774

    
775

    
776
}
(2-2/5)