Project

General

Profile

Download (52 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

    
15
import org.apache.commons.lang.StringUtils;
16
import org.apache.log4j.Logger;
17

    
18
import eu.etaxonomy.cdm.app.common.PesiDestinations;
19
import eu.etaxonomy.cdm.app.common.PesiSources;
20
import eu.etaxonomy.cdm.common.CdmUtils;
21
import eu.etaxonomy.cdm.io.common.Source;
22
import eu.etaxonomy.cdm.io.pesi.out.PesiTransformer;
23

    
24
/**
25
 * Tests the ERMS -> PESI pipeline by comparing the source DB with destination PESI DB.
26
 *
27
 * @author a.mueller
28
 * @since 01.09.2019
29
 */
30
public class PesiErmsValidator {
31

    
32
    private static final Logger logger = Logger.getLogger(PesiErmsValidator.class);
33

    
34
    private static final Source defaultSource = PesiSources.PESI2019_ERMS_2019();
35
    private static final Source defaultDestination = PesiDestinations.pesi_test_local_CDM_ERMS2PESI();
36
//    private static final Source defaultDestination = PesiDestinations.pesi_test_local_CDM_ERMS2PESI_2();
37

    
38
    private Source source = defaultSource;
39
    private Source destination = defaultDestination;
40
    private String moneraFilter = " NOT IN (-1)"; // 147415;
41
//    private String moneraFilter = " NOT IN (147415)"; // 147415;
42

    
43
    private String origErms = "OriginalDB = 'ERMS' ";
44

    
45
    public void invoke(Source source, Source destination){
46
        logger.warn("Validate destination " +  destination.getDatabase());
47
        boolean success = true;
48
        try {
49
            this.source = source;
50
            this.destination = destination;
51
//            success &= testReferences();  //ready, few minor issues to be discussed with VLIZ
52
            success &= testTaxa();
53
//            success &= testTaxonRelations();  //name relations count!,  single record compare tests for synonyms and included in
54
//            success &= testCommonNames();  //source(s) discuss VLIZ, exact duplicates (except for sources), Anus(Korur)
55
//            success &= testDistributions();  //>1000 duplicates in "dr", sources (OccurrenceSource table), 1 long note
56
//            success &= testNotes();  //ecology & link notes test (only count tested), sources untested (NoteSource table)
57
//            success &= testAdditionalTaxonSources();  //ready
58
        } catch (Exception e) {
59
            e.printStackTrace();
60
            success = false;
61
        }
62
        System.out.println("end validation " + (success? "":"NOT ") + "successful.");
63
    }
64

    
65
    private boolean testAdditionalTaxonSources() throws SQLException {
66
        System.out.println("Start validate additional taxon sources");
67
        boolean success = testAdditionalTaxonSourcesCount();
68
        if (success){
69
              success &= testSingleAdditionalTaxonSources(source.getUniqueInteger(countAddtionalTaxonSource));
70
        }
71
        return success;
72
    }
73

    
74
    private boolean testNotes() throws SQLException {
75
        System.out.println("Start validate notes");
76
        boolean success = testNotesCount();
77
        if (success){
78
              success &= testSingleNotes(source.getUniqueInteger("SELECT count(*) FROM notes "));
79
        }
80
        return success;
81
    }
82

    
83
    private boolean testDistributions() throws SQLException {
84
        System.out.println("Start validate distributions");
85
        boolean success = testDistributionCount();
86
        if (success){
87
              success &= testSingleDistributions(source.getUniqueInteger("SELECT count(*) FROM dr "));
88
        }
89
        return success;
90
    }
91

    
92
    private boolean testCommonNames() throws SQLException {
93
        System.out.println("Start validate common names");
94
        boolean success = testCommonNameCount();
95
        if (success){
96
            success &= testSingleCommonNames(source.getUniqueInteger("SELECT count(*) FROM vernaculars "));
97
        }
98
        return success;
99
    }
100

    
101
    int countSynonyms;
102
    int countIncludedIns;
103
    private boolean testTaxonRelations() throws SQLException {
104
        System.out.println("Start validate taxon relations");
105
        boolean success = testSynonymRelations();  //only count, single record test still missing
106
        success &= testIncludedInRelations();  //only count, single record test still missing
107
        success &= testTotalRelations();
108
        success &= testNameRelations();
109
        return success;
110
    }
111

    
112
    private boolean testTotalRelations() {
113
        if (!(countSynonyms < 0 || countIncludedIns < 0)){
114
            int countTotalSrc = countSynonyms + countIncludedIns;
115
            int countSrc = source.getUniqueInteger("SELECT count(*) FROM tu ");
116
            boolean success = equals("Taxrel count + 1 must be same as source taxon count ", countTotalSrc+1, countSrc, String.valueOf(-1));
117
            int countDest = destination.getUniqueInteger("SELECT count(*) FROM Taxon t WHERE t."+ origErms);
118
            success &= equals("Taxrel count + 1 must be same as destination taxon count ", countTotalSrc+1, countDest, String.valueOf(-1));
119
            return success;
120
        }else{
121
            return false;
122
        }
123
    }
124

    
125
    private boolean testSynonymRelations() throws SQLException {
126

    
127
        int countSrc = source.getUniqueInteger(countSynonymRelation);
128
        int countDest = destination.getUniqueInteger("SELECT count(*) FROM RelTaxon WHERE RelTaxonQualifierFk > 101");
129
        boolean success = equals("Synonym count ", countSrc, countDest, String.valueOf(-1));
130
//         update Match_RelStat set RelTaxon  =  102 where tu_unacceptreason like 'currently placed%'
131
//                 update Match_RelStat set RelTaxon   =  102 where tu_unacceptreason like 'currently held%'
132
//                 update Match_RelStat set RelTaxon   =  102 where tu_unacceptreason like 'sy%' or tu_unacceptreason like '%jun%syn%'
133
//                 update Match_RelStat set RelTaxon   =  102 where tu_unacceptreason = '(synonym)'
134
//                 update Match_RelStat set RelTaxon   =  102 where tu_unacceptreason = 'reverted genus transfer'
135
//                 update Match_RelStat set RelTaxon   =  103 where tu_unacceptreason like 'misapplied%'
136
//                 update Match_RelStat set RelTaxon   =  104 where tu_unacceptreason like 'part% synonym%'
137
//                 update Match_RelStat set RelTaxon   =  106 where tu_unacceptreason = 'heterotypic synonym' or tu_unacceptreason = 'subjective synonym'
138
//                 update Match_RelStat set RelTaxon   =  107 where tu_unacceptreason like '%homot%syn%' or tu_unacceptreason = 'objective synonym' synyonym
139
//                 update Match_RelStat set RelTaxon   =  107 where tu_unacceptreason like '%bas[iy][no]%ny%'
140
        if (success){
141
            //TODO test single synonym relations
142
//            success &= testSingleTaxonRelations(source.getUniqueInteger(countSynonymRelation));
143
        }
144
        countSynonyms = (countSrc == countDest)? countSrc : -1;
145
        return success;
146
    }
147

    
148
    private boolean testNameRelations() {
149
        //Name relations
150
        int countSrc = source.getUniqueInteger("SELECT count(*) FROM tu WHERE id " + moneraFilter + " AND ("
151
               + " tu_unacceptreason like '%bas[iy][no]%ny%' OR tu_unacceptreason = 'original combination' "
152
               + " OR tu_unacceptreason = 'Subsequent combination' OR tu_unacceptreason like '%genus transfer%'  "
153
               + " OR tu_unacceptreason = 'genus change' "  //1
154
               + " OR tu_unacceptreason like '%homon%' "   // 2
155
               + " OR tu_unacceptreason like '%spell%' OR tu_unacceptreason like 'lapsus %' " //16
156

    
157
                 + ")");
158
        int countDest = destination.getUniqueInteger("SELECT count(*) FROM RelTaxon WHERE RelTaxonQualifierFk <100 ");
159
        boolean success = equals("Taxon name relation count ", countSrc, countDest, String.valueOf(-1));
160
        if (success){
161
            //TODO test single name relation
162
//            success &= testSingleTaxonRelations(source.getUniqueInteger(countSynonymRelation));
163
        }
164
        return success;
165
    }
166

    
167
    private boolean testIncludedInRelations() {
168
        int countSrc = source.getUniqueInteger(countParentRelation);
169
        int  countDest = destination.getUniqueInteger("SELECT count(*) FROM RelTaxon WHERE RelTaxonQualifierFk = 101 ");
170
        boolean success = equals("Tax included in count ", countSrc, countDest, String.valueOf(-1));
171
        if (success){
172
            //TODO test single includedIn relations
173
//            success &= testSingleTaxonRelations(source.getUniqueInteger(countSynonymRelation));
174
        }
175
        countIncludedIns = (countSrc == countDest)? countSrc : -1;
176
        return success;
177
    }
178

    
179
    private boolean testTaxa() throws SQLException {
180
        System.out.println("Start validate taxa");
181
        boolean success = testTaxaCount();
182
        //FIXME
183
        if (!success){
184
            success &= testSingleTaxa(source.getUniqueInteger(countTaxon));
185
        }
186
        return success;
187
    }
188

    
189
    private boolean testReferences() throws SQLException {
190
        System.out.println("Start validate references");
191
        boolean success = testReferenceCount();
192
        if (success){
193
            success &= testSingleReferences();
194
        }
195
        return success;
196
    }
197

    
198
    private final String countAddtionalTaxonSource = "SELECT count(*) FROM tu_sources ts WHERE ts.tu_id " + moneraFilter;
199
    private boolean testAdditionalTaxonSourcesCount() {
200
        int countSrc = source.getUniqueInteger(countAddtionalTaxonSource);
201
        int countDest = destination.getUniqueInteger("SELECT count(*) FROM AdditionalTaxonSource ");
202
        return equals("AdditionalTaxonSource count ", countSrc, countDest, String.valueOf(-1));
203
    }
204

    
205
    private boolean testNotesCount() {
206
        int countSrc = source.getUniqueInteger("SELECT count(*) FROM notes ");
207
        int countDest = destination.getUniqueInteger("SELECT count(*) FROM Note "
208
                + " WHERE NOT (NoteCategoryFk = 4 AND LastAction IS NULL) AND NOT NoteCategoryFk IN (22,23,24) ");
209
        boolean result = equals("Notes count ", countSrc, countDest, String.valueOf(-1));
210

    
211
        countSrc = source.getUniqueInteger("SELECT count(*) FROM tu "
212
                + " WHERE (tu_marine IS NOT NULL OR tu_brackish IS NOT NULL OR tu_fresh IS NOT NULL OR tu_terrestrial IS NOT NULL) "
213
                + "     AND tu.id " + moneraFilter );
214
        countDest = destination.getUniqueInteger("SELECT count(*) FROM Note "
215
                + " WHERE (NoteCategoryFk = 4 AND LastAction IS NULL) ");
216
        result &= equals("Notes ecology count ", countSrc, countDest, String.valueOf(-1));
217

    
218
        countSrc = source.getUniqueInteger("SELECT count(*) FROM links ");
219
        countDest = destination.getUniqueInteger("SELECT count(*) FROM Note "
220
                + " WHERE NoteCategoryFk IN (22,23,24) ");
221
        result &= equals("Notes link count ", countSrc, countDest, String.valueOf(-1));
222

    
223
        return result;
224
    }
225

    
226
    private boolean testDistributionCount() {
227
        int countSrc = source.getUniqueInteger("SELECT count(*) FROM dr ");
228
        int countDest = destination.getUniqueInteger("SELECT count(*) FROM Occurrence ");
229
        return equals("Occurrence count ", countSrc, countDest, String.valueOf(-1));
230
    }
231

    
232
    private boolean testCommonNameCount() {
233
        int countSrc = source.getUniqueInteger("SELECT count(*) FROM vernaculars ");
234
        int countDest = destination.getUniqueInteger("SELECT count(*) FROM CommonName ");
235
        return equals("CommonName count ", countSrc, countDest, String.valueOf(-1));
236
    }
237

    
238
    private final String countSynonymRelation = "SELECT count(*) FROM tu syn LEFT JOIN tu acc ON syn.tu_accfinal = acc.id WHERE (syn.id <> acc.id AND syn.tu_accfinal IS NOT NULL AND syn.id <> acc.tu_parent) AND syn.id " + moneraFilter;
239
    private final String countParentRelation  = "SELECT count(*)-1 FROM tu syn LEFT JOIN tu acc ON syn.tu_accfinal = acc.id WHERE (syn.id =  acc.id OR  syn.tu_accfinal IS  NULL OR  syn.id =  acc.tu_parent) AND syn.id " + moneraFilter;
240

    
241
    private final String countTaxon = "SELECT count(*) FROM tu WHERE id " + moneraFilter;
242
    private boolean testTaxaCount() {
243
         int countSrc = source.getUniqueInteger(countTaxon);
244
         int countDest = destination.getUniqueInteger("SELECT count(*) FROM Taxon ");
245
         boolean result = equals("Taxon count ", countSrc, countDest, String.valueOf(-1));
246

    
247
         //NomStatus
248
         countSrc = source.getUniqueInteger("SELECT count(*) FROM tu WHERE id " + moneraFilter + " AND ("
249
               + " tu_unacceptreason like '%inval%' OR  tu_unacceptreason like '%not val%' "
250
               + " OR tu_unacceptreason like '%illeg%' OR tu_unacceptreason like '%nud%' "
251
               + " OR tu_unacceptreason like '%rej.%' OR tu_unacceptreason like '%superfl%' "
252
               + " OR tu_unacceptreason like '%Comb. nov%' OR tu_unacceptreason like '%New name%' "
253
               + " OR tu_unacceptreason = 'new combination'  "
254
               + " OR tu_status IN (3,5,6,7,8) )");
255
         countDest = destination.getUniqueInteger("SELECT count(*) FROM Taxon WHERE NameStatusFk IS NOT NULL ");
256
         result = equals("Taxon name status count ", countSrc, countDest, String.valueOf(-1));
257

    
258
         return result;
259
     }
260

    
261
    private boolean testSingleTaxa(int n) throws SQLException {
262
        boolean success = true;
263
        ResultSet srcRS = source.getResultSet(""
264
                + " SELECT t.*, pt.tu_name pt_name, pt.id pId, pt.tu_accfinal pAccId, "
265
                + "        acc.tu_sp as acc_sp, accP.id accPId, "
266
                + "        r.rank_name, st.status_name, "
267
                + "        type.tu_displayname typename, type.tu_authority typeauthor, "
268
                + "        fo.fossil_name, qs.qualitystatus_name "
269
                + " FROM tu t "
270
                + " LEFT JOIN tu as pt on t.tu_parent = pt.id "
271
                + " LEFT JOIN (SELECT DISTINCT rank_id, rank_name FROM ranks WHERE NOT(rank_id = 30 AND rank_name = 'Phylum (Division)' OR rank_id = 40 AND rank_name = 'Subphylum (Subdivision)' OR rank_id = 122 AND rank_name='Subsection')) as r ON t.tu_rank = r.rank_id "
272
                + " LEFT JOIN tu acc ON acc.id = t.tu_accfinal "
273
                + " LEFT JOIN tu accP ON acc.tu_parent = accP.id "
274
                + " LEFT JOIN status st ON st.status_id = t.tu_status "
275
                + " LEFT JOIN tu type ON type.id = t.tu_typetaxon "
276
                + " LEFT JOIN fossil fo ON t.tu_fossil = fo.fossil_id "
277
                + " LEFT JOIN qualitystatus qs ON t.tu_qualitystatus = qs.id "
278
                + " WHERE t.id " + moneraFilter
279
                + " ORDER BY CAST(t.id as nvarchar(20)) ");
280
        ResultSet destRS = destination.getResultSet("SELECT t.*, "
281
                + "     pt.GenusOrUninomial p_GenusOrUninomial, pt.InfraGenericEpithet p_InfraGenericEpithet, pt.SpecificEpithet p_SpecificEpithet, "
282
                + "     pt.treeIndex pTreeIndex, pt.IdInSource pIdInSource, "
283
                + "     s.Name as sourceName, type.IdInSource typeSourceId, r.Rank "
284
                + " FROM Taxon t "
285
                + "    LEFT JOIN Taxon pt ON pt.TaxonId = t.ParentTaxonFk "
286
                + "    LEFT JOIN Taxon type ON type.TaxonId = t.TypeNameFk "
287
                + "    LEFT JOIN Rank r ON r.RankId = t.RankFk AND r.KingdomId = t.KingdomFk "
288
                + "    LEFT JOIN Source s ON s.SourceId = t.SourceFk "
289
                + " WHERE t."+ origErms
290
                + " ORDER BY t.IdInSource");
291
        ResultSet srcRsLastAction = source.getResultSet(""
292
                + " SELECT t.id, s.sessiondate, a.action_name, s.ExpertName "
293
                + " FROM tu t "
294
                + "   LEFT OUTER JOIN tu_sessions MN ON t.id = MN.tu_id "
295
                + "   LEFT JOIN actions a ON a.id = MN.action_id "
296
                + "   LEFT JOIN sessions s ON s.id = MN.session_id  "
297
                + " ORDER BY CAST(t.id as nvarchar(20)), s.sessiondate DESC, a.id DESC ");
298
        int i = 0;
299
        while (srcRS.next() && destRS.next()){
300
            success &= testSingleTaxon(srcRS, destRS);
301
            success &= testLastAction(srcRsLastAction, destRS, String.valueOf(srcRS.getInt("id")), "Taxon");
302
            i++;
303
        }
304
        success &= equals("Taxon count for single compare", n, i, String.valueOf(-1));
305
        return success;
306
    }
307

    
308
    private boolean testSingleTaxon(ResultSet srcRS, ResultSet destRS) throws SQLException {
309
        String id = String.valueOf(srcRS.getInt("id"));
310
        //complete
311
        boolean success = equals("Taxon ID", "tu_id: " + srcRS.getInt("id"), destRS.getString("IdInSource"), id);
312
        success &= equals("Taxon source", "ERMS export for PESI", destRS.getString("sourceName"), id);
313

    
314
        success &= compareKingdom("Taxon kingdom", srcRS, destRS, id);
315
        success &= equals("Taxon rank fk", srcRS.getString("tu_rank"), destRS.getString("RankFk"), id);
316
        success &= equals("Taxon rank cache", normalizeRank(srcRS.getString("rank_name"), srcRS, id), destRS.getString("Rank"), id);
317
        success &= compareNameParts(srcRS, destRS, id);
318

    
319
        success &= equals("Taxon websearchname", srcRS.getString("tu_displayname"), destRS.getString("WebSearchName"), id);
320
        //in ERMS displayName and webShowName should be equal as we do not have a correctly formatted nom. ref.
321
//        success &= equals("Taxon WebShowName", srcDisplayName(srcRS), destRS.getString("WebShowName"), id);
322
        success &= equals("Taxon authority", srcRS.getString("tu_authority"), destRS.getString("AuthorString"), id);
323
//        success &= equals("Taxon FullName", srcFullName(srcRS), destRS.getString("FullName"), id);
324
        success &= isNull("NomRefString", destRS, id);
325
//        success &= equals("Taxon DisplayName", srcDisplayName(srcRS), destRS.getString("DisplayName"), id);  //according to SQL script same as FullName, no nom.ref. information attached
326

    
327
//TODO nameStatusFk       success &= equals("Taxon NameStatusFk", toNameStatus(nullSafeInt(srcRS, "tu_status")),nullSafeInt( destRS,"NameStatusFk"), id);
328
//TODO nameStatusCache    success &= equals("Taxon NameStatusCache", srcRS.getString("status_name"), destRS.getString("NameStatusCache"), id);
329

    
330
//      success &= equals("Taxon TaxonStatusFk", normalizeTaxonStatusFk(srcRS),nullSafeInt( destRS,"TaxonStatusFk"), id);
331
//      success &= equals("Taxon TaxonStatusCache", normalizeTaxonStatusCache(srcRS), destRS.getString("TaxonStatusCache"), id);
332

    
333
        success &= equals("Taxon ParentTaxonFk", srcParentTaxonFk(srcRS), destParentIdInSource(destRS), id);
334
        Integer orgigTypeNameFk = nullSafeInt(srcRS, "tu_typetaxon");
335
        success &= equals("Taxon TypeNameFk", orgigTypeNameFk == null? null : "tu_id: " + orgigTypeNameFk, destRS.getString("typeSourceId"), id);
336
//TODO  success &= equals("Taxon TypeFullNameCache", CdmUtils.concat(" ", srcRS.getString("typename"), srcRS.getString("typeauthor")), destRS.getString("TypeFullNameCache"), id);
337
        success &= equals("Taxon QualityStatusFK", nullSafeInt(srcRS, "tu_qualitystatus"),nullSafeInt( destRS,"QualityStatusFk"), String.valueOf(id));
338
        success &= equals("Taxon QualityStatusCache", srcRS.getString("qualitystatus_name"), destRS.getString("QualityStatusCache"), id);
339
        success &= testTreeIndex(destRS, "TreeIndex", "pTreeIndex", id);
340
        success &= equals("Taxon FossilStatusFk", nullSafeInt(srcRS, "tu_fossil"),nullSafeInt( destRS,"FossilStatusFk"), String.valueOf(id));
341
        success &= equals("Taxon FossilStatusCache", srcRS.getString("fossil_name"), destRS.getString("FossilStatusCache"), id);
342
        success &= equals("Taxon GUID", srcRS.getString("GUID"), destRS.getString("GUID"), id);
343
        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
344
        success &= isNull("ExpertGUID", destRS, id);  //only relevant after merge
345
        success &= isNull("ExpertName", destRS, id);  //only relevant after merge
346
        success &= isNull("SpeciesExpertGUID", destRS, id);  //only relevant after merge
347
        success &= equals("Taxon cache citation", srcRS.getString("cache_citation"), destRS.getString("CacheCitation"), id);
348
        //LastAction(Date) handled in separate method
349
        success &= isNull("GUID2", destRS, id);  //only relevant after merge
350
        success &= isNull("DerivedFromGuid2", destRS, id);  //only relevant after merge
351
        return success;
352
    }
353

    
354
    private Integer destParentIdInSource(ResultSet destRS) throws SQLException {
355
        String parentIdInSource = destRS.getString("pIdInSource");
356
        if (parentIdInSource == null){
357
            return null;
358
        }else{
359
            String idStr = parentIdInSource.replace("tu_id:", "").trim();
360
            Integer result = Integer.valueOf(idStr);
361
            return result;
362
        }
363
    }
364

    
365
    private Integer srcParentTaxonFk(ResultSet srcRS) throws SQLException {
366
        Integer id = nullSafeInt(srcRS,"id");
367
        Integer accId = nullSafeInt(srcRS, "tu_accfinal");
368
        Integer pId = nullSafeInt(srcRS, "pId");
369
        Integer pAccId = nullSafeInt(srcRS, "pAccId");
370
        Integer accPId = nullSafeInt(srcRS, "accPId");  //parent of accepted taxon
371

    
372
        if (accId != null && !id.equals(accId)){
373
            if (id.equals(accPId)){
374
                return pId;    //exceptional handling to avoid recursion mostly for some autonyms and alternate representations
375
            }else{
376
                return null;  //taxon is not accepted
377
            }
378
        }else{
379
            if (id == 1){
380
                return null;  //Biota
381
            }else if (pAccId == null){
382
                return pId;  //handle parent preliminary as accepted
383
            }else if (id.equals(pAccId)){
384
                return pId;  //exceptional handling to avoid recursion mostly for some autonyms and alternate representations
385
            }else{
386
                return pAccId;
387
            }
388
        }
389
    }
390

    
391
    private Integer normalizeTaxonStatusFk(ResultSet srcRS) throws SQLException {
392
        Integer status = nullSafeInt(srcRS, "tu_status");
393
        if(status == 1 || status == 6 || status == 7 || status == 8 || status == 9 || status == 10 ){   //accepted, nomen dubium, temporary name, taxon inquirendum (status uncertain), interim unpublished, uncertain
394
            return 1;
395
        }else if (status == 2 || status == 3 || status == 5){  //unaccepted, nomen nudum, alternate representation
396
            return 2;
397
        }
398
        //4 does not exist and should not happen
399
        return -1;
400
    }
401

    
402
    private String normalizeTaxonStatusCache(ResultSet srcRS) throws SQLException {
403
        Integer status = normalizeTaxonStatusFk(srcRS);
404
        if (status == 1){
405
            return "accepted";
406
        }else if (status == 2){
407
            return "synonym";
408
        }else if (status == 4){
409
            return "pro parte synonym";
410
        }else if (status == 7){
411
            return "unaccepted";
412
        }else{
413
            return "xxx - not yet handled";
414
        }
415
    }
416

    
417
    private boolean testTreeIndex(ResultSet destRS, String childIndexAttr, String parentIndexAttr, String id) throws SQLException {
418
        boolean result;
419
        int taxonStatusFk = destRS.getInt("TaxonStatusFk");
420
        String parentTaxonId = destRS.getString("parentTaxonFk");
421
        int rankFk = destRS.getInt("RankFk");
422
        if (taxonStatusFk == 2 || taxonStatusFk == 4 || rankFk <= 10){  //synonym; pro parte syn; kingdom and higher
423
            result = isNull(childIndexAttr, destRS, id);
424
        }else{
425
            String childIndex = destRS.getString(childIndexAttr);
426
            String parentIndex = destRS.getString(parentIndexAttr);
427
            parentIndex = parentIndex == null? "#": parentIndex;
428
            result = equals("Tree index", childIndex, parentIndex + parentTaxonId + "#", id);
429
        }
430
        return result;
431
    }
432

    
433
    boolean namePartsFirst = true;
434
    private boolean compareNameParts(ResultSet srcRS, ResultSet destRS, String id) throws SQLException {
435
        if (namePartsFirst){
436
            logger.warn("Validation of name parts not fully implemented (difficult). Currently validated via fullname");
437
            namePartsFirst = false;
438
        }
439
        int rankFk = srcRS.getInt("tu_rank");
440
        String genusOrUninomial = null;
441
        String infraGenericEpithet = null;
442
        String specificEpithet = null;
443
        String infraSpecificEpithet = null;
444
        if (rankFk <= 180){
445
            genusOrUninomial = srcRS.getString("tu_name");
446
        }else if (rankFk == 190){
447
            genusOrUninomial = srcRS.getString("pt_name");
448
            infraGenericEpithet =  srcRS.getString("tu_name");
449
            //TODO compareNameParts does not work this way
450
//        }else if (rankFk == 220){
451
//            genusOrUninomial = destRS.getString("p_GenusOrUninomial");
452
//            infraGenericEpithet = destRS.getString("p_InfraGenericEpithet");
453
//            specificEpithet = srcRS.getString("tu_name");
454
        }else{
455
            //TODO exception (compare name parts)
456
            return false;
457
        }
458
        boolean result = testEpis(destRS, genusOrUninomial, infraGenericEpithet,
459
                specificEpithet, infraSpecificEpithet, id);
460
        return result;
461
    }
462

    
463
    private boolean testEpis(ResultSet destRS, String genusOrUninomial, String infraGenericEpithet, String specificEpithet,
464
            String infraSpecificEpithet, String id) throws SQLException {
465
        boolean result = equals("Taxon genusOrUninomial", genusOrUninomial, destRS.getString("GenusOrUninomial"), id) ;
466
        result &= equals("Taxon infraGenericEpithet", infraGenericEpithet, destRS.getString("InfraGenericEpithet"), id) ;
467
        result &= equals("Taxon specificEpithet", specificEpithet, destRS.getString("SpecificEpithet"), id) ;
468
        result &= equals("Taxon infraSpecificEpithet", infraSpecificEpithet, destRS.getString("InfraSpecificEpithet"), id) ;
469
        return result;
470
    }
471

    
472
    private String normalizeRank(String string, ResultSet srcRS, String id) throws SQLException {
473
        String result = string
474
                .replace("Subforma", "Subform")
475
                .replace("Forma", "Form");
476
        int kingdomFk = Integer.valueOf(getSourceKingdomFk(srcRS, id));
477
        if (kingdomFk == 3 || kingdomFk == 4){
478
            result = result.replace("Subphylum", "Subdivision");
479
            result = result.replace("Phylum", "Division");
480
        }
481
        return result;
482
    }
483

    
484
    //see also ErmsTaxonImport.getExpectedTitleCache()
485
    private String srcFullName(ResultSet srcRs) throws SQLException {
486
        String result = null;
487
        String epi = srcRs.getString("tu_name");
488
        String display = srcRs.getString("tu_displayname");
489
        String sp = srcRs.getString("tu_sp");
490
        if (display.indexOf(epi) != display.lastIndexOf(epi) && !sp.startsWith("#2#")){ //autonym, !animal
491
            String authority = srcRs.getString("tu_authority");
492
            result = srcRs.getString("tu_displayname").replaceFirst(epi+" ", CdmUtils.concat(" ", epi, authority)+" ");
493
        }else{
494
            result = CdmUtils.concat(" ", srcRs.getString("tu_displayname"), srcRs.getString("tu_authority"));
495
        }
496
        return result;
497
    }
498

    
499
    private String srcDisplayName(ResultSet srcRs) throws SQLException {
500
        String result = null;
501
        String epi = srcRs.getString("tu_name");
502
        epi = " a" + epi;
503
        String display = "<i>"+srcRs.getString("tu_displayname")+"</i>";
504
        display = display.replace(" var. ", "</i> var. <i>").replace(" f. ", "</i> f. <i>");
505
        String sp = srcRs.getString("tu_sp");
506
        if (display.indexOf(epi) != display.lastIndexOf(epi) && !sp.startsWith("#2#")){ //homonym, animal
507
            result = display.replaceFirst(epi+" ", CdmUtils.concat(" ", " "+epi, srcRs.getString("tu_authority")))+" ";
508
        }else{
509
            result = CdmUtils.concat(" ", display, srcRs.getString("tu_authority"));
510
        }
511
        return result;
512
    }
513

    
514
    String lastLastActionId = "-1";
515
    private boolean testLastAction(ResultSet srcRsLastAction, ResultSet destRs, String id, String table) throws SQLException {
516
        try {
517
            boolean success = true;
518
            String srcId = null;
519
            while (srcRsLastAction.next()){
520
                srcId = String.valueOf(srcRsLastAction.getInt("id"));
521
                if (!lastLastActionId.equals(srcId)){
522
                    lastLastActionId = srcId;
523
                    break;
524
                }
525
            }
526
            if(!id.equals(srcId)){
527
                logger.warn("Last Action SourceIDs are not equal: id: " +id + ", la-id: " + srcId);
528
            }
529
            String destStr = destRs.getString("LastAction");
530
            success &= equals(table + " SpeciesExpertName", srcRsLastAction.getString("ExpertName"), destRs.getString("SpeciesExpertName"), id);  //mapping ExpertName => SpeciesExpertName according to SQL script
531
            success &= equals(table + " Last Action", srcRsLastAction.getString("action_name"), destStr == null? null : destStr, id);
532
            success &= equals(table + " Last Action Date", srcRsLastAction.getTimestamp("sessiondate"), destRs.getTimestamp("LastActionDate"), id);
533

    
534
            return success;
535
        } catch (Exception e) {
536
            e.printStackTrace();
537
            throw e;
538
        }
539
    }
540

    
541
    private boolean compareKingdom(String messageStart, ResultSet srcRS, ResultSet destRS, String id) throws SQLException {
542
        String srcKingdom = getSourceKingdomFk(srcRS, id);
543
        Integer intDest = nullSafeInt(destRS, "KingdomFk");
544
        if (intDest == null){
545
            logger.warn(id +": " + messageStart + " must never be null for destination. Biota needs to be 0, all the rest needs to have >0 int value.");
546
            return false;
547
        }else{
548
            return equals(messageStart, srcKingdom, String.valueOf(intDest), id);
549
        }
550
    }
551

    
552
    private String getSourceKingdomFk(ResultSet srcRS, String id) throws SQLException {
553
        String strSrc = srcRS.getString("acc_sp");
554
        if (strSrc == null){
555
            strSrc = srcRS.getString("tu_sp");
556
        }
557
        if (strSrc == null){
558
            if ("1".equals(id)){
559
                strSrc = "0";  //Biota
560
            }else if ("147415".equals(id)){
561
                strSrc = "6";  //Monera is synonym of Bacteria
562
            }else{
563
                strSrc = id;
564
            }
565
        }else{
566
            strSrc = strSrc.substring(1);
567
            strSrc = strSrc.substring(0, strSrc.indexOf("#"));
568
        }
569
        return strSrc;
570
    }
571

    
572
    private boolean testSingleTaxonRelations(int n) throws SQLException {
573
        boolean success = true;
574
        ResultSet srcRS = source.getResultSet(""
575
                + " SELECT t.* "
576
                + " FROM tu t "
577
                + " WHERE t.id "+ moneraFilter + " AND tu_accfinal <> id "
578
                + " ORDER BY CAST(t.id as nvarchar(20)) ");
579
        ResultSet destRS = destination.getResultSet("SELECT rel.*, t1.IdInSource t1Id, t2.IdInSource t2Id "
580
                + " FROM RelTaxon rel "
581
                + "    LEFT JOIN Taxon t1 ON t1.TaxonId = rel.TaxonFk1 "
582
                + "    LEFT JOIN Taxon t2 ON t2.TaxonId = rel.TaxonFk2 "
583
                + " WHERE t1."+origErms+" AND t2." + origErms
584
                + " ORDER BY t1.IdInSource");
585
        int i = 0;
586
        while (srcRS.next() && destRS.next()){
587
            success &= testSingleTaxonRelation(srcRS, destRS);
588
            i++;
589
        }
590
        success &= equals("Taxon relation count for single compare", n, i, String.valueOf(-1));
591
        return success;
592
    }
593

    
594
    private boolean testSingleTaxonRelation(ResultSet srcRS, ResultSet destRS) throws SQLException {
595
        String id = String.valueOf(srcRS.getInt("id"));
596
        boolean success = equals("Taxon relation taxon1", "tu_id: " + srcRS.getInt("id"), destRS.getString("t1Id"), id);
597
        success &= equals("Taxon relation taxon2", "tu_id: " + srcRS.getInt("tu_accfinal"), destRS.getString("t2Id"), id);
598
        success &= equals("Taxon relation qualifier fk", PesiTransformer.IS_SYNONYM_OF, destRS.getInt("RelTaxonQualifierFk"), id);
599
        success &= equals("Taxon relation qualifier cache", "is synonym of", destRS.getString("RelQualifierCache"), id);
600
        success &= isNull("notes", destRS, id);
601
        //complete if no further relations need to be added
602
        return success;
603
    }
604

    
605
    private boolean testSingleAdditionalTaxonSources(int n) throws SQLException {
606
        boolean success = true;
607
        ResultSet srcRs = source.getResultSet("SELECT CAST(tu.id as nvarchar(20)) tuId, MN.*, s.*, su.sourceuse_name "
608
                + " FROM tu_sources MN INNER JOIN tu ON MN.tu_id = tu.id "
609
                + "    LEFT JOIN sources s ON s.id = MN.source_id "
610
                + "    LEFT JOIN sourceuses su ON MN.sourceuse_id = su.sourceuse_id "
611
                + " WHERE MN.tu_id  " + moneraFilter
612
                + " ORDER BY CAST(tu.id as nvarchar(20)), MN.sourceuse_id, s.id ");  //, no.note (not possible because ntext
613
        ResultSet destRs = destination.getResultSet("SELECT t.IdInSource, ats.*, s.*, su.* "
614
                + " FROM AdditionalTaxonSource ats INNER JOIN Taxon t ON t.TaxonId = ats.TaxonFk "
615
                + "    INNER JOIN Source s ON s.SourceId = ats.SourceFk "
616
                + "    LEFT JOIN SourceUse su ON su.SourceUseId = ats.SourceUseFk "
617
                + " WHERE t."+origErms
618
                + " ORDER BY t.IdInSource, su.SourceUseId, s.RefIdInSource ");
619
        int count = 0;
620
        while (srcRs.next() && destRs.next()){
621
            success &= testSingleAdditionalTaxonSource(srcRs, destRs);
622
            count++;
623
        }
624
        success &= equals("Notes count differs", n, count, "-1");
625
        return success;
626
    }
627

    
628
    private boolean testSingleAdditionalTaxonSource(ResultSet srcRs, ResultSet destRs) throws SQLException {
629
        String id = String.valueOf(srcRs.getInt("tuId") + "-" + srcRs.getString("sourceuse_name"));
630
        boolean success = equals("Additional taxon source taxonID ", "tu_id: " + String.valueOf(srcRs.getInt("tuId")), destRs.getString("IdInSource"), id);
631
        success &= equals("Additional taxon source fk ", srcRs.getString("source_id"), destRs.getString("RefIdInSource"), id);  //currently we use the same id in ERMS and PESI
632
        success &= equals("Additional taxon source use fk ", srcRs.getString("sourceuse_id"), destRs.getString("SourceUseFk"), id);
633
        success &= equals("Additional taxon source use cache ", srcRs.getString("sourceuse_name"), destRs.getString("SourceUseCache"), id);
634
        //TODO some records are still truncated ~ >820 characters
635
        success &= equals("Additional taxon source name cache ", srcRs.getString("source_name"), destRs.getString("SourceNameCache"), id);
636
        success &= equals("Additional taxon source detail ", srcRs.getString("pagenr"), destRs.getString("SourceDetail"), id);
637
        //Complete
638
        return success;
639
    }
640

    
641
    private boolean testSingleNotes(int n) throws SQLException {
642
        boolean success = true;
643
        ResultSet srcRs = source.getResultSet("SELECT CAST(tu.id as nvarchar(20)) tuId, no.*, l.LanName "
644
                + " FROM notes no INNER JOIN tu ON no.tu_id = tu.id "
645
                + "    LEFT JOIN languages l ON l.LanID = no.lan_id "
646
                + " ORDER BY CAST(tu.id as nvarchar(20)), no.type, no.noteSortable ");  //, no.note (not possible because ntext
647
        ResultSet destRs = destination.getResultSet("SELECT t.IdInSource, no.*, cat.NoteCategory, l.Language "
648
                + " FROM Note no INNER JOIN Taxon t ON t.TaxonId = no.TaxonFk "
649
                + "    LEFT JOIN NoteCategory cat ON cat.NoteCategoryId = no.NoteCategoryFk "
650
                + "    LEFT JOIN Language l ON l.LanguageId = no.LanguageFk "
651
                + " WHERE t." + origErms
652
                + "      AND NOT (NoteCategoryFk = 4 AND no.LastAction IS NULL) AND NOT NoteCategoryFk IN (22,23,24) "
653
                + " ORDER BY t.IdInSource, no.NoteCategoryCache, Note_1  ");
654
        int count = 0;
655
        ResultSet srcRsLastAction = source.getResultSet(""
656
                + " SELECT no.id, s.sessiondate, a.action_name, s.ExpertName "
657
                + " FROM notes no "
658
                + "   INNER JOIN tu ON tu.id = no.tu_id "
659
                + "   LEFT JOIN languages l ON l.LanID = no.lan_id"
660
                + "   LEFT JOIN notes_sessions MN ON no.id = MN.note_id "
661
                + "   LEFT JOIN actions a ON a.id = MN.action_id "
662
                + "   LEFT JOIN sessions s ON s.id = MN.session_id  "
663
                + " ORDER BY CAST(tu.id as nvarchar(20)), no.type, no.noteSortable, s.sessiondate DESC, a.id DESC ");
664

    
665
        while (srcRs.next() && destRs.next()){
666
            success &= testSingleNote(srcRs, destRs);
667
            success &= testLastAction(srcRsLastAction, destRs, String.valueOf(srcRs.getInt("id")), "Note");
668
            count++;
669
        }
670
        success &= equals("Notes count differs", n, count, "-1");
671
        return success;
672
    }
673

    
674
    private boolean testSingleNote(ResultSet srcRs, ResultSet destRs) throws SQLException {
675
        String id = String.valueOf(srcRs.getInt("tuId") + "-" + srcRs.getString("type"));
676
        boolean success = equals("Note taxonID ", "tu_id: " + String.valueOf(srcRs.getInt("tuId")), destRs.getString("IdInSource"), id);
677
        success &= equals("Note Note_1 ", srcRs.getString("note"), destRs.getString("Note_1"), id);
678
        success &= isNull("Note_2", destRs, id);
679
        success &= equals("Note category cache", normalizeNoteCatCache(srcRs.getString("type")), destRs.getString("NoteCategoryCache"), id);
680
        success &= equals("Note language ", srcRs.getString("LanName"), destRs.getString("Language"), id);
681
        success &= isNull("Region", destRs, id);
682
        success &= isNull("SpeciesExpertGUID", destRs, id);
683
        //SpeciesExpertName, LastAction, LastActionDate handled in separate method
684
        //complete
685
        return success;
686
    }
687

    
688
    private String normalizeNoteCatCache(String string) {
689
        return StringUtils.capitalize(string)
690
                .replace("Original Combination", "Original combination")
691
                .replace("Taxonomic remark", "Taxonomic Remark");
692
    }
693

    
694
    private boolean testSingleDistributions(int n) throws SQLException {
695
        boolean success = true;
696
        ResultSet srcRs = source.getResultSet("SELECT CAST(ISNULL(tu.tu_accfinal, tu.id) as nvarchar(20)) tuId,"
697
                + " gu.gazetteer_id, dr.*, gu.id guId, gu.gu_name "
698
                + " FROM dr INNER JOIN tu ON dr.tu_id = tu.id "
699
                + "    LEFT JOIN gu ON gu.id = dr.gu_id "
700
                + " ORDER BY CAST(ISNULL(tu.tu_accfinal, tu.id) as nvarchar(20)), gu.gazetteer_id, gu.gu_name, dr.noteSortable ");  //, dr.note (not possible because ntext
701
        ResultSet destRs = destination.getResultSet("SELECT t.IdInSource, a.AreaERMSGazetteerId, oc.*, a.AreaName "
702
                + " FROM Occurrence oc INNER JOIN Taxon t ON t.TaxonId = oc.TaxonFk "
703
                + "    LEFT JOIN Area a ON a.AreaId = oc.AreaFk "
704
                + " WHERE t." + origErms
705
                + " ORDER BY t.IdInSource, a.AreaERMSGazetteerId, a.AreaName, oc.Notes ");
706
        ResultSet srcRsLastAction = source.getResultSet(""
707
                + " SELECT dr.id, s.sessiondate, a.action_name, s.ExpertName "
708
                + " FROM dr "
709
                + "   INNER JOIN tu ON tu.id = dr.tu_id "
710
                + "   LEFT JOIN gu ON gu.id = dr.gu_id "
711
                + "   LEFT JOIN dr_sessions MN ON dr.id = MN.dr_id "
712
                + "   LEFT JOIN actions a ON a.id = MN.action_id "
713
                + "   LEFT JOIN sessions s ON s.id = MN.session_id  "
714
                + " ORDER BY CAST(tu.id as nvarchar(20)), gu.gazetteer_id, gu.gu_name, s.sessiondate DESC, a.id DESC ");
715
        int count = 0;
716
        while (srcRs.next() && destRs.next()){
717
            success &= testSingleDistribution(srcRs, destRs);
718
            //there are >1000 duplicates in dr, therefore this creates lots of warnings
719
            success &= testLastAction(srcRsLastAction, destRs, String.valueOf(srcRs.getInt("id")), "Distribution");
720
            count++;
721
        }
722
        success &= equals("Distribution count differs", n, count, "-1");
723
        return success;
724
    }
725

    
726
    private boolean testSingleDistribution(ResultSet srcRs, ResultSet destRs) throws SQLException {
727
        String id = String.valueOf(srcRs.getInt("tuId") + "-" + srcRs.getString("gu_name"));
728
        boolean success = equals("Distribution taxonID ", "tu_id: " + String.valueOf(srcRs.getInt("tuId")), destRs.getString("IdInSource"), id);
729
        success &= equals("Distribution gazetteer_id ", srcRs.getString("gazetteer_id"), destRs.getString("AreaERMSGazetteerId"), id);
730
        success &= equals("Distribution area name ", srcRs.getString("gu_name"), destRs.getString("AreaName"), id);
731
        success &= equals("Distribution area name cache", srcRs.getString("gu_name"), destRs.getString("AreaNameCache"), id);
732
        success &= equals("Distribution OccurrenceStatusFk", 1, destRs.getInt("OccurrenceStatusFk"), id);
733
        success &= equals("Distribution OccurrenceStatusCache", "Present", destRs.getString("OccurrenceStatusCache"), id);
734
        //TODO see comments
735
        success &= isNull("SourceFk", destRs, id);  //sources should be moved to extra table only, check with script and PESI 2014 (=> has values for ERMS)
736
        success &= isNull("SourceCache", destRs, id);  //sources should be moved to extra table, check with script and PESI 2014 (=> has values for ERMS)
737
        success &= equals("Distribution notes ", srcRs.getString("note"), destRs.getString("Notes"), id);
738
        success &= isNull("SpeciesExpertGUID", destRs, id);  //SpeciesExpertGUID does not exist in ERMS
739
        //SpeciesExpertName,LastAction,LastActionDate handled in separate method
740
        return success;
741
    }
742

    
743
    private boolean testSingleCommonNames(int n) throws SQLException {
744
        boolean success = true;
745
        ResultSet srcRs = source.getResultSet("SELECT v.*, ISNULL([639_3],[639_2]) iso, l.LanName, tu.id tuId "
746
                + " FROM vernaculars v LEFT JOIN tu ON v.tu_id = tu.id LEFT JOIN languages l ON l.LanID = v.lan_id "
747
                + " ORDER BY CAST(tu.id as nvarchar(20)), ISNULL([639_3],[639_2]), v.vername, v.id ");
748
        ResultSet destRs = destination.getResultSet("SELECT cn.*, t.IdInSource, l.ISO639_2, l.ISO639_3 "
749
                + " FROM CommonName cn INNER JOIN Taxon t ON t.TaxonId = cn.TaxonFk LEFT JOIN Language l ON l.LanguageId = cn.LanguageFk "
750
                + " WHERE t." + origErms
751
                + " ORDER BY t.IdInSource, ISNULL("+preferredISO639+", "+alternativeISO639+"), cn.CommonName, cn.LastActionDate ");  //sorting also lastActionDate results in a minimum of exact duplicate problems
752
        ResultSet srcRsLastAction = source.getResultSet(""
753
                + " SELECT v.id, s.sessiondate, a.action_name, s.ExpertName "
754
                + " FROM vernaculars v "
755
                + "   INNER JOIN tu ON tu.id = v.tu_id "
756
                + "   LEFT JOIN languages l ON l.LanID = v.lan_id"
757
                + "   LEFT JOIN vernaculars_sessions MN ON v.id = MN.vernacular_id "
758
                + "   LEFT JOIN actions a ON a.id = MN.action_id "
759
                + "   LEFT JOIN sessions s ON s.id = MN.session_id  "
760
                + " ORDER BY CAST(tu.id as nvarchar(20)), ISNULL([639_3],[639_2]), v.vername, v.id, s.sessiondate DESC, a.id DESC ");
761
        int count = 0;
762
        while (srcRs.next() && destRs.next()){
763
            success &= testSingleCommonName(srcRs, destRs);
764
            success &= testLastAction(srcRsLastAction, destRs, String.valueOf(srcRs.getInt("id")), "CommonName");
765
            count++;
766
        }
767
        success &= equals("Common name count differs", n, count, "-1");
768
        return success;
769
    }
770

    
771
    boolean prefer639_3 = true;
772
    String preferredISO639 = prefer639_3? "ISO639_3":"ISO639_2";
773
    String alternativeISO639 = prefer639_3? "ISO639_2":"ISO639_3";
774

    
775
    private boolean testSingleCommonName(ResultSet srcRs, ResultSet destRs) throws SQLException {
776
        String id = String.valueOf(srcRs.getInt("tuId") + "-" + srcRs.getString("lan_id"));
777
        boolean success = equals("Common name taxonID ", "tu_id: " + String.valueOf(srcRs.getInt("tuId")), destRs.getString("IdInSource"), id);
778
        success &= equals("CommonName name ", srcRs.getString("vername"), destRs.getString("CommonName"), id);
779
        success &= equals("Common name languageFk ", srcRs.getString("iso"), getLanguageIso(destRs), id);
780
        success = equals("CommonName LanguageCache ", normalizeLang(srcRs.getString("LanName")), destRs.getString("LanguageCache"), id);
781
        //TODO needed? success = equals("CommonName language code ", srcRs.getString("lan_id"), destRs.getString("LanguageFk"), id);
782
        success &= isNull("Region", destRs, id);  //region does not seem to exist in ERMS
783
        //TODO see comments
784
//        success &= isNull("SourceFk", destRs);  //sources should be moved to extra table, check with PESI 2014
785
//        success &= isNull("SourceNameCache", destRs);  //sources should be moved to extra table, check with PESI 2014
786
        success &= isNull("SpeciesExpertGUID", destRs, id);  //SpeciesExpertGUID does not exist in ERMS
787
        //SpeciesExpertName,LastAction,LastActionDate handled in separate method
788
        //complete
789
        return success;
790
    }
791

    
792
    private String normalizeLang(String string) {
793
        if ("Spanish".equals(string)){
794
            return "Spanish, Castillian";
795
        }else if ("Modern Greek (1453-)".equals(string)){
796
            return "Greek";
797
        }else if ("Malay (individual language)".equals(string)){
798
            return "Malay";
799
        }else if ("Swahili (individual language)".equals(string)){
800
            return "Swahili";
801
        }
802

    
803
        return string;
804
    }
805

    
806
    private String getLanguageIso(ResultSet destRs) throws SQLException {
807
        String result = destRs.getString(preferredISO639);
808
        if (result == null){
809
            result = destRs.getString(alternativeISO639);
810
        }
811
        return result;
812
    }
813

    
814
    private boolean testSingleReferences() throws SQLException {
815
        boolean success = true;
816
        ResultSet srcRS = source.getResultSet("SELECT s.* FROM sources s ORDER BY s.id ");
817
        ResultSet destRS = destination.getResultSet("SELECT s.* FROM Source s "
818
                + " WHERE s." + origErms
819
                + " ORDER BY s.RefIdInSource ");  // +1 for the source reference "erms" but this has no OriginalDB
820
        while (srcRS.next() && destRS.next()){
821
            success &= testSingleReference(srcRS, destRS);
822
        }
823
        return success;
824
    }
825

    
826
    private boolean testSingleReference(ResultSet srcRS, ResultSet destRS) throws SQLException {
827
        String id = String.valueOf(srcRS.getInt("id"));
828
        boolean success = equals("Reference ID ", srcRS.getInt("id"), destRS.getInt("RefIdInSource"), id);
829
        success &= equals("Reference IMIS_id ", srcRS.getString("imis_id"), destRS.getString("IMIS_Id"), id);
830
        success &= equals("Reference SourceCategoryFk ", convertSourceTypeFk(srcRS.getString("source_type")), destRS.getInt("SourceCategoryFk"), id);
831
        success &= equals("Reference SourceCategoryCache ", convertSourceTypeCache(srcRS.getString("source_type")), destRS.getString("SourceCategoryCache"), id);
832
        success &= equals("Reference name ", srcRS.getString("source_name"), destRS.getString("Name"), id);
833
        success &= equals("Reference abstract ", srcRS.getString("source_abstract"), destRS.getString("Abstract"), id);
834
        success &= equals("Reference title ", srcRS.getString("source_title"), destRS.getString("Title"), id);
835
        success &= equals("Reference author string ", srcRS.getString("source_author"), destRS.getString("AuthorString"), id);
836
        success &= equals("Reference year ", normalizeYear(srcRS.getString("source_year")), destRS.getString("RefYear"), id);
837
        success &= isNull("NomRefCache", destRS, id);  //for ERMS no other value was found in 2014 value
838
        success &= equals("Reference link ", srcRS.getString("source_link"), destRS.getString("Link"), id);
839
        success &= equals("Reference note ", srcRS.getString("source_note"), destRS.getString("Notes"), id);
840
        //complete
841
        return success;
842
    }
843

    
844
    private Integer convertSourceTypeFk(String sourceType) {
845
        if (sourceType == null){
846
            return null;
847
        }else if ("d".equals(sourceType)){
848
            return 4;
849
        }else if ("e".equals(sourceType)){
850
            return 5;
851
        }else if ("p".equals(sourceType)){
852
            return 11;
853
        }
854
        return null;
855
    }
856
    private String convertSourceTypeCache(String sourceType) {
857
        if (sourceType == null){
858
            return null;
859
        }else if ("d".equals(sourceType)){
860
            return "database";
861
        }else if ("e".equals(sourceType)){
862
            return "informal reference";
863
        }else if ("p".equals(sourceType)){
864
            return "publication";
865
        }
866
        return null;
867
    }
868

    
869
    private boolean testReferenceCount() {
870
        int countSrc = source.getUniqueInteger("SELECT count(*) FROM sources ");
871
        int countDest = destination.getUniqueInteger("SELECT count(*) FROM Source s WHERE s."+ origErms);  // +1 for the source reference "erms" but this has no OriginalDB
872
        boolean success = equals("Reference count ", countSrc, countDest, "-1");
873
        return success;
874
    }
875

    
876
    //NOTE: there could be better parsing of source_year during import, this may also need better normalizing in the database
877
    private String normalizeYear(String yearStr) {
878
        if (StringUtils.isBlank(yearStr)){
879
            return yearStr;
880
        }
881
        yearStr = yearStr.trim();
882
        if (yearStr.matches("\\d{4}-\\d{2}")){
883
            yearStr = yearStr.substring(0, 5)+yearStr.substring(0, 2)+yearStr.substring(5);
884
        }
885
        if (yearStr.equals("20 Mar 1891")){
886
            yearStr = "20.3.1891";
887
        }
888
        if (yearStr.equals("July 1900")){
889
            yearStr = "7.1900";
890
        }
891
        return yearStr;
892
    }
893

    
894
    private boolean isNull(String attrName, ResultSet destRS, String id) throws SQLException {
895
        Object value = destRS.getObject(attrName);
896
        if (value != null){
897
            String message = attrName + " was expected to be null but was: " + value.toString() + "; id = " + id;
898
            logger.warn(message);
899
            return false;
900
        }else{
901
            logger.info(attrName + " was null as expected; id = " + id);
902
            return true;
903
        }
904
    }
905

    
906
    private boolean equals(String messageStart, Timestamp srcDate, Timestamp destDate, String id) {
907
        if (!CdmUtils.nullSafeEqual(srcDate, destDate)){
908
            String message = id + ": " + messageStart + " must be equal, but was not.\n Source: "+  srcDate + "; Destination: " + destDate;
909
            logger.warn(message);
910
            return false;
911
        }else{
912
            logger.info(messageStart + " were equal: " + srcDate);
913
            return true;
914
        }
915
    }
916

    
917
    private boolean equals(String messageStart, Integer nSrc, Integer nDest, String id) {
918
        String strId = id.equals("-1")? "": (id+ ": ");
919
        if (!CdmUtils.nullSafeEqual(nSrc,nDest)){
920
            String message = strId+ messageStart + " must be equal, but was not.\n Source: "+  nSrc + "; Destination: " + nDest;
921
            logger.warn(message);
922
            return false;
923
        }else{
924
            logger.info(strId + messageStart + " were equal: " + nSrc);
925
            return true;
926
        }
927
    }
928

    
929
    private boolean equals(String messageStart, String strSrc, String strDest, String id) {
930
        if (StringUtils.isBlank(strSrc)){
931
            strSrc = null;
932
        }else{
933
            strSrc = strSrc.trim();
934
        }
935
        //we do not trim strDest here because this should be done during import already. If not it should be shown here
936
        if (!CdmUtils.nullSafeEqual(strSrc, strDest)){
937
            int index = CdmUtils.diffIndex(strSrc, strDest);
938
            String message = id+ ": " + messageStart + " must be equal, but was not at "+index+".\n  Source:      "+  strSrc + "\n  Destination: " + strDest;
939
            logger.warn(message);
940
            return false;
941
        }else{
942
            logger.info(id+ ": " + messageStart + " were equal: " + strSrc);
943
            return true;
944
        }
945
    }
946

    
947
    protected Integer nullSafeInt(ResultSet rs, String columnName) throws SQLException {
948
        Object intObject = rs.getObject(columnName);
949
        if (intObject == null){
950
            return null;
951
        }else{
952
            return Integer.valueOf(intObject.toString());
953
        }
954
    }
955

    
956
//** ************* MAIN ********************************************/
957

    
958

    
959

    
960
    public static void main(String[] args){
961
        PesiErmsValidator validator = new PesiErmsValidator();
962
        validator.invoke(defaultSource, defaultDestination);
963
        System.exit(0);
964
    }
965
}
(1-1/2)