Project

General

Profile

Download (55.1 KB) Statistics
| Branch: | Revision:
1
/**
2
* Copyright (C) 2019 EDIT
3
* European Distributed Institute of Taxonomy
4
* http://www.e-taxonomy.eu
5
*
6
* The contents of this file are subject to the Mozilla Public License Version 1.1
7
* See LICENSE.TXT at the top of this package for the full license terms.
8
*/
9
package eu.etaxonomy.cdm.app.pesi.validate;
10

    
11
import java.sql.ResultSet;
12
import java.sql.SQLException;
13
import java.sql.Timestamp;
14
import java.time.LocalDate;
15
import java.util.UUID;
16

    
17
import org.apache.commons.lang.StringUtils;
18
import org.apache.log4j.Logger;
19

    
20
import eu.etaxonomy.cdm.app.common.CdmDestinations;
21
import eu.etaxonomy.cdm.app.common.PesiDestinations;
22
import eu.etaxonomy.cdm.app.pesi.EuroMedSourceActivator;
23
import eu.etaxonomy.cdm.common.CdmUtils;
24
import eu.etaxonomy.cdm.common.UTF8;
25
import eu.etaxonomy.cdm.database.ICdmDataSource;
26
import eu.etaxonomy.cdm.io.berlinModel.BerlinModelTransformer;
27
import eu.etaxonomy.cdm.io.common.Source;
28
import eu.etaxonomy.cdm.io.pesi.out.PesiTransformer;
29
import eu.etaxonomy.cdm.model.description.PresenceAbsenceTerm;
30
import eu.etaxonomy.cdm.model.taxon.TaxonRelationshipType;
31

    
32
/**
33
 * Tests the E+M -> PESI pipeline by comparing the source DB with destination PESI DB.
34
 *
35
 * @author a.mueller
36
 * @since 08.10.2019
37
 */
38
public class PesiEuroMedValidator extends PesiValidatorBase {
39

    
40
    private static final Logger logger = Logger.getLogger(PesiEuroMedValidator.class);
41

    
42
    private static final ICdmDataSource defaultSource = CdmDestinations.cdm_test_local_mysql_euromed();
43
//    private static final ICdmDataSource defaultSource = CdmDestinations.cdm_pesi2019_final();
44
//    private static final Source defaultDestination = PesiDestinations.pesi_test_local_CDM_EM2PESI();
45
    private static final Source defaultDestination = PesiDestinations.pesi_test_local_CDM_EM2PESI_2();
46

    
47
    boolean doReferences = false;
48
    boolean doTaxa = true;
49
    boolean doTaxRels = false;
50
    boolean doDistributions = false;
51
    boolean doCommonNames = false;
52
    boolean doNotes = false;
53
    boolean doAdditionalTaxonSources = false;
54

    
55
    private Source source = new Source(defaultSource);
56
    private Source destination = defaultDestination;
57

    
58
    private String origEuroMed = "OriginalDB = 'E+M' ";
59

    
60
    public void invoke(Source source, Source destination){
61
        logger.warn("Validate destination " +  destination.getDatabase());
62
        boolean success = true;
63
        try {
64
            this.source = source;
65
            this.destination = destination;
66
            success &= testReferences();
67
            success &= testTaxa();
68
            success &= testTaxonRelations();
69
            success &= testDistributions();
70
            success &= testCommonNames();
71
            success &= testNotes();
72
            success &= testAdditionalTaxonSources();
73
        } catch (Exception e) {
74
            e.printStackTrace();
75
            success = false;
76
        }
77
        //TBC
78
        System.out.println("end validation " + (success? "":"NOT ") + "successful.");
79
    }
80

    
81
    private boolean testAdditionalTaxonSources() throws SQLException {
82
        if (!doAdditionalTaxonSources){
83
            System.out.println("Ignore validate additional taxon sources");
84
            return true;
85
        }
86
        System.out.println("Start validate additional taxon sources");
87
        boolean success = testAdditionalTaxonSourcesCount();
88
        if (success){
89
              success &= testSingleAdditionalTaxonSources(source.getUniqueInteger(countAddtionalTaxonSource));
90
        }
91
        return success;
92
    }
93

    
94
    private boolean testNotes() throws SQLException {
95
        if (!doNotes){
96
            System.out.println("Ignore validate notes");
97
            return true;
98
        }
99
        System.out.println("Start validate notes");
100
        boolean success = testNotesCount();
101
        if (success){
102
              success &= testSingleNotes(source.getUniqueInteger("SELECT count(*) FROM notes "));
103
        }
104
        return success;
105
    }
106

    
107
    private boolean testDistributions() throws SQLException {
108
        if (!doDistributions){
109
            System.out.println("Ignore validate distributions");
110
            return true;
111
        }
112
        System.out.println("Start validate distributions");
113
        boolean success = testDistributionCount();
114
        if (!success){
115
              success &= testSingleDistributions(source.getUniqueInteger(distributionCountSQL));
116
        }
117
        return success;
118
    }
119

    
120
    private boolean testCommonNames() throws SQLException {
121
        if (!doCommonNames){
122
            System.out.println("Ignore validate common names");
123
            return true;
124
        }
125
        System.out.println("Start validate common names");
126
        boolean success = testCommonNameCount();
127
        if (success){
128
            success &= testSingleCommonNames(source.getUniqueInteger("SELECT count(*) FROM vernaculars "));
129
        }
130
        return success;
131
    }
132

    
133
    int countSynonyms;
134
    int countIncludedIns;
135
    private boolean testTaxonRelations() throws SQLException {
136
        if (!doTaxRels){
137
            System.out.println("Ignore validate taxon relations");
138
            return true;
139
        }
140
        System.out.println("Start validate taxon relations");
141
        boolean success = testSynonymRelations();
142
        success &= testIncludedInRelations();
143
        success &= testTotalRelations();
144
        success &= testNameRelations();
145
        return success;
146
    }
147

    
148
    private boolean testTotalRelations() {
149
        if (!(countSynonyms < 0 || countIncludedIns < 0)){
150
            int countTotalSrc = countSynonyms + countIncludedIns;
151
            int countSrc = source.getUniqueInteger("SELECT count(*) FROM tu ");
152
            boolean success = equals("Taxrel count + 1 must be same as source taxon count ", countTotalSrc+1, countSrc, String.valueOf(-1));
153
            int countDest = destination.getUniqueInteger("SELECT count(*) FROM Taxon t WHERE t."+ origEuroMed);
154
            success &= equals("Taxrel count + 1 must be same as destination taxon count ", countTotalSrc+1, countDest, String.valueOf(-1));
155
            return success;
156
        }else{
157
            return false;
158
        }
159
    }
160

    
161
    private final String countSynonymRelation = "SELECT count(*) FROM TaxonBase syn LEFT JOIN TaxonBase acc ON syn.acceptedTaxon_id = acc.id WHERE syn.publish = 1 AND acc.publish = 1 ";
162
    private boolean testSynonymRelations() throws SQLException {
163

    
164
        int countSrc = source.getUniqueInteger(countSynonymRelation);
165
        int countDest = destination.getUniqueInteger("SELECT count(*) FROM RelTaxon WHERE RelTaxonQualifierFk > 101");
166
        boolean success = equals("Synonym count ", countSrc, countDest, String.valueOf(-1));
167
        if (success){
168
            //TODO test single synonym relations
169
            success &= testSingleSynonymRelations(source.getUniqueInteger(countSynonymRelation));
170
        }
171
        countSynonyms = (countSrc == countDest)? countSrc : -1;
172
        return success;
173
    }
174

    
175
    private boolean testSingleSynonymRelations(int n) throws SQLException {
176
        boolean success = true;
177
        ResultSet srcRS = source.getResultSet(""
178
                + " SELECT t.id tid, pt.id pid "
179
                + " FROM TaxonNode tn "
180
                + "   INNER JOIN TaxonBase t ON tn.taxon_id = t.id "
181
                + "   LEFT JOIN TaxonNode ptn ON ptn.id = tn.parent_id "
182
                + "   LEFT JOIN TaxonBase  pt ON ptn.taxon_id = pt.id "
183
                + " WHERE t.publish = 1 && pt.publish = 1 "
184
                + " ORDER BY CAST(tb.id as char(20)) ");
185

    
186
        ResultSet destRS = destination.getResultSet("SELECT rel.*, t1.IdInSource t1Id, t2.IdInSource t2Id "
187
                + " FROM RelTaxon rel "
188
                + "    LEFT JOIN Taxon t1 ON t1.TaxonId = rel.TaxonFk1 "
189
                + "    LEFT JOIN Taxon t2 ON t2.TaxonId = rel.TaxonFk2 "
190
                + " WHERE t1."+origEuroMed+" AND t2." + origEuroMed + " AND RelTaxonQualifierFk > 101 "
191
                + " ORDER BY t1.IdInSource");
192
        int i = 0;
193
        while (srcRS.next() && destRS.next()){
194
            success &= testSingleSynonymRelation(srcRS, destRS);
195
            i++;
196
        }
197
        success &= equals("Synonym relation count for single compare", n, i, String.valueOf(-1));
198
        return success;
199
    }
200

    
201
    private boolean testSingleSynonymRelation(ResultSet srcRS, ResultSet destRS) throws SQLException {
202
        String id = String.valueOf(srcRS.getInt("id"));
203
        boolean success = equals("Taxon relation taxon1", "NameId: " + srcRS.getInt("id"), destRS.getString("t1Id"), id);
204
        success &= equals("Taxon relation taxon2", "NameId: " + srcRS.getInt("tu_accfinal"), destRS.getString("t2Id"), id);
205
        success &= equals("Taxon relation qualifier fk", PesiTransformer.IS_SYNONYM_OF, destRS.getInt("RelTaxonQualifierFk"), id);
206
        success &= equals("Taxon relation qualifier cache", "is synonym of", destRS.getString("RelQualifierCache"), id);
207
        //TODO enable after next import
208
//        success &= isNull("notes", destRS);
209
        //complete if no further relations need to added
210
        return success;
211
    }
212

    
213
    private boolean testNameRelations() {
214
        //Name relations
215
        int countSrc = source.getUniqueInteger("SELECT count(*) FROM NameRelationship WHERE ("
216
               + " 1=1 "
217
                 + ")");
218
        int countDest = destination.getUniqueInteger("SELECT count(*) FROM RelTaxon WHERE RelTaxonQualifierFk <100 ");
219
        boolean success = equals("Taxon name relation count ", countSrc, countDest, String.valueOf(-1));
220
        if (success){
221
            //TODO test single name relation
222
//            success &= testSingleNameRelations(source.getUniqueInteger(countSynonymRelation));
223
        }
224
        return success;
225
    }
226

    
227
    private final String countParentRelation  = "SELECT count(*) "
228
            + " FROM TaxonNode tn "
229
            + " INNER JOIN TaxonBase tb ON tn.taxon_id = tb.id "
230
            + "   LEFT JOIN TaxonNode ptn ON ptn.id = tn.parent_id "
231
            + "   LEFT JOIN TaxonBase pt ON ptn.taxon_id = pt.id "
232
            + " WHERE tb.publish = 1 && pt.publish = 1  ";
233

    
234
    private boolean testIncludedInRelations() throws SQLException {
235
        int countSrc = source.getUniqueInteger(countParentRelation);
236
        int  countDest = destination.getUniqueInteger("SELECT count(*) FROM RelTaxon WHERE RelTaxonQualifierFk = 101 ");
237
        boolean success = equals("Tax included in count ", countSrc, countDest, String.valueOf(-1));
238
        if (success){
239
            success &= testSingleTaxonRelations(source.getUniqueInteger(countParentRelation));
240
        }
241
        countIncludedIns = (countSrc == countDest)? countSrc : -1;
242
        return success;
243
    }
244

    
245
    private boolean testTaxa() throws SQLException {
246
        if (!doTaxa){
247
            System.out.println("Ignore validate taxa");
248
            return true;
249
        }
250
        System.out.println("Start validate taxa");
251
        boolean success = testTaxaCount();
252
        if (success){
253
            success &= testSingleTaxa(source.getUniqueInteger(countTaxon));
254
        }
255
        return success;
256
    }
257

    
258
    String countReferencesStr = "SELECT count(*) FROM reference ";
259
    private boolean testReferences() throws SQLException {
260
        if (!doReferences){
261
            System.out.println("Ignore validate references");
262
            return true;
263
        }
264
        System.out.println("Start validate references");
265
        boolean success = testReferenceCount();
266
        if (success){
267
            success &= testSingleReferences(source.getUniqueInteger(countReferencesStr));
268
        }
269
        return success;
270
    }
271

    
272
    private final String countAddtionalTaxonSource = "SELECT count(*) FROM tu_sources ts ";
273
    private boolean testAdditionalTaxonSourcesCount() {
274
        int countSrc = source.getUniqueInteger(countAddtionalTaxonSource);
275
        int countDest = destination.getUniqueInteger("SELECT count(*) FROM AdditionalTaxonSource ");
276
        return equals("AdditionalTaxonSource count ", countSrc, countDest, String.valueOf(-1));
277
    }
278

    
279
    private boolean testNotesCount() {
280
        int countSrc = source.getUniqueInteger("SELECT count(*) FROM notes ");
281
        int countDest = destination.getUniqueInteger("SELECT count(*) FROM Note "
282
                + " WHERE (1=1) ");
283
        boolean result = equals("Notes count ", countSrc, countDest, String.valueOf(-1));
284

    
285
        return result;
286
    }
287

    
288
    private String distributionCountWhere = " WHERE deb.DTYPE = 'Distribution' AND tb.publish = 1 AND a.uuid NOT IN ("
289
            + "'111bdf38-7a32-440a-9808-8af1c9e54b51',"   //E+M
290
            //Former UUSR
291
            + "'c4a898ce-0f32-44fe-a8a3-278e11a4ba53','a575d608-dd53-4c01-b2af-5067d0711f64','da4e9cc3-b1cc-403a-81ff-bcc5d9fadbd1',"
292
            + "'7e0f8fa3-5db9-48f0-9fa8-87fcab3eaa53','2188e3a5-0446-47c8-b11b-b4b2b9a71c75','44f262e3-5091-4d28-8081-440d3978fb0b',"
293
            + "'efabc8fd-0b3c-475b-b532-e1ca0ba0bdbb') ";
294
    private String distributionCountSQL = "SELECT count(*) as n "
295
            + " FROM DescriptionElementBase deb INNER JOIN DescriptionBase db ON deb.inDescription_id = db.id "
296
            + "    LEFT JOIN TaxonBase tb ON db.taxon_id = tb.id "
297
            + "    LEFT JOIN DefinedTermBase a ON a.id = deb.area_id "
298
            + distributionCountWhere;
299
    private boolean testDistributionCount() {
300
        int countSrc = source.getUniqueInteger(distributionCountSQL);
301
        int countDest = destination.getUniqueInteger("SELECT count(*) FROM Occurrence ");
302
        return equals("Occurrence count ", countSrc, countDest, String.valueOf(-1));
303
    }
304

    
305
    private boolean testCommonNameCount() {
306
        int countSrc = source.getUniqueInteger("SELECT count(*) FROM vernaculars ");
307
        int countDest = destination.getUniqueInteger("SELECT count(*) FROM CommonName ");
308
        return equals("CommonName count ", countSrc, countDest, String.valueOf(-1));
309
    }
310

    
311
    private final String countTaxon = "SELECT count(*) FROM TaxonBase tb WHERE tb.publish = 1 ";
312
    private final String destTaxonFilter = "(t.SourceFk IS NOT NULL OR t.AuthorString like 'auct.%' OR t.AuthorString like 'sensu %')";
313
    private boolean testTaxaCount() {
314
         int countSrc = source.getUniqueInteger(countTaxon);
315
         int countDest = destination.getUniqueInteger("SELECT count(*) FROM Taxon t WHERE "+ destTaxonFilter);
316
         boolean result = equals("Taxon count ", countSrc, countDest, String.valueOf(-1));
317
         return result;
318
    }
319

    
320
    private boolean testSingleTaxa(int n) throws SQLException {
321
        boolean success = true;
322
        ResultSet srcRS = source.getResultSet("SELECT CAST(tn.id as char(20)) tid, tb.uuid as GUID, pt.id parentId, "
323
                + "      tn.rank_id, rank.titleCache rank_name, "
324
                + "      sec.titleCache secTitle, "
325
                + "      tn.genusOrUninomial, tn.infraGenericEpithet, tn.specificEpithet, tn.infraSpecificEpithet, "
326
                + "      tn.nameCache, tn.authorshipCache, tn.titleCache nameTitleCache, tn.fullTitleCache nameFullTitleCache, "
327
                + "      tb.DTYPE taxStatus, tb.titleCache, tb.appendedPhrase tbAppendedPhrase, tb.sec_id secId, "
328
                + "      taxRelType.uuid taxRelTypeUuid, tr.relatedTo_id relToTaxonId, "
329
                + "      nsType.id nsId, nsType.idInVocabulary nsTitle, "
330
                + "      typeName_id, typeName.titleCache typeFullNameCache, "
331
                + "      CASE WHEN tb.updated IS NOT NULL THEN tb.updated ELSE tb.created END as lastActionDate, "
332
                + "      CASE WHEN tb.updated IS NOT NULL THEN 'changed' ELSE 'created' END as lastAction "
333
                + " FROM TaxonBase tb "
334
                + "     LEFT JOIN TaxonName tn on tb.name_id = tn.id "
335
                + "     LEFT JOIN DefinedTermBase rank ON rank.id = tn.rank_id "
336
                + "     LEFT JOIN Reference sec ON sec.id = tb.sec_id "
337
                + "     LEFT JOIN TaxonName_NomenclaturalStatus nsMN ON tn.id = nsMN.TaxonName_id "
338
                + "     LEFT JOIN NomenclaturalStatus ns ON ns.id = nsMN.status_id "
339
                + "     LEFT JOIN DefinedTermBase nsType ON nsType.id = ns.type_id "
340
                + "     LEFT JOIN TaxonName_TypeDesignationBase typeMN ON typeMN.TaxonName_id = tn.id "
341
                + "     LEFT JOIN TypeDesignationBase td ON td.id = typeMN.typedesignations_id "
342
                + "     LEFT JOIN TaxonName typeName ON typeName.id = td.typeName_id "
343
                + "     LEFT JOIN TaxonNode n ON n.taxon_id = tb.id "
344
                + "     LEFT JOIN TaxonNode ptn ON n.parent_id = ptn.id "
345
                + "     LEFT JOIN TaxonBase pt ON pt.id = ptn.taxon_id AND pt.publish = 1 "
346
                + "     LEFT JOIN TaxonRelationship tr ON tr.relatedFrom_id = tb.id "
347
                + "     LEFT JOIN TaxonBase tbRelTo ON tr.relatedTo_id = tbRelTo.id "
348
                + "     LEFT JOIN DefinedTermBase taxRelType ON taxRelType.id = tr.type_id"
349
                + " WHERE tb.publish = 1 "
350
                + " GROUP BY tid, GUID, tn.rank_id, rank.titleCache, secTitle,"
351
                + "      tn.genusOrUninomial, tn.infraGenericEpithet, tn.specificEpithet, tn.infraSpecificEpithet, "
352
                + "      tn.nameCache, tn.authorshipCache, tn.titleCache, "
353
                + "      tb.DTYPE, tb.updated, tb.created "    //for duplicates caused by >1 name status
354
                + " ORDER BY tid, GUID, lastActionDate ");
355
        ResultSet destRS = destination.getResultSet("SELECT t.*, "
356
                + "     pt.treeIndex pTreeIndex, pt.IdInSource parentSourceId, "  //not needed
357
                + "     s.Name as sourceName, type.IdInSource typeSourceId, r.Rank "
358
                + " FROM Taxon t "
359
                + "    LEFT JOIN Taxon pt ON pt.TaxonId = t.ParentTaxonFk "
360
                + "    LEFT JOIN Taxon type ON type.TaxonId = t.TypeNameFk "
361
                + "    LEFT JOIN Rank r ON r.RankId = t.RankFk AND r.KingdomId = t.KingdomFk "
362
                + "    LEFT JOIN Source s ON s.SourceId = t.SourceFk "
363
                + " WHERE t."+ origEuroMed + " AND " + destTaxonFilter   //FIXME remove SourceFk filter is only preliminary for first check
364
                + " ORDER BY t.IdInSource, t.GUID, t.LastActionDate, AuthorString ");
365
        int i = 0;
366
        logger.error("remove SourceFk filter is only preliminary for first check");
367
        while (srcRS.next() && destRS.next()){
368
            success &= testSingleTaxon(srcRS, destRS);
369
            i++;
370
        }
371
        success &= equals("Taxon count for single compare", n, i, String.valueOf(-1));
372
        return success;
373
    }
374

    
375
    private boolean testSingleTaxon(ResultSet srcRS, ResultSet destRS) throws SQLException {
376
        String id = String.valueOf(srcRS.getInt("tid"));
377
        //TODO decide, according to SQL it also contains the taxon UUID, but in PESI2014 backup I can't find this
378
        boolean success = equals("Taxon ID", "NameId: " + srcRS.getInt("tid"), destRS.getString("IdInSource"), id);
379
        success &= equals("Taxon source", makeSource(srcRS), destRS.getString("sourceName"), id);
380

    
381
        success &= equals("Taxon kingdomFk", "3", destRS.getString("KingdomFk"), id);
382
//difficult to test        success &= equals("Taxon rank fk", srcRS.getString("rank_id"), destRS.getString("RankFk"), id);
383
        success &= equals("Taxon rank cache", normalizeRank(srcRS.getString("rank_name")), destRS.getString("Rank"), id);
384
        success &= equals("Taxon genusOrUninomial", srcRS.getString("genusOrUninomial"), destRS.getString("GenusOrUninomial"), id) ;
385
        success &= equals("Taxon infraGenericEpithet", srcRS.getString("infraGenericEpithet"), destRS.getString("InfraGenericEpithet"), id) ;
386
        success &= equals("Taxon specificEpithet", srcRS.getString("specificEpithet"), destRS.getString("SpecificEpithet"), id) ;
387
        success &= equals("Taxon infraSpecificEpithet", srcRS.getString("infraSpecificEpithet"), destRS.getString("InfraSpecificEpithet"), id) ;
388

    
389
        success &= equals("Taxon websearchname", srcRS.getString("nameCache"), destRS.getString("WebSearchName"), id);
390
//TODO     success &= equals("Taxon WebShowName", srcRS.getString("tu_displayname"), destRS.getString("WebShowName"), id);
391
        success &= equals("Taxon authority", makeAuthorship(srcRS), destRS.getString("AuthorString"), id);
392
        success &= equals("Taxon FullName", makeFullName(srcRS), destRS.getString("FullName"), id);
393
        success &= equals("Taxon NomRefString", makeNomRefString(srcRS), destRS.getString("NomRefString"), id);
394
//      success &= equals("Taxon DisplayName", makeDisplayName(srcRS), destRS.getString("DisplayName"), id);  //in ERMS according to SQL script same as FullName, no nom.ref. information attached
395
//difficult to test   success &= equals("Taxon NameStatusFk", nullSafeInt(srcRS, "nsId"),nullSafeInt( destRS,"NameStatusFk"), id);
396
        success &= equals("Taxon NameStatusCache", srcRS.getString("nsTitle"), destRS.getString("NameStatusCache"), id);
397

    
398
        //TODO mostly Taxonomically Valueless
399
//        success &= equals("Taxon TaxonStatusFk", mapTaxStatusFk(srcRS.getString("taxStatus"), srcRS.getString("taxRelTypeUuid")), nullSafeInt( destRS,"TaxonStatusFk"), id);
400
//        success &= equals("Taxon TaxonStatusCache", mapTaxStatus(srcRS.getString("taxStatus"), srcRS.getString("taxRelTypeUuid")), destRS.getString("TaxonStatusCache"), id);
401

    
402
        success &= equals("Taxon ParentTaxonFk", nullSafeInt(srcRS, "parentId"), nullSafeInt(destRS, "ParentTaxonFk"), id);
403

    
404
        Integer origTypeNameFk = nullSafeInt(srcRS, "typeName_id");
405
        success &= equals("Taxon TypeNameFk", origTypeNameFk == null? null : "NameId: " + origTypeNameFk, destRS.getString("typeSourceId"), id);
406
        success &= equals("Taxon TypeFullNameCache", srcRS.getString("typeFullNameCache"), destRS.getString("TypeFullNameCache"), id);
407
        //according to SQL always constant, could be changed in future
408
        success &= equals("Taxon QualityStatusFK", 2, nullSafeInt( destRS,"QualityStatusFk"), String.valueOf(id));
409
        success &= equals("Taxon QualityStatusCache", "Added by Database Management Team", destRS.getString("QualityStatusCache"), id);
410
        success &= testTreeIndex(destRS, "TreeIndex", "pTreeIndex", id);
411
        success &= isNull("FossilStatusFk", destRS, id);
412
        success &= isNull("FossilStatusCache", destRS, id);
413
        success &= equals("Taxon GUID", srcRS.getString("GUID"), destRS.getString("GUID"), id);
414
        success &= equals("Taxon DerivedFromGuid", srcRS.getString("GUID"), destRS.getString("DerivedFromGuid"), id); //according to SQL script GUID and DerivedFromGuid are always the same, according to 2014DB this is even true for all databases
415
        success &= isNull("ExpertGUID", destRS, id);  //according to SQL + PESI2014
416
//FIXME        success &= equals("Taxon ExpertName", srcRS.getString("secTitle"), destRS.getString("ExpertName"), id);
417
//FIXME        success &= isNull("SpeciesExpertGUID", destRS);
418
//FIXME        success &= equals("Taxon SpeciesExpertName", srcRS.getString("secTitle"), destRS.getString("SpeciesExpertName"), id);
419
//FIXME !!        success &= equals("Taxon cache citation", srcRS.getString("secTitle"), destRS.getString("CacheCitation"), id);
420
        success &= equals("Taxon Last Action", srcRS.getString("lastAction"),  destRS.getString("LastAction"), id);
421
        success &= equals("Taxon Last Action Date", srcRS.getTimestamp("lastActionDate"),  destRS.getTimestamp("LastActionDate"), id);
422

    
423
        success &= isNull("GUID2", destRS, id);  //only relevant after merge
424
        success &= isNull("DerivedFromGuid2", destRS, id);  //only relevant after merge
425
        return success;
426
    }
427

    
428
    private String makeSource(ResultSet srcRs) throws SQLException {
429
        String secStr = srcRs.getString("secTitle");
430
        if (secStr == null){
431
            return EuroMedSourceActivator.sourceReferenceTitle;
432
        }else{
433
            return secStr;
434
        }
435
    }
436

    
437
    private String makeAuthorship(ResultSet srcRs) throws SQLException {
438
        boolean isMisapplied = isMisapplied(srcRs);
439
        if (isMisapplied){
440
            String result = getMisappliedAuthor(srcRs).trim();
441
            return result;
442
        }else{
443
            return srcRs.getString("authorshipCache");
444
        }
445
    }
446

    
447
    private String makeFullName(ResultSet srcRs) throws SQLException {
448
        boolean isMisapplied = isMisapplied(srcRs);
449
        if (isMisapplied){
450
            String result = srcRs.getString("nameCache");
451
            result += getMisappliedAuthor(srcRs);
452
            return result;
453
        }else{
454
            return srcRs.getString("nameTitleCache");
455
        }
456
    }
457

    
458
    private String makeNomRefString(ResultSet srcRS) throws SQLException {
459
        //there is no pure nomRefString field in CDM and also computing is only possible
460
        //with cache strategy which requires a running CDM instance. So this is a workaround
461
        //that maybe needs to be adapted
462
        String result = null;
463
        String fullTitle = srcRS.getString("nameFullTitleCache");
464
        String nameTitleCache = srcRS.getString("nameTitleCache");
465
        String nameStatus = CdmUtils.Nz(srcRS.getString("nsTitle"));
466
        if (fullTitle != null && nameTitleCache != null){
467
            result = fullTitle.substring(nameTitleCache.length())
468
                    .replaceAll("^, ", "")
469
                    .replaceAll("(, |^)"+nameStatus+"$", "")
470
                    .replaceAll("\\[as \".*\"\\]", "")
471
                    .replaceAll(", nom\\. cons\\., nom\\. altern\\.$", "")  //single case with 2 nom. status
472
                    .trim();
473
        }
474
        return result;
475
    }
476

    
477
    private String mapTaxStatus(String dtype, String taxRelTypeUuidStr) {
478
        Integer statusFk = mapTaxStatusFk(dtype, taxRelTypeUuidStr);
479
        if (statusFk == null){
480
            return null;
481
        }else if (statusFk == PesiTransformer.T_STATUS_ACCEPTED){
482
            return "accepted";
483
        }else if (statusFk == PesiTransformer.T_STATUS_SYNONYM){
484
            return "synonym";
485
        }else if (statusFk == PesiTransformer.T_STATUS_PRO_PARTE_SYN){
486
            return "pro parte synonym";
487
        }else if (statusFk == PesiTransformer.T_STATUS_PARTIAL_SYN){
488
            return "partial synonym";
489
        }
490
        return null;
491
    }
492

    
493
    private Integer mapTaxStatusFk(String dtype, String taxRelTypeUuidStr) {
494
        if (dtype == null){
495
            return null;
496
        }else if ("Synonym".equals(dtype)){
497
            return PesiTransformer.T_STATUS_SYNONYM;
498
        }else if ("Taxon".equals(dtype)){
499
            UUID relTypeUuid = taxRelTypeUuidStr == null? null: UUID.fromString(taxRelTypeUuidStr);
500
            if (TaxonRelationshipType.proParteUuids().contains(relTypeUuid)){
501
                return PesiTransformer.T_STATUS_PRO_PARTE_SYN;
502
            }else if (TaxonRelationshipType.partialUuids().contains(relTypeUuid)){
503
                return PesiTransformer.T_STATUS_PARTIAL_SYN;
504
            }else if (TaxonRelationshipType.misappliedNameUuids().contains(relTypeUuid)){
505
                return PesiTransformer.T_STATUS_SYNONYM;  //no explicit MAN status exists in PESI
506
            }else{
507
                return PesiTransformer.T_STATUS_ACCEPTED;
508
            }
509
        }
510
        return null;
511
    }
512

    
513
    private String normalizeRank(String rankStr) {
514
        if (rankStr == null){return null;
515
        }else if (rankStr.equals("Convar")){return "Convariety";
516
        }else if (rankStr.equals("Unranked (infrageneric)")){return "Tax. infragen.";
517
        }else if (rankStr.equals("Unranked (infraspecific)")){return "Tax. infraspec.";
518
        }else if (rankStr.equals("Coll. species")){return "Coll. Species";
519
        }else if (rankStr.equals("Species Aggregate")){return "Aggregate";
520
        }else if (rankStr.equals("Subsection bot.")){return "Subsection";
521
        }return rankStr;
522
    }
523

    
524
    private String makeDisplayName(ResultSet srcRs) throws SQLException {
525
        boolean isMisapplied = isMisapplied(srcRs);
526

    
527
        String result;
528
        String nameTitle = srcRs.getString("nameTitleCache");
529
        String nameCache = srcRs.getString("nameCache");
530
        if(!isMisapplied){
531
            result = srcRs.getString("nameFullTitleCache");
532
            String taggedName = getTaggedNameTitle(nameCache, nameTitle);
533
            result = result.replace(nameTitle, taggedName);
534
            result = result.replaceAll("^<i>"+ UTF8.HYBRID , UTF8.HYBRID+ "<i>").replaceAll(" "+ UTF8.HYBRID, "</i> "+UTF8.HYBRID+"<i>");
535
        }else{
536
            result = srcRs.getString("nameCache");
537
            String taggedName = getTaggedNameTitle(nameCache, nameCache);
538
            result = result.replace(nameCache, taggedName);
539
            //misapplied
540
            result += getMisappliedAuthor(srcRs);
541
        }
542
        String nameStatus = CdmUtils.Nz(srcRs.getString("nsTitle"));
543
        result = result.replaceAll("(, |^)"+nameStatus+"$", "");
544
        return result;
545
    }
546

    
547
    private boolean isMisapplied(ResultSet srcRs) throws SQLException {
548
        String relTypeUuid = srcRs.getString("taxRelTypeUuid");
549
        boolean isMisapplied = relTypeUuid!=null
550
                && (relTypeUuid.equals(TaxonRelationshipType.uuidMisappliedNameFor.toString())
551
                   || relTypeUuid.equals(TaxonRelationshipType.uuidProParteMisappliedNameFor.toString())
552
                   || relTypeUuid.equals(TaxonRelationshipType.uuidPartialMisappliedNameFor.toString()))
553
                //TODO formatting of ppMANs not yet implemented
554
                && nullSafeInt(srcRs, "relToTaxonId") != null;
555
        return isMisapplied;
556
    }
557

    
558
    private String getMisappliedAuthor(ResultSet srcRs) throws SQLException {
559
        String result;
560
        String relAppendedPhrase = srcRs.getString("tbAppendedPhrase");
561
        String secId = srcRs.getString("secId");
562
        String secTitle = srcRs.getString("secTitle");
563
        if(relAppendedPhrase == null && secId == null) {
564
            result = " auct.";
565
        }else if (relAppendedPhrase != null && secId == null){
566
            result = " " + relAppendedPhrase;
567
        }else if (relAppendedPhrase == null && secId != null){
568
            result = " sensu " + secTitle;
569
        }else{
570
            result = " " + relAppendedPhrase + " " + secTitle;
571
        }
572
        String authorship = srcRs.getString("authorshipCache");
573
        if (isNotBlank(authorship)){
574
            result += ", non " + authorship;
575
        }
576
        return result;
577
    }
578

    
579
    private String getTaggedNameTitle(String nameCache, String nameTitle) {
580
        if (nameCache == null){
581
            logger.warn("NameCache is null");
582
            return nameTitle;
583
        }
584
        String result = null;
585
        try {
586
            String[] nameCacheSplit = nameCache.split(" ");
587
            String[] nameTitleSplit = nameTitle.split(" ");
588
            result = "";
589
            boolean currentIsName = false;
590
            for (int i=0, j=0; j < nameTitleSplit.length; j++){
591
                if (i < nameCacheSplit.length && nameCacheSplit[i].equals(nameTitleSplit[j])
592
                        && !isMarker(nameCacheSplit[i])){
593
                    if(!currentIsName){
594
                        result += " <i>" + nameCacheSplit[i];
595
                        currentIsName = true;
596
                    }else{
597
                        result += " " + nameCacheSplit[i];
598
                    }
599
                    if((j+1)==nameTitleSplit.length){
600
                        result += "</i>";
601
                    }
602
                    i++;
603
                }else{
604
                    if(currentIsName){
605
                        result += "</i>";
606
                        currentIsName = false;
607
                    }
608
                    result += " " + nameTitleSplit[j];
609
                    if (i < nameCacheSplit.length && nameCacheSplit[i].equals(nameTitleSplit[j])
610
                            && isMarker(nameCacheSplit[i])){
611
                        i++;
612
                    }
613
                }
614
            }
615
            return result.trim();
616
        } catch (Exception e) {
617
            e.printStackTrace();
618
            return result;
619
        }
620
    }
621

    
622
    private boolean isMarker(String nameCacheSplit) {
623
        return nameCacheSplit.endsWith(".") || nameCacheSplit.equals("[unranked]")
624
                || nameCacheSplit.equals("grex")|| nameCacheSplit.equals("proles")
625
                || nameCacheSplit.equals("race");
626
    }
627

    
628
    private boolean testSingleTaxonRelations(int n) throws SQLException {
629
        boolean success = true;
630
        ResultSet srcRS = source.getResultSet(""
631
                + " SELECT t.name_id tid, pt.name_id pid "
632
                + " FROM TaxonNode tn "
633
                + "   INNER JOIN TaxonBase t ON tn.taxon_id = t.id "
634
                + "   LEFT JOIN TaxonNode ptn ON ptn.id = tn.parent_id "
635
                + "   LEFT JOIN TaxonBase  pt ON ptn.taxon_id = pt.id "
636
                + " WHERE t.publish = 1 && pt.publish = 1 "
637
                + " ORDER BY CAST(t.name_id as char(20)) ");
638

    
639
        ResultSet destRS = destination.getResultSet("SELECT rel.*, t1.IdInSource t1Id, t2.IdInSource t2Id "
640
                + " FROM RelTaxon rel "
641
                + "    LEFT JOIN Taxon t1 ON t1.TaxonId = rel.TaxonFk1 "
642
                + "    LEFT JOIN Taxon t2 ON t2.TaxonId = rel.TaxonFk2 "
643
                + " WHERE t1."+origEuroMed+" AND t2." + origEuroMed + " AND RelTaxonQualifierFk = 101 "
644
                + " ORDER BY t1.IdInSource");
645
        int i = 0;
646
        while (srcRS.next() && destRS.next()){
647
            success &= testSingleTaxonRelation(srcRS, destRS);
648
            i++;
649
        }
650
        success &= equals("Taxon relation count for single compare", n, i, String.valueOf(-1));
651
        return success;
652
    }
653

    
654
    private boolean testSingleTaxonRelation(ResultSet srcRS, ResultSet destRS) throws SQLException {
655
        String id = String.valueOf(srcRS.getInt("tid"));
656
        boolean success = equals("Taxon relation taxon1", "NameId: " + srcRS.getInt("tid"), destRS.getString("t1Id"), id);
657
        success &= equals("Taxon relation taxon2", "NameId: " + srcRS.getInt("pid"), destRS.getString("t2Id"), id);
658
        success &= equals("Taxon relation qualifier fk", PesiTransformer.IS_TAXONOMICALLY_INCLUDED_IN, destRS.getInt("RelTaxonQualifierFk"), id);
659
        success &= equals("Taxon relation qualifier cache", "is taxonomically included in", destRS.getString("RelQualifierCache"), id);
660
        //TODO enable after next import
661
        success &= isNull("notes", destRS, id);
662
        //complete if no further relations need to added
663
        return success;
664
    }
665

    
666
    private boolean testSingleAdditionalTaxonSources(int n) throws SQLException {
667
        boolean success = true;
668
        ResultSet srcRs = source.getResultSet("SELECT CAST(tu.id as char(20)) tuId, MN.*, s.*, su.sourceuse_name "
669
                + " FROM tu_sources MN INNER JOIN tu ON MN.tu_id = tu.id "
670
                + "    LEFT JOIN sources s ON s.id = MN.source_id "
671
                + "    LEFT JOIN sourceuses su ON MN.sourceuse_id = su.sourceuse_id "
672
                + " ORDER BY CAST(tu.id as char(20)), MN.sourceuse_id, s.id ");  //, no.note (not possible because ntext
673
        ResultSet destRs = destination.getResultSet("SELECT t.IdInSource, ats.*, s.*, su.* "
674
                + " FROM AdditionalTaxonSource ats INNER JOIN Taxon t ON t.TaxonId = ats.TaxonFk "
675
                + "    INNER JOIN Source s ON s.SourceId = ats.SourceFk "
676
                + "    LEFT JOIN SourceUse su ON su.SourceUseId = ats.SourceUseFk "
677
                + " WHERE t."+origEuroMed
678
                + " ORDER BY t.IdInSource, su.SourceUseId, s.RefIdInSource ");
679
        int count = 0;
680
        while (srcRs.next() && destRs.next()){
681
            success &= testSingleAdditionalTaxonSource(srcRs, destRs);
682
            count++;
683
        }
684
        success &= equals("Notes count differs", n, count, "-1");
685
        return success;
686
    }
687

    
688
    private boolean testSingleAdditionalTaxonSource(ResultSet srcRs, ResultSet destRs) throws SQLException {
689
        String id = String.valueOf(srcRs.getInt("tuId") + "-" + srcRs.getString("sourceuse_name"));
690
        boolean success = equals("Additional taxon source taxonID ", "tu_id: " + String.valueOf(srcRs.getInt("tuId")), destRs.getString("IdInSource"), id);
691
        success &= equals("Additional taxon source fk ", srcRs.getString("source_id"), destRs.getString("RefIdInSource"), id);  //currently we use the same id in ERMS and PESI
692
        success &= equals("Additional taxon source use fk ", srcRs.getString("sourceuse_id"), destRs.getString("SourceUseFk"), id);
693
        success &= equals("Additional taxon source use cache ", srcRs.getString("sourceuse_name"), destRs.getString("SourceUseCache"), id);
694
        //TODO some records are still truncated ~ >820 characters
695
        success &= equals("Additional taxon source name cache ", srcRs.getString("source_name"), destRs.getString("SourceNameCache"), id);
696
        success &= equals("Additional taxon source detail ", srcRs.getString("pagenr"), destRs.getString("SourceDetail"), id);
697
        //Complete
698
        return success;
699
    }
700

    
701
    private boolean testSingleNotes(int n) throws SQLException {
702
        boolean success = true;
703
        ResultSet srcRs = source.getResultSet("SELECT CAST(tu.id as char(20)) tuId, no.*, l.LanName "
704
                + " FROM notes no INNER JOIN tu ON no.tu_id = tu.id "
705
                + "    LEFT JOIN languages l ON l.LanID = no.lan_id "
706
                + " ORDER BY CAST(tu.id as char(20)), no.type, no.noteSortable ");  //, no.note (not possible because ntext
707
        ResultSet destRs = destination.getResultSet("SELECT t.IdInSource, no.*, cat.NoteCategory, l.Language "
708
                + " FROM Note no INNER JOIN Taxon t ON t.TaxonId = no.TaxonFk "
709
                + "    LEFT JOIN NoteCategory cat ON cat.NoteCategoryId = no.NoteCategoryFk "
710
                + "    LEFT JOIN Language l ON l.LanguageId = no.LanguageFk "
711
                + " WHERE t." + origEuroMed
712
                + "      AND NOT (NoteCategoryFk = 4 AND no.LastAction IS NULL) AND NOT NoteCategoryFk IN (22,23,24) "
713
                + " ORDER BY t.IdInSource, no.NoteCategoryCache, Note_1  ");
714
        int count = 0;
715
        while (srcRs.next() && destRs.next()){
716
            success &= testSingleNote(srcRs, destRs);
717
            count++;
718
        }
719
        success &= equals("Notes count differs", n, count, "-1");
720
        return success;
721
    }
722

    
723
    private boolean testSingleNote(ResultSet srcRs, ResultSet destRs) throws SQLException {
724
        String id = String.valueOf(srcRs.getInt("tuId") + "-" + srcRs.getString("type"));
725
        boolean success = equals("Note taxonID ", "tu_id: " + String.valueOf(srcRs.getInt("tuId")), destRs.getString("IdInSource"), id);
726
        success &= equals("Note Note_1 ", srcRs.getString("note"), destRs.getString("Note_1"), id);
727
        success &= isNull("Note_2", destRs, id);
728
        success &= equals("Note category cache", normalizeNoteCatCache(srcRs.getString("type")), destRs.getString("NoteCategoryCache"), id);
729
        success &= equals("Note language ", srcRs.getString("LanName"), destRs.getString("Language"), id);
730
        success &= isNull("Region", destRs, id);
731
        success &= isNull("SpeciesExpertGUID", destRs, id);
732
        //SpeciesExpertName, LastAction, LastActionDate handled in separate method
733
        //complete
734
        return success;
735
    }
736

    
737
    private String normalizeNoteCatCache(String string) {
738
        return StringUtils.capitalize(string)
739
                .replace("Original Combination", "Original combination")
740
                .replace("Taxonomic remark", "Taxonomic Remark");
741
    }
742

    
743
    private boolean testSingleDistributions(int n) throws SQLException {
744
        boolean success = true;
745
        ResultSet srcRs = source.getResultSet(
746
                  " SELECT CAST(tb.name_id as char(20)) AS tid, a.idInVocabulary, a.titleCache area, st.uuid statusUuid, "
747
                + "        CASE WHEN deb.updated IS NOT NULL THEN deb.updated ELSE deb.created END as lastActionDate, "
748
                + "        CASE WHEN deb.updated IS NOT NULL THEN 'changed' ELSE 'created' END as lastAction "
749
                + " FROM DescriptionElementBase deb INNER JOIN DescriptionBase db ON deb.inDescription_id = db.id "
750
                + "    LEFT JOIN TaxonBase tb ON db.taxon_id = tb.id "
751
                + "    LEFT JOIN DefinedTermBase a ON a.id = deb.area_id "
752
                + "    LEFT JOIN DefinedTermBase st ON st.id = deb.status_id "
753
                + distributionCountWhere
754
                + " ORDER BY CAST(tb.name_id as char(20)), a.idInVocabulary, a.titleCache ");
755
        ResultSet destRs = destination.getResultSet("SELECT t.IdInSource, a.AreaEmCode, oc.*, a.AreaName "
756
                + " FROM Occurrence oc INNER JOIN Taxon t ON t.TaxonId = oc.TaxonFk "
757
                + "    LEFT JOIN Area a ON a.AreaId = oc.AreaFk "
758
                + " WHERE t." + origEuroMed
759
                + " ORDER BY t.IdInSource, a.AreaEmCode, a.AreaName, oc.Notes ");
760
        int count = 0;
761
        while (srcRs.next() && destRs.next()){
762
            success &= testSingleDistribution(srcRs, destRs);
763
            count++;
764
        }
765
        success &= equals("Distribution count differs", n, count, "-1");
766
        return success;
767
    }
768

    
769
    private boolean testSingleDistribution(ResultSet srcRs, ResultSet destRs) throws SQLException {
770
        String id = String.valueOf(srcRs.getInt("tid") + "-" + srcRs.getString("area"));
771
        boolean success = equals("Distribution taxonID ", "NameId: " + String.valueOf(srcRs.getInt("tid")), destRs.getString("IdInSource"), id);
772
        success &= equals("Distribution AreaEmCode ", srcRs.getString("idInVocabulary"), destRs.getString("AreaEmCode"), id);
773
//        success &= equals("Distribution area name ", normalizeDistrArea(srcRs.getString("area")), destRs.getString("AreaName"), id);
774
        success &= equals("Distribution area name cache", normalizeDistrArea(srcRs.getString("area")), destRs.getString("AreaNameCache"), id);
775
        success &= equals("Distribution OccurrenceStatusFk", mapStatus(srcRs.getString("statusUuid")), destRs.getInt("OccurrenceStatusFk"), id);
776
//TODO        success &= equals("Distribution OccurrenceStatusCache", "Present", destRs.getString("OccurrenceStatusCache"), id);
777
        success &= isNull("SourceFk", destRs, id);  //sources should be moved to extra table only, according to script there were values, but in PESI 2014 values existed only in OccurrenceSource table (for all only E+M records)
778
        success &= isNull("SourceCache", destRs, id);  //sources should be moved to extra table, see above
779
//TODO        success &= equals("Distribution notes ", srcRs.getString("note"), destRs.getString("Notes"), id);
780
        success &= isNull("SpeciesExpertGUID", destRs, id);  //SpeciesExpertGUID does not exist in EM and according to script
781
        success &= isNull("SpeciesExpertName", destRs, id);  //SpeciesExpertName does not exist in EM and according to script
782
        success &= equals("Distribution Last Action", srcRs.getString("lastAction"),  destRs.getString("LastAction"), id);
783
        success &= equals("Distribution Last Action Date", srcRs.getTimestamp("lastActionDate"),  destRs.getTimestamp("LastActionDate"), id);
784
        return success;
785
    }
786

    
787
    /**
788
     * @param string
789
     * @return
790
     */
791
    private Integer mapStatus(String uuidStr) {
792
        UUID uuid = UUID.fromString(uuidStr);
793
        if (uuid.equals(PresenceAbsenceTerm.uuidNativeError) ){  //native, reported in error
794
            return PesiTransformer.STATUS_ABSENT;
795
        }else if (uuid.equals(PresenceAbsenceTerm.uuidIntroducesAdventitious)  //casual, introduced adventitious
796
                || uuid.equals(PresenceAbsenceTerm.uuidIntroducedUncertainDegreeNaturalisation)//introduced: uncertain degree of naturalisation
797
                || uuid.equals(PresenceAbsenceTerm.uuidIntroduced)){
798
            return PesiTransformer.STATUS_INTRODUCED;
799
        }else if (uuid.equals(PresenceAbsenceTerm.uuidNative) ){  //native
800
            return PesiTransformer.STATUS_NATIVE;
801
        }else if (uuid.equals(PresenceAbsenceTerm.uuidNaturalised) ){  //naturalised
802
            return PesiTransformer.STATUS_NATURALISED;
803
        }else if (uuid.equals(PresenceAbsenceTerm.uuidNativePresenceQuestionable) ){  //native, presence questionable
804
            return PesiTransformer.STATUS_DOUBTFUL;
805
        }else if (uuid.equals(PresenceAbsenceTerm.uuidCultivated) ){  //cultivated
806
            return PesiTransformer.STATUS_MANAGED;
807
        }else if (uuid.equals(BerlinModelTransformer.uuidStatusUndefined) ){  //native, reported in error
808
            return -1;
809
        }
810

    
811
        return null;
812
    }
813

    
814
    private String normalizeDistrArea(String area) {
815
        if (area == null){
816
            return null;
817
        }else if ("France".equals(area)){return "French mainland";
818
        }else if ("France, with Channel Islands and Monaco".equals(area)){return "France";
819
        }else if ("Greece".equals(area)){return "Greece with Cyclades and more islands";
820
        }else if ("Spain, with Gibraltar and Andorra (without Bl and Ca)".equals(area)){return "Spain";
821
        }else if ("Italy, with San Marino and Vatican City (without Sa and Si(S))".equals(area)){return "Italy";
822
        }else if ("Morocco, with Spanish territories".equals(area)){return "Morocco";
823
        }else if ("Serbia including Kosovo and Vojvodina".equals(area)){return "Serbia including Vojvodina and with Kosovo";
824
        }else if ("Caucasia (Ab + Ar + Gg + Rf(CS))".equals(area)){return "Caucasus region";
825
        }else if ("Georgia, with Abchasia and Adzharia".equals(area)){return "Georgia";
826
        }else if ("Canary Is.".equals(area)){return "Canary Islands";
827
        }else if ("Kriti with Karpathos, Kasos & Gavdhos".equals(area)){return "Crete with Karpathos, Kasos & Gavdhos";
828
        }else if ("Ireland, with N Ireland".equals(area)){return "Ireland";
829
        }else if ("mainland Spain".equals(area)){return "Kingdom of Spain";
830
        }else if ("Portugal".equals(area)){return "Portuguese mainland";
831
        }else if ("Svalbard".equals(area)){return "Svalbard with Björnöya and Jan Mayen";
832
        }else if ("Norway".equals(area)){return "Norwegian mainland";
833
        }else if ("Ukraine".equals(area)){return "Ukraine including Crimea";
834
        }else if ("Turkey-in-Europe".equals(area)){return "European Turkey";
835
        }else if ("Azerbaijan".equals(area)){return "Azerbaijan including Nakhichevan";
836
        }else if ("Ireland".equals(area)){return "Republic of Ireland";
837
        }else if ("France".equals(area)){return "French mainland";
838
        }
839
        return area;
840
    }
841

    
842
    private boolean testSingleCommonNames(int n) throws SQLException {
843
        boolean success = true;
844
        ResultSet srcRs = source.getResultSet("SELECT v.*, ISNULL([639_3],[639_2]) iso, l.LanName, tu.id tuId "
845
                + " FROM vernaculars v LEFT JOIN tu ON v.tu_id = tu.id LEFT JOIN languages l ON l.LanID = v.lan_id "
846
                + " ORDER BY CAST(tu.id as char(20)), ISNULL([639_3],[639_2]), v.vername, v.id ");
847
        ResultSet destRs = destination.getResultSet("SELECT cn.*, t.IdInSource, l.ISO639_2, l.ISO639_3 "
848
                + " FROM CommonName cn INNER JOIN Taxon t ON t.TaxonId = cn.TaxonFk LEFT JOIN Language l ON l.LanguageId = cn.LanguageFk "
849
                + " WHERE t." + origEuroMed
850
                + " ORDER BY t.IdInSource, ISNULL("+preferredISO639+", "+alternativeISO639+"), cn.CommonName, cn.LastActionDate ");  //sorting also lastActionDate results in a minimum of exact duplicate problems
851
        int count = 0;
852
        while (srcRs.next() && destRs.next()){
853
            success &= testSingleCommonName(srcRs, destRs);
854
            count++;
855
        }
856
        success &= equals("Common name count differs", n, count, "-1");
857
        return success;
858
    }
859

    
860
    boolean prefer639_3 = true;
861
    String preferredISO639 = prefer639_3? "ISO639_3":"ISO639_2";
862
    String alternativeISO639 = prefer639_3? "ISO639_2":"ISO639_3";
863

    
864
    private boolean testSingleCommonName(ResultSet srcRs, ResultSet destRs) throws SQLException {
865
        String id = String.valueOf(srcRs.getInt("tuId") + "-" + srcRs.getString("lan_id"));
866
        boolean success = equals("Common name taxonID ", "tu_id: " + String.valueOf(srcRs.getInt("tuId")), destRs.getString("IdInSource"), id);
867
        success &= equals("CommonName name ", srcRs.getString("vername"), destRs.getString("CommonName"), id);
868
        success &= equals("Common name languageFk ", srcRs.getString("iso"), getLanguageIso(destRs), id);
869
        success = equals("CommonName LanguageCache ", normalizeLang(srcRs.getString("LanName")), destRs.getString("LanguageCache"), id);
870
        //TODO needed? success = equals("CommonName language code ", srcRs.getString("lan_id"), destRs.getString("LanguageFk"), id);
871
        success &= isNull("Region", destRs, id);  //region does not seem to exist in ERMS
872
        //TODO see comments
873
//        success &= isNull("SourceFk", destRs);  //sources should be moved to extra table, check with PESI 2014
874
//        success &= isNull("SourceNameCache", destRs);  //sources should be moved to extra table, check with PESI 2014
875
        success &= isNull("SpeciesExpertGUID", destRs, id);  //SpeciesExpertGUID does not exist in ERMS
876
        //SpeciesExpertName,LastAction,LastActionDate handled in separate method
877
        //complete
878
        return success;
879
    }
880

    
881
    private String normalizeLang(String string) {
882
        if ("Spanish".equals(string)){
883
            return "Spanish, Castillian";
884
        }else if ("Modern Greek (1453-)".equals(string)){
885
            return "Greek";
886
        }else if ("Malay (individual language)".equals(string)){
887
            return "Malay";
888
        }else if ("Swahili (individual language)".equals(string)){
889
            return "Swahili";
890
        }
891

    
892
        return string;
893
    }
894

    
895
    private String getLanguageIso(ResultSet destRs) throws SQLException {
896
        String result = destRs.getString(preferredISO639);
897
        if (result == null){
898
            result = destRs.getString(alternativeISO639);
899
        }
900
        return result;
901
    }
902

    
903
    private boolean testSingleReferences(int count) throws SQLException {
904
        boolean success = true;
905
        ResultSet srcRS = source.getResultSet("SELECT r.*, a.titleCache author "
906
                + " FROM Reference r LEFT OUTER JOIN AgentBase a ON r.authorship_id = a.id "
907
                + " ORDER BY r.id ");
908
        ResultSet destRS = destination.getResultSet("SELECT s.* FROM Source s "
909
                + " WHERE s." + origEuroMed
910
                + " ORDER BY s.RefIdInSource ");  // +1 for the source reference "erms" but this has no OriginalDB
911
        int i = 0;
912
        while (srcRS.next() && destRS.next()){
913
            success &= testSingleReference(srcRS, destRS);
914
            i++;
915
        }
916
        success &= equals("References count differs", count, i, "-1");
917
        return success;
918
    }
919

    
920
    private boolean testSingleReference(ResultSet srcRS, ResultSet destRS) throws SQLException {
921
        String id = String.valueOf(srcRS.getInt("id"));
922
        boolean success = equals("Reference ID ", srcRS.getInt("id"), destRS.getInt("RefIdInSource"), id);
923
        success &= isNull("IMIS_Id", destRS, id);  //for E+M no IMIS id exists
924
        success &= equals("Reference SourceCategoryFk ", convertSourceTypeFk(srcRS.getString("refType")), destRS.getInt("SourceCategoryFk"), id);
925
        success &= equals("Reference SourceCategoryCache ", convertSourceTypeCache(srcRS.getString("refType")), destRS.getString("SourceCategoryCache"), id);
926
        success &= equals("Reference name ", srcRS.getString("titleCache"), destRS.getString("Name"), id);
927
        success &= equals("Reference abstract ", srcRS.getString("referenceAbstract"), destRS.getString("Abstract"), id);
928
        success &= equals("Reference title ", srcRS.getString("title"), destRS.getString("Title"), id);
929
        success &= equals("Reference author string ", srcRS.getString("author"), destRS.getString("AuthorString"), id);
930
        //TODO
931
        success &= equals("Reference year ", normalizeYear(srcRS), destRS.getString("RefYear"), id);
932
        //FIXME
933
//        success &= equals("Reference NomRefCache ", srcRS.getString("abbrevTitleCache"), destRS.getString("NomRefCache"), id);
934
        success &= equals("Reference DOI ", srcRS.getString("doi"), destRS.getString("Doi"), id);
935
        success &= equals("Reference link ", srcRS.getString("uri"), destRS.getString("Link"), id);
936
        //TODO Notes
937
//        success &= equals("Reference note ", srcRS.getString("source_note"), destRS.getString("Notes"), id);
938
        //complete
939
        return success;
940
    }
941

    
942
    private Integer convertSourceTypeFk(String sourceType) {
943
        if (sourceType == null){
944
            return null;
945
        }else if ("DB".equals(sourceType)){
946
            return PesiTransformer.REF_DATABASE;
947
        }else if ("JOU".equals(sourceType)){
948
            return PesiTransformer.REF_JOURNAL;
949
        }else if ("BK".equals(sourceType)){
950
            return PesiTransformer.REF_BOOK;
951
        }else if ("GEN".equals(sourceType)){
952
            return PesiTransformer.REF_UNRESOLVED;
953
        }else if ("SER".equals(sourceType)){
954
//            TODO correct?
955
            return PesiTransformer.REF_UNRESOLVED;
956
        }
957
        return null;
958
    }
959
    private String convertSourceTypeCache(String sourceType) {
960
        if (sourceType == null){
961
            return null;
962
        }else if ("DB".equals(sourceType)){
963
            return "database";
964
        }else if ("JOU".equals(sourceType)){
965
            return "journal";
966
        }else if ("BK".equals(sourceType)){
967
            return "book";
968
        }else if ("SER".equals(sourceType)){
969
            return "published";
970
        }else if ("BK".equals(sourceType)){
971
            return "book";
972
        }else if ("GEN".equals(sourceType)){
973
            return "unresolved";
974
        }
975
        return null;
976
    }
977

    
978
    private boolean testReferenceCount() {
979
        int countSrc = source.getUniqueInteger(countReferencesStr);
980
        int countDest = destination.getUniqueInteger("SELECT count(*) FROM Source s WHERE s."+ origEuroMed);  // +1 for the source reference "erms" but this has no OriginalDB
981
        boolean success = equals("Reference count ", countSrc, countDest, "-1");
982
        return success;
983
    }
984

    
985
    private String normalizeYear(ResultSet rs) throws SQLException {
986
        String freetext = rs.getString("datePublished_freetext");
987
        if(StringUtils.isNotBlank(freetext)){
988
            return freetext;
989
        }
990
        String start = rs.getString("datePublished_start");
991
        String end = rs.getString("datePublished_end");
992
        if (start != null){
993
            start = start.substring(0,4);
994
        }
995
        if (end != null){
996
            end = end.substring(0,4);
997
        }
998
        String result = start == null? null: start + (end==null? "": "-"+ end);
999
        return result;
1000
    }
1001

    
1002
    private boolean equals(String messageStart, Timestamp srcDate, Timestamp destDate, String id) {
1003
        if (!CdmUtils.nullSafeEqual(srcDate, destDate)){
1004
            LocalDate date1 = srcDate.toLocalDateTime().toLocalDate();
1005
            LocalDate date2 = destDate.toLocalDateTime().toLocalDate();
1006
            if (date1.equals(date2) || date1.plusDays(1).equals(date2)){
1007
                logger.info(messageStart + " were (almost) equal: " + srcDate);
1008
                return true;
1009
            }else{
1010
                String message = id + ": " + messageStart + " must be equal, but was not.\n Source: "+  srcDate + "; Destination: " + destDate;
1011
                logger.warn(message);
1012
                return false;
1013
            }
1014
        }else{
1015
            logger.info(messageStart + " were equal: " + srcDate);
1016
            return true;
1017
        }
1018
    }
1019

    
1020
    private boolean equals(String messageStart, Integer nSrc, Integer nDest, String id) {
1021
        String strId = id.equals("-1")? "": (id+ ": ");
1022
        if (!CdmUtils.nullSafeEqual(nSrc,nDest)){
1023
            String message = strId+ messageStart + " must be equal, but was not.\n Source: "+  nSrc + "; Destination: " + nDest;
1024
            logger.warn(message);
1025
            return false;
1026
        }else{
1027
            logger.info(strId + messageStart + " were equal: " + nSrc);
1028
            return true;
1029
        }
1030
    }
1031

    
1032
//** ************* MAIN ********************************************/
1033

    
1034
    public static void main(String[] args){
1035
        PesiEuroMedValidator validator = new PesiEuroMedValidator();
1036
        validator.invoke(new Source(defaultSource), defaultDestination);
1037
        System.exit(0);
1038
    }
1039
}
(2-2/3)