Project

General

Profile

Download (67.9 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.cuba;
11

    
12
import java.util.ArrayList;
13
import java.util.Arrays;
14
import java.util.HashMap;
15
import java.util.HashSet;
16
import java.util.List;
17
import java.util.Set;
18
import java.util.UUID;
19
import java.util.regex.Matcher;
20
import java.util.regex.Pattern;
21

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

    
26
import eu.etaxonomy.cdm.common.CdmUtils;
27
import eu.etaxonomy.cdm.io.common.mapping.UndefinedTransformerMethodException;
28
import eu.etaxonomy.cdm.io.excel.common.ExcelImporterBase;
29
import eu.etaxonomy.cdm.model.agent.Person;
30
import eu.etaxonomy.cdm.model.agent.Team;
31
import eu.etaxonomy.cdm.model.agent.TeamOrPersonBase;
32
import eu.etaxonomy.cdm.model.common.Annotation;
33
import eu.etaxonomy.cdm.model.common.AnnotationType;
34
import eu.etaxonomy.cdm.model.common.CdmBase;
35
import eu.etaxonomy.cdm.model.common.IdentifiableSource;
36
import eu.etaxonomy.cdm.model.common.Language;
37
import eu.etaxonomy.cdm.model.common.OriginalSourceType;
38
import eu.etaxonomy.cdm.model.common.Representation;
39
import eu.etaxonomy.cdm.model.description.DescriptionElementBase;
40
import eu.etaxonomy.cdm.model.description.DescriptionElementSource;
41
import eu.etaxonomy.cdm.model.description.Distribution;
42
import eu.etaxonomy.cdm.model.description.Feature;
43
import eu.etaxonomy.cdm.model.description.PresenceAbsenceTerm;
44
import eu.etaxonomy.cdm.model.description.TaxonDescription;
45
import eu.etaxonomy.cdm.model.description.TaxonInteraction;
46
import eu.etaxonomy.cdm.model.description.TextData;
47
import eu.etaxonomy.cdm.model.location.NamedArea;
48
import eu.etaxonomy.cdm.model.name.BotanicalName;
49
import eu.etaxonomy.cdm.model.name.HomotypicalGroup;
50
import eu.etaxonomy.cdm.model.name.IBotanicalName;
51
import eu.etaxonomy.cdm.model.name.NameRelationship;
52
import eu.etaxonomy.cdm.model.name.NameRelationshipType;
53
import eu.etaxonomy.cdm.model.name.NomenclaturalCode;
54
import eu.etaxonomy.cdm.model.name.NomenclaturalStatus;
55
import eu.etaxonomy.cdm.model.name.NomenclaturalStatusType;
56
import eu.etaxonomy.cdm.model.name.Rank;
57
import eu.etaxonomy.cdm.model.name.TaxonNameBase;
58
import eu.etaxonomy.cdm.model.name.TaxonNameFactory;
59
import eu.etaxonomy.cdm.model.reference.Reference;
60
import eu.etaxonomy.cdm.model.reference.ReferenceFactory;
61
import eu.etaxonomy.cdm.model.taxon.Classification;
62
import eu.etaxonomy.cdm.model.taxon.ITaxonTreeNode;
63
import eu.etaxonomy.cdm.model.taxon.Synonym;
64
import eu.etaxonomy.cdm.model.taxon.SynonymType;
65
import eu.etaxonomy.cdm.model.taxon.Taxon;
66
import eu.etaxonomy.cdm.model.taxon.TaxonNode;
67
import eu.etaxonomy.cdm.model.taxon.TaxonRelationshipType;
68
import eu.etaxonomy.cdm.strategy.parser.INonViralNameParser;
69
import eu.etaxonomy.cdm.strategy.parser.NonViralNameParserImpl;
70

    
71
/**
72
 * @author a.mueller
73
 * @created 05.01.2016
74
 */
75

    
76
@Component
77
public class CubaExcelImport extends ExcelImporterBase<CubaImportState> {
78
    private static final long serialVersionUID = -747486709409732371L;
79
    private static final Logger logger = Logger.getLogger(CubaExcelImport.class);
80

    
81
    private static final String HOMONYM_MARKER = "\\s+homon.?$";
82
    private static final String DOUBTFUL_MARKER = "^\\?\\s?";
83

    
84

    
85
    private static UUID rootUuid = UUID.fromString("206d42e4-ac32-4f20-a093-14826014e667");
86
    private static UUID plantaeUuid = UUID.fromString("139e7314-dd19-4286-a01d-8cc94ef77a09");
87

    
88
    private static INonViralNameParser<?> nameParser = NonViralNameParserImpl.NewInstance();
89
    private static NomenclaturalCode nc = NomenclaturalCode.ICNAFP;
90

    
91
    private  static List<String> expectedKeys= Arrays.asList(new String[]{
92
            "Fam. default","Fam. FRC","Fam. A&S","Fam. FC",
93
            "Taxón","(Notas)","Syn.","End","Ind","Ind? D","Nat","Dud P","Adv","Cult C","CuW","PR PR*","Art","Hab(*)","May","Mat","IJ","CuC","VC","Ci","SS","CA","Cam","LT","CuE","Gr","Ho","SC","Gu","Esp","Ja","PR","Men","Bah","Cay","AmN","AmC","AmS","VM"});
94

    
95
	@Override
96
    protected void analyzeRecord(HashMap<String, String> record, CubaImportState state) {
97
	    //we do everything in firstPass here
98
    	return;
99
    }
100

    
101

    
102
    /**
103
     * @param record
104
     * @param state
105
     * @param taxon
106
     */
107
    private void makeCubanDistribution(HashMap<String, String> record, CubaImportState state) {
108
        try {
109
            NamedArea cuba = getNamedArea(state, state.getTransformer().getNamedAreaUuid("Cu"), null, null, null, null, null);
110
            TaxonDescription desc = getTaxonDescription(state.getCurrentTaxon(), false, true);
111
            List<PresenceAbsenceTerm> statuss =  makeCubanStatuss(record, state);
112
            for (PresenceAbsenceTerm status : statuss){
113
                Distribution distribution = Distribution.NewInstance(cuba, status);
114
                desc.addElement(distribution);
115
                distribution.addSource(makeDescriptionSource(state));
116
            }
117
        } catch (UndefinedTransformerMethodException e) {
118
            e.printStackTrace();
119
        }
120
    }
121

    
122

    
123
    /**
124
     * @param record
125
     * @param state
126
     * @return
127
     * @throws UndefinedTransformerMethodException
128
     */
129
    private List<PresenceAbsenceTerm> makeCubanStatuss(HashMap<String, String> record, CubaImportState state) throws UndefinedTransformerMethodException {
130
        PresenceAbsenceTerm highestStatus = null;
131

    
132
        String line = state.getCurrentLine() + ": ";
133
        List<PresenceAbsenceTerm> result = new ArrayList<>();
134

    
135
        String endemicStr = getValue(record, "End");
136
        String indigenousStr = getValue(record, "Ind");
137
        String indigenousDoubtStr = getValue(record, "Ind? D");
138
        String naturalisedStr = getValue(record, "Nat");
139
        String dudStr = getValue(record, "Dud P");
140
        String advStr = getValue(record, "Adv");
141
        String cultStr = getValue(record, "Cult C");
142

    
143
        state.setEndemic(false);
144

    
145
        if (endemicStr != null){
146
            if(endemicStr.equals("+")){
147
                PresenceAbsenceTerm endemicState = state.getTransformer().getPresenceTermByKey("E");
148
                result.add(endemicState);
149
                highestStatus = endemicState;
150
                state.setEndemic(true);
151
            }else if(isMinus(endemicStr)){
152
                UUID endemicUuid = state.getTransformer().getPresenceTermUuid("-E");
153
                PresenceAbsenceTerm endemicState = getPresenceTerm(state, endemicUuid, null, null, null, false);
154
                result.add(endemicState);
155
                checkAbsentHighestState(highestStatus, line, "endemic", false);
156
            }else if(endemicStr.equals("?")){
157
                UUID endemicDoubtfulUuid = state.getTransformer().getPresenceTermUuid("?E");
158
                PresenceAbsenceTerm endemicState = getPresenceTerm(state, endemicDoubtfulUuid, null, null, null, false);
159
                result.add(endemicState);
160
                checkAbsentHighestState(highestStatus, line, "endemic", false);
161
            }else{
162
                logger.warn(line + "Endemic not recognized: " + endemicStr);
163
            }
164
        }
165
        if (indigenousStr != null){
166
            if(indigenousStr.equals("+")){
167
                PresenceAbsenceTerm indigenousState = state.getTransformer().getPresenceTermByKey("Ind.");
168
//                PresenceAbsenceTerm indigenousState = getPresenceTerm(state, indigenousUuid, null, null, null, false);
169
                result.add(indigenousState);
170
                highestStatus = highestStatus != null ? highestStatus : indigenousState;
171
            }else if(isMinus(indigenousStr)){
172
                PresenceAbsenceTerm indigenousState = state.getTransformer().getPresenceTermByKey("-Ind.");
173
                result.add(indigenousState);
174
                checkAbsentHighestState(highestStatus, line, "indigenous", false);
175
            }else if(indigenousStr.equals("?")){
176
                PresenceAbsenceTerm indigenousDoubtState = state.getTransformer().getPresenceTermByKey("?Ind.");
177
//                PresenceAbsenceTerm indigenousDoubtState = getPresenceTerm(state, indigenousDoubtUuid, null, null, null, false);
178
                result.add(indigenousDoubtState);
179
                checkAbsentHighestState(highestStatus, line, "indigenous", true);
180
            }else{
181
                logger.warn(line + "Indigenous not recognized: " + indigenousStr);
182
            }
183
        }
184
        if(indigenousDoubtStr != null){
185
            if(indigenousDoubtStr.equals("D")){
186
                PresenceAbsenceTerm doubtIndigenousState = state.getTransformer().getPresenceTermByKey("Ind.?");
187
//                PresenceAbsenceTerm doubtIndigenousState = getPresenceTerm(state, doubtIndigenousUuid, null, null, null, false);
188
                result.add(doubtIndigenousState);
189
                highestStatus = highestStatus != null ? highestStatus : doubtIndigenousState;
190
            }else if(isMinus(indigenousDoubtStr)){
191
                UUID doubtIndigenousErrorUuid = state.getTransformer().getPresenceTermUuid("-Ind.?");
192
                PresenceAbsenceTerm doubtIndigenousErrorState = getPresenceTerm(state, doubtIndigenousErrorUuid, null, null, null, false);
193
                result.add(doubtIndigenousErrorState);
194
                checkAbsentHighestState(highestStatus, line, "doubtfully indigenous", true);
195
            }else{
196
                logger.warn(line + "doubtfully indigenous not recognized: " + indigenousDoubtStr);
197
            }
198
        }
199
        if(naturalisedStr != null){
200
            if(naturalisedStr.equals("N")){
201
                PresenceAbsenceTerm haturalizedState = state.getTransformer().getPresenceTermByKey("Nat.");
202
                result.add(haturalizedState);
203
                highestStatus = highestStatus != null ? highestStatus : haturalizedState;
204
            }else if(isMinus(naturalisedStr)){
205
                UUID naturalisedErrorUuid = state.getTransformer().getPresenceTermUuid("-Nat.");
206
                PresenceAbsenceTerm naturalisedErrorState = getPresenceTerm(state, naturalisedErrorUuid, null, null, null, false);
207
                result.add(naturalisedErrorState);
208
                checkAbsentHighestState(highestStatus, line, "naturalized", false);
209
            }else if(naturalisedStr.equals("?")){
210
                UUID naturalisedDoubtUuid = state.getTransformer().getPresenceTermUuid("?Nat.");
211
                PresenceAbsenceTerm naturalisedDoubtState = getPresenceTerm(state, naturalisedDoubtUuid, null, null, null, false);
212
                result.add(naturalisedDoubtState);
213
                checkAbsentHighestState(highestStatus, line, "naturalized", true);
214
            }else{
215
                logger.warn(line + "Naturalized not recognized: " + naturalisedStr);
216
            }
217
        }
218
        if(dudStr != null){
219
            if(dudStr.equals("P")){
220
                UUID dudUuid = state.getTransformer().getPresenceTermUuid("Dud.");
221
                PresenceAbsenceTerm dudState = getPresenceTerm(state, dudUuid, null, null, null, false);
222
                result.add(dudState);
223
                highestStatus = highestStatus != null ? highestStatus : dudState;
224
            }else if(isMinus(dudStr)){
225
                UUID nonNativeErrorUuid = state.getTransformer().getPresenceTermUuid("-Dud.");
226
                PresenceAbsenceTerm nonNativeErrorState = getPresenceTerm(state, nonNativeErrorUuid, null, null, null, false);
227
                result.add(nonNativeErrorState);
228
                checkAbsentHighestState(highestStatus, line, "non-native and doubtfully naturalised", false);
229
            }else if(dudStr.equals("?")){
230
                UUID naturalisedDoubtUuid = state.getTransformer().getPresenceTermUuid("?Dud.");
231
                PresenceAbsenceTerm naturalisedDoubtState = getPresenceTerm(state, naturalisedDoubtUuid, null, null, null, false);
232
                result.add(naturalisedDoubtState);
233
                checkAbsentHighestState(highestStatus, line, "non-native and doubtfully naturalised", true);
234
            }else{
235
                logger.warn(line + "non-native and doubtfully naturalised not recognized: " + dudStr);
236
            }
237
        }
238
        if(advStr != null){
239
            if(advStr.equals("A")){
240
                PresenceAbsenceTerm advState = state.getTransformer().getPresenceTermByKey("Adv.");
241
//                PresenceAbsenceTerm advState = getPresenceTerm(state, advUuid, null, null, null, false);
242
                result.add(advState);
243
                highestStatus = highestStatus != null ? highestStatus : advState;
244
            }else if(isMinus(advStr)){
245
                UUID advUuid = state.getTransformer().getPresenceTermUuid("-Adv.");
246
                PresenceAbsenceTerm advState = getPresenceTerm(state, advUuid, null, null, null, false);
247
                result.add(advState);
248
                checkAbsentHighestState(highestStatus, line, "adventive", false);
249
            }else if(advStr.equals("(A)")){
250
                UUID rareCasualUuid = state.getTransformer().getPresenceTermUuid("(A)");
251
                PresenceAbsenceTerm rareCasual = getPresenceTerm(state, rareCasualUuid, null, null, null, false);
252
                result.add(rareCasual);
253
            }else{
254
                logger.warn(line + "'adventive (casual) alien' not recognized: " + advStr);
255
            }
256
        }else if(cultStr != null){
257
            if (! (cultStr.matches("(C|\\(C\\)|\\?|–)"))){
258
                logger.warn("'cultivated' not recognized: " + cultStr);
259
            }else if(cultStr.equals("C")){
260
                PresenceAbsenceTerm cultivatedState = state.getTransformer().getPresenceTermByKey("Cult.");
261
                result.add(cultivatedState);
262
                highestStatus = highestStatus != null ? highestStatus : cultivatedState;
263
            }else if(cultStr.equals("?")){
264
                PresenceAbsenceTerm cultivatedState = state.getTransformer().getPresenceTermByKey("?Cult.");
265
                result.add(cultivatedState);
266
                checkAbsentHighestState(highestStatus, line, "cultivated", true);
267
            }else if(cultStr.equals("(C)")){
268
                UUID ocassualCultUuid = state.getTransformer().getPresenceTermUuid("(C)");
269
                PresenceAbsenceTerm cultivatedState = getPresenceTerm(state, ocassualCultUuid, null, null, null, false);
270
                result.add(cultivatedState);
271
            }else if(isMinus(cultStr)){
272
                PresenceAbsenceTerm cultivatedState = state.getTransformer().getPresenceTermByKey("-Cult.");
273
                result.add(cultivatedState);
274
                checkAbsentHighestState(highestStatus, line, "cultivated", false);
275
            }else{
276
                logger.warn(line + "'cultivated' not recognized: " + cultStr);
277
            }
278
        }
279
        state.setHighestStatusForTaxon(highestStatus);
280
        return result;
281
    }
282

    
283

    
284
    /**
285
     * @param highestStatus
286
     * @param line
287
     */
288
    private void checkAbsentHighestState(PresenceAbsenceTerm highestStatus, String line, String stateLabel, boolean doubtful) {
289
        //can be removed, highest status is not used anymore
290
        if (highestStatus == null){
291
            String absentStr = doubtful ? "doubtful" : "absent";
292
            logger.info(line + "Highest cuban state is " + absentStr + " " + stateLabel);
293
        }
294

    
295
    }
296

    
297

    
298
    /**
299
     * @param indigenousStr
300
     * @return
301
     */
302
    private boolean isMinus(String str) {
303
        return str.equals("-") || str.equals("–") || str.equals("‒");
304
    }
305

    
306

    
307
    /**
308
     * @param indigenousStr
309
     * @return
310
     */
311
    private boolean checkPlusMinusDoubt(String str) {
312
        return str.equals("+") || isMinus(str)|| str.equals("?");
313
    }
314

    
315

    
316
    /**
317
     * @param indigenousStr
318
     * @param indigenousDoubtStr
319
     * @param naturalisedStr
320
     * @param dudStr
321
     * @param advStr
322
     * @param cultStr
323
     */
324
    private boolean checkAllNull(String ... others) {
325
        for (String other : others){
326
            if (other != null){
327
                return false;
328
            }
329
        }
330
        return true;
331
    }
332

    
333

    
334
    private static final String acceptedRegExStr = "\\(([^\\[\\]“”]{6,})\\)";
335
//    String heterotypicRegExStr2 = "([^\\(]{5,}" +"(\\(.+\\))?" + "[^\\)\\(]{2,})" +
336
//                    + "(\\((.{6,})\\))?";
337
    private static final String heterotypicRegExStr = "([^\\(\\[\\]“”]{5,})"
338
                                                     +"(\\((.{6,})\\))?";
339
    private static final String heterotypicRegExStr_TEST = "([^\\(]{5,}" +"(\\(.+\\))?" + "[^\\)\\(]{2,})"
340
            +"(\\((.{6,})\\))?";
341
    private static final String auctRegExStr = "auct\\."
342
            +"((\\sFC(\\-S)?(\\s&\\sA&S)?)|(\\sA&S)|\\sSagra|\\sCombs|\\sBritton|\\sGriseb\\.(\\sFC-S|\\sA&S)?|\\sWright"
343
            + "|\\sHammer|\\sEngl\\.||\\sMaza|\\sMiers|\\sRoig|\\sBorhidi|\\sFRC|\\sCoL"
344
            + "|\\sAckerman|\\sMújica|\\sDíaz|\\sUrb\\.)?(\\s+p\\.\\s*p\\.)?";
345

    
346

    
347
    private static final String missapliedRegExStr = "(\\?\\s)?“(.*{5,})”\\s+(" + auctRegExStr + "|sensu\\s+.{2,})";
348
    private static final String sphalmRegExStr = "“(.*{5,})”\\s+((FC-S|A&S)\\s)?sphalm\\.(\\s(FC(-S)?|A&S|inval\\.))?";
349
    private static final String nomInvalRegExStr = "“(.*{5,})”\\s+nom\\.\\s+inval\\.(\\s(West|Moldenke|FC|Jacq.))?";
350
    private static final String homonymRegExStr = "\\s*(\\[.*\\])*\\s*";
351

    
352
    private static final Pattern acceptedRegEx = Pattern.compile(acceptedRegExStr + homonymRegExStr);
353
    private static final Pattern heterotypicRegEx = Pattern.compile(heterotypicRegExStr + homonymRegExStr);
354
    private static final Pattern missapliedRegEx = Pattern.compile(missapliedRegExStr);
355
    private static final Pattern nomInvalRegEx = Pattern.compile(nomInvalRegExStr);
356
    private static final Pattern sphalmRegEx = Pattern.compile(sphalmRegExStr);
357

    
358
    /**
359
     * @param record
360
     * @param state
361
     * @param taxon
362
     */
363
    private void makeSynonyms(HashMap<String, String> record, CubaImportState state, boolean isFirstSynonym) {
364
//        boolean forAccepted = true;
365
        String synonymStr = record.get("Syn.");
366
        String line = state.getCurrentLine() + ": ";
367

    
368

    
369
        if (synonymStr == null){
370
            //TODO test that this is not a synonym only line
371
            return;
372
        }
373

    
374
        if (state.getCurrentTaxon() == null){
375
            logger.error(line + "Current taxon is null for synonym");
376
            return;
377
        }
378

    
379

    
380
        synonymStr = synonymStr.trim();
381
        synonymStr = synonymStr.replace("[taxon]", "[infraspec.]");
382

    
383
//        String heterotypicRegExStr = "([^\\(]{5,}(\\(.+\\))?[^\\)\\(]{2,})(\\((.{6,})\\))?";
384
//        String heterotypicRegExStr = "([^\\(]{5,})(\\((.{6,})\\))?";
385

    
386
//        Pattern heterotypicRegEx = Pattern.compile(heterotypicRegExStr + homonymRegExStr);
387

    
388

    
389
        Matcher missapliedMatcher = missapliedRegEx.matcher(synonymStr);
390
        Matcher nomInvalMatcher = nomInvalRegEx.matcher(synonymStr);
391
        Matcher acceptedMatcher = acceptedRegEx.matcher(synonymStr);
392
        Matcher heterotypicMatcher = heterotypicRegEx.matcher(synonymStr);
393
        Matcher sphalmMatcher = sphalmRegEx.matcher(synonymStr);
394

    
395
        List<IBotanicalName> homonyms = new ArrayList<>();
396
        if (missapliedMatcher.matches()){
397
            boolean doubtful = missapliedMatcher.group(1) != null;
398
            String firstPart = missapliedMatcher.group(2);
399
            BotanicalName name = (BotanicalName)nameParser.parseSimpleName(firstPart, state.getConfig().getNomenclaturalCode(), Rank.SPECIES());
400
            name.addSource(makeOriginalSource(state));
401

    
402
            String secondPart = missapliedMatcher.group(3);
403
            Taxon misappliedNameTaxon = Taxon.NewInstance(name, null);
404
            misappliedNameTaxon.addSource(makeOriginalSource(state));
405
            misappliedNameTaxon.setDoubtful(doubtful);
406
            if (secondPart.startsWith("sensu")){
407
                secondPart = secondPart.substring(5).trim();
408
                if (secondPart.contains(" ")){
409
                    logger.warn(line + "CHECK: Second part contains more than 1 word. Check if this is correct: " + secondPart);
410
                }
411
                Reference sensu = ReferenceFactory.newGeneric();
412
                Team team = Team.NewTitledInstance(secondPart, null);
413
                sensu.setAuthorship(team);
414
                misappliedNameTaxon.setSec(sensu);
415
            }else if (secondPart.matches(auctRegExStr)){
416
                secondPart = secondPart.replace("p. p.", "p.p.");
417
                misappliedNameTaxon.setAppendedPhrase(secondPart);
418
            }else{
419
                logger.warn(line + "Misapplied second part not recognized: " + secondPart);
420
            }
421
            //TODO
422
            Reference relRef = null;
423
            state.getCurrentTaxon().addMisappliedName(misappliedNameTaxon, relRef, null);
424
        }else if (nomInvalMatcher.matches()){
425
            String firstPart = nomInvalMatcher.group(1);
426
            String afterInval = nomInvalMatcher.group(2);
427
            if (StringUtils.isNotBlank(afterInval)){
428
                logger.warn(state.getCurrentLine() + ": After inval to be implemented: " + afterInval);
429
            }
430
            BotanicalName name = (BotanicalName)nameParser.parseSimpleName(firstPart, state.getConfig().getNomenclaturalCode(), Rank.SPECIES());
431
            name.addSource(makeOriginalSource(state));
432
            NomenclaturalStatus status = NomenclaturalStatus.NewInstance( NomenclaturalStatusType.INVALID());
433
            name.addStatus(status);
434
            Synonym syn = state.getCurrentTaxon().addSynonymName(name, SynonymType.SYNONYM_OF());
435
            syn.addSource(makeOriginalSource(state));
436
        }else if (sphalmMatcher.matches()){
437
            String firstPart = sphalmMatcher.group(1);
438
            String sphalmPart = synonymStr.replace(firstPart, "").replace("“","").replace("”","").trim();
439
            BotanicalName name = (BotanicalName)nameParser.parseSimpleName(firstPart, state.getConfig().getNomenclaturalCode(), Rank.SPECIES());
440
//            NomenclaturalStatus status = NomenclaturalStatus.NewInstance( NomenclaturalStatusType.INVALID());
441
//            name.addStatus(status);
442
            name.addSource(makeOriginalSource(state));
443
            Synonym syn = state.getCurrentTaxon().addSynonymName(name, SynonymType.SYNONYM_OF());
444
            syn.setAppendedPhrase(sphalmPart);
445
            syn.setSec(null);
446
            syn.addSource(makeOriginalSource(state));
447
        }else if (acceptedMatcher.matches()){
448
            String firstPart = acceptedMatcher.group(1);
449
            String homonymPart = acceptedMatcher.groupCount() < 2 ? null : acceptedMatcher.group(2);
450
            List<IBotanicalName> list = handleHomotypicGroup(firstPart, state, state.getCurrentTaxon().getName(), false, homonyms, homonymPart, false);
451
            checkFirstSynonym(state, list, isFirstSynonym, synonymStr, false);
452
        }else if(heterotypicMatcher.matches()){
453
            String firstPart = heterotypicMatcher.group(1).trim();
454
            String secondPart = heterotypicMatcher.groupCount() < 3 ? null : heterotypicMatcher.group(3);
455
            String homonymPart = heterotypicMatcher.groupCount() < 4 ? null : heterotypicMatcher.group(4);
456
            boolean isDoubtful = firstPart.matches("^\\?\\s*.*");
457
            firstPart = replaceHomonIlleg(firstPart);
458
            boolean isHomonym = firstPart.matches(".*" + HOMONYM_MARKER);
459
            BotanicalName synName = makeName(state, firstPart);
460
            if (synName.isProtectedTitleCache()){
461
                logger.warn(line + "Heterotypic base synonym could not be parsed correctly: " + firstPart);
462
            }
463
            if (isHomonym){
464
                homonyms.add(synName);
465
            }
466
            Synonym syn = state.getCurrentTaxon().addHeterotypicSynonymName(synName);
467
            syn.setDoubtful(isDoubtful);
468
            syn.addSource(makeOriginalSource(state));
469
            List<IBotanicalName> list = handleHomotypicGroup(secondPart, state, synName, true, homonyms, homonymPart, isDoubtful);
470
            checkFirstSynonym(state, list, isFirstSynonym, synonymStr, true);
471

    
472
        }else if (isSpecialHeterotypic(synonymStr)){
473
            BotanicalName synName = makeName(state, synonymStr);
474
            if (synName.isProtectedTitleCache()){
475
                logger.warn(line + "Special heterotypic synonym could not be parsed correctly:" + synonymStr);
476
            }
477
            Synonym syn = state.getCurrentTaxon().addHeterotypicSynonymName(synName);
478
            syn.addSource(makeOriginalSource(state));
479
        }else{
480
            logger.warn(line + "Synonym entry does not match: " + synonymStr);
481
        }
482
    }
483

    
484
    /**
485
     * @param state
486
     * @param list
487
     * @param isFirstSynonym
488
     * @param synonymStr
489
     * @param b
490
     */
491
    private void checkFirstSynonym(CubaImportState state, List<IBotanicalName> list, boolean isFirstSynonym, String synonymStr, boolean isHeterotypicMatcher) {
492
        if (!isFirstSynonym){
493
            return;
494
        }
495
        String line = state.getCurrentLine() + ": ";
496
        IBotanicalName currentName = isHeterotypicMatcher? (IBotanicalName)state.getCurrentTaxon().getName(): list.get(0);
497
        boolean currentHasBasionym = currentName.getBasionymAuthorship() != null;
498
        IBotanicalName firstSynonym = isHeterotypicMatcher ? list.get(0): list.get(1);
499
//        if (list.size() <= 1){
500
//            logger.error(line + "homotypic list size is 1 but shouldn't");
501
//            return;
502
//        }
503
        if (isHeterotypicMatcher && currentHasBasionym){
504
            logger.error(line + "Current taxon (" + currentName.getTitleCache() + ") has basionym author but has no homotypic basionym , but : " + synonymStr);
505
        }else if (isHeterotypicMatcher){
506
            //first synonym must not have a basionym author
507
            if (firstSynonym.getBasionymAuthorship() != null){
508
                logger.error(line + "Current taxon (" + currentName.getTitleCache() + ") has no basionym but first synonym requires basionym : " + synonymStr);
509
            }
510
        }else{  //isAcceptedMatcher
511
            if (currentHasBasionym){
512
                if (! matchAuthor(currentName.getBasionymAuthorship(), firstSynonym.getCombinationAuthorship())){
513
                    logger.info(line + "Current basionym author and first synonym combination author do not match: " + currentName.getTitleCache() + "<->" + firstSynonym.getTitleCache());
514
                }
515
            }else{
516
                if (! matchAuthor(currentName.getCombinationAuthorship(), firstSynonym.getBasionymAuthorship())){
517
                    logger.info(line + "Current combination author and first synonym basionym author do not match: " + currentName.getTitleCache() + "<->" + firstSynonym.getTitleCache());
518
                }
519
            }
520
        }
521

    
522
    }
523

    
524

    
525
    /**
526
     * @param synonymStr
527
     * @return
528
     */
529
    private boolean isSpecialHeterotypic(String synonymStr) {
530
        if (synonymStr == null){
531
            return false;
532
        }else if (synonymStr.equals("Rhynchospora prenleloupiana (‘prenteloupiana’) Boeckeler")){
533
            return true;
534
        }else if (synonymStr.equals("Psidium longipes var. orbiculare (O.Berg) McVaugh")){
535
            return true;
536
        }
537
        return false;
538
    }
539

    
540

    
541
    /**
542
     * @param areaKey
543
     * @param record
544
     * @param state
545
     * @param taxon
546
     */
547
    private void makeSingleProvinceDistribution(String areaKey,
548
            HashMap<String, String> record,
549
            CubaImportState state) {
550
        try {
551
            UUID areaUuid = state.getTransformer().getNamedAreaUuid(areaKey);
552
            if (areaUuid == null){
553
                logger.warn("Area not recognized: " + areaKey);
554
                return;
555
            }
556
            if (record.get(areaKey)==null){
557
                return; //no status defined
558
            }
559

    
560
            NamedArea area = getNamedArea(state, areaUuid, null, null, null, null, null);
561
            if (area == null){
562
                logger.warn(state.getCurrentLine() + ": Area not recognized: " + area);
563
            }
564
            TaxonDescription desc = getTaxonDescription(state.getCurrentTaxon(), false, true);
565
            PresenceAbsenceTerm status =  makeProvinceStatus(areaKey, record, state);
566
            if (status == null){
567
                logger.warn(state.getCurrentLine() + ": Province distribution status could not be defined: " + record.get(areaKey));
568
            }
569
            Distribution distribution = Distribution.NewInstance(area, status);
570
            desc.addElement(distribution);
571
            distribution.addSource(makeDescriptionSource(state));
572
        } catch (UndefinedTransformerMethodException e) {
573
            e.printStackTrace();
574
        }
575

    
576
    }
577

    
578

    
579
    /**
580
     * @param synonymStr
581
     * @param state
582
     * @param homonyms
583
     * @param homonymPart
584
     * @param isDoubtful
585
     * @param taxon
586
     * @param homotypicalGroup
587
     */
588
    private List<IBotanicalName> handleHomotypicGroup(String homotypicStrOrig,
589
            CubaImportState state,
590
            IBotanicalName homotypicName,
591
            boolean isHeterotypic,
592
            List<IBotanicalName> homonyms,
593
            String homonymPart,
594
            boolean isDoubtful) {
595

    
596
        List<IBotanicalName> homotypicNameList = new ArrayList<>();
597
        homotypicNameList.add(homotypicName);
598

    
599
        String homotypicStr = homotypicStrOrig;
600
        if (homotypicStr == null){
601
            return homotypicNameList;
602
        }else if (homotypicStr.startsWith("(") && homotypicStr.endsWith("")){
603
            homotypicStr = homotypicStr.substring(1, homotypicStr.length() - 1);
604
        }
605

    
606
        HomotypicalGroup homotypicGroup = homotypicName.getHomotypicalGroup();
607
        String[] splits = homotypicStr.split("\\s*,\\s*");
608
        for (String split : splits){
609
            split = replaceHomonIlleg(split);
610
            boolean isHomonym = split.matches(".*" + HOMONYM_MARKER);
611
            TaxonNameBase<?,?> newName = makeName(state, split);
612
            newName.setHomotypicalGroup(homotypicGroup);  //not really necessary as this is later set anyway
613
            if (newName.isProtectedTitleCache()){
614
                logger.warn(state.getCurrentLine() + ": homotypic name part could not be parsed: " + split);
615
            }
616
            if (isHomonym){
617
                homonyms.add(newName);
618
            }
619
            if (isHeterotypic){
620
                Synonym syn = state.getCurrentTaxon().addHeterotypicSynonymName(newName, null, null, homotypicGroup);
621
                syn.setDoubtful(isDoubtful);
622
                syn.addSource(makeOriginalSource(state));
623
//                newName.addBasionym(homotypicName);
624
            }else{
625
                state.getCurrentTaxon().addHomotypicSynonymName(newName);
626
            }
627
            handleBasionym(state, homotypicNameList, homonyms, newName);
628
            homotypicNameList.add(newName);
629
        }
630
        makeHomonyms(homonyms, homonymPart, state, homotypicGroup);
631
        return homotypicNameList;
632
    }
633

    
634

    
635
    /**
636
     * @param split
637
     * @return
638
     */
639
    private String replaceHomonIlleg(String split) {
640
        String result = split.trim().replace("homon. illeg.", "nom. illeg. homon.").trim();
641
        return result;
642
    }
643

    
644

    
645
    /**
646
     * @param homonyms
647
     * @param homonymPart
648
     * @param state
649
     * @param currentBasionym
650
     */
651
    private void makeHomonyms(List<IBotanicalName> homonyms, String homonymPartOrig, CubaImportState state,
652
            HomotypicalGroup homotypicGroup) {
653
        String line = state.getCurrentLine() + ": ";
654
        String homonymPart = homonymPartOrig == null ? "" : homonymPartOrig.trim();
655
        if (homonyms.isEmpty() && homonymPart.equals("")){
656
            return;
657
        }else if (homonymPart.equals("")){
658
            logger.warn(line + "SynonymPart has homonyms but homonymPart is empty");
659
            return;
660
        }
661
        homonymPart = homonymPart.substring(1, homonymPart.length() - 1);
662
        String[] splits = homonymPart.split("\\]\\s*\\[");
663
        if (splits.length != homonyms.size()){
664
            if(homonyms.size() == 0 && splits.length >= 1){
665
                handleSimpleBlockingNames(splits, state, homotypicGroup);
666
            }else{
667
                logger.warn(line + "Number of homonyms (" + homonyms.size() + ") and homonymParts ("+splits.length+") does not match");
668
            }
669
            return;
670
        }
671
        int i = 0;
672
        for (String split : splits){
673
            split = split.replaceAll("^non\\s+", "");
674
            BotanicalName newName = makeName(state, split);
675
//            BotanicalName newName = (BotanicalName)nameParser.parseReferencedName(split, state.getConfig().getNomenclaturalCode(), Rank.SPECIES());
676
            if (newName.isProtectedTitleCache()){
677
                logger.warn(state.getCurrentLine() + ": homonym name could not be parsed: " + split);
678
            }
679
            homonyms.get(i).addRelationshipToName(newName, NameRelationshipType.LATER_HOMONYM(), null);
680
            i++;
681
        }
682
    }
683

    
684
    /**
685
     * @param homonymPart
686
     * @param state
687
     * @param homotypicGroup
688
     */
689
    private void handleSimpleBlockingNames(String[] splitsi,
690
            CubaImportState state,
691
            HomotypicalGroup homotypicGroup) {
692
        List<IBotanicalName> replacementNameCandidates = new ArrayList<>();
693
        for (String spliti : splitsi){
694

    
695
            String split = spliti.replaceAll("^non\\s+", "");
696
            BotanicalName newName = makeName(state, split);
697
            if (newName.isProtectedTitleCache()){
698
                logger.warn(state.getCurrentLine() + ": blocking name could not be parsed: " + split);
699
            }
700
            Set<IBotanicalName> typifiedNames = (Set)homotypicGroup.getTypifiedNames();
701
            Set<IBotanicalName> candidates = new HashSet<>();
702
            for (IBotanicalName name : typifiedNames){
703
                if (name.getGenusOrUninomial() != null && name.getGenusOrUninomial().equals(newName.getGenusOrUninomial())){
704
                    if (name.getStatus().isEmpty() || ! name.getStatus().iterator().next().getType().equals(NomenclaturalStatusType.ILLEGITIMATE())){
705
                        candidates.add(name);
706
                    }
707
                }
708
            }
709
            if (candidates.size() == 1){
710
                TaxonNameBase<?,?> blockedName = (TaxonNameBase<?,?>)candidates.iterator().next();
711
                newName.addRelationshipToName(blockedName, NameRelationshipType.BLOCKING_NAME_FOR(), null);
712
                replacementNameCandidates.add(blockedName);
713
            }else{
714
                logger.warn(state.getCurrentLine() + ": Blocking name could not be handled. " + candidates.size() + " candidates.");
715
            }
716
        }
717
        makeReplacedSynonymIfPossible(state, homotypicGroup, replacementNameCandidates);
718
    }
719

    
720
    /**
721
     * @param homotypicGroup
722
     * @param replacementNameCandidates
723
     */
724
    private void makeReplacedSynonymIfPossible(CubaImportState state,
725
            HomotypicalGroup homotypicGroup,
726
            List<IBotanicalName> replacementNameCandidates) {
727
        String line = state.getCurrentLine() +": ";
728
        List<BotanicalName> replacedCandidates = new ArrayList<>();
729
        for (TaxonNameBase<?, ?> typifiedName : homotypicGroup.getTypifiedNames()){
730
            BotanicalName candidate = (BotanicalName)typifiedName;
731
            if (candidate.getBasionymAuthorship() == null){
732
                if (candidate.getStatus().isEmpty()){
733
                    if (! replacementNameCandidates.contains(candidate)){
734
                        replacedCandidates.add(candidate);
735
                    }
736
                }
737
            }
738
        }
739
        if (replacedCandidates.size() == 1){
740
            TaxonNameBase<?,?> replacedSynonym = replacedCandidates.iterator().next();
741
            for (IBotanicalName replacementName : replacementNameCandidates){
742
                replacementName.addReplacedSynonym(replacedSynonym, null, null, null);
743
            }
744
        }else if (replacedCandidates.size() < 1){
745
            logger.warn(line + "No replaced synonym candidate found");
746
        }else{
747
            logger.warn(line + "More than 1 ("+replacedCandidates.size()+") replaced synonym candidates found");
748
        }
749
    }
750

    
751

    
752
    /**
753
     * @param homotypicGroup
754
     * @param newName
755
     */
756
    private void handleBasionym(CubaImportState state, List<IBotanicalName> homotypicNameList,
757
            List<IBotanicalName> homonyms, IBotanicalName newName) {
758
        for (IBotanicalName existingName : homotypicNameList){
759
            if (existingName != newName){  //should not happen anymore, as new name is added later
760
                boolean onlyIfNotYetExists = true;
761
                createBasionymRelationIfPossible(state, existingName, newName, homonyms.contains(newName), onlyIfNotYetExists);
762
            }
763
        }
764
    }
765

    
766
    /**
767
     * @param state
768
     * @param name1
769
     * @param name2
770
     * @return
771
     */
772
    private void createBasionymRelationIfPossible(CubaImportState state, IBotanicalName name1,
773
            IBotanicalName name2,
774
            boolean name2isHomonym, boolean onlyIfNotYetExists) {
775
        TaxonNameBase<?,?> basionymName = TaxonNameBase.castAndDeproxy(name1);
776
        TaxonNameBase<?,?> newCombination = TaxonNameBase.castAndDeproxy(name2);
777
        //exactly one name must have a basionym author
778
        if (name1.getBasionymAuthorship() == null && name2.getBasionymAuthorship() == null
779
                || name1.getBasionymAuthorship() != null && name2.getBasionymAuthorship() != null){
780
            return;
781
        }
782

    
783
        //switch order if necessary
784
        if (! name2isHomonym && basionymName.getBasionymAuthorship() != null && newCombination.getBasionymAuthorship() == null){
785
            basionymName = TaxonNameBase.castAndDeproxy(name2);
786
            newCombination = TaxonNameBase.castAndDeproxy(name1);
787
        }
788
        if (matchAuthor(basionymName.getCombinationAuthorship(), newCombination.getBasionymAuthorship())
789
                && matchLastNamePart(basionymName, newCombination)){
790
            newCombination.addBasionym(basionymName);
791
        }else{
792
            if ( (newCombination.getBasionyms().isEmpty() || ! onlyIfNotYetExists)
793
                    && isLegitimate(basionymName)
794
                    && ! name2isHomonym){
795
                logger.info(state.getCurrentLine() + ": Names are potential basionyms but either author or name part do not match: " + basionymName.getTitleCache() + " <-> " + newCombination.getTitleCache());
796
            }
797
        }
798
    }
799

    
800
    /**
801
     * @param basionymName
802
     * @return
803
     */
804
    private boolean isLegitimate(IBotanicalName basionymName) {
805
        for (NomenclaturalStatus nomStatus : basionymName.getStatus()){
806
            if (nomStatus.getType()!= null && nomStatus.getType().isIllegitimateType()){
807
                    return false;
808
            }
809
        }
810
        for (NameRelationship nameRel : basionymName.getNameRelations()){
811
            if (nameRel.getType()!= null && nameRel.getType().isIllegitimateType()){
812
                    return false;
813
            }
814
        }
815
        return true;
816
    }
817

    
818

    
819
    /**
820
     * @param basionymName
821
     * @param newCombination
822
     * @return
823
     */
824
    private boolean matchLastNamePart(IBotanicalName name1, IBotanicalName name2) {
825
        String lastNamePart1 = name1.getLastNamePart();
826
        String lastNamePart2 = name2.getLastNamePart();
827
        if (lastNamePart1 != null && lastNamePart2 != null){
828
            lastNamePart1 = normalizeBasionymNamePart(lastNamePart1);
829
            lastNamePart2 = normalizeBasionymNamePart(lastNamePart2);
830
            return (lastNamePart1.equals(lastNamePart2));
831
        }else{
832
            return false;
833
        }
834
    }
835

    
836
    /**
837
     * @param lastNamePart1
838
     * @return
839
     */
840
    private String normalizeBasionymNamePart(String lastNamePart) {
841
        String namePart = lastNamePart.toLowerCase()
842
                .replaceAll("(um|us|a|is|e|os|on|or)$", "")
843
                .replaceAll("er$", "r")    //e.g. ruber <-> rubra
844
                .replaceAll("ese$", "s");  //e.g.  cayanensis <-> cayanenese
845
                //TODO tampensis / tampense
846
        return namePart;
847
    }
848

    
849

    
850
    /**
851
     * @param combinationAuthorship
852
     * @param basi
853
     * @return
854
     */
855
    private boolean matchAuthor(TeamOrPersonBase<?> author1, TeamOrPersonBase<?> author2) {
856
        if (author1 == null || author2 == null){
857
            return false;
858
        }else {
859
            return author1.getNomenclaturalTitle().equals(author2.getNomenclaturalTitle());
860
        }
861
    }
862

    
863

    
864
    /**
865
     * @param record
866
     * @param state
867
     * @param taxon
868
     */
869
    private void makeNotes(HashMap<String, String> record, CubaImportState state) {
870
        String notesStr = getValue(record, "(Notas)");
871
        if (notesStr == null){
872
            return;
873
        }else{
874
            Annotation annotation = Annotation.NewDefaultLanguageInstance(notesStr);
875
            //TODO
876
            annotation.setAnnotationType(AnnotationType.TECHNICAL());
877
            state.getCurrentTaxon().addAnnotation(annotation);
878
        }
879
    }
880

    
881

    
882
    /**
883
     * @param record
884
     * @param state
885
     * @param familyTaxon
886
     * @return
887
     */
888
    private Taxon makeTaxon(HashMap<String, String> record, CubaImportState state, TaxonNode familyNode, boolean isSynonym) {
889
        String taxonStrOrig = getValue(record, "Taxón");
890
        if (taxonStrOrig == null){
891
            return isSynonym ? state.getCurrentTaxon() : null;
892
        }
893

    
894
        boolean isAbsent = false;
895
        String taxonStr = taxonStrOrig;
896
        if (taxonStrOrig.startsWith("[") && taxonStrOrig.endsWith("]")){
897
            taxonStr = taxonStr.substring(1, taxonStr.length() - 1);
898
            isAbsent = true;
899
        }
900

    
901
        boolean isAuct = false;
902
        if (taxonStr.endsWith("auct.")){
903
            isAuct = true;
904
            taxonStr.replace("auct.", "").trim();
905
        }
906
        state.setTaxonIsAbsent(isAbsent);
907
        BotanicalName botanicalName = makeName(state, taxonStr);
908
        Reference sec = getSecReference(state);
909
        Taxon taxon = Taxon.NewInstance(botanicalName, sec);
910
        if (isAuct){
911
            taxon.setAppendedPhrase("auct.");
912
        }
913

    
914
        TaxonNode higherNode;
915
        if (botanicalName.isProtectedTitleCache()){
916
            logger.warn(state.getCurrentLine() + ": Taxon could not be parsed: " + taxonStrOrig);
917
            higherNode = familyNode;
918
        }else{
919
            String genusStr = botanicalName.getGenusOrUninomial();
920
            Taxon genus = state.getHigherTaxon(genusStr);
921
            if (genus != null){
922
                higherNode = genus.getTaxonNodes().iterator().next();
923
            }else{
924
                BotanicalName name = TaxonNameFactory.NewBotanicalInstance(Rank.GENUS());
925
                name.addSource(makeOriginalSource(state));
926
                name.setGenusOrUninomial(genusStr);
927
                genus = Taxon.NewInstance(name, sec);
928
                genus.addSource(makeOriginalSource(state));
929
                higherNode = familyNode.addChildTaxon(genus, null, null);
930
                state.putHigherTaxon(genusStr, genus);
931
            }
932
        }
933
        taxon.addSource(makeOriginalSource(state));
934

    
935
        TaxonNode newNode = higherNode.addChildTaxon(taxon, null, null);
936
        if(isAbsent){
937
            botanicalName.setTitleCache(taxonStrOrig, true);
938
            newNode.setExcluded(true);
939
        }
940

    
941
        return taxon;
942
    }
943

    
944
    private final String orthVarRegExStr = "[A-Z][a-z]+\\s[a-z]+\\s(\\(‘([a-z]){3,}’\\))\\s(\\([A-Z][a-z]+\\.?\\)\\s)?[A-Z][a-zó]+\\.?";
945
    private final Pattern orthVarRegEx = Pattern.compile(orthVarRegExStr);
946
    /**
947
     * @param taxonStr
948
     * @return
949
     */
950
    private BotanicalName makeName(CubaImportState state, String nameStrOrig) {
951
        //normalize
952
        String nameStr = normalizeStatus(nameStrOrig);
953
        //orthVar
954
        Matcher orthVarMatcher = orthVarRegEx.matcher(nameStr);
955
        String orthVar = null;
956
        if (orthVarMatcher.matches()) {
957
            orthVar = orthVarMatcher.group(1);
958
            nameStr = nameStr.replace(" " + orthVar, "").trim().replaceAll("\\s{2,}", " ");
959
            orthVar = orthVar.substring(2, orthVar.length() - 2);
960
        }
961

    
962
        boolean isNomInval = false;
963
        if (nameStr.endsWith("nom. inval.")){
964
            isNomInval = true;
965
            nameStr = nameStr.replace("nom. inval.", "").trim();
966
        }
967

    
968
        BotanicalName result = (BotanicalName)nameParser.parseReferencedName(nameStr, nc, Rank.SPECIES());
969
        result.addSource(makeOriginalSource(state));
970
        if (isNomInval){
971
            result.addStatus(NomenclaturalStatus.NewInstance(NomenclaturalStatusType.INVALID()));
972
        }
973
        if (orthVar != null){
974
            BotanicalName orthVarName = (BotanicalName)result.clone();
975
            orthVarName.addSource(makeOriginalSource(state));
976
            //TODO
977
            Reference citation = null;
978
            orthVarName.addRelationshipToName(result, NameRelationshipType.ORTHOGRAPHIC_VARIANT(), citation, null, null);
979
            orthVarName.setSpecificEpithet(orthVar);
980
        }
981
        normalizeAuthors(result);
982
        return result;
983

    
984
    }
985

    
986
    /**
987
     * @param result
988
     */
989
    private void normalizeAuthors(IBotanicalName result) {
990
        result.setCombinationAuthorship(normalizeAuthor(result.getCombinationAuthorship()));
991
        result.setExCombinationAuthorship(normalizeAuthor(result.getExCombinationAuthorship()));
992
        result.setExBasionymAuthorship(normalizeAuthor(result.getExBasionymAuthorship()));
993
        result.setBasionymAuthorship(normalizeAuthor(result.getBasionymAuthorship()));
994

    
995
    }
996

    
997

    
998
    /**
999
     * @param combinationAuthorship
1000
     * @return
1001
     */
1002
    private TeamOrPersonBase<?> normalizeAuthor(TeamOrPersonBase<?> author) {
1003
        if (author == null){
1004
            return null;
1005
        }
1006
        TeamOrPersonBase<?> result;
1007
        if (author.isInstanceOf(Person.class)){
1008
            result = normalizePerson(CdmBase.deproxy(author, Person.class));
1009
        }else{
1010
            Team team = CdmBase.deproxy(author, Team.class);
1011
            List<Person> list = team.getTeamMembers();
1012
            for(int i = 0; i < list.size(); i++){
1013
                Person person = list.get(i);
1014
                Person tmpMember = normalizePerson(person);
1015
                list.set(i, tmpMember);
1016
            }
1017
            return team;
1018
        }
1019
        return result;
1020
    }
1021

    
1022

    
1023
    /**
1024
     * @param deproxy
1025
     * @return
1026
     */
1027
    private Person normalizePerson(Person person) {
1028
        String title = person.getNomenclaturalTitle();
1029
        title = title.replaceAll("(?<=[a-zA-Z])\\.(?=[a-zA-Z])", ". ");
1030
        person.setNomenclaturalTitle(title);
1031
        boolean isFilius = title.endsWith(" f.");
1032
        if (isFilius){
1033
            title.replace(" f.", "");
1034
        }
1035

    
1036
        String[] splits = title.split("\\s+");
1037
        int nNotFirstName = isFilius ? 2 : 1;
1038
        person.setLastname(splits[splits.length - nNotFirstName] + (isFilius? " f." : ""));
1039
        person.setFirstname(CdmUtils.concat(" ", Arrays.copyOfRange(splits, 0, splits.length-nNotFirstName)));
1040
        return person;
1041
    }
1042

    
1043

    
1044
    /**
1045
     * @param state
1046
     * @return
1047
     */
1048
    private Reference getSecReference(CubaImportState state) {
1049
        Reference result = state.getSecReference();
1050
        if (result == null){
1051
            result = ReferenceFactory.newDatabase();
1052
            result.setTitle("Flora of Cuba");
1053
            state.setSecReference(result);
1054
        }
1055
        return result;
1056
    }
1057

    
1058

    
1059
    private static final String[] nomStatusStrings = new String[]{"nom. cons.", "ined.", "nom. illeg.",
1060
            "nom. rej.","nom. cons. prop.","nom. altern.","nom. confus.","nom. dub.", "nom. nud."};
1061
    /**
1062
     * @param taxonStr
1063
     * @return
1064
     */
1065
    private String normalizeStatus(String nameStr) {
1066
        if (nameStr == null){
1067
            return null;
1068
        }
1069
        String result = nameStr.replaceAll(HOMONYM_MARKER, "").trim();
1070
        for (String nomStatusStr : nomStatusStrings){
1071
            nomStatusStr = " " + nomStatusStr;
1072
            if (result.endsWith(nomStatusStr)){
1073
                result = result.replace(nomStatusStr, "," + nomStatusStr);
1074
            }
1075
        }
1076
        result = result.replaceAll(DOUBTFUL_MARKER, "").trim();
1077
        result = result.replace("[taxon]", "[infraspec.]");
1078
        return result;
1079

    
1080

    
1081
    }
1082

    
1083

    
1084
    /**
1085
     * @param record
1086
     * @param state
1087
     * @return
1088
     */
1089
    private TaxonNode getFamilyTaxon(HashMap<String, String> record, CubaImportState state) {
1090
        String familyStr = getValue(record, "Fam. default");
1091
        if (familyStr == null){
1092
            return null;
1093
        }
1094
        familyStr = familyStr.trim();
1095
        String alternativeFamilyStr = null;
1096
        if (familyStr.contains("/")){
1097
            String[] splits = familyStr.split("/");
1098
            if (splits.length > 2){
1099
                logger.warn(state.getCurrentLine() +": " + "More than 1 alternative name:" + familyStr);
1100
            }
1101
            familyStr = splits[0].trim();
1102
            alternativeFamilyStr = splits[1].trim();
1103
        }
1104

    
1105
        Taxon family = state.getHigherTaxon(familyStr);
1106
        TaxonNode familyNode;
1107
        if (family != null){
1108
            familyNode = family.getTaxonNodes().iterator().next();
1109
        }else{
1110
            BotanicalName name = makeFamilyName(state, familyStr);
1111
            Reference sec = getSecReference(state);
1112
            family = Taxon.NewInstance(name, sec);
1113
            ITaxonTreeNode rootNode = getClassification(state);
1114
            familyNode = rootNode.addChildTaxon(family, sec, null);
1115
            state.putHigherTaxon(familyStr, family);
1116

    
1117
        }
1118

    
1119
        if (isNotBlank(alternativeFamilyStr)){
1120
            NameRelationshipType type = NameRelationshipType.ALTERNATIVE_NAME();
1121
            BotanicalName alternativeName = makeFamilyName(state, alternativeFamilyStr);
1122
            BotanicalName familyName = (BotanicalName)family.getName();
1123
            boolean hasRelation = false;
1124
            for (NameRelationship nameRel : familyName.getRelationsToThisName()){
1125
                if (nameRel.getType().equals(type)){
1126
                    if (nameRel.getFromName().equals(alternativeName)){
1127
                        hasRelation = true;
1128
                    }
1129
                }
1130
            }
1131
            if (!hasRelation){
1132
                familyName.addRelationshipFromName(alternativeName, type, null);
1133
            }
1134

    
1135
        }
1136

    
1137
        return familyNode;
1138
    }
1139

    
1140

    
1141
    /**
1142
     * @param state
1143
     * @param taxon
1144
     */
1145
    private void validateTaxonIsAbsent(CubaImportState state, Taxon taxon) {
1146
        if (!state.isTaxonIsAbsent()){
1147
            return;
1148
        }
1149

    
1150
        for (DescriptionElementBase el : taxon.getDescriptions().iterator().next().getElements()){
1151
            if (el instanceof Distribution){
1152
                Distribution dist = (Distribution)el;
1153
                NamedArea area = dist.getArea();
1154
                if (isCubanArea(area)){
1155
                    PresenceAbsenceTerm status = dist.getStatus();
1156
                    if (status != null && !status.isAbsenceTerm()){
1157
                        if (!isDoubtfulTerm(status)){
1158
                            String name = taxon.getName().getTitleCache();
1159
                            logger.error(state.getCurrentLine() +": Taxon ("+name+")is absent'[]' but has presence distribution: " + status.getTitleCache());
1160
                            return;
1161
                        }
1162
                    }
1163
                }
1164
            }
1165
        }
1166
    }
1167

    
1168
    /**
1169
     * @param state
1170
     * @param taxon
1171
     */
1172
    private void validateEndemic(CubaImportState state, Taxon taxon) {
1173

    
1174
        boolean hasExternalPresence = false;
1175
        for (DescriptionElementBase el : taxon.getDescriptions().iterator().next().getElements()){
1176
            if (el instanceof Distribution){
1177
                Distribution dist = (Distribution)el;
1178
                NamedArea area = dist.getArea();
1179
                if (!isCubanArea(area)){
1180
                    PresenceAbsenceTerm status = dist.getStatus();
1181
                    if (status != null && !status.isAbsenceTerm()){
1182
                        if (!isDoubtfulTerm(status)){
1183
                            hasExternalPresence = true;
1184
                            if (state.isEndemic()){
1185
                                String name = taxon.getName().getTitleCache();
1186
                                logger.error(state.getCurrentLine() +": Taxon ("+name+")is endemic but has non-cuban distribution: " + area.getIdInVocabulary() + "-" + status.getIdInVocabulary());
1187
                                return;
1188
                            }
1189
                        }
1190
                    }
1191
                }
1192
            }
1193
        }
1194
        if (!state.isEndemic() && ! hasExternalPresence){
1195
            String name = taxon.getName().getTitleCache();
1196
            logger.error(state.getCurrentLine() +": Taxon ("+name+")is not endemic but has no non-cuban distribution" );
1197
        }
1198
    }
1199

    
1200

    
1201
    /**
1202
     * @param state
1203
     * @param taxon
1204
     * @param famStr
1205
     * @param famRef
1206
     * @return
1207
     */
1208
    private Taxon makeAlternativeFamilyTaxon(CubaImportState state, String famStr, Reference famRef) {
1209
        String key = famRef.getTitle() + ":"+ famStr;
1210
        Taxon family = state.getHigherTaxon(key);
1211
        if (family == null){
1212
            BotanicalName name = makeFamilyName(state, famStr);
1213
            family = Taxon.NewInstance(name, famRef);
1214
            state.putHigherTaxon(key, family);
1215
        }
1216

    
1217
        return family;
1218
    }
1219

    
1220

    
1221
    /**
1222
     * @param state
1223
     * @param famStr
1224
     * @return
1225
     */
1226
    private BotanicalName makeFamilyName(CubaImportState state, String famStr) {
1227
        BotanicalName name = state.getFamilyName(famStr);
1228
        if (name == null){
1229
            name = TaxonNameFactory.NewBotanicalInstance(Rank.FAMILY());
1230
            name.setGenusOrUninomial(famStr);
1231
            state.putFamilyName(famStr, name);
1232
            name.addSource(makeOriginalSource(state));
1233
        }
1234
        return name;
1235
    }
1236

    
1237

    
1238
    /**
1239
     * @param state
1240
     * @return
1241
     */
1242
    private TaxonNode getClassification(CubaImportState state) {
1243
        Classification classification = state.getClassification();
1244
        if (classification == null){
1245
            classification = getClassificationService().find(state.getConfig().getClassificationUuid());
1246
        }
1247
        TaxonNode rootNode = state.getRootNode();
1248
        if (rootNode == null){
1249
            rootNode = getTaxonNodeService().find(plantaeUuid);
1250
        }
1251
        if (rootNode == null){
1252
            Reference sec = getSecReference(state);
1253
            if (classification == null){
1254
                String classificationName = state.getConfig().getClassificationName();
1255
                //TODO
1256
                Language language = Language.DEFAULT();
1257
                classification = Classification.NewInstance(classificationName, sec, language);
1258
                state.setClassification(classification);
1259
                classification.setUuid(state.getConfig().getClassificationUuid());
1260
                classification.getRootNode().setUuid(rootUuid);
1261
            }
1262

    
1263
            BotanicalName plantaeName = TaxonNameFactory.NewBotanicalInstance(Rank.KINGDOM());
1264
            plantaeName.setGenusOrUninomial("Plantae");
1265
            Taxon plantae = Taxon.NewInstance(plantaeName, sec);
1266
            TaxonNode plantaeNode = classification.addChildTaxon(plantae, null, null);
1267
            plantaeNode.setUuid(plantaeUuid);
1268
            state.setRootNode(plantaeNode);
1269
            getClassificationService().save(classification);
1270

    
1271
            rootNode = plantaeNode;
1272
        }
1273
        return rootNode;
1274
    }
1275

    
1276

    
1277
    /**
1278
     * @param record
1279
     * @param originalKey
1280
     * @return
1281
     */
1282
    private String getValue(HashMap<String, String> record, String originalKey) {
1283
        String value = record.get(originalKey);
1284
        if (! StringUtils.isBlank(value)) {
1285
        	if (logger.isDebugEnabled()) { logger.debug(originalKey + ": " + value); }
1286
        	value = CdmUtils.removeDuplicateWhitespace(value.trim()).toString();
1287
        	return value;
1288
        }else{
1289
        	return null;
1290
        }
1291
    }
1292

    
1293

    
1294

    
1295
	/**
1296
	 *  Stores taxa records in DB
1297
	 */
1298
	@Override
1299
    protected void firstPass(CubaImportState state) {
1300
	    boolean isSynonymOnly = false;
1301

    
1302
        String line = state.getCurrentLine() + ": ";
1303
        HashMap<String, String> record = state.getOriginalRecord();
1304

    
1305
        Set<String> keys = record.keySet();
1306
        for (String key: keys) {
1307
            if (! expectedKeys.contains(key)){
1308
                logger.warn(line + "Unexpected Key: " + key);
1309
            }
1310
        }
1311

    
1312
        if (record.get("Fam. default") == null && keys.size() == 2 && record.get("Syn.") == null && record.get("Nat") != null && record.get("Adv") != null){
1313
            //second header line, don't handle
1314
            return;
1315
        }
1316

    
1317
        //Fam.
1318
        TaxonNode familyTaxon = getFamilyTaxon(record, state);
1319
        if (familyTaxon == null){
1320
            if (record.get("Taxón") != null){
1321
                logger.warn(line + "Family not recognized but taxon exists: " + record.get("Taxón"));
1322
                return;
1323
            }else if (record.get("Syn.") == null){
1324
                logger.warn(line + "Family not recognized but also no synonym exists");
1325
                return;
1326
            }else{
1327
                isSynonymOnly = true;
1328
            }
1329
        }
1330

    
1331
       //Taxón
1332
        Taxon taxon = makeTaxon(record, state, familyTaxon, isSynonymOnly);
1333
        if (taxon == null && ! isSynonymOnly){
1334
            logger.warn(line + "taxon could not be created and is null");
1335
            return;
1336
        }
1337
        state.setCurrentTaxon(taxon);
1338

    
1339
        //Fam. ALT
1340
        if (!isSynonymOnly){
1341
            makeAlternativeFamilies(record, state, familyTaxon, taxon);
1342
        }
1343

    
1344
        //(Notas)
1345
        makeNotes(record, state);
1346

    
1347
        //Syn.
1348
        makeSynonyms(record, state, !isSynonymOnly);
1349

    
1350
        //End, Ind, Ind? D, Nat N, Dud P, Adv A, Cult C
1351
        makeCubanDistribution(record, state);
1352

    
1353

    
1354
//        "CuW","PR PR*","Art","Hab(*)","May","Mat","IJ",
1355
//        "CuC","VC","Ci","SS","CA","Cam","LT",
1356
//        "CuE","Gr","Ho","SC","Gu",
1357
        makeProvincesDistribution(record, state);
1358

    
1359
//      "Esp","Ja","PR","Men","Bah","Cay",
1360
//      "AmN","AmC","AmS","VM"});
1361
        makeOtherAreasDistribution(record, state);
1362

    
1363
        validateTaxonIsAbsent(state, taxon);
1364
        if (!isSynonymOnly){
1365
            validateEndemic(state, taxon);
1366
        }
1367

    
1368
        state.setHighestStatusForTaxon(null);
1369

    
1370
		return;
1371
    }
1372

    
1373

    
1374
    /**
1375
     * @param state
1376
     * @return
1377
     */
1378
    private IdentifiableSource makeOriginalSource(CubaImportState state) {
1379
        return IdentifiableSource.NewDataImportInstance("line: " + state.getCurrentLine(), null, state.getConfig().getSourceReference());
1380
    }
1381
    /**
1382
     * @param state
1383
     * @return
1384
     */
1385
    private DescriptionElementSource makeDescriptionSource(CubaImportState state) {
1386
        return DescriptionElementSource.NewDataImportInstance("line: " + state.getCurrentLine(), null, state.getConfig().getSourceReference());
1387
    }
1388

    
1389
    private static Set<UUID> doubtfulStatus = new HashSet<>();
1390

    
1391
    /**
1392
     * @param status
1393
     * @return
1394
     */
1395
    private boolean isDoubtfulTerm(PresenceAbsenceTerm status) {
1396
        if (doubtfulStatus.isEmpty()){
1397
            doubtfulStatus.add(CubaTransformer.nonNativeDoubtfullyNaturalisedUuid);
1398
            doubtfulStatus.add(CubaTransformer.doubtfulIndigenousDoubtfulUuid);
1399
            doubtfulStatus.add(CubaTransformer.endemicDoubtfullyPresentUuid);
1400
            doubtfulStatus.add(CubaTransformer.naturalisedDoubtfullyPresentUuid);
1401
            doubtfulStatus.add(CubaTransformer.nonNativeDoubtfullyPresentUuid);
1402
            doubtfulStatus.add(CubaTransformer.occasionallyCultivatedUuid);
1403
            doubtfulStatus.add(CubaTransformer.rareCasualUuid);
1404
            doubtfulStatus.add(PresenceAbsenceTerm.NATIVE_PRESENCE_QUESTIONABLE().getUuid());
1405
            doubtfulStatus.add(PresenceAbsenceTerm.CULTIVATED_PRESENCE_QUESTIONABLE().getUuid());
1406
        }
1407
        boolean isDoubtful = doubtfulStatus.contains(status.getUuid());
1408
        return isDoubtful;
1409
    }
1410

    
1411

    
1412
    /**
1413
     * @param area
1414
     * @return
1415
     */
1416
    private boolean isCubanArea(NamedArea area) {
1417
        if (area.getUuid().equals(CubaTransformer.uuidCuba)){
1418
            return true;
1419
        }else if (area.getPartOf()!= null){
1420
            return isCubanArea(area.getPartOf());
1421
        }else{
1422
            return false;
1423
        }
1424
    }
1425

    
1426

    
1427
    /**
1428
     * @param record
1429
     * @param state
1430
     * @param familyTaxon
1431
     * @param taxon
1432
     */
1433
    private void makeAlternativeFamilies(HashMap<String, String> record,
1434
            CubaImportState state,
1435
            TaxonNode familyTaxon,
1436
            Taxon taxon) {
1437

    
1438
        String famFRC = record.get("Fam. FRC");
1439
        String famAS = record.get("Fam. A&S");
1440
        String famFC = record.get("Fam. FC");
1441

    
1442
        Reference refFRC = makeReference(state, CubaTransformer.uuidRefFRC);
1443
        Reference refAS = makeReference(state, CubaTransformer.uuidRefAS);
1444
        Reference refFC = makeReference(state, CubaTransformer.uuidRefFC);
1445

    
1446
        makeSingleAlternativeFamily(state, taxon, famFRC, refFRC);
1447
        makeSingleAlternativeFamily(state, taxon, famAS, refAS);
1448
        makeSingleAlternativeFamily(state, taxon, famFC, refFC);
1449
    }
1450

    
1451

    
1452
    /**
1453
     * @param state
1454
     * @param uuidreffrc
1455
     * @return
1456
     */
1457
    private Reference makeReference(CubaImportState state, UUID uuidRef) {
1458
        Reference ref = state.getReference(uuidRef);
1459
        if (ref == null){
1460
            ref = getReferenceService().find(uuidRef);
1461
            state.putReference(uuidRef, ref);
1462
        }
1463
        return ref;
1464
    }
1465

    
1466

    
1467
    /**
1468
     * @param state
1469
     * @param taxon
1470
     * @param famString
1471
     * @param famRef
1472
     */
1473
    private void makeSingleAlternativeFamily(CubaImportState state, Taxon taxon, String famStr, Reference famRef) {
1474
        if (isBlank(famStr)){
1475
            famStr = "-";
1476
//            return;
1477
        }
1478

    
1479
        TaxonDescription desc = getTaxonDescription(taxon, false, true);
1480

    
1481
        UUID altFamUuid1;
1482
        UUID altFamUuid2;
1483
        try {
1484
            altFamUuid1 = state.getTransformer().getFeatureUuid("Alt.Fam.");
1485
            altFamUuid2 = state.getTransformer().getFeatureUuid("Alt.Fam.2");
1486
        } catch (UndefinedTransformerMethodException e) {
1487
            throw new RuntimeException(e);
1488
        }
1489

    
1490

    
1491
        Taxon famTaxon = makeAlternativeFamilyTaxon(state, famStr, famRef);
1492

    
1493

    
1494
        //TextData
1495
        Feature feature1 = getFeature(state, altFamUuid1, "Families in other Floras (Text)", "Families in other Floras (Text)", "Other floras", null);
1496
        feature1.addRepresentation(Representation.NewInstance("Familias en otras Floras", "Familias en otras Floras", null, Language.SPANISH_CASTILIAN()));
1497
//        TextData textData = TextData.NewInstance(feature1, famStr, Language.DEFAULT(), null);
1498
        TextData textData = TextData.NewInstance(feature1, null, Language.DEFAULT(), null);
1499
        textData.addSource(OriginalSourceType.PrimaryTaxonomicSource, null,null, famRef, null, famTaxon.getName(),null);
1500
        desc.addElement(textData);
1501

    
1502

    
1503

    
1504
        //TaxonInteraction
1505
        Feature feature2 = getFeature(state, altFamUuid2, "Families in other Floras", "Families in other Floras", "Other floras(2)", null);
1506
        feature2.setSupportsTaxonInteraction(true);
1507
        feature2.addRepresentation(Representation.NewInstance("Familias en otras Floras", "Familias en otras Floras", null, Language.SPANISH_CASTILIAN()));
1508
        TaxonInteraction taxInteract = TaxonInteraction.NewInstance(feature2);
1509
        textData.putText(Language.SPANISH_CASTILIAN(), "Familias en otras Floras");
1510
        taxInteract.setTaxon2(famTaxon);
1511
        taxInteract.addSource(OriginalSourceType.PrimaryTaxonomicSource, null,null, famRef, null);
1512
        desc.addElement(taxInteract);
1513

    
1514
        //Concept Relation
1515
        famTaxon.addTaxonRelation(taxon, TaxonRelationshipType.INCLUDES(), taxon.getSec(), null);
1516

    
1517
    }
1518

    
1519

    
1520

    
1521

    
1522

    
1523
    /**
1524
     * @param record
1525
     * @param state
1526
     * @param taxon
1527
     */
1528
    // "CuW","PR PR*","Art","Hab(*)","May","Mat","IJ",
1529
//  "CuC","VC","Ci","SS","CA","Cam","LT",
1530
//  "CuE","Gr","Ho","SC","Gu",
1531
    private void makeProvincesDistribution(HashMap<String, String> record, CubaImportState state) {
1532
        List<String> areaKeys = Arrays.asList(new String[]{
1533
                "CuW","PR PR*","Art","Hab(*)","May","Mat","IJ",
1534
                "CuC","VC","Ci","SS","CA","Cam","LT",
1535
                "CuE","Gr","Ho","SC","Gu",
1536
                });
1537
        for (String areaKey : areaKeys){
1538
            state.setCubanProvince(true);
1539
            makeSingleProvinceDistribution(areaKey, record, state);
1540
        }
1541
    }
1542

    
1543
    private void makeOtherAreasDistribution(HashMap<String, String> record, CubaImportState state) {
1544
        List<String> areaKeys = Arrays.asList(new String[]{
1545
                "Esp","Ja","PR","Men","Bah","Cay",
1546
                "AmN","AmC","AmS","VM"});
1547
        for (String areaKey : areaKeys){
1548
            state.setCubanProvince(false);
1549
            makeSingleProvinceDistribution(areaKey, record, state);
1550
        }
1551
    }
1552

    
1553

    
1554

    
1555

    
1556
    /**
1557
     * @param areaKey
1558
     * @param record
1559
     * @param state
1560
     * @param highestStatus
1561
     * @return
1562
     * @throws UndefinedTransformerMethodException
1563
     */
1564
    private PresenceAbsenceTerm makeProvinceStatus(String areaKey,
1565
            HashMap<String, String> record,
1566
            CubaImportState state) throws UndefinedTransformerMethodException {
1567

    
1568
        String statusStr = record.get(areaKey);
1569
        if (statusStr == null){
1570
            return null;
1571
        }else{
1572
            statusStr = statusStr.trim();
1573
        }
1574
        PresenceAbsenceTerm status = state.getTransformer().getPresenceTermByKey(statusStr);
1575
        if (status == null){
1576
//            PresenceAbsenceTerm highestStatus = state.getHighestStatusForTaxon();
1577
            if (state.isCubanProvince() && isMinus(statusStr)){
1578
//                getAbsenceTermForStatus(state, highestStatus);
1579
                //we now handle cuban provinces same as external regions
1580
                status = state.getTransformer().getPresenceTermByKey("--");
1581
            }else if (! state.isCubanProvince() && isMinus(statusStr)){
1582
                status = state.getTransformer().getPresenceTermByKey("--");
1583
            }else{
1584
//                logger.warn("Unhandled status str for provinces / external regions: " + statusStr);
1585
                UUID statusUuid = state.getTransformer().getPresenceTermUuid(statusStr);
1586
                if (statusUuid == null){
1587
                    logger.error(state.getCurrentLine() + ": Undefined status str for provinces / external regions. No UUID given: '" + statusStr + "'");
1588
                }else{
1589
                    status = getPresenceTerm(state, statusUuid, statusStr, statusStr, statusStr, false);
1590
                }
1591
            }
1592
        }
1593

    
1594
        return status;
1595
    }
1596

    
1597

    
1598
    /**
1599
     * @param highestStatus
1600
     * @throws UndefinedTransformerMethodException
1601
     */
1602
    private PresenceAbsenceTerm getAbsenceTermForStatus(CubaImportState state, PresenceAbsenceTerm highestStatus) throws UndefinedTransformerMethodException {
1603
        if (highestStatus == null){
1604
            logger.warn(state.getCurrentLine() + ": Highest status not defined");
1605
            return null;
1606
        }
1607
        PresenceAbsenceTerm result = null;
1608
        if (highestStatus.equals(getStatus(state, "E"))){
1609
            result = getStatus(state, "-E");
1610
        }else if (highestStatus.getUuid().equals(state.getTransformer().getPresenceTermUuid("Ind.")) || highestStatus.equals(PresenceAbsenceTerm.NATIVE())){
1611
            result = getStatus(state, "-Ind.");
1612
        }else if (highestStatus.equals(getStatus(state, "Ind.?"))){
1613
            result = getStatus(state, "-Ind.?");  //TODO
1614
        }else if (highestStatus.equals(getStatus(state, "N"))){
1615
            result = getStatus(state, "-N");
1616
        }else if (highestStatus.equals(getStatus(state, "P"))){
1617
            result = getStatus(state, "-P");
1618
        }else if (highestStatus.equals(getStatus(state, "A"))){
1619
            result = getStatus(state, "-A");
1620
        }else if (highestStatus.equals(getStatus(state, "C"))){
1621
            result = getStatus(state, "-C");
1622
        }
1623
        logger.warn(state.getCurrentLine() + ": Absent province status could not be defined for highest status " + highestStatus.getTitleCache());
1624
        return result;
1625
    }
1626

    
1627

    
1628
    /**
1629
     * @param string
1630
     * @return
1631
     * @throws UndefinedTransformerMethodException
1632
     */
1633
    private PresenceAbsenceTerm getStatus(CubaImportState state, String key) throws UndefinedTransformerMethodException {
1634
        PresenceAbsenceTerm status = state.getTransformer().getPresenceTermByKey(key);
1635
        if (status == null){
1636
            UUID statusUuid = state.getTransformer().getPresenceTermUuid(key);
1637
            status = getPresenceTerm(state, statusUuid, null, null, null, false);
1638
        }
1639
        return status;
1640
    }
1641

    
1642

    
1643
    /**
1644
	 *  Stores parent-child, synonym and common name relationships
1645
	 */
1646
	@Override
1647
    protected void secondPass(CubaImportState state) {
1648
//		CyprusRow cyprusRow = state.getCyprusRow();
1649
		return;
1650
	}
1651

    
1652

    
1653
    @Override
1654
    protected boolean isIgnore(CubaImportState state) {
1655
        return ! state.getConfig().isDoTaxa();
1656
    }
1657

    
1658
    @Override
1659
    protected boolean doCheck(CubaImportState state) {
1660
        logger.warn("DoCheck not yet implemented for CubaExcelImport");
1661
        return true;
1662
    }
1663

    
1664
}
(1-1/5)