Project

General

Profile

Download (78.4 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
package eu.etaxonomy.cdm.io.specimen.abcd206.in;
10

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

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

    
27
import eu.etaxonomy.cdm.api.application.ICdmRepository;
28
import eu.etaxonomy.cdm.api.facade.DerivedUnitFacade;
29
import eu.etaxonomy.cdm.api.service.DeleteResult;
30
import eu.etaxonomy.cdm.api.service.config.SpecimenDeleteConfigurator;
31
import eu.etaxonomy.cdm.common.StreamUtils;
32
import eu.etaxonomy.cdm.common.URI;
33
import eu.etaxonomy.cdm.ext.occurrence.bioCase.BioCaseQueryServiceWrapper;
34
import eu.etaxonomy.cdm.hibernate.HibernateProxyHelper;
35
import eu.etaxonomy.cdm.io.common.ICdmIO;
36
import eu.etaxonomy.cdm.io.common.MapWrapper;
37
import eu.etaxonomy.cdm.io.specimen.SpecimenImportBase;
38
import eu.etaxonomy.cdm.io.specimen.SpecimenUserInteraction;
39
import eu.etaxonomy.cdm.io.specimen.UnitsGatheringArea;
40
import eu.etaxonomy.cdm.io.specimen.UnitsGatheringEvent;
41
import eu.etaxonomy.cdm.io.specimen.abcd206.in.molecular.AbcdDnaParser;
42
import eu.etaxonomy.cdm.model.agent.Institution;
43
import eu.etaxonomy.cdm.model.agent.Person;
44
import eu.etaxonomy.cdm.model.agent.Team;
45
import eu.etaxonomy.cdm.model.agent.TeamOrPersonBase;
46
import eu.etaxonomy.cdm.model.common.Annotation;
47
import eu.etaxonomy.cdm.model.common.CdmBase;
48
import eu.etaxonomy.cdm.model.common.IdentifiableSource;
49
import eu.etaxonomy.cdm.model.common.Language;
50
import eu.etaxonomy.cdm.model.common.LanguageString;
51
import eu.etaxonomy.cdm.model.location.NamedArea;
52
import eu.etaxonomy.cdm.model.media.Media;
53
import eu.etaxonomy.cdm.model.media.Rights;
54
import eu.etaxonomy.cdm.model.media.RightsType;
55
import eu.etaxonomy.cdm.model.molecular.DnaSample;
56
import eu.etaxonomy.cdm.model.occurrence.Collection;
57
import eu.etaxonomy.cdm.model.occurrence.DerivationEvent;
58
import eu.etaxonomy.cdm.model.occurrence.DerivationEventType;
59
import eu.etaxonomy.cdm.model.occurrence.DerivedUnit;
60
import eu.etaxonomy.cdm.model.occurrence.FieldUnit;
61
import eu.etaxonomy.cdm.model.occurrence.GatheringEvent;
62
import eu.etaxonomy.cdm.model.occurrence.MediaSpecimen;
63
import eu.etaxonomy.cdm.model.occurrence.SpecimenOrObservationBase;
64
import eu.etaxonomy.cdm.model.occurrence.SpecimenOrObservationType;
65
import eu.etaxonomy.cdm.model.reference.OriginalSourceBase;
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.term.DefinedTerm;
70
import eu.etaxonomy.cdm.model.term.DefinedTermBase;
71
import eu.etaxonomy.cdm.model.term.TermType;
72
import eu.etaxonomy.cdm.model.term.TermVocabulary;
73
import eu.etaxonomy.cdm.strategy.parser.TimePeriodParser;
74

    
75
/**
76
 * @author p.kelbert
77
 * @author p.plitzner
78
 * @author k.luther
79
 * @since 20.10.2008
80
 */
81
@Component
82
public class Abcd206Import extends SpecimenImportBase<Abcd206ImportConfigurator, Abcd206ImportState> {
83

    
84
    private static final long serialVersionUID = 3918095362150986307L;
85

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

    
88
    private static final Logger logger = Logger.getLogger(Abcd206Import.class);
89

    
90
    public Abcd206Import() {
91
        super();
92
    }
93

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

    
116
                    response = queryService.query(config.getOccurenceQuery(), sourceUri);
117
                    state.setActualAccessPoint(sourceUri);
118

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

    
125
            if (state.getRef() == null) {
126
                String name = NB(state.getConfig().getSourceReferenceTitle());
127
                for (Reference reference : referenceStore.getAllValues()) {
128
                    if (!StringUtils.isBlank(reference.getTitleCache())) {
129
                        if (reference.getTitleCache().equalsIgnoreCase(name)) {
130
                            state.setRef(reference);
131

    
132
                        }
133
                    }
134
                }
135
                if (state.getRef() == null) {
136
                    if (state.getConfig().getSourceReference() != null) {
137
                        state.setRef(state.getConfig().getSourceReference());
138
                        state.addImportReference(state.getRef());
139

    
140
                    } else {
141
                        state.setRef(ReferenceFactory.newGeneric());
142
                        state.getRef().setUri(sourceUri);
143

    
144
                        if (sourceUri != null) {
145
                            state.getRef().setTitle(StringUtils.substringAfter(sourceUri.toString(), "dsa="));
146
                        }
147

    
148
                        if (!StringUtils.isBlank(state.getConfig().getSourceReferenceTitle())) {
149
                            state.getRef().setTitle(state.getConfig().getSourceReferenceTitle());
150
                        }
151
                        state.addImportReference(state.getRef());
152
                    }
153

    
154
                }
155
            }
156
            // }
157

    
158
            save(state.getRef(), state);
159
            state.getConfig().setSourceReference(state.getRef());
160

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

    
210
            if (response == null) {
211
                response = state.getConfig().getSource();
212
            }
213
            UnitAssociationWrapper unitAssociationWrapper = AbcdParseUtility.parseUnitsNodeList(response,
214
                    state.getReport());
215
            NodeList unitsList = unitAssociationWrapper.getAssociatedUnits();
216
            state.setPrefix(unitAssociationWrapper.getPrefix());
217

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

    
224
                state.setDataHolder(new Abcd206DataHolder());
225
                state.getDataHolder().reset();
226

    
227
                Abcd206XMLFieldGetter abcdFieldGetter = new Abcd206XMLFieldGetter(state.getDataHolder(),
228
                        state.getPrefix());
229
                if (config.getNomenclaturalCode() != null) {
230
                    state.getDataHolder().setNomenclatureCode(config.getNomenclaturalCode().getKey());
231
                }
232
                prepareCollectors(state, unitsList, abcdFieldGetter);
233

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

    
237
                commitTransaction(state.getTx());
238
                state.setTx(startTransaction());
239
                if (state.getDefaultClassification(false) != null) {
240
                    state.setDefaultClassification(
241
                            getClassificationService().load(state.getDefaultClassification(false).getUuid()));
242
                }
243
                if (state.getClassification() != null) {
244
                    state.setClassification(getClassificationService().load(state.getClassification().getUuid()));
245
                }
246
                state.setAssociationRefs(new ArrayList<>());
247
                state.setDescriptionRefs(new ArrayList<>());
248
                state.setDerivedUnitSources(new ArrayList<>());
249
                for (int i = 0; i < unitsList.getLength(); i++) {
250
                    commitTransaction(state.getTx());
251
                    state.setTx(startTransaction());
252

    
253
                    if (state.getConfig().getProgressMonitor().isCanceled()) {
254
                        break;
255
                    }
256

    
257
                    state.reset();
258
                    state.getDataHolder().setNomenclatureCode(state.getConfig().getNomenclaturalCode()!= null? state.getConfig().getNomenclaturalCode().getKey() : null);
259
                    Element item = (Element) unitsList.item(i);
260
                    Abcd206ImportParser.setUnitPropertiesXML(item, abcdFieldGetter, state);
261
                    updateProgress(state, "Importing data for unit " + state.getDataHolder().getUnitID() + " (" + i
262
                            + "/" + unitsList.getLength() + ")");
263

    
264
                    // import unit + field unit data
265
                    state.setAssociatedUnitIds(state.getDataHolder().getAssociatedUnitIds());
266

    
267
                    this.handleSingleUnit(state, item, true);
268
                    state.setLastFieldUnit(null);
269

    
270
                }
271
                commitTransaction(state.getTx());
272
                state.setTx(startTransaction());
273
                if (state.getConfig().isDeduplicateReferences()) {
274
                    getReferenceService().deduplicate(Reference.class, null, null);
275
                }
276
                if (state.getConfig().isDeduplicateClassifications()) {
277
                    getClassificationService().deduplicate(Classification.class, null, null);
278
                }
279
            }
280
            commitTransaction(state.getTx());
281
        } catch (Exception e) {
282
            String errorDuringImport = "Exception during import!";
283
            logger.error(errorDuringImport, e);
284
            state.getReport().addException(errorDuringImport, e);
285
        } finally {
286
            state.getReport().printReport(state.getConfig().getReportUri());
287
        }
288
        if (state.getConfig().isDownloadSequenceData()) {
289
            for (URI uri : state.getSequenceDataStableIdentifier()) {
290
                // Files.createDirectories(file.getParent()); // optional, make
291
                // sure parent dir exists
292
                try {
293
                    StreamUtils.downloadFile(uri.toURL(), "temp");
294
                } catch (IOException e) {
295
                    // TODO Auto-generated catch block
296
                    e.printStackTrace();
297
                }
298

    
299
            }
300
        }
301

    
302
        return;
303
    }
304

    
305
    /**
306
     *
307
     */
308
    private void createKindOfUnitsMap(Abcd206ImportState state) {
309

    
310
        ICdmRepository cdmRepository = state.getConfig().getCdmAppController();
311
        if (cdmRepository == null) {
312
            cdmRepository = this;
313
        }
314

    
315
        List<DefinedTerm> terms = cdmRepository.getTermService().listByTermType(TermType.KindOfUnit, null, 0, null,
316
                null);
317
        kindOfUnitsMap = new HashMap<>();
318
        for (DefinedTerm kindOfUnit : terms) {
319
            if (kindOfUnit != null && kindOfUnit.getLabel() != null) {
320
                String kindOfUnitLabel = kindOfUnit.getLabel().toLowerCase();
321
                kindOfUnitsMap.put(kindOfUnitLabel, kindOfUnit);
322
            }
323

    
324
        }
325
    }
326

    
327
    /**
328
     * @param state
329
     * @param item
330
     */
331
    private void getSiblings(Abcd206ImportState state, Object item, DerivedUnitFacade facade) {
332
        String unitId = facade.getCatalogNumber();
333
        if (unitId == null) {
334
            unitId = facade.getAccessionNumber();
335
        }
336
        if (unitId == null){
337
            unitId = facade.getBarcode();
338
        }
339

    
340
        UnitAssociationParser unitParser = new UnitAssociationParser(state.getPrefix(), state.getReport(),
341
                state.getCdmRepository());
342
        UnitAssociationWrapper unitAssociationWrapper = null;
343
        for (URI accessPoint : state.getAllAccesPoint()) {
344
            unitAssociationWrapper = unitParser.parseSiblings(unitId, accessPoint);
345
            if (unitAssociationWrapper != null && unitAssociationWrapper.getAssociatedUnits() != null) {
346
                break;
347
            }
348
        }
349

    
350
        DerivedUnit currentUnit = state.getDerivedUnitBase();
351
        // DerivationEvent currentDerivedFrom = currentUnit.getDerivedFrom();
352
        FieldUnit currentFieldUnit = facade.getFieldUnit(false);
353
        if (unitAssociationWrapper != null) {
354
            NodeList associatedUnits = unitAssociationWrapper.getAssociatedUnits();
355
            if (associatedUnits != null) {
356
                for (int m = 0; m < associatedUnits.getLength(); m++) {
357
                    if (associatedUnits.item(m) instanceof Element) {
358
                        state.reset();
359
                        String associationType = AbcdParseUtility
360
                                .parseFirstTextContent(((Element) associatedUnits.item(m))
361
                                        .getElementsByTagName(state.getPrefix() + "AssociationType"));
362

    
363
                        Abcd206ImportParser.setUnitPropertiesXML((Element) associatedUnits.item(m),
364
                                new Abcd206XMLFieldGetter(state.getDataHolder(), unitAssociationWrapper.getPrefix()),
365
                                state);
366
                        // logger.debug("derived unit: " +
367
                        // state.getDerivedUnitBase().toString() + " associated
368
                        // unit: " +state.getDataHolder().getKindOfUnit() + ", "
369
                        // + state.getDataHolder().accessionNumber + ", " +
370
                        // state.getDataHolder().getRecordBasis() + ", " +
371
                        // state.getDataHolder().getUnitID());
372

    
373
                        handleSingleUnit(state, associatedUnits.item(m), false);
374

    
375
                        DerivedUnit associatedUnit = state.getDerivedUnitBase();
376
                        FieldUnit associatedFieldUnit = null;
377
                        commitTransaction(state.getTx());
378
                        state.setTx(startTransaction());
379
                        java.util.Collection<FieldUnit> associatedFieldUnits = null;
380
                        try {
381
                            associatedFieldUnits = state.getCdmRepository().getOccurrenceService()
382
                                    .findFieldUnits(associatedUnit.getUuid(), null);
383
                        } catch (NullPointerException e) {
384
                            logger.error("Search for associated field unit creates a NPE" + e.getMessage());
385
                        }
386
                        // ignore field unit if associated unit has more than
387
                        // one
388
                        if (associatedFieldUnits != null && associatedFieldUnits.size() > 1) {
389
                            state.getReport()
390
                                    .addInfoMessage(String.format("%s has more than one field unit.", associatedUnit));
391
                        } else if (associatedFieldUnits != null && associatedFieldUnits.size() == 1) {
392
                            associatedFieldUnit = associatedFieldUnits.iterator().next();
393
                        }
394
                        // parent-child relation:
395
                        if (associationType != null && (associationType.contains("individual") || associationType.contains("culture")
396
                                || associationType.contains("sample") || associationType.contains("isolated"))) {
397
                            DerivationEvent updatedDerivationEvent = DerivationEvent.NewSimpleInstance(currentUnit,
398
                                    associatedUnit, DerivationEventType.ACCESSIONING());
399

    
400
                            updatedDerivationEvent.setDescription(associationType);
401
                            if (associatedFieldUnit != null && associatedFieldUnit != currentFieldUnit && currentFieldUnit != null) {
402
                                // associatedFieldUnit.removeDerivationEvent(updatedDerivationEvent);
403
                                // save(associatedFieldUnit, state);
404
                                // if
405
                                // (associatedFieldUnit.getDerivationEvents().isEmpty()){
406
                                SpecimenDeleteConfigurator config = new SpecimenDeleteConfigurator();
407
                                config.setDeleteChildren(false);
408
                                DeleteResult result = state.getCdmRepository().getOccurrenceService()
409
                                        .delete(associatedFieldUnit, config);
410
                                if (!result.isOk()) {
411
                                    logger.debug("Deletion of field unit " + associatedFieldUnit.getFieldNumber()
412
                                            + " not successfull");
413
                                }
414
                                state.setFieldUnit(currentFieldUnit);
415

    
416
                                // }
417

    
418
                            }
419
                            state.getReport().addDerivate(associatedUnit, currentUnit, state.getConfig());
420
                        }
421
                        save(associatedUnit, state);
422

    
423
                    }
424
                }
425
            }
426
        }
427
        state.reset();
428
        state.setDerivedUnitBase(currentUnit);
429

    
430
    }
431

    
432
    /**
433
     * Handle a single unit
434
     *
435
     * @param state
436
     * @param item
437
     */
438
    @Override
439
    public void handleSingleUnit(Abcd206ImportState state, Object itemObject) {
440
        handleSingleUnit(state, itemObject, true);
441
    }
442

    
443
    @SuppressWarnings("rawtypes")
444
    public void handleSingleUnit(Abcd206ImportState state, Object itemObject, boolean handleAssociatedUnits) {
445
        Element item = (Element) itemObject;
446

    
447
        Abcd206ImportConfigurator config = state.getConfig();
448
        if (logger.isDebugEnabled()) {
449
            logger.info("handleSingleUnit " + state.getRef());
450
        }
451
        try {
452
            ICdmRepository cdmAppController = state.getConfig().getCdmAppController();
453
            if (cdmAppController == null) {
454
                cdmAppController = this;
455
            }
456
            // check if unit already exists
457
            DerivedUnitFacade derivedUnitFacade = null;
458
            if (state.getConfig().isIgnoreImportOfExistingSpecimen() && state.getDataHolder().getUnitID() != null) {
459

    
460
                SpecimenOrObservationBase<?> existingSpecimen = findExistingSpecimen(state.getDataHolder().getUnitID(),
461
                        state);
462
                if (existingSpecimen != null && existingSpecimen.isInstanceOf(DerivedUnit.class)) {
463
                    DerivedUnit derivedUnit = HibernateProxyHelper.deproxy(existingSpecimen, DerivedUnit.class);
464
                    state.setDerivedUnitBase(derivedUnit);
465
                    derivedUnitFacade = DerivedUnitFacade.NewInstance(state.getDerivedUnitBase());
466
                    if (handleAssociatedUnits) {
467
                        importAssociatedUnits(state, item, derivedUnitFacade);
468
                    }
469
                    if (state.getConfig().getDnaSoure() != null) {
470
                        importAssociatedDna(state, item, derivedUnitFacade);
471
                    }
472

    
473
                    state.getReport().addAlreadyExistingSpecimen(SpecimenImportUtility.getUnitID(derivedUnit, config),
474
                            derivedUnit);
475

    
476
                    return;
477
                }
478
            } else {
479
                System.err.println("dataholder does not contain unit id");
480
            }
481

    
482

    
483
            // import DNA unit
484
            if (state.getDataHolder().getKindOfUnit() != null
485
                    && state.getDataHolder().getKindOfUnit().equalsIgnoreCase("dna")) {
486
                AbcdDnaParser dnaParser = new AbcdDnaParser(state.getPrefix(), state.getReport(),
487
                        state.getCdmRepository());
488
                DnaSample dnaSample = dnaParser.parse(item, state);
489
                //dnaSample.addSource(OriginalSourceType.Import, dnaSample.getAccessionNumber(), "", state.getImportReference(state.getActualAccessPoint()), "");
490
                save(dnaSample, state);
491
                // set dna as derived unit to avoid creating an extra specimen
492
                // for this dna sample (instead just the field unit will be
493
                // created)
494
                state.setDerivedUnitBase(dnaSample);
495
                derivedUnitFacade = DerivedUnitFacade.NewInstance(state.getDerivedUnitBase());
496
            } else {
497
                // create facade
498
                derivedUnitFacade = getFacade(state);
499
                state.setDerivedUnitBase(derivedUnitFacade.innerDerivedUnit());
500

    
501
            }
502

    
503
            /**
504
             * GATHERING EVENT
505
             */
506

    
507
            // look for existing fieldUnit
508
            FieldUnit fieldUnit = null;
509
            if (StringUtils.isNotBlank(state.getDataHolder().getFieldNumber())){
510
                fieldUnit = state.getFieldUnit(state.getDataHolder().getFieldNumber());
511
                if (fieldUnit != null){
512
                    state.setLastFieldUnit(fieldUnit);
513
                }
514
            }else{
515
                fieldUnit = state.getLastFieldUnit();
516

    
517
            }
518
            if (fieldUnit == null){
519
                fieldUnit = FieldUnit.NewInstance();
520
                fieldUnit.setFieldNumber(state.getDataHolder().getFieldNumber());
521
                state.setLastFieldUnit(fieldUnit);
522
            }
523

    
524
            // gathering event
525
            UnitsGatheringEvent unitsGatheringEvent = new UnitsGatheringEvent(cdmAppController.getTermService(),
526
                    state.getDataHolder().locality, state.getDataHolder().languageIso, state.getDataHolder().longitude,
527
                    state.getDataHolder().latitude, state.getDataHolder().getGatheringCoordinateErrorMethod(),
528
                    state.getDataHolder().getGatheringElevationText(), state.getDataHolder().getGatheringElevationMin(),
529
                    state.getDataHolder().getGatheringElevationMax(), state.getDataHolder().getGatheringElevationUnit(),
530
                    state.getDataHolder().getGatheringDateText(), state.getDataHolder().getGatheringNotes(),
531
                    state.getDataHolder().getGatheringMethod(),
532
                    state.getTransformer().getReferenceSystemByKey(state.getDataHolder().getGatheringSpatialDatum()),
533
                    state.getConfig());
534

    
535
            unitsGatheringEvent.setGatheringDepth(state.getDataHolder().getGatheringDepthText(),
536
                    state.getDataHolder().getGatheringDepthMin(), state.getDataHolder().getGatheringDepthMax(),
537
                    state.getDataHolder().getGatheringDepthUnit());
538
            // unitsGatheringEvent.setHeight(heightText, heightMin, heightMax,
539
            // heightUnit);
540
            if (state.getDataHolder().gatheringAgentsList.isEmpty()) {
541
                TeamOrPersonBase team = state.getPersonStore().get(state.getDataHolder().gatheringAgentsText);
542
                if (team == null){
543
                    team = parseAuthorString(state.getDataHolder().gatheringAgentsText);
544
                    if (team != null){
545
                        state.getPersonStore().put(team.getTitleCache(), team);
546
                    }
547
                }
548
                if (team != null){
549
                    unitsGatheringEvent.setCollector(team,
550
                            config);
551
                }
552

    
553

    
554
            } else {
555
                TeamOrPersonBase team = state.getPersonStore().get(state.getDataHolder().gatheringAgentsList.toString());
556
                if (team == null){
557
                    team = parseAuthorString(state.getDataHolder().gatheringAgentsList.toString());
558
                    if (team != null){
559
                        state.getPersonStore().put(team.getTitleCache(), team);
560
                    }
561

    
562
                }
563
                if (team != null){
564
                    unitsGatheringEvent.setCollector(team,
565
                            config);
566
                }
567
            }
568
            // count
569
            UnitsGatheringArea unitsGatheringArea = new UnitsGatheringArea();
570
            // unitsGatheringArea.setConfig(state.getConfig(),getOccurrenceService(),
571
            // getTermService());
572
            unitsGatheringArea.setParams(state.getDataHolder().isocountry, state.getDataHolder().country,
573
                    (state.getConfig()), cdmAppController.getTermService(),
574
                    cdmAppController.getVocabularyService());
575

    
576
            DefinedTermBase<?> areaCountry = unitsGatheringArea.getCountry();
577

    
578
            // other areas
579
            unitsGatheringArea = new UnitsGatheringArea();
580
            // unitsGatheringArea.setConfig(state.getConfig(),getOccurrenceService(),getTermService());
581

    
582
            unitsGatheringArea.setAreas(state.getDataHolder().getNamedAreaList(), (state.getConfig()),
583
                    cdmAppController.getTermService(), cdmAppController.getVocabularyService());
584

    
585
            ArrayList<DefinedTermBase> nas = unitsGatheringArea.getAreas();
586
            for (DefinedTermBase namedArea : nas) {
587
                unitsGatheringEvent.addArea(namedArea);
588
            }
589

    
590
            // copy gathering event to facade
591
            GatheringEvent gatheringEvent = unitsGatheringEvent.getGatheringEvent();
592
            if (fieldUnit != null) {
593
                derivedUnitFacade.setFieldUnit(fieldUnit);
594
                if (derivedUnitFacade.getGatheringPeriod() == null && gatheringEvent.getTimeperiod() != null){
595
                    derivedUnitFacade.setGatheringPeriod(gatheringEvent.getTimeperiod());
596
                }
597
                if (derivedUnitFacade.getLocality() == null && gatheringEvent.getLocality() != null){
598
                    derivedUnitFacade.setLocality(gatheringEvent.getLocality());
599
                }
600
                if (derivedUnitFacade.getExactLocation() == null && gatheringEvent.getExactLocation() != null){
601
                    derivedUnitFacade.setExactLocation(gatheringEvent.getExactLocation());
602
                }
603

    
604
                if (derivedUnitFacade.getCollector() == null && gatheringEvent.getCollector() != null){
605
                    derivedUnitFacade.setCollector(gatheringEvent.getCollector());
606
                }
607
                if (derivedUnitFacade.getCountry() == null && areaCountry != null){
608
                    derivedUnitFacade.setCountry((NamedArea) areaCountry);
609
                }
610
                if (StringUtils.isBlank(derivedUnitFacade.getAbsoluteElevationText()) && StringUtils.isNotBlank(gatheringEvent.getAbsoluteElevationText())){
611
                    derivedUnitFacade.setAbsoluteElevationText(gatheringEvent.getAbsoluteElevationText());
612
                }
613
                if (derivedUnitFacade.getAbsoluteElevation() == null && gatheringEvent.getAbsoluteElevation() != null){
614
                    derivedUnitFacade.setAbsoluteElevation(gatheringEvent.getAbsoluteElevation());
615
                }
616
                if (derivedUnitFacade.getAbsoluteElevationMaximum() == null && gatheringEvent.getAbsoluteElevationMax() != null){
617
                    derivedUnitFacade.setAbsoluteElevationMax(gatheringEvent.getAbsoluteElevationMax());
618
                }
619
                if (StringUtils.isBlank(derivedUnitFacade.getDistanceToGroundText()) && StringUtils.isNotBlank(gatheringEvent.getDistanceToGroundText())){
620
                    derivedUnitFacade.setDistanceToGroundText(gatheringEvent.getDistanceToGroundText());
621
                }
622
                if (derivedUnitFacade.getDistanceToGroundMax() == null && gatheringEvent.getDistanceToGroundMax() != null){
623
                    derivedUnitFacade.setDistanceToGroundMax(gatheringEvent.getDistanceToGroundMax());
624
                }
625
                if (derivedUnitFacade.getDistanceToGround() == null && gatheringEvent.getDistanceToGround() != null){
626
                    derivedUnitFacade.setDistanceToGround(gatheringEvent.getDistanceToGround());
627
                }
628
                if (StringUtils.isBlank(derivedUnitFacade.getDistanceToWaterSurfaceText()) && StringUtils.isNotBlank(gatheringEvent.getDistanceToWaterSurfaceText())){
629
                    derivedUnitFacade.setDistanceToWaterSurfaceText(gatheringEvent.getDistanceToWaterSurfaceText());
630
                }
631
                if (derivedUnitFacade.getDistanceToWaterSurfaceMax() == null && gatheringEvent.getDistanceToWaterSurfaceMax() != null){
632
                    derivedUnitFacade.setDistanceToWaterSurfaceMax(gatheringEvent.getDistanceToWaterSurfaceMax());
633
                }
634
                if (derivedUnitFacade.getDistanceToWaterSurface() == null && gatheringEvent.getDistanceToWaterSurface() != null){
635
                    derivedUnitFacade.setDistanceToWaterSurface(gatheringEvent.getDistanceToWaterSurface());
636
                }
637
                if (derivedUnitFacade.getGatheringPeriod() == null && gatheringEvent.getTimeperiod() != null){
638
                    derivedUnitFacade.setGatheringPeriod(gatheringEvent.getTimeperiod());
639
                }
640
                if (derivedUnitFacade.getCollectingMethod() == null && gatheringEvent.getCollectingMethod() != null){
641
                    derivedUnitFacade.setCollectingMethod(gatheringEvent.getCollectingMethod());
642
                }
643
                for (DefinedTermBase<?> area : unitsGatheringArea.getAreas()) {
644
                    derivedUnitFacade.addCollectingArea((NamedArea) area);
645
                }
646
             // add unitNotes
647
                if (state.getDataHolder().getUnitNotes() != null) {
648
                    derivedUnitFacade
649
                            .addAnnotation(Annotation.NewDefaultLanguageInstance(NB(state.getDataHolder().getUnitNotes())));
650
                }
651
                if (gatheringEvent.getAnnotations() != null) {
652
                    for (Annotation annotation : gatheringEvent.getAnnotations()) {
653
                        derivedUnitFacade.getGatheringEvent(true).addAnnotation(annotation);
654
                    }
655
                }
656

    
657
            }else{
658
//TODO??
659
            }
660

    
661

    
662

    
663

    
664
            // derivedUnitFacade.addCollectingAreas(unitsGatheringArea.getAreas());
665
            // TODO exsiccatum
666

    
667
            // add fieldNumber
668
            String fieldNumber = null;
669
            if (derivedUnitFacade.getFieldUnit(false) != null) {
670
                fieldNumber = derivedUnitFacade.getFieldUnit(false).getFieldNumber();
671
                if (fieldNumber == null){
672
                    derivedUnitFacade.setFieldNumber(NB(state.getDataHolder().getFieldNumber()));
673
                }
674
            }
675

    
676
            save(unitsGatheringEvent.getLocality(), state);
677

    
678

    
679

    
680

    
681
            // //add Multimedia URLs
682
            if (state.getDataHolder().getMultimediaObjects().size() != -1) {
683
                for (String multimediaObject : state.getDataHolder().getMultimediaObjects().keySet()) {
684
                    Media media;
685
                    try {
686
                        media = extractMedia(state, multimediaObject);
687
                        if (media == null) {
688
                            continue;
689
                        }
690
                        derivedUnitFacade.addDerivedUnitMedia(media);
691
                        if (state.getConfig().isAddMediaAsMediaSpecimen()) {
692
                            // add media also as specimen scan
693
                            MediaSpecimen mediaSpecimen = MediaSpecimen
694
                                    .NewInstance(SpecimenOrObservationType.StillImage);
695
                            mediaSpecimen.setMediaSpecimen(media);
696
                            // do it only once!!
697
                            DefinedTermBase specimenScanTerm = getTermService().load(SPECIMEN_SCAN_TERM);
698
                            if (specimenScanTerm instanceof DefinedTerm) {
699
                                mediaSpecimen.setKindOfUnit((DefinedTerm) specimenScanTerm);
700
                            }
701
                            DerivationEvent derivationEvent = DerivationEvent
702
                                    .NewInstance(DerivationEventType.PREPARATION());
703
                            derivationEvent.addDerivative(mediaSpecimen);
704
                            derivedUnitFacade.innerDerivedUnit().addDerivationEvent(derivationEvent);
705
                        }
706

    
707
                    } catch (MalformedURLException e) {
708
                        // TODO Auto-generated catch block
709
                        e.printStackTrace();
710
                    }
711

    
712
                }
713
            }
714
            // multimedia for fieldUnit
715
            if (state.getDataHolder().getGatheringMultimediaObjects().size() != -1) {
716
                for (String multimediaObject : state.getDataHolder().getGatheringMultimediaObjects().keySet()) {
717
                    Media media;
718
                    try {
719
                        media = extractMedia(state, multimediaObject);
720
                        if (media == null) {
721
                            continue;
722
                        }
723
                        derivedUnitFacade.addFieldObjectMedia(media);
724

    
725
                    } catch (MalformedURLException e) {
726
                        // TODO Auto-generated catch block
727
                        e.printStackTrace();
728
                    }
729

    
730
                }
731
            }
732

    
733

    
734
            if (derivedUnitFacade.getFieldUnit(false) != null) {
735
                state.setFieldUnit(derivedUnitFacade.getFieldUnit(false));
736
            }
737

    
738
            // handle collection data
739
            setCollectionData(state, derivedUnitFacade);
740

    
741
            // Reference stuff
742
            SpecimenUserInteraction sui = config.getSpecimenUserInteraction();
743
            Map<String, OriginalSourceBase> sourceMap = new HashMap<>();
744

    
745
            state.getDataHolder().setDocSources(new ArrayList<>());
746

    
747

    
748

    
749
            IdentifiableSource sour = getIdentifiableSource(state.getImportReference(state.getActualAccessPoint()), null);
750
            String idInSource = derivedUnitFacade.getAccessionNumber() != null ? derivedUnitFacade.getAccessionNumber()
751
                    : derivedUnitFacade.getCatalogNumber() != null ? derivedUnitFacade.getCatalogNumber() : derivedUnitFacade.getBarcode();
752
            //sour.getCitation().setUri(state.getActualAccessPoint());
753
            sour.setIdInSource(idInSource);
754
            try {
755
                if (sour.getCitation() != null) {
756
                    if (StringUtils.isNotBlank(sour.getCitationMicroReference())) {
757
                        state.getDataHolder().getDocSources()
758
                                .add(sour.getCitation().getTitleCache() + "---" + sour.getCitationMicroReference());
759
                    } else {
760
                        state.getDataHolder().getDocSources().add(sour.getCitation().getTitleCache());
761
                    }
762
                }
763
            } catch (Exception e) {
764
                logger.warn("oups");
765
            }
766

    
767
            derivedUnitFacade.addSource(sour);
768

    
769

    
770
            save(state.getDerivedUnitBase(), state);
771

    
772
            if (logger.isDebugEnabled()) {
773
                logger.info("saved ABCD specimen ...");
774
            }
775

    
776
            // handle identifications
777
            handleIdentifications(state, derivedUnitFacade);
778

    
779
            // associatedUnits
780
            if (handleAssociatedUnits) {
781
                importAssociatedUnits(state, item, derivedUnitFacade);
782
            }
783
            if (state.getConfig().getDnaSoure() != null ) {
784
                boolean uriCorrect = true;
785
                try{
786
                    state.getConfig().getDnaSoure().toString();
787
                }catch(Exception e){
788
                    uriCorrect = false;
789
                }
790
                if (uriCorrect){
791
                    try{
792
                        importAssociatedDna(state, item, derivedUnitFacade);
793
                    }catch(Exception e){
794
                        String message = "Error when importing Dna! " + itemObject.toString();
795
                        state.getReport().addException(message, e);
796
                        state.setUnsuccessfull();
797
                    }
798
                }
799

    
800
            }
801
            // siblings/ other children
802
            if (derivedUnitFacade.getType() != null
803
                    && (derivedUnitFacade.getType().equals(SpecimenOrObservationType.LivingSpecimen)
804
                            || derivedUnitFacade.getType().equals(SpecimenOrObservationType.TissueSample)
805
                            || derivedUnitFacade.getType().equals(SpecimenOrObservationType.OtherSpecimen)
806
                            || derivedUnitFacade.getType().equals(SpecimenOrObservationType.MaterialSample))
807
                    && state.getConfig().isGetSiblings()) {
808
                getSiblings(state, item, derivedUnitFacade);
809
            }
810

    
811
        } catch (Exception e) {
812
            String message = "Error when reading record! " + itemObject.toString();
813
            state.getReport().addException(message, e);
814
            state.setUnsuccessfull();
815
        }
816

    
817
        return;
818
    }
819

    
820
    /**
821
     * @param state
822
     * @param multimediaObject
823
     * @return
824
     * @throws MalformedURLException
825
     */
826
    private Media extractMedia(Abcd206ImportState state, String multimediaObject) throws MalformedURLException {
827
        Media media;
828
        media = getImageMedia(multimediaObject, READ_MEDIA_DATA);
829

    
830
        Map<String, String> attributes = state.getDataHolder().getMultimediaObjects().get(multimediaObject);
831
        if (attributes == null) {
832
            attributes = state.getDataHolder().getGatheringMultimediaObjects().get(multimediaObject);
833
            if (attributes == null) {
834
                logger.error(multimediaObject + " does not exist in dataHolder");
835
                state.getResult().addError(multimediaObject + " does not exist in dataHolder");
836
                return null;
837
            }
838
        }
839
        if (attributes.containsKey("Context")) {
840
            LanguageString description = LanguageString.NewInstance(attributes.get("Context"), Language.ENGLISH());
841
            media.putDescription(description);
842
        }
843
        if (attributes.containsKey("Comment")) {
844
            LanguageString description = LanguageString.NewInstance(attributes.get("Comment"), Language.ENGLISH());
845
            media.putDescription(description);
846
        }
847
        if (attributes.containsKey("Creators")) {
848
            String creators = attributes.get("Creators");
849
            Person artist;
850
            Team artistTeam;
851
            String[] artists;
852
            if (creators != null) {
853
                if (creators.contains("&")) {
854
                    artists = creators.split("&");
855
                    artistTeam = new Team();
856
                    for (String creator : artists) {
857
                        artist = Person.NewTitledInstance(creator);
858
                        artistTeam.addTeamMember(artist);
859
                    }
860
                    media.setArtist(artistTeam);
861
                } else {
862

    
863
                    artist = Person.NewTitledInstance(creators);
864
                    media.setArtist(artist);
865
                }
866
            }
867

    
868
        }
869
        if (attributes.containsKey("CreateDate")) {
870
            String createDate = attributes.get("CreateDate");
871

    
872
            if (createDate != null) {
873

    
874
                media.setMediaCreated(TimePeriodParser.parseString(createDate));
875
            }
876

    
877
        }
878

    
879
        if (attributes.containsKey("License")) {
880
            String licence = attributes.get("License");
881

    
882
            if (licence != null) {
883
                Rights right = Rights.NewInstance(licence, Language.ENGLISH(), RightsType.LICENSE());
884
                media.addRights(right);
885
            }
886

    
887
        }
888
        return media;
889
    }
890

    
891
    @Override
892
    protected void importAssociatedUnits(Abcd206ImportState state, Object itemObject,
893
            DerivedUnitFacade derivedUnitFacade) {
894
        SpecimenDeleteConfigurator deleteConfig = new SpecimenDeleteConfigurator();
895
        deleteConfig.setDeleteChildren(false);
896
        Abcd206ImportConfigurator config = state.getConfig();
897
        // import associated units
898
        FieldUnit currentFieldUnit = derivedUnitFacade.innerFieldUnit();
899
        // TODO: push state (think of implementing stack architecture for state
900
        DerivedUnit currentUnit = state.getDerivedUnitBase();
901
        DerivationEvent currentDerivedFrom = currentUnit.getDerivedFrom();
902
        URI currentAccessPoint = state.getActualAccessPoint();
903
        String currentPrefix = state.getPrefix();
904
        Element item = null;
905
        if (itemObject instanceof Element) {
906
            item = (Element) itemObject;
907
        }
908
        NodeList unitAssociationList = null;
909
        if (item != null) {
910
            unitAssociationList = item.getElementsByTagName(currentPrefix + "UnitAssociation");
911
            for (int k = 0; k < unitAssociationList.getLength(); k++) {
912
                if (unitAssociationList.item(k) instanceof Element) {
913
                    Element unitAssociation = (Element) unitAssociationList.item(k);
914
                    UnitAssociationParser unitAssociationParser = new UnitAssociationParser(currentPrefix,
915
                            state.getReport(), state.getCdmRepository());
916
                    UnitAssociationWrapper associationWrapper = unitAssociationParser.parse(unitAssociation);
917
                    if (associationWrapper != null) {
918
                        state.setActualAccessPoint(associationWrapper.getAccesPoint());
919
                        NodeList associatedUnits = associationWrapper.getAssociatedUnits();
920
                        if (associatedUnits != null) {
921
                            for (int m = 0; m < associatedUnits.getLength(); m++) {
922
                                if (associatedUnits.item(m) instanceof Element) {
923
                                    state.reset();
924
                                    state.setPrefix(associationWrapper.getPrefix());
925
                                    Abcd206ImportParser.setUnitPropertiesXML((Element) associatedUnits.item(m),
926
                                            new Abcd206XMLFieldGetter(state.getDataHolder(), state.getPrefix()), state);
927
                                    // logger.debug("derived unit: " +
928
                                    // state.getDerivedUnitBase().toString()
929
                                    // + " associated unit: " +
930
                                    // state.getDataHolder().getKindOfUnit() +
931
                                    // ", "
932
                                    // + state.getDataHolder().accessionNumber +
933
                                    // ", "
934
                                    // + state.getDataHolder().getRecordBasis()
935
                                    // + ", "
936
                                    // + state.getDataHolder().getUnitID());
937
                                    handleSingleUnit(state, associatedUnits.item(m), true);
938

    
939
                                    DerivedUnit associatedUnit = state.getDerivedUnitBase();
940
                                    FieldUnit associatedFieldUnit = null;
941
                                    java.util.Collection<FieldUnit> associatedFieldUnits = state.getCdmRepository()
942
                                            .getOccurrenceService().findFieldUnits(associatedUnit.getUuid(), null);
943
                                    // ignore field unit if associated unit has
944
                                    // more than one
945
                                    if (associatedFieldUnits != null && associatedFieldUnits.size() > 1) {
946
                                        state.getReport().addInfoMessage(
947
                                                String.format("%s has more than one field unit.", associatedUnit));
948
                                    } else if (associatedFieldUnits != null && associatedFieldUnits.size() == 1) {
949
                                        associatedFieldUnit = associatedFieldUnits.iterator().next();
950
                                    }
951

    
952
                                    // attach current unit and associated unit
953
                                    // depending on association type
954

    
955
                                    // parent-child relation:
956
                                    // copy derivation event and connect parent
957
                                    // and sub derivative
958
                                    // if(associationWrapper.getAssociationType().contains("individual")
959
                                    // ||
960
                                    // associationWrapper.getAssociationType().contains("culture")
961
                                    // ||
962
                                    // associationWrapper.getAssociationType().contains("sample")
963
                                    // ||
964
                                    // associationWrapper.getAssociationType().contains("same
965
                                    // in situ")){
966
                                    if (currentDerivedFrom == null) {
967
                                        state.getReport()
968
                                                .addInfoMessage(String.format(
969
                                                        "No derivation event found for unit %s. Defaulting to ACCESSIONING event.",
970
                                                        SpecimenImportUtility.getUnitID(currentUnit, config)));
971
                                        DerivationEvent.NewSimpleInstance(associatedUnit, currentUnit,
972
                                                DerivationEventType.ACCESSIONING());
973
                                    } else {
974
                                        DerivationEvent updatedDerivationEvent = DerivationEvent.NewSimpleInstance(
975
                                                associatedUnit, currentUnit, currentDerivedFrom.getType());
976
                                        updatedDerivationEvent.setActor(currentDerivedFrom.getActor());
977
                                        updatedDerivationEvent.setDescription(currentDerivedFrom.getDescription());
978
                                        updatedDerivationEvent.setInstitution(currentDerivedFrom.getInstitution());
979
                                        updatedDerivationEvent.setTimeperiod(currentDerivedFrom.getTimeperiod());
980

    
981
                                    }
982
                                    state.getReport().addDerivate(associatedUnit, currentUnit, config);
983
                                    // }
984
                                    // siblings relation
985
                                    // connect current unit to field unit of
986
                                    // associated unit
987
                                    // else
988
                                    // if(associationWrapper.getAssociationType().contains("population")||
989
                                    // associationWrapper.getAssociationType().contains("sample")){
990
                                    // //no associated field unit -> using
991
                                    // current one
992
                                    // if(associatedFieldUnit==null){
993
                                    // if(currentFieldUnit!=null){
994
                                    // DerivationEvent.NewSimpleInstance(currentFieldUnit,
995
                                    // associatedUnit,
996
                                    // DerivationEventType.ACCESSIONING());
997
                                    // }
998
                                    // }
999
                                    // else{
1000
                                    // if(currentDerivedFrom==null){
1001
                                    // state.getReport().addInfoMessage("No
1002
                                    // derivation event found for unit
1003
                                    // "+SpecimenImportUtility.getUnitID(currentUnit,
1004
                                    // config)+". Defaulting to ACCESIONING
1005
                                    // event.");
1006
                                    // DerivationEvent.NewSimpleInstance(associatedFieldUnit,
1007
                                    // currentUnit,
1008
                                    // DerivationEventType.ACCESSIONING());
1009
                                    // }
1010
                                    // if(currentDerivedFrom!=null &&
1011
                                    // associatedFieldUnit==currentFieldUnit){
1012
                                    // DerivationEvent updatedDerivationEvent =
1013
                                    // DerivationEvent.NewSimpleInstance(associatedFieldUnit,
1014
                                    // currentUnit,
1015
                                    // currentDerivedFrom.getType());
1016
                                    // updatedDerivationEvent.setActor(currentDerivedFrom.getActor());
1017
                                    // updatedDerivationEvent.setDescription(currentDerivedFrom.getDescription());
1018
                                    // updatedDerivationEvent.setInstitution(currentDerivedFrom.getInstitution());
1019
                                    // updatedDerivationEvent.setTimeperiod(currentDerivedFrom.getTimeperiod());
1020
                                    // }
1021
                                    // }
1022
                                    // }
1023

    
1024
                                    // delete current field unit if replaced
1025
                                    if (currentFieldUnit != null && currentDerivedFrom != null
1026
                                            && currentFieldUnit.getDerivationEvents().size() == 1
1027
                                            && currentFieldUnit.getDerivationEvents().contains(currentDerivedFrom) // making
1028
                                                                                                                   // sure
1029
                                                                                                                   // that
1030
                                                                                                                   // the
1031
                                                                                                                   // field
1032
                                                                                                                   // unit
1033
                                            && currentDerivedFrom.getDerivatives().size() == 1
1034
                                            && currentDerivedFrom.getDerivatives().contains(currentUnit) // is
1035
                                                                                                         // not
1036
                                                                                                         // attached
1037
                                                                                                         // to
1038
                                                                                                         // other
1039
                                                                                                         // derived
1040
                                                                                                         // units
1041
                                            && currentDerivedFrom != currentUnit.getDerivedFrom() // <-
1042
                                                                                                  // derivation
1043
                                                                                                  // has
1044
                                                                                                  // been
1045
                                                                                                  // replaced
1046
                                                                                                  // and
1047
                                                                                                  // can
1048
                                                                                                  // be
1049
                                                                                                  // deleted
1050
                                    ) {
1051
                                        currentFieldUnit.removeDerivationEvent(currentDerivedFrom);
1052
                                        if (associatedFieldUnit != null && associatedFieldUnit.getGatheringEvent() != null && associatedFieldUnit.getGatheringEvent().getActor() == null && currentFieldUnit.getGatheringEvent().getActor() != null){
1053
                                            associatedFieldUnit.getGatheringEvent().setActor(currentFieldUnit.getGatheringEvent().getActor());
1054
                                        }
1055
                                        if (associatedFieldUnit != null && associatedFieldUnit.getFieldNumber() == null && currentFieldUnit.getFieldNumber() != null) {
1056
                                            associatedFieldUnit.setFieldNumber(currentFieldUnit.getFieldNumber());
1057
                                        }
1058

    
1059
                                        if (currentFieldUnit.getDerivationEvents().isEmpty()) {
1060
                                            DeleteResult result = state.getCdmRepository().getOccurrenceService()
1061
                                                    .delete(currentFieldUnit, deleteConfig);
1062

    
1063

    
1064
                                        } else {
1065

    
1066
                                            logger.debug("there are still derivation events in fieldUnit "
1067
                                                    + currentFieldUnit.getId());
1068
                                        }
1069

    
1070
                                    }
1071
                                    state.setLastFieldUnit(associatedFieldUnit);
1072
                                    save(associatedUnit, state);
1073
                                }
1074
                            }
1075
                        }
1076
                    }
1077
                }
1078
            }
1079
        }
1080
        // TODO: pop state
1081
        state.reset();
1082
        state.setDerivedUnitBase(currentUnit);
1083
        state.setActualAccessPoint(currentAccessPoint);
1084
        state.setPrefix(currentPrefix);
1085
    }
1086

    
1087
    private void importAssociatedDna(Abcd206ImportState state, Object itemObject, DerivedUnitFacade derivedUnitFacade) {
1088
        URI dnaSource = state.getConfig().getDnaSoure();
1089
        String unitId = derivedUnitFacade.getCatalogNumber();
1090
        if (unitId == null) {
1091
            unitId = derivedUnitFacade.getAccessionNumber();
1092
        }
1093
        if (unitId == null) {
1094
            unitId = derivedUnitFacade.getBarcode();
1095
        }
1096

    
1097
        UnitAssociationParser unitParser = new UnitAssociationParser(state.getPrefix(), state.getReport(),
1098
                state.getCdmRepository());
1099
        UnitAssociationWrapper unitAssociationWrapper = null;
1100

    
1101
        unitAssociationWrapper = unitParser.parseSiblings(unitId, dnaSource);
1102

    
1103
        DerivedUnit currentUnit = state.getDerivedUnitBase();
1104
        // DerivationEvent currentDerivedFrom = currentUnit.getDerivedFrom();
1105
        FieldUnit currentFieldUnit = derivedUnitFacade.getFieldUnit(false);
1106
        if (unitAssociationWrapper != null) {
1107
            NodeList associatedUnits = unitAssociationWrapper.getAssociatedUnits();
1108
            if (associatedUnits != null) {
1109
                for (int m = 0; m < associatedUnits.getLength(); m++) {
1110
                    if (associatedUnits.item(m) instanceof Element) {
1111
                        state.reset();
1112
                        String associationType = AbcdParseUtility
1113
                                .parseFirstTextContent(((Element) associatedUnits.item(m))
1114
                                        .getElementsByTagName(unitAssociationWrapper.getPrefix() + "AssociationType"));
1115
                        Abcd206XMLFieldGetter fieldGetter = new Abcd206XMLFieldGetter(state.getDataHolder(), unitAssociationWrapper.getPrefix());
1116
                        Abcd206ImportParser.setUnitPropertiesXML((Element) associatedUnits.item(m),
1117
                                fieldGetter,
1118
                                state);
1119
                        // logger.debug("derived unit: " +
1120
                        // state.getDerivedUnitBase().toString() + " associated
1121
                        // unit: " +state.getDataHolder().getKindOfUnit() + ", "
1122
                        // + state.getDataHolder().accessionNumber + ", " +
1123
                        // state.getDataHolder().getRecordBasis() + ", " +
1124
                        // state.getDataHolder().getUnitID());
1125
                        URI lastAccessPoint = state.getActualAccessPoint();
1126
                        state.setActualAccessPoint(dnaSource);
1127
                        String oldPrefix = state.getPrefix();
1128
                        state.setPrefix(unitAssociationWrapper.getPrefix());
1129
                        handleSingleUnit(state, associatedUnits.item(m), false);
1130
                        state.setActualAccessPoint(lastAccessPoint);
1131
                        state.setPrefix(oldPrefix);
1132
                        DerivedUnit associatedUnit = state.getDerivedUnitBase();
1133
                        FieldUnit associatedFieldUnit = null;
1134
                        java.util.Collection<FieldUnit> associatedFieldUnits = state.getCdmRepository()
1135
                                .getOccurrenceService().findFieldUnits(associatedUnit.getUuid(), null);
1136
                        // ignore field unit if associated unit has more than
1137
                        // one
1138
                        if (associatedFieldUnits.size() > 1) {
1139
                            state.getReport()
1140
                                    .addInfoMessage(String.format("%s has more than one field unit.", associatedUnit));
1141
                        } else if (associatedFieldUnits.size() == 1) {
1142
                            associatedFieldUnit = associatedFieldUnits.iterator().next();
1143
                        }
1144
                        // parent-child relation:
1145
                        if (associationType != null && (associationType.contains("individual")
1146
                                || associationType.contains("culture") || associationType.contains("sample")
1147
                                || associationType.contains("isolated"))) {
1148
                            DerivationEvent updatedDerivationEvent = DerivationEvent.NewSimpleInstance(currentUnit,
1149
                                    associatedUnit, DerivationEventType.ACCESSIONING());
1150

    
1151
                            updatedDerivationEvent.setDescription(associationType);
1152
                            if (associatedFieldUnit != null && !associatedFieldUnit.equals(currentFieldUnit) && currentFieldUnit != null) {
1153
                                associatedFieldUnit.removeDerivationEvent(updatedDerivationEvent);
1154
                                if ((associatedFieldUnit.getGatheringEvent() != null && associatedFieldUnit.getGatheringEvent().getActor() != null) && (currentFieldUnit.getGatheringEvent() != null && currentFieldUnit.getGatheringEvent().getActor() == null)){
1155
                                    currentFieldUnit.getGatheringEvent().setActor(associatedFieldUnit.getGatheringEvent().getActor());
1156
                                }
1157
                                if (associatedFieldUnit.getFieldNumber() != null && currentFieldUnit.getFieldNumber() == null){
1158
                                    currentFieldUnit.setFieldNumber(associatedFieldUnit.getFieldNumber());
1159
                                }
1160

    
1161

    
1162

    
1163
                                SpecimenDeleteConfigurator deleteConfig = new SpecimenDeleteConfigurator();
1164
                                deleteConfig.setDeleteChildren(false);
1165
                                DeleteResult result = state.getCdmRepository().getOccurrenceService()
1166
                                        .delete(associatedFieldUnit, deleteConfig);
1167
                                state.setFieldUnit(currentFieldUnit);
1168

    
1169
                                // }
1170
                                if (updatedDerivationEvent.getOriginals().isEmpty()) {
1171
                                    // state.getCdmRepository().getOccurrenceService().deleteDerivationEvent(updatedDerivationEvent);
1172
                                }
1173
                            }else{
1174
                                state.setLastFieldUnit(associatedFieldUnit);
1175
                            }
1176
                            state.getReport().addDerivate(associatedUnit, currentUnit, state.getConfig());
1177
                        }
1178
                        save(associatedUnit, state);
1179

    
1180
                    }
1181
                }
1182
            }
1183
        }
1184
        state.reset();
1185
        state.setDerivedUnitBase(currentUnit);
1186

    
1187
    }
1188

    
1189
    /**
1190
     * @param derivedUnitFacade
1191
     * @param sour
1192
     * @return
1193
     */
1194
    private boolean sourceNotLinkedToElement(DerivedUnitFacade derivedUnitFacade, OriginalSourceBase source) {
1195
        Set<IdentifiableSource> linkedSources = derivedUnitFacade.getSources();
1196
        for (IdentifiableSource is : linkedSources) {
1197
            if (is.getCitation() != null && source.getCitation() != null
1198
                    && is.getCitation().getTitleCache().equalsIgnoreCase(source.getCitation().getTitleCache())) {
1199
                String isDetail = is.getCitationMicroReference();
1200
                if ((StringUtils.isBlank(isDetail) && StringUtils.isBlank(source.getCitationMicroReference()))
1201
                        || (isDetail != null && isDetail.equalsIgnoreCase(source.getCitationMicroReference()))) {
1202
                    return false;
1203
                }
1204
            }
1205
        }
1206
        return true;
1207
    }
1208

    
1209

    
1210

    
1211
    /**
1212
     * setCollectionData : store the collection object into the
1213
     * derivedUnitFacade
1214
     *
1215
     * @param state
1216
     */
1217
    protected void setCollectionData(Abcd206ImportState state, DerivedUnitFacade derivedUnitFacade) {
1218
        Abcd206ImportConfigurator config = state.getConfig();
1219
        SpecimenImportUtility.setUnitID(derivedUnitFacade.innerDerivedUnit(), state.getDataHolder().getUnitID(),
1220
                config);
1221
        if (!config.isMapUnitIdToAccessionNumber()) {
1222
            derivedUnitFacade.setAccessionNumber(NB(state.getDataHolder().accessionNumber));
1223
        }
1224
        // derivedUnitFacade.setCollectorsNumber(NB(state.getDataHolder().collectorsNumber));
1225

    
1226
        /*
1227
         * INSTITUTION & COLLECTION
1228
         */
1229
        // manage institution
1230
        Institution institution = this.getInstitution(NB(state.getDataHolder().institutionCode), state);
1231
        // manage collection
1232
        Collection collection = this.getCollection(institution, NB(state.getDataHolder().collectionCode), state);
1233
        // link specimen & collection
1234
        derivedUnitFacade.setCollection(collection);
1235
    }
1236

    
1237
    /**
1238
     * getFacade : get the DerivedUnitFacade based on the recordBasis
1239
     *
1240
     * @param state
1241
     *
1242
     * @return DerivedUnitFacade
1243
     */
1244
    @Override
1245
    protected DerivedUnitFacade getFacade(Abcd206ImportState state) {
1246
        if (logger.isDebugEnabled()) {
1247
            logger.info("getFacade()");
1248
        }
1249
        SpecimenOrObservationType type = null;
1250
        DefinedTerm kindOfUnit = null;
1251

    
1252
        // create specimen
1253
        if (NB((state.getDataHolder()).getRecordBasis()) != null) {
1254
            if (state.getDataHolder().getRecordBasis().toLowerCase().indexOf("living") > -1) {
1255
                type = SpecimenOrObservationType.LivingSpecimen;
1256
            } else if (state.getDataHolder().getRecordBasis().toLowerCase().startsWith("s")
1257
                    || state.getDataHolder().getRecordBasis().toLowerCase().indexOf("specimen") > -1) {// specimen
1258
                type = SpecimenOrObservationType.PreservedSpecimen;
1259
            } else if (state.getDataHolder().getRecordBasis().toLowerCase().startsWith("o")
1260
                    || state.getDataHolder().getRecordBasis().toLowerCase().indexOf("observation") > -1) {
1261
                if (state.getDataHolder().getRecordBasis().toLowerCase().contains("machine")
1262
                        && state.getDataHolder().getRecordBasis().toLowerCase().contains("observation")) {
1263
                    type = SpecimenOrObservationType.MachineObservation;
1264
                } else if (state.getDataHolder().getRecordBasis().toLowerCase().contains("human")
1265
                        && state.getDataHolder().getRecordBasis().toLowerCase().contains("observation")) {
1266
                    type = SpecimenOrObservationType.HumanObservation;
1267
                } else {
1268
                    type = SpecimenOrObservationType.Observation;
1269
                }
1270
            } else if (state.getDataHolder().getRecordBasis().toLowerCase().indexOf("fossil") > -1) {
1271
                type = SpecimenOrObservationType.Fossil;
1272
            } else if (state.getDataHolder().getRecordBasis().toLowerCase().indexOf("materialsample") > -1) {
1273
                type = SpecimenOrObservationType.MaterialSample;
1274
            } else if (state.getDataHolder().getRecordBasis().toLowerCase().indexOf("sample") > -1) {
1275
                type = SpecimenOrObservationType.TissueSample;
1276
            }
1277

    
1278
            if (type == null) {
1279
                logger.info("The basis of record does not seem to be known: " + state.getDataHolder().getRecordBasis());
1280
                type = SpecimenOrObservationType.DerivedUnit;
1281
            }
1282
        } else {
1283
            logger.info("The basis of record is null");
1284
            type = SpecimenOrObservationType.DerivedUnit;
1285
        }
1286

    
1287
        if (NB((state.getDataHolder()).getKindOfUnit()) != null) {
1288
            kindOfUnit = getKindOfUnit(state, null, state.getDataHolder().getKindOfUnit().toLowerCase(), null, null,
1289
                    null);
1290
            if (kindOfUnit == null) {
1291
                if (state.getDataHolder().getKindOfUnit().toLowerCase().indexOf("clone") > -1) {
1292
                    kindOfUnit = getKindOfUnit(state, null, "clone culture", "clone culture", "cc", null);
1293
                } else if (state.getDataHolder().getKindOfUnit().toLowerCase().startsWith("live")) {
1294
                    kindOfUnit = getKindOfUnit(state, null, "live sample", "live sample", "ls", null);
1295
                } else if (state.getDataHolder().getKindOfUnit().toLowerCase().startsWith("microscopic slide")) {
1296
                    kindOfUnit = getKindOfUnit(state, null, "microscopic slide", "microscopic slide", "ms", null);
1297
                }
1298

    
1299
                if (kindOfUnit == null) {
1300
                    logger.info("The kind of unit does not seem to be known: " + state.getDataHolder().getKindOfUnit());
1301

    
1302
                }
1303
            }
1304
        } else {
1305
            logger.info("The kind of unit is null");
1306

    
1307
        }
1308
        DerivedUnitFacade derivedUnitFacade = DerivedUnitFacade.NewInstance(type);
1309
        derivedUnitFacade.setFieldUnit(state.getFieldUnit(state.getDataHolder().getFieldNumber()));
1310
        derivedUnitFacade.setDerivedUnitKindOfUnit(kindOfUnit);
1311
        derivedUnitFacade.setPreferredStableUri(state.getDataHolder().getPreferredStableUri());
1312
        // derivedUnitFacade.setDerivedUnitKindOfUnit(kindOfUnit);
1313
        return derivedUnitFacade;
1314
    }
1315

    
1316
    private void getCollectorsFromXML(Element root, Abcd206XMLFieldGetter abcdFieldGetter, Abcd206ImportState state) {
1317
        NodeList group;
1318

    
1319
        group = root.getChildNodes();
1320
        for (int i = 0; i < group.getLength(); i++) {
1321
            if (group.item(i).getNodeName().equals(state.getPrefix() + "Identifications")) {
1322
                group = group.item(i).getChildNodes();
1323
                break;
1324
            }
1325
        }
1326
        // state.getDataHolder().gatheringAgents = "";
1327

    
1328
        abcdFieldGetter.getType(root);
1329
        abcdFieldGetter.getGatheringPeople(root);
1330
    }
1331

    
1332

    
1333
    /**
1334
     * Load the list of names from the ABCD file and save them
1335
     *
1336
     * @param state
1337
     *            : the current ABCD import state
1338
     * @param unitsList
1339
     *            : the unit list from the ABCD file
1340
     * @param abcdFieldGetter
1341
     *            : the ABCD parser
1342
     */
1343
    private void prepareCollectors(Abcd206ImportState state, NodeList unitsList,
1344
            Abcd206XMLFieldGetter abcdFieldGetter) {
1345

    
1346
        TeamOrPersonBase<?> teamOrPerson = null;
1347
        Team team = null;
1348
        // ImportHelper.setOriginalSource(teamOrPerson,
1349
        // state.getConfig().getSourceReference(), collector, "Collector");
1350
        for (int i = 0; i < unitsList.getLength(); i++) {
1351
            this.getCollectorsFromXML((Element) unitsList.item(i), abcdFieldGetter, state);
1352
            if (!(state.getDataHolder().gatheringAgentsList.isEmpty())) {
1353
                if (state.getDataHolder().gatheringAgentsList.size() == 1) {
1354
                    teamOrPerson = parseAuthorString(state.getDataHolder().gatheringAgentsList.get(0));
1355
                } else {
1356
                    team = new Team();
1357
                    for (String collector : state.getDataHolder().gatheringAgentsList) {
1358
                        teamOrPerson = parseAuthorString(collector);
1359
                        if (teamOrPerson instanceof Person) {
1360
                            team.addTeamMember((Person) teamOrPerson);
1361
                        } else {
1362
                            for (Person person : ((Team) teamOrPerson).getTeamMembers()) {
1363
                                team.addTeamMember(person);
1364
                            }
1365
                        }
1366
                    }
1367
                    if (team.getTeamMembers() != null && team.getTeamMembers().isEmpty()){
1368
                        teamOrPerson = team;
1369
                    }
1370
                }
1371
                if (!state.getPersonStore().containsId(teamOrPerson.getTitleCache())) {
1372
                    state.getPersonStore().put(teamOrPerson.getTitleCache(), teamOrPerson);
1373
                    if (logger.isDebugEnabled()) {
1374
                        logger.debug("Stored author " + state.getDataHolder().gatheringAgentsList.toString());
1375
                    }
1376
                    logger.warn("Not imported author with duplicated aut_id "
1377
                            + state.getDataHolder().gatheringAgentsList.toString());
1378
                }
1379
            }
1380
            if (!StringUtils.isBlank(state.getDataHolder().gatheringAgentsText)
1381
                    && state.getDataHolder().gatheringAgentsList.isEmpty()) {
1382
                teamOrPerson = parseAuthorString(state.getDataHolder().gatheringAgentsText);
1383
                // if (teamOrPerson instanceof Person) {
1384
                // //team.addTeamMember((Person) teamOrPerson);
1385
                // } else {
1386
                // team = new Team();
1387
                // for (Person person : ((Team) teamOrPerson).getTeamMembers())
1388
                // {
1389
                // team.addTeamMember(person);
1390
                // }
1391
                // }
1392
                if (!state.getPersonStore().containsId(teamOrPerson.getTitleCache())) {
1393
                    state.getPersonStore().put(teamOrPerson.getTitleCache(), teamOrPerson);
1394
                    if (logger.isDebugEnabled()) {
1395
                        logger.debug("Stored author " + state.getDataHolder().gatheringAgentsText);
1396
                    }
1397
                    logger.warn("Not imported author with duplicated aut_id "
1398
                            + state.getDataHolder().gatheringAgentsList.toString());
1399
                }
1400
            }
1401

    
1402
        }
1403

    
1404
        // List<String> collectorsU = new ArrayList<String>(new
1405
        // HashSet<String>(collectors));
1406
        // List<String> teamsU = new ArrayList<String>(new
1407
        // HashSet<String>(teams));
1408
        //
1409
        //
1410
        // //existing teams in DB
1411
        // Map<String,Team> titleCacheTeam = new HashMap<String, Team>();
1412
        // List<UuidAndTitleCache<Team>> hiberTeam = new
1413
        // ArrayList<UuidAndTitleCache<Team>>();//getAgentService().getTeamUuidAndTitleCache();
1414

    
1415
        // Set<UUID> uuids = new HashSet<UUID>();
1416
        // for (UuidAndTitleCache<Team> hibernateT:hiberTeam){
1417
        // uuids.add(hibernateT.getUuid());
1418
        // }
1419
        // if (!uuids.isEmpty()){
1420
        // List<AgentBase> existingTeams = getAgentService().find(uuids);
1421
        // for (AgentBase<?> existingP:existingTeams){
1422
        // titleCacheTeam.put(existingP.getTitleCache(),CdmBase.deproxy(existingP,Team.class));
1423
        // }
1424
        // }
1425

    
1426
        // Map<String,UUID> teamMap = new HashMap<String, UUID>();
1427
        // for (UuidAndTitleCache<Team> uuidt:hiberTeam){
1428
        // teamMap.put(uuidt.getTitleCache(), uuidt.getUuid());
1429
        // }
1430

    
1431
        // existing persons in DB
1432
        // List<UuidAndTitleCache<Person>> hiberPersons = new
1433
        // ArrayList<UuidAndTitleCache<Person>>();//getAgentService().getPersonUuidAndTitleCache();
1434
        // Map<String,Person> titleCachePerson = new HashMap<String, Person>();
1435
        // uuids = new HashSet<UUID>();
1436
        // for (UuidAndTitleCache<Person> hibernateP:hiberPersons){
1437
        // uuids.add(hibernateP.getUuid());
1438
        // }
1439
        //
1440
        // if (!uuids.isEmpty()){
1441
        // List<AgentBase> existingPersons = getAgentService().find(uuids);
1442
        // for (AgentBase<?> existingP:existingPersons){
1443
        // titleCachePerson.put(existingP.getTitleCache(),CdmBase.deproxy(existingP,Person.class));
1444
        // }
1445
        // }
1446
        //
1447
        // Map<String,UUID> personMap = new HashMap<String, UUID>();
1448
        // for (UuidAndTitleCache<Person> person:hiberPersons){
1449
        // personMap.put(person.getTitleCache(), person.getUuid());
1450
        // }
1451
        //
1452
        // java.util.Collection<Person> personToadd = new ArrayList<Person>();
1453
        // java.util.Collection<Team> teamToAdd = new ArrayList<Team>();
1454
        //
1455
        // for (String collector:collectorsU){
1456
        // Person p = Person.NewInstance();
1457
        // p.setTitleCache(collector,true);
1458
        // if (!personMap.containsKey(p.getTitleCache())){
1459
        // personToadd.add(p);
1460
        // }
1461
        // }
1462
        // for (String team:teamsU){
1463
        // Team p = Team.NewInstance();
1464
        // p.setTitleCache(team,true);
1465
        // if (!teamMap.containsKey(p.getTitleCache())){
1466
        // teamToAdd.add(p);
1467
        // }
1468
        // }
1469
        //
1470
        // if(!personToadd.isEmpty()){
1471
        // for (Person agent: personToadd){
1472
        // save(agent, state);
1473
        // titleCachePerson.put(agent.getTitleCache(),CdmBase.deproxy(agent,
1474
        // Person.class) );
1475
        // }
1476
        // }
1477
        //
1478
        // Person ptmp ;
1479
        // Map <String,Integer>teamdone = new HashMap<String, Integer>();
1480
        // for (List<String> collteam: collectorinteams){
1481
        // if (!teamdone.containsKey(StringUtils.join(collteam.toArray(),"-"))){
1482
        // Team team = new Team();
1483
        // boolean em =true;
1484
        // for (String collector:collteam){
1485
        // ptmp = Person.NewInstance();
1486
        // ptmp.setTitleCache(collector,true);
1487
        // Person p2 = titleCachePerson.get(ptmp.getTitleCache());
1488
        // team.addTeamMember(p2);
1489
        // em=false;
1490
        // }
1491
        // if (!em) {
1492
        // teamToAdd.add(team);
1493
        // }
1494
        // teamdone.put(StringUtils.join(collteam.toArray(),"-"),0);
1495
        // }
1496
        // }
1497
        //
1498
        // if(!teamToAdd.isEmpty()){
1499
        // for (Team agent: teamToAdd){
1500
        // save(agent, state);
1501
        // titleCacheTeam.put(agent.getTitleCache(), CdmBase.deproxy(
1502
        // agent,Team.class) );
1503
        // }
1504
        // }
1505

    
1506
        // ((Abcd206ImportConfigurator)
1507
        // state.getConfig()).setTeams(titleCacheTeam);
1508
        // ((Abcd206ImportConfigurator)
1509
        // state.getConfig()).setPersons(titleCachePerson);
1510
    }
1511

    
1512
    @Override
1513
    protected boolean doCheck(Abcd206ImportState state) {
1514
        logger.warn("Checking not yet implemented for " + this.getClass().getSimpleName());
1515
        return true;
1516
    }
1517

    
1518
    @Override
1519
    protected boolean isIgnore(Abcd206ImportState state) {
1520
        return false;
1521
    }
1522

    
1523
    @Override
1524
    protected DefinedTerm getKindOfUnit(Abcd206ImportState state, UUID uuid, String label, String description,
1525
            String labelAbbrev, TermVocabulary<DefinedTerm> voc) {
1526

    
1527
        DefinedTerm unit = null;
1528

    
1529
        if (uuid == null) {
1530
            unit = this.kindOfUnitsMap.get(label.toLowerCase());
1531
        } else {
1532
            unit = state.getKindOfUnit(uuid);
1533

    
1534
        }
1535
        if (unit == null) {
1536
            unit = (DefinedTerm) getTermService().find(uuid);
1537
            if (unit == null) {
1538
                if (uuid == null) {
1539
                    uuid = UUID.randomUUID();
1540
                }
1541
                unit = DefinedTerm.NewKindOfUnitInstance(description, label, labelAbbrev);
1542
                unit.setUuid(uuid);
1543
                if (voc == null) {
1544
                    boolean isOrdered = false;
1545
                    voc = getVocabulary(state, TermType.KindOfUnit, uuidUserDefinedKindOfUnitVocabulary,
1546
                            "User defined vocabulary for kind-of-units", "User Defined Measurement kind-of-units", null,
1547
                            null, isOrdered, unit);
1548
                }
1549
                voc.addTerm(unit);
1550
                getTermService().save(unit);
1551
            }
1552
            state.putKindOfUnit(unit);
1553
            kindOfUnitsMap.put(unit.getLabel().toLowerCase(), unit);
1554
        }
1555
        return unit;
1556
    }
1557

    
1558

    
1559

    
1560
}
(2-2/15)