Project

General

Profile

Download (56.8 KB) Statistics
| Branch: | 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.iapt;
11

    
12
import com.fasterxml.jackson.core.JsonProcessingException;
13
import com.fasterxml.jackson.databind.ObjectMapper;
14
import eu.etaxonomy.cdm.api.facade.DerivedUnitFacade;
15
import eu.etaxonomy.cdm.common.CdmUtils;
16
import eu.etaxonomy.cdm.io.mexico.SimpleExcelTaxonImport;
17
import eu.etaxonomy.cdm.io.mexico.SimpleExcelTaxonImportState;
18
import eu.etaxonomy.cdm.model.agent.Institution;
19
import eu.etaxonomy.cdm.model.agent.Person;
20
import eu.etaxonomy.cdm.model.agent.TeamOrPersonBase;
21
import eu.etaxonomy.cdm.model.common.*;
22
import eu.etaxonomy.cdm.model.name.*;
23
import eu.etaxonomy.cdm.model.occurrence.*;
24
import eu.etaxonomy.cdm.model.occurrence.Collection;
25
import eu.etaxonomy.cdm.model.reference.Reference;
26
import eu.etaxonomy.cdm.model.reference.ReferenceFactory;
27
import eu.etaxonomy.cdm.model.taxon.*;
28
import eu.etaxonomy.cdm.strategy.parser.NonViralNameParserImpl;
29
import org.apache.commons.lang.ArrayUtils;
30
import org.apache.commons.lang.StringEscapeUtils;
31
import org.apache.commons.lang.StringUtils;
32
import org.apache.log4j.Level;
33
import org.apache.log4j.Logger;
34
import org.joda.time.DateTimeFieldType;
35
import org.joda.time.Partial;
36
import org.joda.time.format.DateTimeFormat;
37
import org.joda.time.format.DateTimeFormatter;
38
import org.springframework.stereotype.Component;
39

    
40
import java.util.*;
41
import java.util.regex.Matcher;
42
import java.util.regex.Pattern;
43

    
44
/**
45
 * @author a.mueller
46
 * @created 05.01.2016
47
 */
48

    
49
@Component("iAPTExcelImport")
50
public class IAPTExcelImport<CONFIG extends IAPTImportConfigurator> extends SimpleExcelTaxonImport<CONFIG> {
51
    private static final long serialVersionUID = -747486709409732371L;
52
    private static final Logger logger = Logger.getLogger(IAPTExcelImport.class);
53
    public static final String ANNOTATION_MARKER_STRING = "[*]";
54

    
55

    
56
    private static UUID ROOT_UUID = UUID.fromString("4137fd2a-20f6-4e70-80b9-f296daf51d82");
57

    
58
    private static NonViralNameParserImpl nameParser = NonViralNameParserImpl.NewInstance();
59

    
60
    private final static String REGISTRATIONNO_PK= "RegistrationNo_Pk";
61
    private final static String HIGHERTAXON= "HigherTaxon";
62
    private final static String FULLNAME= "FullName";
63
    private final static String AUTHORSSPELLING= "AuthorsSpelling";
64
    private final static String LITSTRING= "LitString";
65
    private final static String REGISTRATION= "Registration";
66
    private final static String TYPE= "Type";
67
    private final static String CAVEATS= "Caveats";
68
    private final static String FULLBASIONYM= "FullBasionym";
69
    private final static String FULLSYNSUBST= "FullSynSubst";
70
    private final static String NOTESTXT= "NotesTxt";
71
    private final static String REGDATE= "RegDate";
72
    private final static String NAMESTRING= "NameString";
73
    private final static String BASIONYMSTRING= "BasionymString";
74
    private final static String SYNSUBSTSTR= "SynSubstStr";
75
    private final static String AUTHORSTRING= "AuthorString";
76

    
77
    private  static List<String> expectedKeys= Arrays.asList(new String[]{
78
            REGISTRATIONNO_PK, HIGHERTAXON, FULLNAME, AUTHORSSPELLING, LITSTRING, REGISTRATION, TYPE, CAVEATS, FULLBASIONYM, FULLSYNSUBST, NOTESTXT, REGDATE, NAMESTRING, BASIONYMSTRING, SYNSUBSTSTR, AUTHORSTRING});
79

    
80
    private static final Pattern nomRefTokenizeP = Pattern.compile("^(?<title>.*):\\s(?<detail>[^\\.:]+)\\.(?<date>.*?)(?:\\s\\((?<issue>[^\\)]*)\\)\\s*)?\\.?$");
81
    private static final Pattern[] datePatterns = new Pattern[]{
82
            // NOTE:
83
            // The order of the patterns is extremely important!!!
84
            //
85
            // all patterns cover the years 1700 - 1999
86
            Pattern.compile("^(?<year>1[7,8,9][0-9]{2})$"), // only year, like '1969'
87
            Pattern.compile("^(?<monthName>\\p{L}+\\.?)\\s(?<day>[0-9]{1,2})(?:st|rd|th)?\\.?,?\\s(?<year>(?:1[7,8,9])?[0-9]{2})$"), // full date like April 12, 1969 or april 12th 1999
88
            Pattern.compile("^(?<monthName>\\p{L}+\\.?),?\\s?(?<year>(?:1[7,8,9])?[0-9]{2})$"), // April 99 or April, 1999 or Apr. 12
89
            Pattern.compile("^(?<day>[0-9]{1,2})([\\.\\-/])(\\s?)(?<month>[0-1]?[0-9])\\2\\3(?<year>(?:1[7,8,9])?[0-9]{2})$"), // full date like 12.04.1969 or 12. 04. 1969 or 12/04/1969 or 12-04-1969
90
            Pattern.compile("^(?<day>[0-9]{1,2})([\\.\\-/])(?<monthName>[IVX]{1,2})\\2(?<year>(?:1[7,8,9])?[0-9]{2})$"), // full date like 12-VI-1969
91
            Pattern.compile("^(?:(?<day>[0-9]{1,2})(?:\\sde)?\\s)?(?<monthName>\\p{L}+)(?:\\sde)?\\s(?<year>(?:1[7,8,9])?[0-9]{2})$"), // full and partial date like 12 de Enero de 1999 or Enero de 1999
92
            Pattern.compile("^(?<month>[0-1]?[0-9])([\\.\\-/])(?<year>(?:1[7,8,9])?[0-9]{2})$"), // partial date like 04.1969 or 04/1969 or 04-1969
93
            Pattern.compile("^(?<year>(?:1[7,8,9])?[0-9]{2})([\\.\\-/])(?<month>[0-1]?[0-9])$"),//  partial date like 1999-04
94
            Pattern.compile("^(?<monthName>[IVX]{1,2})([\\.\\-/])(?<year>(?:1[7,8,9])?[0-9]{2})$"), // partial date like VI-1969
95
            Pattern.compile("^(?<day>[0-9]{1,2})(?:[\\./]|th|rd|st)?\\s(?<monthName>\\p{L}+\\.?),?\\s?(?<year>(?:1[7,8,9])?[0-9]{2})$"), // full date like 12. April 1969 or april 1999 or 22 Dec.1999
96
        };
97
    protected static final Pattern typeSpecimenSplitPattern =  Pattern.compile("^(?:\"*[Tt]ype: (?<fieldUnit>.*?))(?:[Hh]olotype:(?<holotype>.*?)\\.?)?(?:[Ii]sotype[^:]*:(?<isotype>.*)\\.?)?\\.?$");
98

    
99
    private static final Pattern typeNameBasionymPattern =  Pattern.compile("\\([Bb]asionym\\s?\\:\\s?(?<basionymName>[^\\)]*).*$");
100
    private static final Pattern typeNameNotePattern =  Pattern.compile("\\[([^\\[]*)"); // matches the inner of '[...]'
101
    private static final Pattern typeNameSpecialSplitPattern =  Pattern.compile("(?<note>.*\\;.*?)\\:(?<agent>)\\;(<name>.*)");
102

    
103
    protected static final Pattern collectorPattern =  Pattern.compile(".*?(?<fullStr1>\\([Ll]eg\\.\\s+(?<data1>[^\\)]*)\\)).*$|.*?(?<fullStr2>\\s[Ll]eg\\.\\:?\\s+(?<data2>.*?)\\.?)$|^(?<fullStr3>[Ll]eg\\.\\:?\\s+(?<data3>.*?)\\.?)");
104
    private static final Pattern collectionDataPattern =  Pattern.compile("^(?<collector>[^,]*),\\s?(?<detail>.*?)\\.?$");
105
    private static final Pattern collectorsNumber =  Pattern.compile("^([nN]o\\.\\s.*)$");
106

    
107
    // AccessionNumbers: , #.*, n°:?, 96/3293, No..*, -?\w{1,3}-[0-9\-/]*
108
    private static final Pattern accessionNumberOnlyPattern = Pattern.compile("^(?<accNumber>(?:n°\\:?\\s?|#|No\\.?\\s?)?[\\d\\w\\-/]*)$");
109

    
110
    private static final Pattern[] specimenTypePatterns = new Pattern[]{
111
            Pattern.compile("^(?<colCode>[A-Z]+|CPC Micropaleontology Lab\\.?)\\s+(?:\\((?<institute>.*[^\\)])\\))(?<accNumber>.*)?$"), // like: GAUF (Gansu Agricultural University) No. 1207-1222
112
            Pattern.compile("^(?<colCode>[A-Z]+|CPC Micropaleontology Lab\\.?)\\s+(?:Coll\\.\\s(?<subCollection>[^\\.,;]*)(.))(?<accNumber>.*)?$"), // like KASSEL Coll. Krasske, Praep. DII 78
113
            Pattern.compile("^(?:in\\s)?(?<institute>[Cc]oll\\.\\s.*?)(?:\\s+(?<accNumber>(Praep\\.|slide|No\\.|Inv\\. Nr\\.|Nr\\.).*))?$"), // like Coll. Lange-Bertalot, Bot. Inst., Univ. Frankfurt/Main, Germany Praep. Neukaledonien OTL 62
114
            Pattern.compile("^(?<institute>Inst\\.\\s.*?)\\s+(?<accNumber>N\\s.*)?$"), // like Inst. Geological Sciences, Acad. Sci. Belarus, Minsk N 212 A
115
            Pattern.compile("^(?<colCode>[A-Z]+)(?:\\s+(?<accNumber>.*))?$"), // identifies the Collection code and takes the rest as accessionNumber if any
116
    };
117

    
118

    
119
    private static final Pattern registrationPattern = Pattern.compile("^Registration date\\:\\s(?<regdate>\\d\\d\\.\\d\\d\\.\\d\\d); no\\.\\:\\s(?<regid>\\d+);\\soffice\\:\\s(?<office>.*?)\\.(?:\\s\\[Form no\\.\\:\\s(?<formNo>d+)\\])?$"); // Registration date: 29.06.98; no.: 2922; office: Berlin.
120

    
121
    private static Map<String, Integer> monthFromNameMap = new HashMap<>();
122

    
123
    static {
124
        String[] ck = new String[]{"leden", "únor", "březen", "duben", "květen", "červen", "červenec ", "srpen", "září", "říjen", "listopad", "prosinec"};
125
        String[] fr = new String[]{"janvier", "février", "mars", "avril", "mai", "juin", "juillet", "août", "septembre", "octobre", "novembre", "décembre"};
126
        String[] de = new String[]{"januar", "februar", "märz", "april", "mai", "juni", "juli", "august", "september", "oktober", "november", "dezember"};
127
        String[] en = new String[]{"january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december"};
128
        String[] it = new String[]{"gennaio", "febbraio", "marzo", "aprile", "maggio", "giugno", "luglio", "agosto", "settembre", "ottobre", "novembre", "dicembre"};
129
        String[] sp = new String[]{"enero", "febrero", "marzo", "abril", "mayo", "junio", "julio", "agosto", "septiembre", "octubre", "noviembre", "diciembre"};
130
        String[] de_abbrev = new String[]{"jan.", "feb.", "märz", "apr.", "mai", "jun.", "jul.", "aug.", "sept.", "okt.", "nov.", "dez."};
131
        String[] en_abbrev = new String[]{"jan.", "feb.", "mar.", "apr.", "may", "jun.", "jul.", "aug.", "sep.", "oct.", "nov.", "dec."};
132
        String[] port = new String[]{"Janeiro", "Fevereiro", "Março", "Abril", "Maio", "Junho", "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro"};
133
        String[] rom_num = new String[]{"i", "ii", "iii", "iv", "v", "vi", "vii", "viii", "ix", "x", "xi", "xii"};
134

    
135
        String[][] perLang =  new String[][]{ck, de, fr, en, it, sp, port, de_abbrev, en_abbrev, rom_num};
136

    
137
        for (String[] months: perLang) {
138
            for(int m = 1; m < 13; m++){
139
                monthFromNameMap.put(months[m - 1].toLowerCase(), m);
140
            }
141
        }
142

    
143
        // special cases
144
        monthFromNameMap.put("mar", 3);
145
        monthFromNameMap.put("dec", 12);
146
        monthFromNameMap.put("februari", 2);
147
        monthFromNameMap.put("març", 3);
148
    }
149

    
150

    
151
    DateTimeFormatter formatterYear = DateTimeFormat.forPattern("yyyy");
152

    
153
    private Map<String, Collection> collectionMap = new HashMap<>();
154

    
155
    private ExtensionType extensionTypeIAPTRegData = null;
156

    
157
    private Set<String> nameSet = new HashSet<>();
158
    private DefinedTermBase duplicateRegistration = null;
159

    
160
    enum TypesName {
161
        fieldUnit, holotype, isotype;
162

    
163
        public SpecimenTypeDesignationStatus status(){
164
            switch (this) {
165
                case holotype:
166
                    return SpecimenTypeDesignationStatus.HOLOTYPE();
167
                case isotype:
168
                    return SpecimenTypeDesignationStatus.ISOTYPE();
169
                default:
170
                    return null;
171
            }
172
        }
173
    }
174

    
175
    private MarkerType markerTypeFossil = null;
176
    private Rank rankUnrankedSupraGeneric = null;
177
    private Rank familyIncertisSedis = null;
178
    private AnnotationType annotationTypeCaveats = null;
179

    
180
    private Reference bookVariedadesTradicionales = null;
181

    
182
    /**
183
     * HACK for unit simple testing
184
     */
185
    boolean _testMode = System.getProperty("TEST_MODE") != null;
186

    
187
    private Taxon makeTaxon(HashMap<String, String> record, SimpleExcelTaxonImportState<CONFIG> state,
188
                            TaxonNode higherTaxonNode, boolean isFossil) {
189

    
190
        String regNumber = getValue(record, REGISTRATIONNO_PK, false);
191
        String regStr = getValue(record, REGISTRATION, true);
192
        String titleCacheStr = getValue(record, FULLNAME, true);
193
        String nameStr = getValue(record, NAMESTRING, true);
194
        String authorStr = getValue(record, AUTHORSTRING, true);
195
        String nomRefStr = getValue(record, LITSTRING, true);
196
        String authorsSpelling = getValue(record, AUTHORSSPELLING, true);
197
        String notesTxt = getValue(record, NOTESTXT, true);
198
        String caveats = getValue(record, CAVEATS, true);
199
        String fullSynSubstStr = getValue(record, FULLSYNSUBST, true);
200
        String fullBasionymStr = getValue(record, FULLBASIONYM, true);
201
        String basionymNameStr = getValue(record, FULLBASIONYM, true);
202
        String synSubstStr = getValue(record, SYNSUBSTSTR, true);
203
        String typeStr = getValue(record, TYPE, true);
204

    
205

    
206
        String nomRefTitle = null;
207
        String nomRefDetail;
208
        String nomRefPupDate = null;
209
        String nomRefIssue = null;
210
        Partial pupDate = null;
211

    
212
        boolean restoreOriginalReference = false;
213
        boolean nameIsValid = true;
214

    
215
        // preprocess nomRef: separate citation, reference detail, publishing date
216
        if(!StringUtils.isEmpty(nomRefStr)){
217
            nomRefStr = nomRefStr.trim();
218

    
219
            // handle the special case which is hard to parse:
220
            //
221
            // Las variedades tradicionales de frutales de la Cuenca del Río Segura. Catálogo Etnobotánico (1): Frutos secos, oleaginosos, frutales de hueso, almendros y frutales de pepita: 154. 1997.
222
            if(nomRefStr.startsWith("Las variedades tradicionales de frutales ")){
223

    
224
                if(bookVariedadesTradicionales == null){
225
                    bookVariedadesTradicionales = ReferenceFactory.newBook();
226
                    bookVariedadesTradicionales.setTitle("Las variedades tradicionales de frutales de la Cuenca del Río Segura. Catálogo Etnobotánico (1): Frutos secos, oleaginosos, frutales de hueso, almendros y frutales de pepita");
227
                    bookVariedadesTradicionales.setDatePublished(TimePeriod.NewInstance(1997));
228
                    getReferenceService().save(bookVariedadesTradicionales);
229
                }
230
                nomRefStr = nomRefStr.replaceAll("^.*?\\:.*?\\:", "Las variedades tradicionales:");
231
                restoreOriginalReference = true;
232
            }
233

    
234
            Matcher m = nomRefTokenizeP.matcher(nomRefStr);
235
            if(m.matches()){
236
                nomRefTitle = m.group("title");
237
                nomRefDetail = m.group("detail");
238
                nomRefPupDate = m.group("date").trim();
239
                nomRefIssue = m.group("issue");
240

    
241
                pupDate = parseDate(regNumber, nomRefPupDate);
242
                if (pupDate != null) {
243
                    nomRefTitle = nomRefTitle + ": " + nomRefDetail + ". " + pupDate.toString(formatterYear) + ".";
244
                } else {
245
                    logger.warn(csvReportLine(regNumber, "Pub date", nomRefPupDate, "in", nomRefStr, "not parsable"));
246
                }
247
            } else {
248
                nomRefTitle = nomRefStr;
249
            }
250
        }
251

    
252
        BotanicalName taxonName = makeBotanicalName(state, regNumber, titleCacheStr, nameStr, authorStr, nomRefTitle);
253

    
254
        // always add the original strings of parsed data as annotation
255
        taxonName.addAnnotation(Annotation.NewInstance("imported and parsed data strings:" +
256
                        "\n -  '" + LITSTRING + "': "+ nomRefStr +
257
                        "\n -  '" + TYPE + "': " + typeStr +
258
                        "\n -  '" + REGISTRATION  + "': " + regStr
259
                , AnnotationType.TECHNICAL(), Language.DEFAULT()));
260

    
261
        if(restoreOriginalReference){
262
            taxonName.setNomenclaturalReference(bookVariedadesTradicionales);
263
        }
264
        if(pupDate != null) {
265
            taxonName.getNomenclaturalReference().setDatePublished(TimePeriod.NewInstance(pupDate));
266
        }
267
        if(nomRefIssue != null) {
268
            ((Reference)taxonName.getNomenclaturalReference()).setVolume(nomRefIssue);
269
        }
270

    
271

    
272
        if(!StringUtils.isEmpty(notesTxt)){
273
            notesTxt = notesTxt.replace("Notes: ", "").trim();
274
            taxonName.addAnnotation(Annotation.NewInstance(notesTxt, AnnotationType.EDITORIAL(), Language.DEFAULT()));
275
            nameIsValid = false;
276

    
277
        }
278
        if(!StringUtils.isEmpty(caveats)){
279
            caveats = caveats.replace("Caveats: ", "").trim();
280
            taxonName.addAnnotation(Annotation.NewInstance(caveats, annotationTypeCaveats(), Language.DEFAULT()));
281
            nameIsValid = false;
282
        }
283

    
284
        if(nameIsValid){
285
            // Status is always considered valid if no notes and cavets are set
286
            taxonName.addStatus(NomenclaturalStatus.NewInstance(NomenclaturalStatusType.VALID()));
287
        }
288

    
289
        getNameService().save(taxonName);
290

    
291
        // Namerelations
292
        if(!StringUtils.isEmpty(authorsSpelling)){
293
            authorsSpelling = authorsSpelling.replaceFirst("Author's spelling:", "").replaceAll("\"", "").trim();
294

    
295
            String[] authorSpellingTokens = StringUtils.split(authorsSpelling, " ");
296
            String[] nameStrTokens = StringUtils.split(nameStr, " ");
297

    
298
            ArrayUtils.reverse(authorSpellingTokens);
299
            ArrayUtils.reverse(nameStrTokens);
300

    
301
            for (int i = 0; i < nameStrTokens.length; i++){
302
                if(i < authorSpellingTokens.length){
303
                    nameStrTokens[i] = authorSpellingTokens[i];
304
                }
305
            }
306
            ArrayUtils.reverse(nameStrTokens);
307

    
308
            String misspelledNameStr = StringUtils.join (nameStrTokens, ' ');
309
            // build the fullnameString of the misspelled name
310
            misspelledNameStr = taxonName.getTitleCache().replace(nameStr, misspelledNameStr);
311

    
312
            TaxonNameBase misspelledName = (BotanicalName) nameParser.parseReferencedName(misspelledNameStr, NomenclaturalCode.ICNAFP, null);
313
            misspelledName.addRelationshipToName(taxonName, NameRelationshipType.MISSPELLING(), null);
314
            getNameService().save(misspelledName);
315
        }
316

    
317
        // Replaced Synonyms
318
        if(!StringUtils.isEmpty(fullSynSubstStr)){
319
            fullSynSubstStr = fullSynSubstStr.replace("Syn. subst.: ", "");
320
            BotanicalName replacedSynonymName = makeBotanicalName(state, regNumber, fullSynSubstStr, synSubstStr, null, null);
321
            replacedSynonymName.addReplacedSynonym(taxonName, null, null, null);
322
            getNameService().save(replacedSynonymName);
323
        }
324

    
325
        Reference sec = state.getConfig().getSecReference();
326
        Taxon taxon = Taxon.NewInstance(taxonName, sec);
327

    
328
        // Basionym
329
        if(fullBasionymStr != null){
330
            fullBasionymStr = fullBasionymStr.replaceAll("^\\w*:\\s", ""); // Strip off the leading 'Basionym: "
331
            basionymNameStr = basionymNameStr.replaceAll("^\\w*:\\s", ""); // Strip off the leading 'Basionym: "
332
            BotanicalName basionym = makeBotanicalName(state, regNumber, fullBasionymStr, basionymNameStr, null, null);
333
            getNameService().save(basionym);
334
            taxonName.addBasionym(basionym);
335

    
336
            Synonym syn = Synonym.NewInstance(basionym, sec);
337
            taxon.addSynonym(syn, SynonymRelationshipType.HOMOTYPIC_SYNONYM_OF());
338
            getTaxonService().save(syn);
339
        }
340

    
341
        // Markers
342
        if(isFossil){
343
            taxon.addMarker(Marker.NewInstance(markerTypeFossil(), true));
344
        }
345
        if(!nameSet.add(titleCacheStr)){
346
            taxonName.addMarker(Marker.NewInstance(markerDuplicateRegistration(), true));
347
            logger.warn(csvReportLine(regNumber, "Duplicate registration of", titleCacheStr));
348
        }
349

    
350

    
351
        // Types
352
        if(!StringUtils.isEmpty(typeStr)){
353

    
354
            if(taxonName.getRank().isSpecies() || taxonName.getRank().isLower(Rank.SPECIES())) {
355
                makeSpecimenTypeData(typeStr, taxonName, regNumber, state, false);
356
            } else {
357
                makeNameTypeData(typeStr, taxonName, regNumber, state);
358
            }
359
        }
360

    
361
        getTaxonService().save(taxon);
362

    
363
        if(taxonName.getRank().equals(Rank.SPECIES()) || taxonName.getRank().isLower(Rank.SPECIES())){
364
            // try to find the genus, it should have been imported already, Genera are coming first in the import file
365
            Taxon genus = ((IAPTImportState)state).getGenusTaxonMap().get(taxonName.getGenusOrUninomial());
366
            if(genus != null){
367
                higherTaxonNode = genus.getTaxonNodes().iterator().next();
368
            } else {
369
                logger.info(csvReportLine(regNumber, "Parent genus not found for", nameStr));
370
            }
371
        }
372

    
373
        if(higherTaxonNode != null){
374
            higherTaxonNode.addChildTaxon(taxon, null, null);
375
            getTaxonNodeService().save(higherTaxonNode);
376
        }
377

    
378
        if(taxonName.getRank().isGenus()){
379
            ((IAPTImportState)state).getGenusTaxonMap().put(taxonName.getGenusOrUninomial(), taxon);
380
        }
381

    
382
        return taxon;
383
    }
384

    
385
    private void makeSpecimenTypeData(String typeStr, BotanicalName taxonName, String regNumber, SimpleExcelTaxonImportState<CONFIG> state, boolean isFossil) {
386

    
387
        Matcher m = typeSpecimenSplitPattern.matcher(typeStr);
388

    
389
        if(m.matches()){
390
            String fieldUnitStr = m.group(TypesName.fieldUnit.name());
391
            // boolean isFieldUnit = typeStr.matches(".*([°']|\\d+\\s?m\\s|\\d+\\s?km\\s).*"); // check for location or unit m, km // makes no sense!!!!
392
            FieldUnit fieldUnit = parseFieldUnit(fieldUnitStr, regNumber, state);
393
            if(fieldUnit == null) {
394
                // create a field unit with only a titleCache using the fieldUnitStr substring
395
                logger.warn(csvReportLine(regNumber, "Type: fieldUnitStr can not be parsed", fieldUnitStr));
396
                fieldUnit = FieldUnit.NewInstance();
397
                fieldUnit.setTitleCache(fieldUnitStr, true);
398
                getOccurrenceService().save(fieldUnit);
399
            }
400
            getOccurrenceService().save(fieldUnit);
401

    
402
            SpecimenOrObservationType specimenType;
403
            if(isFossil){
404
                specimenType = SpecimenOrObservationType.Fossil;
405
            } else {
406
                specimenType = SpecimenOrObservationType.PreservedSpecimen;
407
            }
408

    
409
            // all others ..
410
            addSpecimenTypes(taxonName, fieldUnit, m.group(TypesName.holotype.name()), TypesName.holotype, false, regNumber, specimenType);
411
            addSpecimenTypes(taxonName, fieldUnit, m.group(TypesName.isotype.name()), TypesName.isotype, true, regNumber, specimenType);
412

    
413
        } else {
414
            // create a field unit with only a titleCache using the full typeStr
415
            FieldUnit fieldUnit = FieldUnit.NewInstance();
416
            fieldUnit.setTitleCache(typeStr, true);
417
            getOccurrenceService().save(fieldUnit);
418
            logger.warn(csvReportLine(regNumber, "Type: field 'Type' can not be parsed", typeStr));
419
        }
420
        getNameService().save(taxonName);
421
    }
422

    
423
    private void makeNameTypeData(String typeStr, BotanicalName taxonName, String regNumber, SimpleExcelTaxonImportState<CONFIG> state) {
424

    
425
        String nameStr = typeStr.replaceAll("^Type\\s?\\:\\s?", "");
426
        if(nameStr.isEmpty()) {
427
            return;
428
        }
429

    
430
        String basionymNameStr = null;
431
        String noteStr = null;
432
        String agentStr = null;
433

    
434
        Matcher m;
435

    
436
        if(typeStr.startsWith("not to be indicated")){
437
            // Special case:
438
            // Type: not to be indicated (Art. H.9.1. Tokyo Code); stated parent genera: Hechtia Klotzsch; Deuterocohnia Mez
439
            // FIXME
440
            m = typeNameSpecialSplitPattern.matcher(nameStr);
441
            if(m.matches()){
442
                nameStr = m.group("name");
443
                noteStr = m.group("note");
444
                agentStr = m.group("agent");
445
                // TODO better import of agent?
446
                if(agentStr != null){
447
                    noteStr = noteStr + ": " + agentStr;
448
                }
449
            }
450
        } else {
451
            // Generic case
452
            m = typeNameBasionymPattern.matcher(nameStr);
453
            if (m.find()) {
454
                basionymNameStr = m.group("basionymName");
455
                if (basionymNameStr != null) {
456
                    nameStr = nameStr.replace(m.group(0), "");
457
                }
458
            }
459

    
460
            m = typeNameNotePattern.matcher(nameStr);
461
            if (m.find()) {
462
                noteStr = m.group(1);
463
                if (noteStr != null) {
464
                    nameStr = nameStr.replace(m.group(0), "");
465
                }
466
            }
467
        }
468

    
469
        BotanicalName typeName = (BotanicalName) nameParser.parseFullName(nameStr, NomenclaturalCode.ICNAFP, null);
470

    
471
        if(typeName.isProtectedTitleCache() || typeName.getNomenclaturalReference() != null && typeName.getNomenclaturalReference().isProtectedTitleCache()) {
472
            logger.warn(csvReportLine(regNumber, "NameType not parsable", typeStr, nameStr));
473
        }
474

    
475
        if(basionymNameStr != null){
476
            BotanicalName basionymName = (BotanicalName) nameParser.parseFullName(nameStr, NomenclaturalCode.ICNAFP, null);
477
            getNameService().save(basionymName);
478
            typeName.addBasionym(basionymName);
479
        }
480

    
481

    
482
        NameTypeDesignation nameTypeDesignation = NameTypeDesignation.NewInstance();
483
        nameTypeDesignation.setTypeName(typeName);
484
        getNameService().save(typeName);
485

    
486
        if(noteStr != null){
487
            nameTypeDesignation.addAnnotation(Annotation.NewInstance(noteStr, AnnotationType.EDITORIAL(), Language.UNKNOWN_LANGUAGE()));
488
        }
489
        taxonName.addNameTypeDesignation(typeName, null, null, null, null, false);
490

    
491
    }
492

    
493
    /**
494
     * Currently only parses the collector, fieldNumber and the collection date.
495
     *
496
     * @param fieldUnitStr
497
     * @param regNumber
498
     * @param state
499
     * @return null if the fieldUnitStr could not be parsed
500
     */
501
    protected FieldUnit parseFieldUnit(String fieldUnitStr, String regNumber, SimpleExcelTaxonImportState<CONFIG> state) {
502

    
503
        FieldUnit fieldUnit = null;
504

    
505
        Matcher m1 = collectorPattern.matcher(fieldUnitStr);
506
        if(m1.matches()){
507

    
508
            String collectorData = m1.group(2); // like ... (leg. Metzeltin, 30. 9. 1996)
509
            String removal = m1.group(1);
510
            if(collectorData == null){
511
                collectorData = m1.group(4); // like ... leg. Metzeltin, 30. 9. 1996
512
                removal = m1.group(3);
513
            }
514
            if(collectorData == null){
515
                collectorData = m1.group(6); // like ^leg. J. J. Halda 18.3.1997$
516
                removal = null;
517
            }
518
            if(collectorData == null){
519
                return null;
520
            }
521

    
522
            // the fieldUnitStr is parsable
523
            // remove all collectorData from the fieldUnitStr and use the rest as locality
524
            String locality = null;
525
            if(removal != null){
526
                locality = fieldUnitStr.replace(removal, "");
527
            }
528

    
529
            String collectorStr = null;
530
            String detailStr = null;
531
            Partial date = null;
532
            String fieldNumber = null;
533

    
534
            Matcher m2 = collectionDataPattern.matcher(collectorData);
535
            if(m2.matches()){
536
                collectorStr = m2.group("collector");
537
                detailStr = m2.group("detail");
538

    
539
                // Try to make sense of the detailStr
540
                if(detailStr != null){
541
                    detailStr = detailStr.trim();
542
                    // 1. try to parse as date
543
                    date = parseDate(regNumber, detailStr);
544
                    if(date == null){
545
                        // 2. try to parse as number
546
                        if(collectorsNumber.matcher(detailStr).matches()){
547
                            fieldNumber = detailStr;
548
                        }
549
                    }
550
                }
551
                if(date == null && fieldNumber == null){
552
                    // detailed parsing not possible, so need fo fallback
553
                    collectorStr = collectorData;
554
                }
555
            }
556

    
557
            if(collectorStr == null) {
558
                collectorStr = collectorData;
559
            }
560

    
561
            fieldUnit = FieldUnit.NewInstance();
562
            GatheringEvent ge = GatheringEvent.NewInstance();
563
            if(locality != null){
564
                ge.setLocality(LanguageString.NewInstance(locality, Language.UNKNOWN_LANGUAGE()));
565
            }
566

    
567
            TeamOrPersonBase agent =  state.getAgentBase(collectorStr);
568
            if(agent == null) {
569
                agent = Person.NewTitledInstance(collectorStr);
570
                getAgentService().save(agent);
571
                state.putAgentBase(collectorStr, agent);
572
            }
573
            ge.setCollector(agent);
574

    
575
            if(date != null){
576
                ge.setGatheringDate(date);
577
            }
578

    
579
            getEventBaseService().save(ge);
580
            fieldUnit.setGatheringEvent(ge);
581

    
582
            if(fieldNumber != null) {
583
                fieldUnit.setFieldNumber(fieldNumber);
584
            }
585
            getOccurrenceService().save(fieldUnit);
586

    
587
        }
588

    
589
        return fieldUnit;
590
    }
591

    
592
    protected Partial parseDate(String regNumber, String dateStr) {
593

    
594
        Partial pupDate = null;
595
        boolean parseError = false;
596

    
597
        String day = null;
598
        String month = null;
599
        String monthName = null;
600
        String year = null;
601

    
602
        for(Pattern p : datePatterns){
603
            Matcher m2 = p.matcher(dateStr);
604
            if(m2.matches()){
605
                try {
606
                    year = m2.group("year");
607
                } catch (IllegalArgumentException e){
608
                    // named capture group not found
609
                }
610
                try {
611
                    month = m2.group("month");
612
                } catch (IllegalArgumentException e){
613
                    // named capture group not found
614
                }
615

    
616
                try {
617
                    monthName = m2.group("monthName");
618
                    month = monthFromName(monthName, regNumber);
619
                    if(month == null){
620
                        parseError = true;
621
                    }
622
                } catch (IllegalArgumentException e){
623
                    // named capture group not found
624
                }
625
                try {
626
                    day = m2.group("day");
627
                } catch (IllegalArgumentException e){
628
                    // named capture group not found
629
                }
630

    
631
                if(year != null){
632
                    if (year.length() == 2) {
633
                        // it is an abbreviated year from the 19** years
634
                        year = "19" + year;
635
                    }
636
                    break;
637
                } else {
638
                    parseError = true;
639
                }
640
            }
641
        }
642
        if(year == null){
643
            parseError = true;
644
        }
645
        List<DateTimeFieldType> types = new ArrayList<>();
646
        List<Integer> values = new ArrayList<>();
647
        if(!parseError) {
648
            types.add(DateTimeFieldType.year());
649
            values.add(Integer.parseInt(year));
650
            if (month != null) {
651
                types.add(DateTimeFieldType.monthOfYear());
652
                values.add(Integer.parseInt(month));
653
            }
654
            if (day != null) {
655
                types.add(DateTimeFieldType.dayOfMonth());
656
                values.add(Integer.parseInt(day));
657
            }
658
            pupDate = new Partial(types.toArray(new DateTimeFieldType[types.size()]), ArrayUtils.toPrimitive(values.toArray(new Integer[values.size()])));
659
        }
660
        return pupDate;
661
    }
662

    
663
    private String monthFromName(String monthName, String regNumber) {
664

    
665
        Integer month = monthFromNameMap.get(monthName.toLowerCase());
666
        if(month == null){
667
            logger.warn(csvReportLine(regNumber, "Unknown month name", monthName));
668
            return null;
669
        } else {
670
            return month.toString();
671
        }
672
    }
673

    
674

    
675
    private void addSpecimenTypes(BotanicalName taxonName, FieldUnit fieldUnit, String typeStr, TypesName typeName, boolean multiple, String regNumber, SpecimenOrObservationType specimenType){
676

    
677
        if(StringUtils.isEmpty(typeStr)){
678
            return;
679
        }
680
        typeStr = typeStr.trim().replaceAll("\\.$", "");
681

    
682
        Collection collection = null;
683
        DerivedUnit specimen = null;
684

    
685
        List<DerivedUnit> specimens = new ArrayList<>();
686
        if(multiple){
687
            String[] tokens = typeStr.split("\\s?,\\s?");
688
            for (String t : tokens) {
689
                // command to  list all complex parsabel types:
690
                // csvcut -t -c RegistrationNo_Pk,Type iapt.csv | csvgrep -c Type -m "Holotype" | egrep -o 'Holotype:\s([A-Z]*\s)[^.]*?'
691
                // csvcut -t -c RegistrationNo_Pk,Type iapt.csv | csvgrep -c Type -m "Holotype" | egrep -o 'Isotype[^:]*:\s([A-Z]*\s)[^.]*?'
692

    
693
                if(!t.isEmpty()){
694
                    // trying to parse the string
695
                    specimen = parseSpecimenType(fieldUnit, typeName, collection, t, regNumber);
696
                    if(specimen != null){
697
                        specimens.add(specimen);
698
                    } else {
699
                        // parsing was not successful make simple specimen
700
                        specimens.add(makeSpecimenType(fieldUnit, t, specimenType));
701
                    }
702
                }
703
            }
704
        } else {
705
            specimen = parseSpecimenType(fieldUnit, typeName, collection, typeStr, regNumber);
706
            if(specimen != null) {
707
                specimens.add(specimen);
708
                // remember current collection
709
                collection = specimen.getCollection();
710
            } else {
711
                // parsing was not successful make simple specimen
712
                specimens.add(makeSpecimenType(fieldUnit, typeStr, SpecimenOrObservationType.PreservedSpecimen));
713
            }
714
        }
715

    
716
        for(DerivedUnit s : specimens){
717
            taxonName.addSpecimenTypeDesignation(s, typeName.status(), null, null, null, false, true);
718
       }
719
    }
720

    
721
    private DerivedUnit makeSpecimenType(FieldUnit fieldUnit, String titleCache, SpecimenOrObservationType specimenType) {
722
        DerivedUnit specimen;DerivedUnitFacade facade = DerivedUnitFacade.NewInstance(specimenType, fieldUnit);
723
        facade.setTitleCache(titleCache.trim(), true);
724
        specimen = facade.innerDerivedUnit();
725
        return specimen;
726
    }
727

    
728
    /**
729
     *
730
     * @param fieldUnit
731
     * @param typeName
732
     * @param collection
733
     * @param text
734
     * @param regNumber
735
     * @return
736
     */
737
    protected DerivedUnit parseSpecimenType(FieldUnit fieldUnit, TypesName typeName, Collection collection, String text, String regNumber) {
738

    
739
        DerivedUnit specimen = null;
740

    
741
        String collectionCode = null;
742
        String collectionTitle = null;
743
        String subCollectionStr = null;
744
        String instituteStr = null;
745
        String accessionNumber = null;
746

    
747
        boolean unusualAccessionNumber = false;
748

    
749
        text = text.trim();
750

    
751
        // 1.  For Isotypes often the accession number is noted alone if the
752
        //     preceeding entry has a collection code.
753
        if(typeName .equals(TypesName.isotype) && collection != null){
754
            Matcher m = accessionNumberOnlyPattern.matcher(text);
755
            if(m.matches()){
756
                try {
757
                    accessionNumber = m.group("accNumber");
758
                    specimen = makeSpecimenType(fieldUnit, collection, accessionNumber);
759
                } catch (IllegalArgumentException e){
760
                    // match group acc_number not found
761
                }
762
            }
763
        }
764

    
765
        //2. try it the 'normal' way
766
        if(specimen == null) {
767
            for (Pattern p : specimenTypePatterns) {
768
                Matcher m = p.matcher(text);
769
                if (m.matches()) {
770
                    // collection code or collectionTitle is mandatory
771
                    try {
772
                        collectionCode = m.group("colCode");
773
                    } catch (IllegalArgumentException e){
774
                        // match group colCode not found
775
                    }
776

    
777
                    try {
778
                        instituteStr = m.group("institute");
779
                    } catch (IllegalArgumentException e){
780
                        // match group col_name not found
781
                    }
782

    
783
                    try {
784
                        subCollectionStr = m.group("subCollection");
785
                    } catch (IllegalArgumentException e){
786
                        // match group subCollection not found
787
                    }
788
                    try {
789
                        accessionNumber = m.group("accNumber");
790

    
791
                        // try to improve the accessionNumber
792
                        if(accessionNumber!= null) {
793
                            accessionNumber = accessionNumber.trim();
794
                            Matcher m2 = accessionNumberOnlyPattern.matcher(accessionNumber);
795
                            String betterAccessionNumber = null;
796
                            if (m2.matches()) {
797
                                try {
798
                                    betterAccessionNumber = m.group("accNumber");
799
                                } catch (IllegalArgumentException e) {
800
                                    // match group acc_number not found
801
                                }
802
                            }
803
                            if (betterAccessionNumber != null) {
804
                                accessionNumber = betterAccessionNumber;
805
                            } else {
806
                                unusualAccessionNumber = true;
807
                            }
808
                        }
809

    
810
                    } catch (IllegalArgumentException e){
811
                        // match group acc_number not found
812
                    }
813

    
814
                    if(collectionCode == null && instituteStr == null){
815
                        logger.warn(csvReportLine(regNumber, "Type: neither 'collectionCode' nor 'institute' found in ", text));
816
                        continue;
817
                    }
818
                    collection = getCollection(collectionCode, instituteStr, subCollectionStr);
819
                    specimen = makeSpecimenType(fieldUnit, collection, accessionNumber);
820
                    break;
821
                }
822
            }
823
        }
824
        if(specimen == null) {
825
            logger.warn(csvReportLine(regNumber, "Type: Could not parse specimen", typeName.name().toString(), text));
826
        }
827
        if(unusualAccessionNumber){
828
            logger.warn(csvReportLine(regNumber, "Type: Unusual accession number", typeName.name().toString(), text, accessionNumber));
829
        }
830
        return specimen;
831
    }
832

    
833
    private DerivedUnit makeSpecimenType(FieldUnit fieldUnit, Collection collection, String accessionNumber) {
834

    
835
        DerivedUnitFacade facade = DerivedUnitFacade.NewInstance(SpecimenOrObservationType.PreservedSpecimen, fieldUnit);
836
        facade.setCollection(collection);
837
        if(accessionNumber != null){
838
            facade.setAccessionNumber(accessionNumber);
839
        }
840
        return facade.innerDerivedUnit();
841
    }
842

    
843
    private BotanicalName makeBotanicalName(SimpleExcelTaxonImportState<CONFIG> state, String regNumber, String titleCacheStr, String nameStr,
844
                                            String authorStr, String nomRefTitle) {
845

    
846
        BotanicalName taxonName;// cache field for the taxonName.titleCache
847
        String taxonNameTitleCache = null;
848
        Map<String, AnnotationType> nameAnnotations = new HashMap<>();
849

    
850
        // TitleCache preprocessing
851
        if(titleCacheStr.endsWith(ANNOTATION_MARKER_STRING) || (authorStr != null && authorStr.endsWith(ANNOTATION_MARKER_STRING))){
852
            nameAnnotations.put("Author abbreviation not checked.", AnnotationType.EDITORIAL());
853
            titleCacheStr = titleCacheStr.replace(ANNOTATION_MARKER_STRING, "").trim();
854
            if(authorStr != null) {
855
                authorStr = authorStr.replace(ANNOTATION_MARKER_STRING, "").trim();
856
            }
857
        }
858

    
859
        // parse the full taxon name
860
        if(!StringUtils.isEmpty(nomRefTitle)){
861
            String referenceSeparator = nomRefTitle.startsWith("in ") ? " " : ", ";
862
            String taxonFullNameStr = titleCacheStr + referenceSeparator + nomRefTitle;
863
            logger.debug(":::::" + taxonFullNameStr);
864
            taxonName = (BotanicalName) nameParser.parseReferencedName(taxonFullNameStr, NomenclaturalCode.ICNAFP, null);
865
        } else {
866
            taxonName = (BotanicalName) nameParser.parseFullName(titleCacheStr, NomenclaturalCode.ICNAFP, null);
867
        }
868

    
869
        taxonNameTitleCache = taxonName.getTitleCache().trim();
870
        if (taxonName.isProtectedTitleCache()) {
871
            logger.warn(csvReportLine(regNumber, "Name could not be parsed", titleCacheStr));
872
        } else {
873

    
874
            boolean doRestoreTitleCacheStr = false;
875

    
876
            // Check if titleCache and nameCache are plausible
877
            String titleCacheCompareStr = titleCacheStr;
878
            String nameCache = taxonName.getNameCache();
879
            String nameCompareStr = nameStr;
880
            if(taxonName.isBinomHybrid()){
881
                titleCacheCompareStr = titleCacheCompareStr.replace(" x ", " ×");
882
                nameCompareStr = nameCompareStr.replace(" x ", " ×");
883
            }
884
            if(taxonName.isMonomHybrid()){
885
                titleCacheCompareStr = titleCacheCompareStr.replaceAll("^X ", "× ");
886
                nameCompareStr = nameCompareStr.replace("^X ", "× ");
887
            }
888
            if(authorStr != null && authorStr.contains(" et ")){
889
                titleCacheCompareStr = titleCacheCompareStr.replaceAll(" et ", " & ");
890
            }
891
            if (!taxonNameTitleCache.equals(titleCacheCompareStr)) {
892
                logger.warn(csvReportLine(regNumber, "The generated titleCache differs from the imported string", taxonNameTitleCache, " != ", titleCacheStr, " ==> original titleCacheStr has been restored"));
893
                doRestoreTitleCacheStr = true;
894
            }
895
            if (!nameCache.trim().equals(nameCompareStr)) {
896
                logger.warn(csvReportLine(regNumber, "The parsed nameCache differs from field '" + NAMESTRING + "'", nameCache, " != ", nameCompareStr));
897
            }
898

    
899
            //  Author
900
            //nameParser.handleAuthors(taxonName, titleCacheStr, authorStr);
901
            //if (!titleCacheStr.equals(taxonName.getTitleCache())) {
902
            //    logger.warn(regNumber + ": titleCache has changed after setting authors, will restore original titleCacheStr");
903
            //    doRestoreTitleCacheStr = true;
904
            //}
905

    
906
            if(doRestoreTitleCacheStr){
907
                taxonName.setTitleCache(titleCacheStr, true);
908
            }
909

    
910
            // deduplicate
911
            replaceAuthorNamesAndNomRef(state, taxonName);
912
        }
913

    
914
        // Annotations
915
        if(!nameAnnotations.isEmpty()){
916
            for(String text : nameAnnotations.keySet()){
917
                taxonName.addAnnotation(Annotation.NewInstance(text, nameAnnotations.get(text), Language.DEFAULT()));
918
            }
919
        }
920

    
921
        taxonName.addSource(OriginalSourceType.Import, regNumber, null, state.getConfig().getSourceReference(), null);
922

    
923
        getNameService().save(taxonName);
924

    
925
        return taxonName;
926
    }
927

    
928
    /**
929
     * @param state
930
     * @return
931
     */
932
    private TaxonNode getClassificationRootNode(IAPTImportState state) {
933

    
934
     //   Classification classification = state.getClassification();
935
     //   if (classification == null){
936
     //       IAPTImportConfigurator config = state.getConfig();
937
     //       classification = Classification.NewInstance(state.getConfig().getClassificationName());
938
     //       classification.setUuid(config.getClassificationUuid());
939
     //       classification.setReference(config.getSecReference());
940
     //       classification = getClassificationService().find(state.getConfig().getClassificationUuid());
941
     //   }
942
        TaxonNode rootNode = state.getRootNode();
943
        if (rootNode == null){
944
            rootNode = getTaxonNodeService().find(ROOT_UUID);
945
        }
946
        if (rootNode == null){
947
            Classification classification = state.getClassification();
948
            if (classification == null){
949
                Reference sec = state.getSecReference();
950
                String classificationName = state.getConfig().getClassificationName();
951
                Language language = Language.DEFAULT();
952
                classification = Classification.NewInstance(classificationName, sec, language);
953
                state.setClassification(classification);
954
                classification.setUuid(state.getConfig().getClassificationUuid());
955
                classification.getRootNode().setUuid(ROOT_UUID);
956
                getClassificationService().save(classification);
957
            }
958
            rootNode = classification.getRootNode();
959
            state.setRootNode(rootNode);
960
        }
961
        return rootNode;
962
    }
963

    
964
    private Collection getCollection(String collectionCode, String instituteStr, String subCollectionStr){
965

    
966
        Collection superCollection = null;
967
        if(subCollectionStr != null){
968
            superCollection = getCollection(collectionCode, instituteStr, null);
969
            collectionCode = subCollectionStr;
970
            instituteStr = null;
971
        }
972

    
973
        final String key = collectionCode + "-#i:" + StringUtils.defaultString(instituteStr);
974

    
975
        Collection collection = collectionMap.get(key);
976

    
977
        if(collection == null) {
978
            collection = Collection.NewInstance();
979
            collection.setCode(collectionCode);
980
            if(instituteStr != null){
981
                collection.setInstitute(Institution.NewNamedInstance(instituteStr));
982
            }
983
            if(superCollection != null){
984
                collection.setSuperCollection(superCollection);
985
            }
986
            collectionMap.put(key, collection);
987
            if(!_testMode) {
988
                getCollectionService().save(collection);
989
            }
990
        }
991

    
992
        return collection;
993
    }
994

    
995

    
996
    /**
997
     * @param record
998
     * @param originalKey
999
     * @param doUnescapeHtmlEntities
1000
     * @return
1001
     */
1002
    private String getValue(HashMap<String, String> record, String originalKey, boolean doUnescapeHtmlEntities) {
1003
        String value = record.get(originalKey);
1004

    
1005
        value = fixCharacters(value);
1006

    
1007
        if (! StringUtils.isBlank(value)) {
1008
        	if (logger.isDebugEnabled()) {
1009
        	    logger.debug(originalKey + ": " + value);
1010
        	}
1011
        	value = CdmUtils.removeDuplicateWhitespace(value.trim()).toString();
1012
            if(doUnescapeHtmlEntities){
1013
                value = StringEscapeUtils.unescapeHtml(value);
1014
            }
1015
        	return value.trim();
1016
        }else{
1017
        	return null;
1018
        }
1019
    }
1020

    
1021
    /**
1022
     * Fixes broken characters.
1023
     * For details see
1024
     * http://dev.e-taxonomy.eu/redmine/issues/6035
1025
     *
1026
     * @param value
1027
     * @return
1028
     */
1029
    private String fixCharacters(String value) {
1030

    
1031
        value = StringUtils.replace(value, "s$K", "š");
1032
        value = StringUtils.replace(value, "n$K", "ň");
1033
        value = StringUtils.replace(value, "e$K", "ě");
1034
        value = StringUtils.replace(value, "r$K", "ř");
1035
        value = StringUtils.replace(value, "c$K", "č");
1036
        value = StringUtils.replace(value, "z$K", "ž");
1037
        value = StringUtils.replace(value, "S>U$K", "Š");
1038
        value = StringUtils.replace(value, "C>U$K", "Č");
1039
        value = StringUtils.replace(value, "R>U$K", "Ř");
1040
        value = StringUtils.replace(value, "Z>U$K", "Ž");
1041
        value = StringUtils.replace(value, "g$K", "ǧ");
1042
        value = StringUtils.replace(value, "s$A", "ś");
1043
        value = StringUtils.replace(value, "n$A", "ń");
1044
        value = StringUtils.replace(value, "c$A", "ć");
1045
        value = StringUtils.replace(value, "e$E", "ę");
1046
        value = StringUtils.replace(value, "o$H", "õ");
1047
        value = StringUtils.replace(value, "s$C", "ş");
1048
        value = StringUtils.replace(value, "t$C", "ț");
1049
        value = StringUtils.replace(value, "S>U$C", "Ş");
1050
        value = StringUtils.replace(value, "a$O", "å");
1051
        value = StringUtils.replace(value, "A>U$O", "Å");
1052
        value = StringUtils.replace(value, "u$O", "ů");
1053
        value = StringUtils.replace(value, "g$B", "ğ");
1054
        value = StringUtils.replace(value, "g$B", "ĕ");
1055
        value = StringUtils.replace(value, "a$B", "ă");
1056
        value = StringUtils.replace(value, "l$/", "ł");
1057
        value = StringUtils.replace(value, ">i", "ı");
1058
        value = StringUtils.replace(value, "i$U", "ï");
1059
        // Special-cases
1060
        value = StringUtils.replace(value, "&yacute", "ý");
1061
        value = StringUtils.replace(value, ">L", "Ł"); // corrected rule
1062
        value = StringUtils.replace(value, "E>U$D", "З");
1063
        value = StringUtils.replace(value, "S>U$E", "Ş");
1064
        value = StringUtils.replace(value, "s$E", "ş");
1065

    
1066
        value = StringUtils.replace(value, "c$k", "č");
1067
        value = StringUtils.replace(value, " U$K", " Š");
1068

    
1069
        value = StringUtils.replace(value, "O>U>!", "Ø");
1070
        value = StringUtils.replace(value, "o>!", "ø");
1071
        value = StringUtils.replace(value, "S$K", "Ŝ");
1072
        value = StringUtils.replace(value, ">l", "ğ");
1073

    
1074
        value = StringUtils.replace(value, "§B>i", "ł");
1075

    
1076

    
1077

    
1078
        return value;
1079
    }
1080

    
1081

    
1082
    /**
1083
	 *  Stores taxa records in DB
1084
	 */
1085
	@Override
1086
    protected void firstPass(SimpleExcelTaxonImportState<CONFIG> state) {
1087

    
1088
        String lineNumber = "L#" + state.getCurrentLine() + ": ";
1089
        logger.setLevel(Level.DEBUG);
1090
        HashMap<String, String> record = state.getOriginalRecord();
1091
        logger.debug(lineNumber + record.toString());
1092

    
1093
        Set<String> keys = record.keySet();
1094
        for (String key: keys) {
1095
            if (! expectedKeys.contains(key)){
1096
                logger.warn(lineNumber + "Unexpected Key: " + key);
1097
            }
1098
        }
1099

    
1100
        String reg_id = record.get(REGISTRATIONNO_PK);
1101

    
1102
        //higherTaxon
1103
        String higherTaxaString = record.get(HIGHERTAXON);
1104
        boolean isFossil = false;
1105
        if(higherTaxaString.startsWith("FOSSIL ")){
1106
            higherTaxaString = higherTaxaString.replace("FOSSIL ", "");
1107
            isFossil = true;
1108
        }
1109
        TaxonNode higherTaxon = getHigherTaxon(higherTaxaString, (IAPTImportState)state);
1110

    
1111
       //Taxon
1112
        Taxon taxon = makeTaxon(record, state, higherTaxon, isFossil);
1113
        if (taxon == null){
1114
            logger.warn(lineNumber + "taxon could not be created and is null");
1115
            return;
1116
        }
1117
        ((IAPTImportState)state).setCurrentTaxon(taxon);
1118

    
1119
        // Registration
1120
        IAPTRegData regData = makeIAPTRegData(state);
1121
        ObjectMapper mapper = new ObjectMapper();
1122
        try {
1123
            String regdataJson = mapper.writeValueAsString(regData);
1124
            Extension.NewInstance(taxon.getName(), regdataJson, getExtensionTypeIAPTRegData());
1125
            getNameService().save(taxon.getName());
1126
        } catch (JsonProcessingException e) {
1127
            logger.error("Error on converting IAPTRegData", e);
1128
        }
1129

    
1130
        logger.info("#of imported Genera: " + ((IAPTImportState) state).getGenusTaxonMap().size());
1131
		return;
1132
    }
1133

    
1134
    private ExtensionType getExtensionTypeIAPTRegData() {
1135
        if(extensionTypeIAPTRegData == null){
1136
            extensionTypeIAPTRegData = ExtensionType.NewInstance("IAPTRegData.json", "IAPTRegData.json", "");
1137
            getTermService().save(extensionTypeIAPTRegData);
1138
        }
1139
        return extensionTypeIAPTRegData;
1140
    }
1141

    
1142
    private IAPTRegData makeIAPTRegData(SimpleExcelTaxonImportState<CONFIG> state) {
1143

    
1144
        HashMap<String, String> record = state.getOriginalRecord();
1145
        String registrationStr = getValue(record, REGISTRATION);
1146
        String regDateStr = getValue(record, REGDATE);
1147
        String regStr = getValue(record, REGISTRATION, true);
1148

    
1149
        String dateStr = null;
1150
        String office = null;
1151
        Integer regID = null;
1152
        Integer formNo = null;
1153

    
1154
        Matcher m = registrationPattern.matcher(registrationStr);
1155
        if(m.matches()){
1156
            dateStr = m.group("regdate");
1157
            if(parseDate( regStr, dateStr) == null){
1158
                // check for valid dates
1159
                logger.warn(csvReportLine(regStr, REGISTRATION + ": could not parse date", dateStr, " in ", registrationStr));
1160
            };
1161
            office = m.group("office");
1162
            regID = Integer.valueOf(m.group("regid"));
1163
            try {
1164
                formNo = Integer.valueOf(m.group("formNo"));
1165
            } catch(IllegalArgumentException e){
1166
                // ignore
1167
            }
1168
        } else {
1169
            logger.warn(csvReportLine(regStr, REGISTRATION + ": could not be parsed", registrationStr));
1170
        }
1171
        IAPTRegData regData = new IAPTRegData(dateStr, office, regID, formNo);
1172
        return regData;
1173
    }
1174

    
1175
    private TaxonNode getHigherTaxon(String higherTaxaString, IAPTImportState state) {
1176
        String[] higherTaxaNames = higherTaxaString.toLowerCase().replaceAll("[\\[\\]]", "").split(":");
1177
        TaxonNode higherTaxonNode = null;
1178

    
1179
        ITaxonTreeNode rootNode = getClassificationRootNode(state);
1180
        for (String htn :  higherTaxaNames) {
1181
            htn = StringUtils.capitalize(htn.trim());
1182
            Taxon higherTaxon = state.getHigherTaxon(htn);
1183
            if (higherTaxon != null){
1184
                higherTaxonNode = higherTaxon.getTaxonNodes().iterator().next();
1185
            }else{
1186
                BotanicalName name = makeHigherTaxonName(state, htn);
1187
                Reference sec = state.getSecReference();
1188
                higherTaxon = Taxon.NewInstance(name, sec);
1189
                getTaxonService().save(higherTaxon);
1190
                higherTaxonNode = rootNode.addChildTaxon(higherTaxon, sec, null);
1191
                state.putHigherTaxon(htn, higherTaxon);
1192
                getClassificationService().saveTreeNode(higherTaxonNode);
1193
            }
1194
            rootNode = higherTaxonNode;
1195
        }
1196
        return higherTaxonNode;
1197
    }
1198

    
1199
    private BotanicalName makeHigherTaxonName(IAPTImportState state, String name) {
1200

    
1201
        Rank rank = guessRank(name);
1202

    
1203
        BotanicalName taxonName = BotanicalName.NewInstance(rank);
1204
        taxonName.addSource(makeOriginalSource(state));
1205
        taxonName.setGenusOrUninomial(StringUtils.capitalize(name));
1206
        return taxonName;
1207
    }
1208

    
1209
    private Rank guessRank(String name) {
1210

    
1211
        // normalize
1212
        name = name.replaceAll("\\(.*\\)", "").trim();
1213

    
1214
        if(name.matches("^Plantae$|^Fungi$")){
1215
           return Rank.KINGDOM();
1216
        } else if(name.matches("^Incertae sedis$|^No group assigned$")){
1217
           return rankFamilyIncertisSedis();
1218
        } else if(name.matches(".*phyta$|.*mycota$")){
1219
           return Rank.PHYLUM();
1220
        } else if(name.matches(".*phytina$|.*mycotina$")){
1221
           return Rank.SUBPHYLUM();
1222
        } else if(name.matches("Gymnospermae$|.*ones$")){ // Monocotyledones, Dicotyledones
1223
            return rankUnrankedSupraGeneric();
1224
        } else if(name.matches(".*opsida$|.*phyceae$|.*mycetes$|.*ones$|^Musci$|^Hepaticae$")){
1225
           return Rank.CLASS();
1226
        } else if(name.matches(".*idae$|.*phycidae$|.*mycetidae$")){
1227
           return Rank.SUBCLASS();
1228
        } else if(name.matches(".*ales$")){
1229
           return Rank.ORDER();
1230
        } else if(name.matches(".*ineae$")){
1231
           return Rank.SUBORDER();
1232
        } else if(name.matches(".*aceae$")){
1233
            return Rank.FAMILY();
1234
        } else if(name.matches(".*oideae$")){
1235
           return Rank.SUBFAMILY();
1236
        } else
1237
        //    if(name.matches(".*eae$")){
1238
        //    return Rank.TRIBE();
1239
        // } else
1240
            if(name.matches(".*inae$")){
1241
           return Rank.SUBTRIBE();
1242
        } else if(name.matches(".*ae$")){
1243
           return Rank.FAMILY();
1244
        }
1245
        return Rank.UNKNOWN_RANK();
1246
    }
1247

    
1248
    private Rank rankUnrankedSupraGeneric() {
1249

    
1250
        if(rankUnrankedSupraGeneric == null){
1251
            rankUnrankedSupraGeneric = Rank.NewInstance(RankClass.Suprageneric, "Unranked supra generic", " ", " ");
1252
            getTermService().save(rankUnrankedSupraGeneric);
1253
        }
1254
        return rankUnrankedSupraGeneric;
1255
    }
1256

    
1257
    private Rank rankFamilyIncertisSedis() {
1258

    
1259
        if(familyIncertisSedis == null){
1260
            familyIncertisSedis = Rank.NewInstance(RankClass.Suprageneric, "Family incertis sedis", " ", " ");
1261
            getTermService().save(familyIncertisSedis);
1262
        }
1263
        return familyIncertisSedis;
1264
    }
1265

    
1266
    private AnnotationType annotationTypeCaveats(){
1267
        if(annotationTypeCaveats == null){
1268
            annotationTypeCaveats = AnnotationType.NewInstance("Caveats", "Caveats", "");
1269
            getTermService().save(annotationTypeCaveats);
1270
        }
1271
        return annotationTypeCaveats;
1272
    }
1273

    
1274

    
1275
    /**
1276
     * @param state
1277
     * @return
1278
     */
1279
    private IdentifiableSource makeOriginalSource(IAPTImportState state) {
1280
        return IdentifiableSource.NewDataImportInstance("line: " + state.getCurrentLine(), null, state.getConfig().getSourceReference());
1281
    }
1282

    
1283

    
1284
    private Reference makeReference(IAPTImportState state, UUID uuidRef) {
1285
        Reference ref = state.getReference(uuidRef);
1286
        if (ref == null){
1287
            ref = getReferenceService().find(uuidRef);
1288
            state.putReference(uuidRef, ref);
1289
        }
1290
        return ref;
1291
    }
1292

    
1293
    private MarkerType markerTypeFossil(){
1294
        if(this.markerTypeFossil == null){
1295
            markerTypeFossil = MarkerType.NewInstance("isFossilTaxon", "isFossil", null);
1296
            getTermService().save(this.markerTypeFossil);
1297
        }
1298
        return markerTypeFossil;
1299
    }
1300

    
1301
    private MarkerType markerDuplicateRegistration(){
1302
        if(this.duplicateRegistration == null){
1303
            duplicateRegistration = MarkerType.NewInstance("duplicateRegistration", "duplicateRegistration", null);
1304
            getTermService().save(this.duplicateRegistration);
1305
        }
1306
        return markerTypeFossil;
1307
    }
1308

    
1309
    private String csvReportLine(String regId, String message, String ... fields){
1310
        StringBuilder out = new StringBuilder("regID#");
1311
        out.append(regId).append(",\"").append(message).append('"');
1312

    
1313
        for(String f : fields){
1314
            out.append(",\"").append(f).append('"');
1315
        }
1316
        return out.toString();
1317
    }
1318

    
1319

    
1320
}
(1-1/5)