Project

General

Profile

Download (55 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.io.specimen.abcd206.in;
11

    
12
import java.io.InputStream;
13
import java.net.MalformedURLException;
14
import java.util.ArrayList;
15
import java.util.HashMap;
16
import java.util.HashSet;
17
import java.util.List;
18
import java.util.Map;
19
import java.util.Set;
20
import java.util.UUID;
21

    
22
import org.apache.commons.lang.StringUtils;
23
import org.apache.log4j.Logger;
24
import org.springframework.stereotype.Component;
25
import org.w3c.dom.Element;
26
import org.w3c.dom.NodeList;
27

    
28
import eu.etaxonomy.cdm.api.application.ICdmApplicationConfiguration;
29
import eu.etaxonomy.cdm.api.facade.DerivedUnitFacade;
30
import eu.etaxonomy.cdm.ext.occurrence.bioCase.BioCaseQueryServiceWrapper;
31
import eu.etaxonomy.cdm.hibernate.HibernateProxyHelper;
32
import eu.etaxonomy.cdm.io.common.ICdmIO;
33
import eu.etaxonomy.cdm.io.common.MapWrapper;
34
import eu.etaxonomy.cdm.io.specimen.SpecimenImportBase;
35
import eu.etaxonomy.cdm.io.specimen.SpecimenUserInteraction;
36
import eu.etaxonomy.cdm.io.specimen.UnitsGatheringArea;
37
import eu.etaxonomy.cdm.io.specimen.UnitsGatheringEvent;
38
import eu.etaxonomy.cdm.io.specimen.abcd206.in.molecular.AbcdDnaParser;
39
import eu.etaxonomy.cdm.model.agent.Institution;
40
import eu.etaxonomy.cdm.model.agent.Person;
41
import eu.etaxonomy.cdm.model.agent.Team;
42
import eu.etaxonomy.cdm.model.agent.TeamOrPersonBase;
43
import eu.etaxonomy.cdm.model.common.Annotation;
44
import eu.etaxonomy.cdm.model.common.CdmBase;
45
import eu.etaxonomy.cdm.model.common.DefinedTerm;
46
import eu.etaxonomy.cdm.model.common.DefinedTermBase;
47
import eu.etaxonomy.cdm.model.common.IdentifiableSource;
48
import eu.etaxonomy.cdm.model.common.Language;
49
import eu.etaxonomy.cdm.model.common.LanguageString;
50
import eu.etaxonomy.cdm.model.common.OriginalSourceBase;
51
import eu.etaxonomy.cdm.model.common.OriginalSourceType;
52
import eu.etaxonomy.cdm.model.description.DescriptionElementSource;
53
import eu.etaxonomy.cdm.model.location.NamedArea;
54
import eu.etaxonomy.cdm.model.media.Media;
55
import eu.etaxonomy.cdm.model.molecular.DnaSample;
56
import eu.etaxonomy.cdm.model.name.SpecimenTypeDesignationStatus;
57
import eu.etaxonomy.cdm.model.occurrence.Collection;
58
import eu.etaxonomy.cdm.model.occurrence.DerivationEvent;
59
import eu.etaxonomy.cdm.model.occurrence.DerivationEventType;
60
import eu.etaxonomy.cdm.model.occurrence.DerivedUnit;
61
import eu.etaxonomy.cdm.model.occurrence.FieldUnit;
62
import eu.etaxonomy.cdm.model.occurrence.GatheringEvent;
63
import eu.etaxonomy.cdm.model.occurrence.MediaSpecimen;
64
import eu.etaxonomy.cdm.model.occurrence.SpecimenOrObservationBase;
65
import eu.etaxonomy.cdm.model.occurrence.SpecimenOrObservationType;
66
import eu.etaxonomy.cdm.model.reference.Reference;
67
import eu.etaxonomy.cdm.model.reference.ReferenceFactory;
68
import eu.etaxonomy.cdm.model.taxon.Classification;
69
import eu.etaxonomy.cdm.model.taxon.TaxonBase;
70

    
71
/**
72
 * @author p.kelbert
73
 * @author p.plitzner
74
 * @created 20.10.2008
75
 */
76
@Component
77
public class Abcd206Import extends SpecimenImportBase<Abcd206ImportConfigurator, Abcd206ImportState> {
78

    
79
    private static final UUID SPECIMEN_SCAN_TERM = UUID.fromString("acda15be-c0e2-4ea8-8783-b9b0c4ad7f03");
80

    
81
    private static final Logger logger = Logger.getLogger(Abcd206Import.class);
82

    
83

    
84

    
85

    
86

    
87
    public Abcd206Import() {
88
        super();
89
    }
90

    
91
    @Override
92
    protected boolean doCheck(Abcd206ImportState state) {
93
        logger.warn("Checking not yet implemented for " + this.getClass().getSimpleName());
94
        return true;
95
    }
96

    
97

    
98
    @Override
99
    @SuppressWarnings("rawtypes")
100
    public void doInvoke(Abcd206ImportState state) {
101
        Abcd206ImportConfigurator config = state.getConfig();
102
        Map<String, MapWrapper<? extends CdmBase>> stores = state.getStores();
103
        MapWrapper<TeamOrPersonBase<?>> authorStore = (MapWrapper<TeamOrPersonBase<?>>)stores.get(ICdmIO.TEAM_STORE);
104
        state.setPersonStore(authorStore);
105
        MapWrapper<Reference> referenceStore = (MapWrapper<Reference>)stores.get(ICdmIO.REFERENCE_STORE);
106
        MapWrapper<TaxonBase> taxonBaseStore = (MapWrapper<TaxonBase>)stores.get(ICdmIO.TAXON_STORE);
107
        try{
108
            state.setTx(startTransaction());
109
            logger.info("INVOKE Specimen Import from ABCD2.06 XML ");
110
            InputStream response = null;
111
            //init cd repository
112
            if(state.getCdmRepository()==null){
113
                state.setCdmRepository(this);
114
            }
115
            if (config.getOccurenceQuery() != null){
116
                BioCaseQueryServiceWrapper queryService = new BioCaseQueryServiceWrapper();
117
                try {
118

    
119
                   response = queryService.query(config.getOccurenceQuery(), config.getSourceUri());
120

    
121
                }catch(Exception e){
122
                    logger.error("An error during ABCD import");
123
                }
124
            }
125
            SpecimenUserInteraction sui = ((Abcd206ImportConfigurator)state.getConfig()).getSpecimenUserInteraction();
126

    
127
            //init import reference
128
        //  List<Reference> references = getReferenceService().list(Reference.class, null, null, null, null);
129
         //   List<Reference> references = new ArrayList<Reference>();
130

    
131
//            if (state.getConfig().isInteractWithUser()){
132
//                Map<String,Reference> refMap = new HashMap<String, Reference>();
133
//                for (Reference reference : references) {
134
//                    if (! StringUtils.isBlank(reference.getTitleCache())) {
135
//                        refMap.put(reference.getTitleCache(),reference);
136
//                    }
137
//                }
138
//                state.setRef(sui.askForReference(refMap));
139
//
140
//                if (state.getRef() == null){
141
//                    String cla = sui.createNewReference();
142
//                    if (refMap.get(cla)!= null) {
143
//                        state.setRef(refMap.get(cla));
144
//                    } else {
145
//                        state.setRef(ReferenceFactory.newGeneric());
146
//                        state.getRef().setTitle(cla);
147
//                    }
148
//                }
149
//                else{
150
//                    state.setRef(getReferenceService().find(state.getRef().getUuid()));
151
//                }
152
//            }else{
153
                if (state.getRef()==null){
154
                    String name = NB(((Abcd206ImportConfigurator) state.getConfig()).getSourceReferenceTitle());
155
                    for (Reference reference : referenceStore.getAllValues()) {
156
                        if (! StringUtils.isBlank(reference.getTitleCache())) {
157
                            if (reference.getTitleCache().equalsIgnoreCase(name)) {
158
                                state.setRef(reference);
159
                            }
160
                        }
161
                    }
162
                    if (state.getRef() == null){
163
                        state.setRef(ReferenceFactory.newGeneric());
164
                        state.getRef().setTitle("ABCD classic");
165
                    }
166
                }
167
            //}
168
            save(state.getRef(), state);
169
            ((Abcd206ImportConfigurator) state.getConfig()).setSourceReference(state.getRef());
170

    
171
            if(((Abcd206ImportConfigurator) state.getConfig()).getClassificationUuid()!=null){
172
                //load classification from config if it exists
173
                state.setClassification(getClassificationService().load(((Abcd206ImportConfigurator) state.getConfig()).getClassificationUuid()));
174
            }
175
            if(state.getClassification()==null){//no existing classification was set in config
176
                List<Classification> classificationList = getClassificationService().list(Classification.class, null, null, null, null);
177
                //get classification via user interaction
178
                if (((Abcd206ImportConfigurator) state.getConfig()).isUseClassification() && ((Abcd206ImportConfigurator) state.getConfig()).isInteractWithUser()){
179
                    Map<String,Classification> classMap = new HashMap<String, Classification>();
180
                    for (Classification tree : classificationList) {
181
                        if (! StringUtils.isBlank(tree.getTitleCache())) {
182
                            classMap.put(tree.getTitleCache(),tree);
183
                        }
184
                    }
185
                    state.setClassification(sui.askForClassification(classMap));
186
                    if (state.getClassification() == null){
187
                        String cla = sui.createNewClassification();
188
                        if (classMap.get(cla)!= null) {
189
                            state.setClassification(classMap.get(cla));
190
                        } else {
191
                            state.setClassification(Classification.NewInstance(cla, state.getRef(), Language.DEFAULT()));
192
                        }
193
                    }
194
                    save(state.getClassification(), state);
195
                }
196
                // use default classification as the classification to import into
197
                if (state.getClassification() == null) {
198
                    String name = NB(((Abcd206ImportConfigurator) state.getConfig()).getClassificationName());
199
                    for (Classification classif : classificationList){
200
                        if (classif.getTitleCache() != null && classif.getTitleCache().equalsIgnoreCase(name)) {
201
                            state.setClassification(classif);
202
                        }
203
                    }
204
                    if (state.getClassification() == null){
205
                        state.setClassification(Classification.NewInstance(name, state.getRef(), Language.DEFAULT()));
206
                        //we do not need a default classification when creating an empty new one
207
                        state.setDefaultClassification(state.getClassification());
208
                        save(state.getDefaultClassification(), state);
209
                    }
210
                    save(state.getClassification(), state);
211
                }
212
            }
213

    
214
            if (response == null){
215
                response =(InputStream) ((Abcd206ImportConfigurator) state.getConfig()).getSource();
216
            }
217
            UnitAssociationWrapper unitAssociationWrapper = AbcdParseUtility.parseUnitsNodeList(response, state.getReport());
218
            NodeList unitsList = unitAssociationWrapper.getAssociatedUnits();
219
            state.setPrefix(unitAssociationWrapper.getPrefix());
220

    
221
            if (unitsList != null) {
222
                String message = "nb units to insert: " + unitsList.getLength();
223
                logger.info(message);
224
                state.getConfig().getProgressMonitor().beginTask("Importing ABCD file", unitsList.getLength() + 3);
225
                updateProgress(state, message);
226

    
227
                state.setDataHolder(new Abcd206DataHolder());
228
                state.getDataHolder().reset();
229

    
230
                Abcd206XMLFieldGetter abcdFieldGetter = new Abcd206XMLFieldGetter(state.getDataHolder(), state.getPrefix());
231

    
232
                prepareCollectors(state, unitsList, abcdFieldGetter);
233

    
234

    
235
                // save authors
236
                getAgentService().saveOrUpdate((java.util.Collection)state.getPersonStore().objects());
237

    
238
                commitTransaction(state.getTx());
239
                state.setTx(startTransaction());
240

    
241
                state.setAssociationRefs(new ArrayList<OriginalSourceBase<?>>());
242
                state.setDescriptionRefs(new ArrayList<OriginalSourceBase<?>>());
243
                state.setDerivedUnitSources(new ArrayList<OriginalSourceBase<?>>());
244

    
245
                for (int i = 0; i < unitsList.getLength(); i++) {
246
                    if(state.getConfig().getProgressMonitor().isCanceled()){
247
                        break;
248
                    }
249

    
250
                    state.reset();
251

    
252
                    Element item = (Element) unitsList.item(i);
253
                    this.setUnitPropertiesXML( item, abcdFieldGetter, state);
254
                    updateProgress(state, "Importing data for unit "+state.getDataHolder().getUnitID()+" ("+i+"/"+unitsList.getLength()+")");
255

    
256
                    //import unit + field unit data
257
                    this.handleSingleUnit(state, item);
258

    
259
                }
260
                if(((Abcd206ImportConfigurator)state.getConfig()).isDeduplicateReferences()){
261
                    getReferenceService().deduplicate(Reference.class, null, null);
262
                }
263
                if(((Abcd206ImportConfigurator)state.getConfig()).isDeduplicateClassifications()){
264
                    getClassificationService().deduplicate(Classification.class, null, null);
265
                }
266
            }
267
            commitTransaction(state.getTx());
268
        }
269
        catch(Exception e){
270
            String errorDuringImport = "Exception during import!";
271
            logger.error(errorDuringImport, e);
272
            state.getReport().addException(errorDuringImport, e);
273
        }
274
        finally{
275
            state.getReport().printReport(state.getConfig().getReportUri());
276
        }
277
        return;
278
    }
279

    
280
    /**
281
     * Handle a single unit
282
     * @param state
283
     * @param item
284
     */
285
    @Override
286
    @SuppressWarnings("rawtypes")
287
    public void handleSingleUnit(Abcd206ImportState state, Object itemObject) {
288
        Element item = (Element) itemObject;
289

    
290
        Abcd206ImportConfigurator config = state.getConfig();
291
        if (DEBUG) {
292
            logger.info("handleSingleUnit "+state.getRef());
293
        }
294
        try {
295
            ICdmApplicationConfiguration cdmAppController = state.getConfig().getCdmAppController();
296
            if(cdmAppController==null){
297
                cdmAppController = this;
298
            }
299
            //check if unit already exists
300
            DerivedUnitFacade derivedUnitFacade = null;
301
            if(((Abcd206ImportConfigurator)state.getConfig()).isIgnoreImportOfExistingSpecimen()){
302
                SpecimenOrObservationBase<?> existingSpecimen = findExistingSpecimen(state.getDataHolder().getUnitID(), state);
303
                if(existingSpecimen!=null && existingSpecimen.isInstanceOf(DerivedUnit.class)){
304
                    DerivedUnit derivedUnit = HibernateProxyHelper.deproxy(existingSpecimen, DerivedUnit.class);
305
                    state.setDerivedUnitBase(derivedUnit);
306
                    derivedUnitFacade = DerivedUnitFacade.NewInstance(state.getDerivedUnitBase());
307
                    importAssociatedUnits(state, item, derivedUnitFacade);
308
                    state.getReport().addAlreadyExistingSpecimen(SpecimenImportUtility.getUnitID(derivedUnit, config), derivedUnit);
309
                    return;
310
                }
311
            }
312
            // TODO: implement overwrite/merge specimen
313
//            else if(state.getConfig().isOverwriteExistingSpecimens()){
314
//                Pager<SpecimenOrObservationBase> existingSpecimens = cdmAppController.getOccurrenceService().findByTitle(config);
315
//                if(!existingSpecimens.getRecords().isEmpty()){
316
//                    derivedUnitFacade = DerivedUnitFacade.NewInstance(derivedUnit);
317
//                    derivedUnitBase = derivedUnitFacade.innerDerivedUnit();
318
//                    fieldUnit = derivedUnitFacade.getFieldUnit(true);
319
//                }
320
//            }
321
            //import new specimen
322

    
323
            // import DNA unit
324
            if(state.getDataHolder().getKindOfUnit() !=null && state.getDataHolder().getKindOfUnit().equalsIgnoreCase("dna")){
325
                AbcdDnaParser dnaParser = new AbcdDnaParser(state.getPrefix(), state.getReport(), state.getCdmRepository());
326
                DnaSample dnaSample = dnaParser.parse(item, state);
327
                save(dnaSample, state);
328
                //set dna as derived unit to avoid creating an extra specimen for this dna sample (instead just the field unit will be created)
329
                state.setDerivedUnitBase(dnaSample);
330
                derivedUnitFacade = DerivedUnitFacade.NewInstance(state.getDerivedUnitBase());
331
            }
332
            else{
333
                // create facade
334
                derivedUnitFacade = getFacade(state);
335
                state.setDerivedUnitBase(derivedUnitFacade.innerDerivedUnit());
336
            }
337

    
338
            /**
339
             * GATHERING EVENT
340
             */
341
            // gathering event
342
            UnitsGatheringEvent unitsGatheringEvent = new UnitsGatheringEvent(cdmAppController.getTermService(),
343
                    state.getDataHolder().locality, state.getDataHolder().languageIso, state.getDataHolder().longitude,
344
                    state.getDataHolder().latitude, state.getDataHolder().getGatheringElevationText(),
345
                    state.getDataHolder().getGatheringElevationMin(), state.getDataHolder().getGatheringElevationMax(),
346
                    state.getDataHolder().getGatheringElevationUnit(), state.getDataHolder().getGatheringDateText(),
347
                    state.getDataHolder().getGatheringNotes(), state.getTransformer().getReferenceSystemByKey(
348
                            state.getDataHolder().getGatheringSpatialDatum()),
349
                     state.getConfig());
350

    
351
            unitsGatheringEvent.setGatheringDepth(state.getDataHolder().getGatheringDepthText(),state.getDataHolder().getGatheringDepthMin(), state.getDataHolder().getGatheringDepthMax(), state.getDataHolder().getGatheringDepthUnit());
352
            //unitsGatheringEvent.setHeight(heightText, heightMin, heightMax, heightUnit);
353
            unitsGatheringEvent.setCollector(state.getPersonStore().get(state.getDataHolder().gatheringAgents), config);
354
            // count
355
            UnitsGatheringArea unitsGatheringArea = new UnitsGatheringArea();
356
            //  unitsGatheringArea.setConfig(state.getConfig(),getOccurrenceService(), getTermService());
357
            unitsGatheringArea.setParams(state.getDataHolder().isocountry, state.getDataHolder().country, (state.getConfig()), cdmAppController.getTermService(), cdmAppController.getOccurrenceService());
358

    
359
            DefinedTermBase<?> areaCountry =  unitsGatheringArea.getCountry();
360

    
361
            // other areas
362
            unitsGatheringArea = new UnitsGatheringArea();
363
            //            unitsGatheringArea.setConfig(state.getConfig(),getOccurrenceService(),getTermService());
364

    
365
            unitsGatheringArea.setAreas(state.getDataHolder().getNamedAreaList(),(state.getConfig()), cdmAppController.getTermService(), cdmAppController.getVocabularyService());
366

    
367
            ArrayList<DefinedTermBase> nas = unitsGatheringArea.getAreas();
368
            for (DefinedTermBase namedArea : nas) {
369
                unitsGatheringEvent.addArea(namedArea);
370
            }
371

    
372
            // copy gathering event to facade
373
            GatheringEvent gatheringEvent = unitsGatheringEvent.getGatheringEvent();
374
            derivedUnitFacade.setLocality(gatheringEvent.getLocality());
375
            derivedUnitFacade.setExactLocation(gatheringEvent.getExactLocation());
376
            derivedUnitFacade.setCollector(gatheringEvent.getCollector());
377
            derivedUnitFacade.setCountry((NamedArea)areaCountry);
378
            derivedUnitFacade.setAbsoluteElevationText(gatheringEvent.getAbsoluteElevationText());
379
            derivedUnitFacade.setAbsoluteElevation(gatheringEvent.getAbsoluteElevation());
380
            derivedUnitFacade.setAbsoluteElevationMax(gatheringEvent.getAbsoluteElevationMax());
381
            derivedUnitFacade.setDistanceToGroundText(gatheringEvent.getDistanceToGroundText());
382
            derivedUnitFacade.setDistanceToGroundMax(gatheringEvent.getDistanceToGroundMax());
383
            derivedUnitFacade.setDistanceToGround(gatheringEvent.getDistanceToGround());
384
            derivedUnitFacade.setDistanceToWaterSurfaceText(gatheringEvent.getDistanceToWaterSurfaceText());
385
            derivedUnitFacade.setDistanceToWaterSurfaceMax(gatheringEvent.getDistanceToWaterSurfaceMax());
386
            derivedUnitFacade.setDistanceToWaterSurface(gatheringEvent.getDistanceToWaterSurface());
387
            derivedUnitFacade.setGatheringPeriod(gatheringEvent.getTimeperiod());
388

    
389
            for(DefinedTermBase<?> area:unitsGatheringArea.getAreas()){
390
                derivedUnitFacade.addCollectingArea((NamedArea) area);
391
            }
392
            //            derivedUnitFacade.addCollectingAreas(unitsGatheringArea.getAreas());
393
            // TODO exsiccatum
394

    
395
            // add fieldNumber
396
            derivedUnitFacade.setFieldNumber(NB(state.getDataHolder().getFieldNumber()));
397

    
398
            // add unitNotes
399
            derivedUnitFacade.addAnnotation(Annotation.NewDefaultLanguageInstance(NB(state.getDataHolder().getUnitNotes())));
400

    
401

    
402

    
403
            // //add Multimedia URLs
404
            if (state.getDataHolder().getMultimediaObjects().size() != -1) {
405
                for (String multimediaObject : state.getDataHolder().getMultimediaObjects().keySet()) {
406
                    Media media;
407
                    try {
408
                        media = getImageMedia(multimediaObject, READ_MEDIA_DATA);
409
                        Map<String, String> attributes = state.getDataHolder().getMultimediaObjects().get(multimediaObject);
410
                        if (attributes.containsKey("Context")){
411
                            LanguageString description = LanguageString.NewInstance(attributes.get("Context"), Language.ENGLISH());
412
                            media.addDescription(description);
413
                        }
414
                        if (attributes.containsKey("Comment")){
415
                            LanguageString description = LanguageString.NewInstance(attributes.get("Comment"), Language.ENGLISH());
416
                            media.addDescription(description);
417
                        }
418
                        if (attributes.containsKey("Creators")){
419
                            String creators = attributes.get("Creators");
420
                            Person artist;
421
                            Team artistTeam;
422
                            String[] artists;
423
                            if (creators != null){
424
                                if (creators.contains("&")){
425
                                    artists = creators.split("&");
426
                                    artistTeam = new Team();
427
                                    for (String creator:artists){
428
                                        artist = Person.NewTitledInstance(creator);
429
                                        artistTeam.addTeamMember(artist);
430
                                    }
431
                                    media.setArtist(artistTeam);
432
                                } else{
433

    
434
                                    artist = Person.NewTitledInstance(creators);
435
                                    media.setArtist(artist);
436
                                }
437
                            }
438

    
439

    
440

    
441
                        }
442

    
443
                        derivedUnitFacade.addDerivedUnitMedia(media);
444
                        if(((Abcd206ImportConfigurator)state.getConfig()).isAddMediaAsMediaSpecimen()){
445
                            //add media also as specimen scan
446
                            MediaSpecimen mediaSpecimen = MediaSpecimen.NewInstance(SpecimenOrObservationType.StillImage);
447
                            mediaSpecimen.setMediaSpecimen(media);
448
                            //do it only once!!
449
                            DefinedTermBase specimenScanTerm = getTermService().load(SPECIMEN_SCAN_TERM);
450
                            if(specimenScanTerm instanceof DefinedTerm){
451
                                mediaSpecimen.setKindOfUnit((DefinedTerm) specimenScanTerm);
452
                            }
453
                            DerivationEvent derivationEvent = DerivationEvent.NewInstance(DerivationEventType.PREPARATION());
454
                            derivationEvent.addDerivative(mediaSpecimen);
455
                            derivedUnitFacade.innerDerivedUnit().addDerivationEvent(derivationEvent);
456
                        }
457

    
458
                    } catch (MalformedURLException e) {
459
                        // TODO Auto-generated catch block
460
                        e.printStackTrace();
461
                    }
462

    
463
                }
464
            }
465
            //multimedia for fieldUnit
466
            if (state.getDataHolder().getGatheringMultimediaObjects().size() != -1) {
467
                for (String multimediaObject : state.getDataHolder().getGatheringMultimediaObjects().keySet()) {
468
                    Media media;
469
                    try {
470
                        media = getImageMedia(multimediaObject, READ_MEDIA_DATA);
471
                        Map<String, String> attributes = state.getDataHolder().getGatheringMultimediaObjects().get(multimediaObject);
472
                        if (attributes.containsKey("Context")){
473
                            LanguageString description = LanguageString.NewInstance(attributes.get("Context"), Language.ENGLISH());
474
                            media.addDescription(description);
475
                        }
476
                        if (attributes.containsKey("Comment")){
477
                            LanguageString description = LanguageString.NewInstance(attributes.get("Comment"), Language.ENGLISH());
478
                            media.addDescription(description);
479
                        }
480
                        if (attributes.containsKey("Creators")){
481
                            String creators = attributes.get("Creators");
482
                            Person artist;
483
                            Team artistTeam;
484
                            String[] artists;
485
                            if (creators != null){
486
                                if (creators.contains("&")){
487
                                    artists = creators.split("&");
488
                                    artistTeam = new Team();
489
                                    for (String creator:artists){
490
                                        artist = Person.NewTitledInstance(creator);
491
                                        artistTeam.addTeamMember(artist);
492
                                    }
493
                                    media.setArtist(artistTeam);
494
                                } else{
495

    
496
                                    artist = Person.NewTitledInstance(creators);
497
                                    media.setArtist(artist);
498
                                }
499
                            }
500

    
501

    
502

    
503
                        }
504

    
505
                        derivedUnitFacade.addFieldObjectMedia(media);
506

    
507

    
508
                    } catch (MalformedURLException e) {
509
                        // TODO Auto-generated catch block
510
                        e.printStackTrace();
511
                    }
512

    
513
                }
514
            }
515

    
516
            //			/*
517
            //			 * merge AND STORE DATA
518
            //			 */
519
            //			getTermService().saveOrUpdate(areaCountry);// TODO save area sooner
520
            //
521
            //			for (NamedArea area : otherAreas) {
522
            //				getTermService().saveOrUpdate(area);// merge it sooner (foreach area)
523
            //			}
524
           save(derivedUnitFacade.getFieldUnit(false), state);
525
            save(unitsGatheringEvent.getLocality(), state);
526

    
527
            // handle collection data
528
            setCollectionData(state, derivedUnitFacade);
529

    
530
            //Reference stuff
531
            SpecimenUserInteraction sui = config.getSpecimenUserInteraction();
532
            Map<String,OriginalSourceBase<?>> sourceMap = new HashMap<String, OriginalSourceBase<?>>();
533

    
534
            state.getDataHolder().setDocSources(new ArrayList<String>());
535
            for (String[] fullReference : state.getDataHolder().getReferenceList()) {
536
                String strReference=fullReference[0];
537
                String citationDetail = fullReference[1];
538
                String citationURL = fullReference[2];
539

    
540
                if (!citationURL.isEmpty()) {
541
                    citationDetail+=", "+citationURL;
542
                }
543

    
544
                Reference reference;
545
                if(strReference.equals(state.getRef().getTitleCache())){
546
                    reference = state.getRef();
547
                }
548
                else{
549
                    reference = ReferenceFactory.newGeneric();
550
                    reference.setTitle(strReference);
551
                }
552

    
553
                IdentifiableSource sour = getIdentifiableSource(reference,citationDetail);
554

    
555
                try{
556
                    if (sour.getCitation() != null){
557
                        if(StringUtils.isNotBlank(sour.getCitationMicroReference())) {
558
                            state.getDataHolder().getDocSources().add(sour.getCitation().getTitleCache()+ "---"+sour.getCitationMicroReference());
559
                        } else {
560
                            state.getDataHolder().getDocSources().add(sour.getCitation().getTitleCache());
561
                        }
562
                    }
563
                }catch(Exception e){
564
                    logger.warn("oups");
565
                }
566
                reference.addSource(sour);
567
                save(reference, state);
568
            }
569
            List<IdentifiableSource> issTmp = new ArrayList<IdentifiableSource>();//getCommonService().list(IdentifiableSource.class, null, null, null, null);
570
            List<DescriptionElementSource> issTmp2 = new ArrayList<DescriptionElementSource>();//getCommonService().list(DescriptionElementSource.class, null, null, null, null);
571

    
572
            Set<OriginalSourceBase> osbSet = new HashSet<OriginalSourceBase>();
573
            if(issTmp2!=null) {
574
                osbSet.addAll(issTmp2);
575
            }
576
            if(issTmp!=null) {
577
                osbSet.addAll(issTmp);
578
            }
579

    
580
            addToSourceMap(sourceMap, osbSet);
581

    
582
            if( ((Abcd206ImportConfigurator) state.getConfig()).isInteractWithUser()){
583
                List<OriginalSourceBase<?>>sources=null;
584
                if(!state.isDerivedUnitSourcesSet()){
585
                    sources= sui.askForSource(sourceMap, "the unit itself","",getReferenceService(), state.getDataHolder().getDocSources());
586
                    state.setDerivedUnitSources(sources);
587
                    state.setDerivedUnitSourcesSet(true);
588
                }
589
                else{
590
                    sources=state.getDerivedUnitSources();
591
                }
592
//                System.out.println("nb sources: "+sources.size());
593
//                System.out.println("derivedunitfacade : "+derivedUnitFacade.getTitleCache());
594
                for (OriginalSourceBase<?> sour:sources){
595
                    if(sour.isInstanceOf(IdentifiableSource.class)){
596
                        if(sourceNotLinkedToElement(derivedUnitFacade,sour)) {
597
//                            System.out.println("add source to derivedunitfacade1 "+derivedUnitFacade.getTitleCache());
598
                            derivedUnitFacade.addSource((IdentifiableSource)sour.clone());
599
                        }
600
                    }else{
601
                        if(sourceNotLinkedToElement(derivedUnitFacade,sour)) {
602
//                            System.out.println("add source to derivedunitfacade2 "+derivedUnitFacade.getTitleCache());
603
                            derivedUnitFacade.addSource(OriginalSourceType.Import,sour.getCitation(),sour.getCitationMicroReference(), ioName);
604
                        }
605
                    }
606
                }
607
            }else{
608
                for (OriginalSourceBase<?> sr : sourceMap.values()){
609
                    if(sr.isInstanceOf(IdentifiableSource.class)){
610
                        if(sourceNotLinkedToElement(derivedUnitFacade,sr)) {
611
//                            System.out.println("add source to derivedunitfacade3 "+derivedUnitFacade.getTitleCache());
612
                            derivedUnitFacade.addSource((IdentifiableSource)sr.clone());
613
                        }
614
                    }else{
615
                        if(sourceNotLinkedToElement(derivedUnitFacade,sr)) {
616
//                            System.out.println("add source to derivedunitfacade4 "+derivedUnitFacade.getTitleCache());
617
                            derivedUnitFacade.addSource(OriginalSourceType.Import,sr.getCitation(),sr.getCitationMicroReference(), ioName);
618
                        }
619
                    }
620
                }
621
            }
622

    
623
            save(state.getDerivedUnitBase(), state);
624

    
625
            if(DEBUG) {
626
                logger.info("saved ABCD specimen ...");
627
            }
628

    
629
            // handle identifications
630
            handleIdentifications(state, derivedUnitFacade);
631

    
632
            //associatedUnits
633
            importAssociatedUnits(state, item, derivedUnitFacade);
634

    
635

    
636

    
637
        } catch (Exception e) {
638
            String message = "Error when reading record!";
639
            logger.warn(message);
640
            state.getReport().addException(message, e);
641
            e.printStackTrace();
642
            state.setUnsuccessfull();
643
        }
644

    
645
        return;
646
    }
647

    
648
    @Override
649
    protected void importAssociatedUnits(Abcd206ImportState state, Object itemObject, DerivedUnitFacade derivedUnitFacade) {
650

    
651
        Abcd206ImportConfigurator config = state.getConfig();
652
        //import associated units
653
        FieldUnit currentFieldUnit = derivedUnitFacade.innerFieldUnit();
654
        //TODO: push state (think of implementing stack architecture for state
655
        DerivedUnit currentUnit = state.getDerivedUnitBase();
656
        DerivationEvent currentDerivedFrom = currentUnit.getDerivedFrom();
657
        String currentPrefix = state.getPrefix();
658
        Element item = null;
659
        if (itemObject instanceof Element){
660
            item = (Element)itemObject;
661
        }
662
        NodeList unitAssociationList = null;
663
        if (item != null){
664
            unitAssociationList = item.getElementsByTagName(currentPrefix+"UnitAssociation");
665
            for(int k=0;k<unitAssociationList.getLength();k++){
666
                if(unitAssociationList.item(k) instanceof Element){
667
                    Element unitAssociation = (Element)unitAssociationList.item(k);
668
                    UnitAssociationParser unitAssociationParser = new UnitAssociationParser(currentPrefix, state.getReport(), state.getCdmRepository());
669
                    UnitAssociationWrapper associationWrapper = unitAssociationParser.parse(unitAssociation);
670
                    if(associationWrapper!=null){
671
                        NodeList associatedUnits = associationWrapper.getAssociatedUnits();
672
                        if(associatedUnits!=null){
673
                            for(int m=0;m<associatedUnits.getLength();m++){
674
                                if(associatedUnits.item(m) instanceof Element){
675
                                    state.reset();
676
                                    state.setPrefix(associationWrapper.getPrefix());
677
                                    this.setUnitPropertiesXML((Element) associatedUnits.item(m), new Abcd206XMLFieldGetter(state.getDataHolder(), state.getPrefix()), state);
678
                                    handleSingleUnit(state, associatedUnits.item(m));
679

    
680
                                    DerivedUnit associatedUnit = state.getDerivedUnitBase();
681
                                    FieldUnit associatedFieldUnit = null;
682
                                    java.util.Collection<FieldUnit> associatedFieldUnits = state.getCdmRepository().getOccurrenceService().getFieldUnits(associatedUnit.getUuid());
683
                                    //ignore field unit if associated unit has more than one
684
                                    if(associatedFieldUnits.size()>1){
685
                                        state.getReport().addInfoMessage(String.format("%s has more than one field unit.", associatedUnit));
686
                                    }
687
                                    else if(associatedFieldUnits.size()==1){
688
                                        associatedFieldUnit = associatedFieldUnits.iterator().next();
689
                                    }
690

    
691
                                    //attach current unit and associated unit depending on association type
692

    
693
                                    //parent-child relation:
694
                                    //copy derivation event and connect parent and sub derivative
695
                                    if(associationWrapper.getAssociationType().contains("individual")){
696
                                        if(currentDerivedFrom==null){
697
                                            state.getReport().addInfoMessage(String.format("No derivation event found for unit %s. Defaulting to ACCESSIONING event.",SpecimenImportUtility.getUnitID(currentUnit, config)));
698
                                            DerivationEvent.NewSimpleInstance(associatedUnit, currentUnit, DerivationEventType.ACCESSIONING());
699
                                        }
700
                                        else{
701
                                            DerivationEvent updatedDerivationEvent = DerivationEvent.NewSimpleInstance(associatedUnit, currentUnit, currentDerivedFrom.getType());
702
                                            updatedDerivationEvent.setActor(currentDerivedFrom.getActor());
703
                                            updatedDerivationEvent.setDescription(currentDerivedFrom.getDescription());
704
                                            updatedDerivationEvent.setInstitution(currentDerivedFrom.getInstitution());
705
                                            updatedDerivationEvent.setTimeperiod(currentDerivedFrom.getTimeperiod());
706
                                        }
707
                                        state.getReport().addDerivate(associatedUnit, currentUnit, config);
708
                                    }
709
                                    //siblings relation
710
                                    //connect current unit to field unit of associated unit
711
                                    else if(associationWrapper.getAssociationType().contains("population")){
712
                                        //no associated field unit -> using current one
713
                                        if(associatedFieldUnit==null){
714
                                            if(currentFieldUnit!=null){
715
                                                DerivationEvent.NewSimpleInstance(currentFieldUnit, associatedUnit, DerivationEventType.ACCESSIONING());
716
                                            }
717
                                        }
718
                                        else{
719
                                            if(currentDerivedFrom==null){
720
                                                state.getReport().addInfoMessage("No derivation event found for unit "+SpecimenImportUtility.getUnitID(currentUnit, config)+". Defaulting to ACCESIONING event.");
721
                                                DerivationEvent.NewSimpleInstance(associatedFieldUnit, currentUnit, DerivationEventType.ACCESSIONING());
722
                                            }
723
                                            if(currentDerivedFrom!=null && associatedFieldUnit!=currentFieldUnit){
724
                                                DerivationEvent updatedDerivationEvent = DerivationEvent.NewSimpleInstance(associatedFieldUnit, currentUnit, currentDerivedFrom.getType());
725
                                                updatedDerivationEvent.setActor(currentDerivedFrom.getActor());
726
                                                updatedDerivationEvent.setDescription(currentDerivedFrom.getDescription());
727
                                                updatedDerivationEvent.setInstitution(currentDerivedFrom.getInstitution());
728
                                                updatedDerivationEvent.setTimeperiod(currentDerivedFrom.getTimeperiod());
729
                                            }
730
                                        }
731
                                    }
732

    
733
                                    //delete current field unit if replaced
734
                                    if(currentFieldUnit!=null && currentDerivedFrom!=null
735
                                            && currentFieldUnit.getDerivationEvents().size()==1  && currentFieldUnit.getDerivationEvents().contains(currentDerivedFrom) //making sure that the field unit
736
                                            && currentDerivedFrom.getDerivatives().size()==1 && currentDerivedFrom.getDerivatives().contains(currentUnit) //is not attached to other derived units
737
                                            && currentDerivedFrom!=currentUnit.getDerivedFrom() // <- derivation has been replaced and can be deleted
738
                                            ){
739
                                        currentFieldUnit.removeDerivationEvent(currentDerivedFrom);
740
                                        state.getCdmRepository().getOccurrenceService().delete(currentFieldUnit);
741
                                    }
742

    
743
                                    save(associatedUnit, state);
744
                                }
745
                            }
746
                        }
747
                    }
748
                }
749
            }
750
        }
751
        //TODO: pop state
752
        state.reset();
753
        state.setDerivedUnitBase(currentUnit);
754
        state.setPrefix(currentPrefix);
755
    }
756

    
757

    
758

    
759

    
760
    /**
761
     * @param derivedUnitFacade
762
     * @param sour
763
     * @return
764
     */
765
    private boolean sourceNotLinkedToElement(DerivedUnitFacade derivedUnitFacade, OriginalSourceBase<?> source) {
766
        Set<IdentifiableSource> linkedSources = derivedUnitFacade.getSources();
767
        for (IdentifiableSource is:linkedSources){
768
            if (is.getCitation()!=null && source.getCitation()!=null &&
769
                    is.getCitation().getTitleCache().equalsIgnoreCase(source.getCitation().getTitleCache())){
770
                String isDetail =  is.getCitationMicroReference();
771
                if ((StringUtils.isBlank(isDetail) && StringUtils.isBlank(source.getCitationMicroReference()))
772
                        || (isDetail != null && isDetail.equalsIgnoreCase(source.getCitationMicroReference())) ) {
773
                    return false;
774
                }
775
            }
776
        }
777
        return true;
778
    }
779

    
780

    
781

    
782
    //    /**
783
    //     * @param reference
784
    //     * @param citationDetail
785
    //     * @return
786
    //     */
787
    //    private DescriptionElementSource getDescriptionSource(Reference reference, String citationDetail) {
788
    //
789
    //        List<OriginalSourceBase> issTmp2 = getCommonService().list(DescriptionElementSource.class, null, null, null, null);
790
    //
791
    //        try {
792
    //            for (OriginalSourceBase<?> osb:issTmp2){
793
    //                if (osb.getCitation().equals(reference) && osb.getCitationMicroReference().equalsIgnoreCase(citationDetail)) {
794
    //                    return (DescriptionElementSource) osb.clone();
795
    //                }
796
    //            }
797
    //        } catch (CloneNotSupportedException e) {
798
    //            // TODO Auto-generated catch block
799
    //            e.printStackTrace();
800
    //        }
801
    //
802
    //        DescriptionElementSource sour = DescriptionElementSource.NewInstance(OriginalSourceType.Import,null,null, reference,citationDetail);
803
    //        return sour;
804
    //    }
805

    
806

    
807

    
808

    
809
    /**
810
     * setCollectionData : store the collection object into the
811
     * derivedUnitFacade
812
     *
813
     * @param state
814
     */
815
    protected void setCollectionData(Abcd206ImportState state, DerivedUnitFacade derivedUnitFacade) {
816
        Abcd206ImportConfigurator config = state.getConfig();
817
        SpecimenImportUtility.setUnitID(derivedUnitFacade.innerDerivedUnit(), state.getDataHolder().getUnitID(), config);
818
        if(!config.isMapUnitIdToAccessionNumber()){
819
            derivedUnitFacade.setAccessionNumber(NB(state.getDataHolder().accessionNumber));
820
        }
821
        // derivedUnitFacade.setCollectorsNumber(NB(state.getDataHolder().collectorsNumber));
822

    
823
        /*
824
         * INSTITUTION & COLLECTION
825
         */
826
        // manage institution
827
        Institution institution = this.getInstitution(NB(state.getDataHolder().institutionCode), state);
828
        // manage collection
829
        Collection collection = this.getCollection(institution, NB(state.getDataHolder().collectionCode), state);
830
        // link specimen & collection
831
        derivedUnitFacade.setCollection(collection);
832
    }
833

    
834
    /**
835
     * getFacade : get the DerivedUnitFacade based on the recordBasis
836
     * @param state
837
     *
838
     * @return DerivedUnitFacade
839
     */
840
    @Override
841
    protected DerivedUnitFacade getFacade(Abcd206ImportState state) {
842
        if(DEBUG) {
843
            logger.info("getFacade()");
844
        }
845
        SpecimenOrObservationType type = null;
846

    
847
        // create specimen
848
        if (NB((state.getDataHolder()).getRecordBasis()) != null) {
849
            if (state.getDataHolder().getRecordBasis().toLowerCase().startsWith("s") || state.getDataHolder().getRecordBasis().toLowerCase().indexOf("specimen")>-1) {// specimen
850
                type = SpecimenOrObservationType.PreservedSpecimen;
851
            }
852
            else if (state.getDataHolder().getRecordBasis().toLowerCase().startsWith("o") ||state.getDataHolder().getRecordBasis().toLowerCase().indexOf("observation")>-1 ) {
853
                type = SpecimenOrObservationType.Observation;
854
            }
855
            else if (state.getDataHolder().getRecordBasis().toLowerCase().indexOf("fossil")>-1){
856
                type = SpecimenOrObservationType.Fossil;
857
            }
858
            else if (state.getDataHolder().getRecordBasis().toLowerCase().indexOf("living")>-1) {
859
                type = SpecimenOrObservationType.LivingSpecimen;
860
            }
861
            if (type == null) {
862
                logger.info("The basis of record does not seem to be known: " + state.getDataHolder().getRecordBasis());
863
                type = SpecimenOrObservationType.DerivedUnit;
864
            }
865
        } else {
866
            logger.info("The basis of record is null");
867
            type = SpecimenOrObservationType.DerivedUnit;
868
        }
869
        DerivedUnitFacade derivedUnitFacade = DerivedUnitFacade.NewInstance(type);
870
        return derivedUnitFacade;
871
    }
872

    
873
    private void getCollectorsFromXML(Element root, Abcd206XMLFieldGetter abcdFieldGetter, Abcd206ImportState state) {
874
        NodeList group;
875

    
876
        group = root.getChildNodes();
877
        for (int i = 0; i < group.getLength(); i++) {
878
            if (group.item(i).getNodeName().equals(state.getPrefix() + "Identifications")) {
879
                group = group.item(i).getChildNodes();
880
                break;
881
            }
882
        }
883
        //state.getDataHolder().gatheringAgents = "";
884

    
885
        abcdFieldGetter.getType(root);
886
        abcdFieldGetter.getGatheringPeople(root);
887
    }
888

    
889
    /**
890
     * Store the unit's properties into variables Look which unit is the
891
     * preferred one Look what kind of name it is supposed to be, for the
892
     * parsing (Botanical, Zoological)
893
     * @param state
894
     *
895
     * @param racine: the root node for a single unit
896
     */
897
    private void setUnitPropertiesXML(Element root, Abcd206XMLFieldGetter abcdFieldGetter, Abcd206ImportState state) {
898
        try {
899
            NodeList group;
900

    
901
            group = root.getChildNodes();
902
            for (int i = 0; i < group.getLength(); i++) {
903
                if (group.item(i).getNodeName().equals(state.getPrefix() + "Identifications")) {
904
                    group = group.item(i).getChildNodes();
905
                    break;
906
                }
907
            }
908
            state.getDataHolder().setIdentificationList(new ArrayList<Identification>());
909
            state.getDataHolder().setStatusList(new ArrayList<SpecimenTypeDesignationStatus>());
910
            state.getDataHolder().setAtomisedIdentificationList(new ArrayList<HashMap<String, String>>());
911
            state.getDataHolder().setReferenceList(new ArrayList<String[]>());
912
            state.getDataHolder().setMultimediaObjects(new HashMap<String,Map<String, String>>());
913
            state.getDataHolder().setGatheringMultimediaObjects(new HashMap<String,Map<String, String>>());
914

    
915
            abcdFieldGetter.getScientificNames(group);
916
            abcdFieldGetter.getType(root);
917

    
918
            if(DEBUG) {
919
                logger.info("this.identificationList "+state.getDataHolder().getIdentificationList().toString());
920
            }
921
            abcdFieldGetter.getIDs(root);
922
            abcdFieldGetter.getRecordBasis(root);
923
            abcdFieldGetter.getKindOfUnit(root);
924
            abcdFieldGetter.getMultimedia(root);
925
            abcdFieldGetter.getNumbers(root);
926
            abcdFieldGetter.getGeolocation(root, state);
927
            abcdFieldGetter.getGatheringPeople(root);
928
            abcdFieldGetter.getGatheringDate(root);
929
            abcdFieldGetter.getGatheringElevation(root);
930
            abcdFieldGetter.getGatheringNotes(root);
931
            abcdFieldGetter.getGatheringImages(root);
932
            abcdFieldGetter.getAssociatedUnitIds(root);
933
            abcdFieldGetter.getUnitNotes(root);
934
            boolean referencefound = abcdFieldGetter.getReferences(root);
935
            if (!referencefound) {
936
                String[]a = {state.getRef().getTitleCache(),"",""};
937
                state.getDataHolder().getReferenceList().add(a);
938
            }
939

    
940
        } catch (Exception e) {
941
            logger.info("Error occured while parsing XML file" + e);
942
            e.printStackTrace();
943
        }
944
    }
945

    
946
    //    private void compareABCDtoCDM(URI urlFileName, List<String> knownElts, Abcd206XMLFieldGetter abcdFieldGetter) {
947
    //        try {
948
    //            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
949
    //            DocumentBuilder constructeur = factory.newDocumentBuilder();
950
    //            URL url = urlFileName.toURL();
951
    //            Object o = url.getContent();
952
    //            InputStream is = (InputStream) o;
953
    //            Document document = constructeur.parse(is);
954
    //            Element root = document.getDocumentElement();
955
    //            abcdFieldGetter.traverse(root);
956
    //        }
957
    //        catch (ParserConfigurationException e){
958
    //            e.printStackTrace();
959
    //        }
960
    //        catch (SAXException e) {
961
    //            e.printStackTrace();
962
    //        }
963
    //        catch (IOException e) {
964
    //            e.printStackTrace();
965
    //        }
966
    //        Set<String> elts = state.getDataHolder().allABCDelements.keySet();
967
    //        Iterator<String> it = elts.iterator();
968
    //        String elt;
969
    //        while (it.hasNext()) {
970
    //            elt = it.next();
971
    //            if (knownElts.indexOf(elt) == -1) {
972
    //                if(DEBUG) {
973
    //                    logger.info("Unmerged ABCD element: " + elt + " - "+ state.getDataHolder().allABCDelements.get(elt));
974
    //                }
975
    //            }
976
    //        }
977
    //    }
978

    
979
    /**
980
     * Load the list of names from the ABCD file and save them
981
     * @param state : the current ABCD import state
982
     * @param unitsList : the unit list from the ABCD file
983
     * @param abcdFieldGetter : the ABCD parser
984
     */
985
    private void prepareCollectors(Abcd206ImportState state, NodeList unitsList, Abcd206XMLFieldGetter abcdFieldGetter) {
986

    
987
        TeamOrPersonBase teamOrPerson = null;
988

    
989
        //ImportHelper.setOriginalSource(teamOrPerson, state.getConfig().getSourceReference(), collector, "Collector");
990
        for (int i = 0; i < unitsList.getLength(); i++) {
991
            this.getCollectorsFromXML((Element) unitsList.item(i), abcdFieldGetter, state);
992
            if (!StringUtils.isBlank(state.getDataHolder().gatheringAgents)){
993
                teamOrPerson = parseAuthorString(state.getDataHolder().gatheringAgents);
994
                if (!state.getPersonStore().containsId(state.getDataHolder().gatheringAgents)) {
995
                    state.getPersonStore().put(state.getDataHolder().gatheringAgents, teamOrPerson);
996
                    if (logger.isDebugEnabled()) { logger.debug("Stored author " + state.getDataHolder().gatheringAgents  ); }
997
                } else {
998
                    logger.warn("Not imported author with duplicated aut_id " + state.getDataHolder().gatheringAgents  );
999
                }
1000
            }
1001

    
1002
        }
1003

    
1004

    
1005

    
1006

    
1007
//        List<String> collectorsU = new ArrayList<String>(new HashSet<String>(collectors));
1008
//        List<String> teamsU = new ArrayList<String>(new HashSet<String>(teams));
1009
//
1010
//
1011
//        //existing teams in DB
1012
//        Map<String,Team> titleCacheTeam = new HashMap<String, Team>();
1013
       // List<UuidAndTitleCache<Team>> hiberTeam = new ArrayList<UuidAndTitleCache<Team>>();//getAgentService().getTeamUuidAndTitleCache();
1014

    
1015
//        Set<UUID> uuids = new HashSet<UUID>();
1016
//        for (UuidAndTitleCache<Team> hibernateT:hiberTeam){
1017
//            uuids.add(hibernateT.getUuid());
1018
//        }
1019
//        if (!uuids.isEmpty()){
1020
//            List<AgentBase> existingTeams = getAgentService().find(uuids);
1021
//            for (AgentBase<?> existingP:existingTeams){
1022
//                titleCacheTeam.put(existingP.getTitleCache(),CdmBase.deproxy(existingP,Team.class));
1023
//            }
1024
//        }
1025

    
1026

    
1027
//        Map<String,UUID> teamMap = new HashMap<String, UUID>();
1028
//        for (UuidAndTitleCache<Team> uuidt:hiberTeam){
1029
//            teamMap.put(uuidt.getTitleCache(), uuidt.getUuid());
1030
//        }
1031

    
1032
        //existing persons in DB
1033
//        List<UuidAndTitleCache<Person>> hiberPersons = new ArrayList<UuidAndTitleCache<Person>>();//getAgentService().getPersonUuidAndTitleCache();
1034
//        Map<String,Person> titleCachePerson = new HashMap<String, Person>();
1035
//        uuids = new HashSet<UUID>();
1036
//        for (UuidAndTitleCache<Person> hibernateP:hiberPersons){
1037
//            uuids.add(hibernateP.getUuid());
1038
//        }
1039
//
1040
//        if (!uuids.isEmpty()){
1041
//            List<AgentBase> existingPersons = getAgentService().find(uuids);
1042
//            for (AgentBase<?> existingP:existingPersons){
1043
//                titleCachePerson.put(existingP.getTitleCache(),CdmBase.deproxy(existingP,Person.class));
1044
//            }
1045
//        }
1046
//
1047
//        Map<String,UUID> personMap = new HashMap<String, UUID>();
1048
//        for (UuidAndTitleCache<Person> person:hiberPersons){
1049
//            personMap.put(person.getTitleCache(), person.getUuid());
1050
//        }
1051
//
1052
//        java.util.Collection<Person> personToadd = new ArrayList<Person>();
1053
//        java.util.Collection<Team> teamToAdd = new ArrayList<Team>();
1054
//
1055
//        for (String collector:collectorsU){
1056
//            Person p = Person.NewInstance();
1057
//            p.setTitleCache(collector,true);
1058
//            if (!personMap.containsKey(p.getTitleCache())){
1059
//                personToadd.add(p);
1060
//            }
1061
//        }
1062
//        for (String team:teamsU){
1063
//            Team p = Team.NewInstance();
1064
//            p.setTitleCache(team,true);
1065
//            if (!teamMap.containsKey(p.getTitleCache())){
1066
//                teamToAdd.add(p);
1067
//            }
1068
//        }
1069
//
1070
//        if(!personToadd.isEmpty()){
1071
//            for (Person agent: personToadd){
1072
//                save(agent, state);
1073
//                titleCachePerson.put(agent.getTitleCache(),CdmBase.deproxy(agent, Person.class) );
1074
//            }
1075
//        }
1076
//
1077
//        Person ptmp ;
1078
//        Map <String,Integer>teamdone = new HashMap<String, Integer>();
1079
//        for (List<String> collteam: collectorinteams){
1080
//            if (!teamdone.containsKey(StringUtils.join(collteam.toArray(),"-"))){
1081
//                Team team = new Team();
1082
//                boolean em =true;
1083
//                for (String collector:collteam){
1084
//                    ptmp = Person.NewInstance();
1085
//                    ptmp.setTitleCache(collector,true);
1086
//                    Person p2 = titleCachePerson.get(ptmp.getTitleCache());
1087
//                    team.addTeamMember(p2);
1088
//                    em=false;
1089
//                }
1090
//                if (!em) {
1091
//                    teamToAdd.add(team);
1092
//                }
1093
//                teamdone.put(StringUtils.join(collteam.toArray(),"-"),0);
1094
//            }
1095
//        }
1096
//
1097
//        if(!teamToAdd.isEmpty()){
1098
//            for (Team agent: teamToAdd){
1099
//                save(agent, state);
1100
//                titleCacheTeam.put(agent.getTitleCache(), CdmBase.deproxy( agent,Team.class) );
1101
//            }
1102
//        }
1103

    
1104
//        ((Abcd206ImportConfigurator) state.getConfig()).setTeams(titleCacheTeam);
1105
//        ((Abcd206ImportConfigurator) state.getConfig()).setPersons(titleCachePerson);
1106
    }
1107

    
1108
    @Override
1109
    protected boolean isIgnore(Abcd206ImportState state) {
1110
        return false;
1111
    }
1112

    
1113

    
1114

    
1115
}
(2-2/14)