Project

General

Profile

Download (47.7 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_2018();
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!,  Implement single compare tests
54
//            success &= testCommonNames();  //source(s) discuss VLIZ, exact duplicates (except for sources), Anus(Korur)
55
//            success &= testDistributions();  //>1000 duplicates in "dr", sources (OccurrenceSource table), area spellings(Baelt Sea), 1 long note
56
//              success &= testNotes();  //ecology & link notes test (only count tested), sources untested (NoteSource table), few duplicates,
57
            success &= testAdditionalTaxonSources();  //ready
58
        } catch (Exception e) {
59
            e.printStackTrace();
60
            success = false;
61
        }
62
        //TBC
63
        System.out.println("end validation " + (success? "":"NOT ") + "successful.");
64
    }
65

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

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

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

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

    
102
    int countSynonyms;
103
    int countIncludedIns;
104
    private boolean testTaxonRelations() {
105
        System.out.println("Start validate taxon relations");
106
        boolean success = testSynonymRelations();
107
        success &= testIncludedInRelations();
108
        success &= testTotalRelations();
109
        success &= testNameRelations();
110
        return success;
111
    }
112

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

    
126
    private boolean testSynonymRelations() {
127

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

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

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

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

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

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

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

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

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

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

    
224
        return result;
225
    }
226

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

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

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

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

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

    
259
         return result;
260
     }
261

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

    
305

    
306
    private boolean testSingleTaxon(ResultSet srcRS, ResultSet destRS) throws SQLException {
307
        String id = String.valueOf(srcRS.getInt("id"));
308
        boolean success = equals("Taxon ID", "tu_id: " + srcRS.getInt("id"), destRS.getString("IdInSource"), id);
309
        success &= equals("Taxon source", "ERMS export for PESI", destRS.getString("sourceName"), id);
310
//TODO some
311
        success &= compareKingdom("Taxon kingdom", srcRS, destRS, id);
312
        success &= equals("Taxon rank fk", srcRS.getString("tu_rank"), destRS.getString("RankFk"), id);
313
        success &= equals("Taxon rank cache", normalizeRank(srcRS.getString("rank_name"), srcRS, id), destRS.getString("Rank"), id);
314
        success &= compareNameParts(srcRS, destRS, id);
315

    
316
        success &= equals("Taxon websearchname", srcRS.getString("tu_displayname"), destRS.getString("WebSearchName"), id);
317
//        success &= equals("Taxon WebShowName", srcRS.getString("tu_displayname"), destRS.getString("WebShowName"), id);
318
        success &= equals("Taxon authority", srcRS.getString("tu_authority"), destRS.getString("AuthorString"), id);
319
//        success &= equals("Taxon FullName", srcFullName(srcRS), destRS.getString("FullName"), id);
320
        success &= isNull("NomRefString", destRS);
321
//        success &= equals("Taxon DisplayName", srcDisplayName(srcRS), destRS.getString("DisplayName"), id);  //according to SQL script same as FullName, no nom.ref. information attached
322

    
323
//TODO        success &= equals("Taxon NameStatusFk", toNameStatus(nullSafeInt(srcRS, "tu_status")),nullSafeInt( destRS,"NameStatusFk"), id);
324
//TODO        success &= equals("Taxon NameStatusCache", srcRS.getString("status_name"), destRS.getString("NameStatusCache"), id);
325

    
326
//TODO        success &= equals("Taxon TaxonStatusFk", nullSafeInt(srcRS, "tu_status"),nullSafeInt( destRS,"TaxonStatusFk"), id);
327
//TODO        success &= equals("Taxon TaxonStatusCache", srcRS.getString("status_name"), destRS.getString("TaxonStatusCache"), id);
328

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

    
350
    boolean namePartsFirst = true;
351
    private boolean compareNameParts(ResultSet srcRS, ResultSet destRS, String id) throws SQLException {
352
        if (namePartsFirst){
353
            logger.warn("Validation of name parts not fully implemented (difficult). Currently validated via fullname");
354
            namePartsFirst = false;
355
        }
356
        int rankFk = srcRS.getInt("tu_rank");
357
        String genusOrUninomial = null;
358
        String infraGenericEpithet = null;
359
        String specificEpithet = null;
360
        String infraSpecificEpithet = null;
361
        if (rankFk <= 180){
362
            genusOrUninomial = srcRS.getString("tu_name");
363
        }else if (rankFk == 190){
364
            genusOrUninomial = srcRS.getString("tu1_name");
365
            infraGenericEpithet =  srcRS.getString("tu_name");
366
            //TODO does not work this way
367
//        }else if (rankFk == 220){
368
//            genusOrUninomial = destRS.getString("p_GenusOrUninomial");
369
//            infraGenericEpithet = destRS.getString("p_InfraGenericEpithet");
370
//            specificEpithet = srcRS.getString("tu_name");
371
        }else{
372
            //TODO exception
373
            return false;
374
        }
375
        boolean result = testEpis(destRS, genusOrUninomial, infraGenericEpithet,
376
                specificEpithet, infraSpecificEpithet, id);
377
        return result;
378
    }
379

    
380
    private boolean testEpis(ResultSet destRS, String genusOrUninomial, String infraGenericEpithet, String specificEpithet,
381
            String infraSpecificEpithet, String id) throws SQLException {
382
        boolean result = equals("Taxon genusOrUninomial", genusOrUninomial, destRS.getString("GenusOrUninomial"), id) ;
383
        result &= equals("Taxon infraGenericEpithet", infraGenericEpithet, destRS.getString("InfraGenericEpithet"), id) ;
384
        result &= equals("Taxon specificEpithet", specificEpithet, destRS.getString("SpecificEpithet"), id) ;
385
        result &= equals("Taxon infraSpecificEpithet", infraSpecificEpithet, destRS.getString("InfraSpecificEpithet"), id) ;
386
        return result;
387
    }
388

    
389
    private String normalizeRank(String string, ResultSet srcRS, String id) throws SQLException {
390
        String result = string
391
                .replace("Subforma", "Subform")
392
                .replace("Forma", "Form");
393
        int kingdomFk = Integer.valueOf(getSourceKingdomFk(srcRS, id));
394
        if (kingdomFk == 3 || kingdomFk == 4){
395
            result = result.replace("Subphylum", "Subdivision");
396
            result = result.replace("Phylum", "Division");
397
        }
398
        return result;
399
    }
400

    
401
    //see also ErmsTaxonImport.getExpectedTitleCache()
402
    private String srcFullName(ResultSet srcRs) throws SQLException {
403
        String result = null;
404
        String epi = srcRs.getString("tu_name");
405
        epi = " a" + epi;
406
        String display = srcRs.getString("tu_displayname");
407
        String sp = srcRs.getString("tu_sp");
408
        if (display.indexOf(epi) != display.lastIndexOf(epi) && !sp.startsWith("#2#")){ //homonym, animal
409
            result = srcRs.getString("tu_displayname").replaceFirst(epi+" ", CdmUtils.concat(" ", " "+epi, srcRs.getString("tu_authority")))+" ";
410
        }else{
411
            result = CdmUtils.concat(" ", srcRs.getString("tu_displayname"), srcRs.getString("tu_authority"));
412
        }
413
        return result;
414
    }
415

    
416
    private String srcDisplayName(ResultSet srcRs) throws SQLException {
417
        String result = null;
418
        String epi = srcRs.getString("tu_name");
419
        epi = " a" + epi;
420
        String display = "<i>"+srcRs.getString("tu_displayname")+"</i>";
421
        display = display.replace(" var. ", "</i> var. <i>").replace(" f. ", "</i> f. <i>");
422
        String sp = srcRs.getString("tu_sp");
423
        if (display.indexOf(epi) != display.lastIndexOf(epi) && !sp.startsWith("#2#")){ //homonym, animal
424
            result = display.replaceFirst(epi+" ", CdmUtils.concat(" ", " "+epi, srcRs.getString("tu_authority")))+" ";
425
        }else{
426
            result = CdmUtils.concat(" ", display, srcRs.getString("tu_authority"));
427
        }
428
        return result;
429
    }
430

    
431
    String lastLastActionId = "-1";
432
    private boolean testLastAction(ResultSet srcRsLastAction, ResultSet destRs, String id, String table) throws SQLException {
433
        try {
434
            boolean success = true;
435
            String srcId = null;
436
            while (srcRsLastAction.next()){
437
                srcId = String.valueOf(srcRsLastAction.getInt("id"));
438
                if (!lastLastActionId.equals(srcId)){
439
                    lastLastActionId = srcId;
440
                    break;
441
                }
442
            }
443
            if(!id.equals(srcId)){
444
                logger.warn("Last Action SourceIDs are not equal: id: " +id + ", la-id: " + srcId);
445
            }
446
            String destStr = destRs.getString("LastAction");
447
            success &= equals(table + " SpeciesExpertName", srcRsLastAction.getString("ExpertName"), destRs.getString("SpeciesExpertName"), id);  //mapping ExpertName => SpeciesExpertName according to SQL script
448
            success &= equals(table + " Last Action", srcRsLastAction.getString("action_name"), destStr == null? null : destStr, id);
449
            success &= equals(table + " Last Action Date", srcRsLastAction.getTimestamp("sessiondate"), destRs.getTimestamp("LastActionDate"), id);
450

    
451
            return success;
452
        } catch (Exception e) {
453
            e.printStackTrace();
454
            throw e;
455
        }
456
    }
457

    
458
    private boolean compareKingdom(String messageStart, ResultSet srcRS, ResultSet destRS, String id) throws SQLException {
459
        String srcKingdom = getSourceKingdomFk(srcRS, id);
460
        Integer intDest = nullSafeInt(destRS, "KingdomFk");
461
        if (intDest == null){
462
            logger.warn(id +": " + messageStart + " must never be null for destination. Biota needs to be 0, all the rest needs to have >0 int value.");
463
            return false;
464
        }else{
465
            return equals(messageStart, srcKingdom, String.valueOf(intDest), id);
466
        }
467
    }
468

    
469
    private String getSourceKingdomFk(ResultSet srcRS, String id) throws SQLException {
470
        String strSrc = srcRS.getString("acc_sp");
471
        if (strSrc == null){
472
            strSrc = srcRS.getString("tu_sp");
473
        }
474
        if (strSrc == null){
475
            if ("1".equals(id)){
476
                strSrc = "0";  //Biota
477
            }else if ("147415".equals(id)){
478
                strSrc = "6";  //Monera is synonym of Bacteria
479
            }else{
480
                strSrc = id;
481
            }
482
        }else{
483
            strSrc = strSrc.substring(1);
484
            strSrc = strSrc.substring(0, strSrc.indexOf("#"));
485
        }
486
        return strSrc;
487
    }
488

    
489
    private boolean testSingleTaxonRelations(int n) throws SQLException {
490
        boolean success = true;
491
        ResultSet srcRS = source.getResultSet(""
492
                + " SELECT t.* "
493
                + " FROM tu t "
494
                + " WHERE t.id "+ moneraFilter + " AND tu_acctaxon <> id "
495
                + " ORDER BY CAST(t.id as nvarchar(20)) ");
496
        ResultSet destRS = destination.getResultSet("SELECT rel.*, t1.IdInSource t1Id, t2.IdInSource t2Id "
497
                + " FROM RelTaxon rel "
498
                + "    LEFT JOIN Taxon t1 ON t1.TaxonId = rel.TaxonFk1 "
499
                + "    LEFT JOIN Taxon t2 ON t2.TaxonId = rel.TaxonFk2 "
500
                + " WHERE t1."+origErms+" AND t2." + origErms
501
                + " ORDER BY t1.IdInSource");
502
        int i = 0;
503
        while (srcRS.next() && destRS.next()){
504
            success &= testSingleTaxonRelation(srcRS, destRS);
505
            i++;
506
        }
507
        success &= equals("Taxon relation count for single compare", n, i, String.valueOf(-1));
508
        return success;
509
    }
510

    
511
    private boolean testSingleTaxonRelation(ResultSet srcRS, ResultSet destRS) throws SQLException {
512
        String id = String.valueOf(srcRS.getInt("id"));
513
        boolean success = equals("Taxon relation taxon1", "tu_id: " + srcRS.getInt("id"), destRS.getString("t1Id"), id);
514
        success &= equals("Taxon relation taxon2", "tu_id: " + srcRS.getInt("tu_acctaxon"), destRS.getString("t2Id"), id);
515
        success &= equals("Taxon relation qualifier fk", PesiTransformer.IS_SYNONYM_OF, destRS.getInt("RelTaxonQualifierFk"), id);
516
        success &= equals("Taxon relation qualifier cache", "is synonym of", destRS.getString("RelQualifierCache"), id);
517
        //TODO enable after next import
518
//        success &= isNull("notes", destRS);
519
        //complete if no further relations need to added
520
        return success;
521
    }
522

    
523
    private boolean testSingleAdditionalTaxonSources(int n) throws SQLException {
524
        boolean success = true;
525
        ResultSet srcRs = source.getResultSet("SELECT CAST(tu.id as nvarchar(20)) tuId, MN.*, s.*, su.sourceuse_name "
526
                + " FROM tu_sources MN INNER JOIN tu ON MN.tu_id = tu.id "
527
                + "    LEFT JOIN sources s ON s.id = MN.source_id "
528
                + "    LEFT JOIN sourceuses su ON MN.sourceuse_id = su.sourceuse_id "
529
                + " WHERE MN.tu_id  " + moneraFilter
530
                + " ORDER BY CAST(tu.id as nvarchar(20)), MN.sourceuse_id, s.id ");  //, no.note (not possible because ntext
531
        ResultSet destRs = destination.getResultSet("SELECT t.IdInSource, ats.*, s.*, su.* "
532
                + " FROM AdditionalTaxonSource ats INNER JOIN Taxon t ON t.TaxonId = ats.TaxonFk "
533
                + "    INNER JOIN Source s ON s.SourceId = ats.SourceFk "
534
                + "    LEFT JOIN SourceUse su ON su.SourceUseId = ats.SourceUseFk "
535
                + " WHERE t."+origErms
536
                + " ORDER BY t.IdInSource, su.SourceUseId, s.RefIdInSource ");
537
        int count = 0;
538
        while (srcRs.next() && destRs.next()){
539
            success &= testSingleAdditionalTaxonSource(srcRs, destRs);
540
            count++;
541
        }
542
        success &= equals("Notes count differs", n, count, "-1");
543
        return success;
544
    }
545

    
546
    private boolean testSingleAdditionalTaxonSource(ResultSet srcRs, ResultSet destRs) throws SQLException {
547
        String id = String.valueOf(srcRs.getInt("tuId") + "-" + srcRs.getString("sourceuse_name"));
548
        boolean success = equals("Additional taxon source taxonID ", "tu_id: " + String.valueOf(srcRs.getInt("tuId")), destRs.getString("IdInSource"), id);
549
        success &= equals("Additional taxon source fk ", srcRs.getString("source_id"), destRs.getString("RefIdInSource"), id);  //currently we use the same id in ERMS and PESI
550
        success &= equals("Additional taxon source use fk ", srcRs.getString("sourceuse_id"), destRs.getString("SourceUseFk"), id);
551
        success &= equals("Additional taxon source use cache ", srcRs.getString("sourceuse_name"), destRs.getString("SourceUseCache"), id);
552
        //TODO some records are still truncated ~ >820 characters
553
        success &= equals("Additional taxon source name cache ", srcRs.getString("source_name"), destRs.getString("SourceNameCache"), id);
554
        success &= equals("Additional taxon source detail ", srcRs.getString("pagenr"), destRs.getString("SourceDetail"), id);
555
        //Complete
556
        return success;
557
    }
558

    
559
    private boolean testSingleNotes(int n) throws SQLException {
560
        boolean success = true;
561
        ResultSet srcRs = source.getResultSet("SELECT CAST(tu.id as nvarchar(20)) tuId, no.*, l.LanName "
562
                + " FROM notes no INNER JOIN tu ON no.tu_id = tu.id "
563
                + "    LEFT JOIN languages l ON l.LanID = no.lan_id "
564
                + " ORDER BY CAST(tu.id as nvarchar(20)), no.type, no.noteSortable ");  //, no.note (not possible because ntext
565
        ResultSet destRs = destination.getResultSet("SELECT t.IdInSource, no.*, cat.NoteCategory, l.Language "
566
                + " FROM Note no INNER JOIN Taxon t ON t.TaxonId = no.TaxonFk "
567
                + "    LEFT JOIN NoteCategory cat ON cat.NoteCategoryId = no.NoteCategoryFk "
568
                + "    LEFT JOIN Language l ON l.LanguageId = no.LanguageFk "
569
                + " WHERE t." + origErms
570
                + "      AND NOT (NoteCategoryFk = 4 AND no.LastAction IS NULL) AND NOT NoteCategoryFk IN (22,23,24) "
571
                + " ORDER BY t.IdInSource, no.NoteCategoryCache, Note_1  ");
572
        int count = 0;
573
        ResultSet srcRsLastAction = source.getResultSet(""
574
                + " SELECT no.id, s.sessiondate, a.action_name, s.ExpertName "
575
                + " FROM notes no "
576
                + "   INNER JOIN tu ON tu.id = no.tu_id "
577
                + "   LEFT JOIN languages l ON l.LanID = no.lan_id"
578
                + "   LEFT JOIN notes_sessions MN ON no.id = MN.note_id "
579
                + "   LEFT JOIN actions a ON a.id = MN.action_id "
580
                + "   LEFT JOIN sessions s ON s.id = MN.session_id  "
581
                + " ORDER BY CAST(tu.id as nvarchar(20)), no.type, no.noteSortable, s.sessiondate DESC, a.id DESC ");
582

    
583
        while (srcRs.next() && destRs.next()){
584
            success &= testSingleNote(srcRs, destRs);
585
            success &= testLastAction(srcRsLastAction, destRs, String.valueOf(srcRs.getInt("id")), "Note");
586
            count++;
587
        }
588
        success &= equals("Notes count differs", n, count, "-1");
589
        return success;
590
    }
591

    
592
    private boolean testSingleNote(ResultSet srcRs, ResultSet destRs) throws SQLException {
593
        String id = String.valueOf(srcRs.getInt("tuId") + "-" + srcRs.getString("type"));
594
        boolean success = equals("Note taxonID ", "tu_id: " + String.valueOf(srcRs.getInt("tuId")), destRs.getString("IdInSource"), id);
595
        success &= equals("Note Note_1 ", srcRs.getString("note"), destRs.getString("Note_1"), id);
596
        success &= isNull("Note_2", destRs);
597
        success &= equals("Note category cache", normalizeNoteCatCache(srcRs.getString("type")), destRs.getString("NoteCategoryCache"), id);
598
        success &= equals("Note language ", srcRs.getString("LanName"), destRs.getString("Language"), id);
599
        success &= isNull("Region", destRs);
600
        success &= isNull("SpeciesExpertGUID", destRs);
601
        //SpeciesExpertName, LastAction, LastActionDate handled in separate method
602
        //complete
603
        return success;
604
    }
605

    
606
    private String normalizeNoteCatCache(String string) {
607
        return StringUtils.capitalize(string)
608
                .replace("Original Combination", "Original combination")
609
                .replace("Taxonomic remark", "Taxonomic Remark");
610
    }
611

    
612
    private boolean testSingleDistributions(int n) throws SQLException {
613
        boolean success = true;
614
        ResultSet srcRs = source.getResultSet("SELECT CAST(ISNULL(tu.tu_accfinal, tu.id) as nvarchar(20)) tuId,"
615
                + " gu.gazetteer_id, dr.*, gu.id guId, gu.gu_name "
616
                + " FROM dr INNER JOIN tu ON dr.tu_id = tu.id "
617
                + "    LEFT JOIN gu ON gu.id = dr.gu_id "
618
                + " 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
619
        ResultSet destRs = destination.getResultSet("SELECT t.IdInSource, a.AreaERMSGazetteerId, oc.*, a.AreaName "
620
                + " FROM Occurrence oc INNER JOIN Taxon t ON t.TaxonId = oc.TaxonFk "
621
                + "    LEFT JOIN Area a ON a.AreaId = oc.AreaFk "
622
                + " WHERE t." + origErms
623
                + " ORDER BY t.IdInSource, a.AreaERMSGazetteerId, a.AreaName, oc.Notes ");
624
        ResultSet srcRsLastAction = source.getResultSet(""
625
                + " SELECT dr.id, s.sessiondate, a.action_name, s.ExpertName "
626
                + " FROM dr "
627
                + "   INNER JOIN tu ON tu.id = dr.tu_id "
628
                + "   LEFT JOIN gu ON gu.id = dr.gu_id "
629
                + "   LEFT JOIN dr_sessions MN ON dr.id = MN.dr_id "
630
                + "   LEFT JOIN actions a ON a.id = MN.action_id "
631
                + "   LEFT JOIN sessions s ON s.id = MN.session_id  "
632
                + " ORDER BY CAST(tu.id as nvarchar(20)), gu.gazetteer_id, gu.gu_name, s.sessiondate DESC, a.id DESC ");
633
        int count = 0;
634
        while (srcRs.next() && destRs.next()){
635
            success &= testSingleDistribution(srcRs, destRs);
636
            //there are >1000 duplicates in dr, therefore this creates lots of warnings
637
            success &= testLastAction(srcRsLastAction, destRs, String.valueOf(srcRs.getInt("id")), "Distribution");
638
            count++;
639
        }
640
        success &= equals("Distribution count differs", n, count, "-1");
641
        return success;
642
    }
643

    
644
    private boolean testSingleDistribution(ResultSet srcRs, ResultSet destRs) throws SQLException {
645
        String id = String.valueOf(srcRs.getInt("tuId") + "-" + srcRs.getString("gu_name"));
646
        boolean success = equals("Distribution taxonID ", "tu_id: " + String.valueOf(srcRs.getInt("tuId")), destRs.getString("IdInSource"), id);
647
        success &= equals("Distribution gazetteer_id ", srcRs.getString("gazetteer_id"), destRs.getString("AreaERMSGazetteerId"), id);
648
        success &= equals("Distribution area name ", srcRs.getString("gu_name"), destRs.getString("AreaName"), id);
649
        success &= equals("Distribution area name cache", srcRs.getString("gu_name"), destRs.getString("AreaNameCache"), id);
650
        success &= equals("Distribution OccurrenceStatusFk", 1, destRs.getInt("OccurrenceStatusFk"), id);
651
        success &= equals("Distribution OccurrenceStatusCache", "Present", destRs.getString("OccurrenceStatusCache"), id);
652
        //TODO see comments
653
        success &= isNull("SourceFk", destRs);  //sources should be moved to extra table only, check with script and PESI 2014 (=> has values for ERMS)
654
        success &= isNull("SourceCache", destRs);  //sources should be moved to extra table, check with script and PESI 2014 (=> has values for ERMS)
655
        success &= equals("Distribution notes ", srcRs.getString("note"), destRs.getString("Notes"), id);
656
        success &= isNull("SpeciesExpertGUID", destRs);  //SpeciesExpertGUID does not exist in ERMS
657
        //SpeciesExpertName,LastAction,LastActionDate handled in separate method
658
        return success;
659
    }
660

    
661
    private boolean testSingleCommonNames(int n) throws SQLException {
662
        boolean success = true;
663
        ResultSet srcRs = source.getResultSet("SELECT v.*, ISNULL([639_3],[639_2]) iso, l.LanName, tu.id tuId "
664
                + " FROM vernaculars v LEFT JOIN tu ON v.tu_id = tu.id LEFT JOIN languages l ON l.LanID = v.lan_id "
665
                + " ORDER BY CAST(tu.id as nvarchar(20)), ISNULL([639_3],[639_2]), v.vername, v.id ");
666
        ResultSet destRs = destination.getResultSet("SELECT cn.*, t.IdInSource, l.ISO639_2, l.ISO639_3 "
667
                + " FROM CommonName cn INNER JOIN Taxon t ON t.TaxonId = cn.TaxonFk LEFT JOIN Language l ON l.LanguageId = cn.LanguageFk "
668
                + " WHERE t." + origErms
669
                + " ORDER BY t.IdInSource, ISNULL("+preferredISO639+", "+alternativeISO639+"), cn.CommonName, cn.LastActionDate ");  //sorting also lastActionDate results in a minimum of exact duplicate problems
670
        ResultSet srcRsLastAction = source.getResultSet(""
671
                + " SELECT v.id, s.sessiondate, a.action_name, s.ExpertName "
672
                + " FROM vernaculars v "
673
                + "   INNER JOIN tu ON tu.id = v.tu_id "
674
                + "   LEFT JOIN languages l ON l.LanID = v.lan_id"
675
                + "   LEFT JOIN vernaculars_sessions MN ON v.id = MN.vernacular_id "
676
                + "   LEFT JOIN actions a ON a.id = MN.action_id "
677
                + "   LEFT JOIN sessions s ON s.id = MN.session_id  "
678
                + " ORDER BY CAST(tu.id as nvarchar(20)), ISNULL([639_3],[639_2]), v.vername, v.id, s.sessiondate DESC, a.id DESC ");
679
        int count = 0;
680
        while (srcRs.next() && destRs.next()){
681
            success &= testSingleCommonName(srcRs, destRs);
682
            success &= testLastAction(srcRsLastAction, destRs, String.valueOf(srcRs.getInt("id")), "CommonName");
683
            count++;
684
        }
685
        success &= equals("Common name count differs", n, count, "-1");
686
        return success;
687
    }
688

    
689
    boolean prefer639_3 = true;
690
    String preferredISO639 = prefer639_3? "ISO639_3":"ISO639_2";
691
    String alternativeISO639 = prefer639_3? "ISO639_2":"ISO639_3";
692

    
693
    private boolean testSingleCommonName(ResultSet srcRs, ResultSet destRs) throws SQLException {
694
        String id = String.valueOf(srcRs.getInt("tuId") + "-" + srcRs.getString("lan_id"));
695
        boolean success = equals("Common name taxonID ", "tu_id: " + String.valueOf(srcRs.getInt("tuId")), destRs.getString("IdInSource"), id);
696
        success &= equals("CommonName name ", srcRs.getString("vername"), destRs.getString("CommonName"), id);
697
        success &= equals("Common name languageFk ", srcRs.getString("iso"), getLanguageIso(destRs), id);
698
        success = equals("CommonName LanguageCache ", normalizeLang(srcRs.getString("LanName")), destRs.getString("LanguageCache"), id);
699
        //TODO needed? success = equals("CommonName language code ", srcRs.getString("lan_id"), destRs.getString("LanguageFk"), id);
700
        success &= isNull("Region", destRs);  //region does not seem to exist in ERMS
701
        //TODO see comments
702
//        success &= isNull("SourceFk", destRs);  //sources should be moved to extra table, check with PESI 2014
703
//        success &= isNull("SourceNameCache", destRs);  //sources should be moved to extra table, check with PESI 2014
704
        success &= isNull("SpeciesExpertGUID", destRs);  //SpeciesExpertGUID does not exist in ERMS
705
        //SpeciesExpertName,LastAction,LastActionDate handled in separate method
706
        //complete
707
        return success;
708
    }
709

    
710
    private String normalizeLang(String string) {
711
        if ("Spanish".equals(string)){
712
            return "Spanish, Castillian";
713
        }else if ("Modern Greek (1453-)".equals(string)){
714
            return "Greek";
715
        }else if ("Malay (individual language)".equals(string)){
716
            return "Malay";
717
        }else if ("Swahili (individual language)".equals(string)){
718
            return "Swahili";
719
        }
720

    
721
        return string;
722
    }
723

    
724
    private String getLanguageIso(ResultSet destRs) throws SQLException {
725
        String result = destRs.getString(preferredISO639);
726
        if (result == null){
727
            result = destRs.getString(alternativeISO639);
728
        }
729
        return result;
730
    }
731

    
732
    private boolean testSingleReferences() throws SQLException {
733
        boolean success = true;
734
        ResultSet srcRS = source.getResultSet("SELECT s.* FROM sources s ORDER BY s.id ");
735
        ResultSet destRS = destination.getResultSet("SELECT s.* FROM Source s "
736
                + " WHERE s." + origErms
737
                + " ORDER BY s.RefIdInSource ");  // +1 for the source reference "erms" but this has no OriginalDB
738
        while (srcRS.next() && destRS.next()){
739
            success &= testSingleReference(srcRS, destRS);
740
        }
741
        return success;
742
    }
743

    
744
    private boolean testSingleReference(ResultSet srcRS, ResultSet destRS) throws SQLException {
745
        String id = String.valueOf(srcRS.getInt("id"));
746
        boolean success = equals("Reference ID ", srcRS.getInt("id"), destRS.getInt("RefIdInSource"), id);
747
        success &= equals("Reference IMIS_id ", srcRS.getString("imis_id"), destRS.getString("IMIS_Id"), id);
748
        success &= equals("Reference SourceCategoryFk ", convertSourceTypeFk(srcRS.getString("source_type")), destRS.getInt("SourceCategoryFk"), id);
749
        success &= equals("Reference SourceCategoryCache ", convertSourceTypeCache(srcRS.getString("source_type")), destRS.getString("SourceCategoryCache"), id);
750
        success &= equals("Reference name ", srcRS.getString("source_name"), destRS.getString("Name"), id);
751
        success &= equals("Reference abstract ", srcRS.getString("source_abstract"), destRS.getString("Abstract"), id);
752
        success &= equals("Reference title ", srcRS.getString("source_title"), destRS.getString("Title"), id);
753
        success &= equals("Reference author string ", srcRS.getString("source_author"), destRS.getString("AuthorString"), id);
754
        success &= equals("Reference year ", normalizeYear(srcRS.getString("source_year")), destRS.getString("RefYear"), id);
755
        success &= isNull("NomRefCache", destRS);  //for ERMS no other value was found in 2014 value
756
        success &= equals("Reference link ", srcRS.getString("source_link"), destRS.getString("Link"), id);
757
        success &= equals("Reference note ", srcRS.getString("source_note"), destRS.getString("Notes"), id);
758
        //complete
759
        return success;
760
    }
761

    
762
    private Integer convertSourceTypeFk(String sourceType) {
763
        if (sourceType == null){
764
            return null;
765
        }else if ("d".equals(sourceType)){
766
            return 4;
767
        }else if ("e".equals(sourceType)){
768
            return 5;
769
        }else if ("p".equals(sourceType)){
770
            return 11;
771
        }else if ("i".equals(sourceType)){
772
            return 12;
773
        }
774
        return null;
775
    }
776
    private String convertSourceTypeCache(String sourceType) {
777
        if (sourceType == null){
778
            return null;
779
        }else if ("d".equals(sourceType)){
780
            return "database";
781
        }else if ("e".equals(sourceType)){
782
            return "informal reference";
783
        }else if ("p".equals(sourceType)){
784
            return "publication";
785
        }else if ("i".equals(sourceType)){
786
            //TODO
787
            return "i";
788
        }
789
        return null;
790
    }
791

    
792
    private boolean testReferenceCount() {
793
        int countSrc = source.getUniqueInteger("SELECT count(*) FROM sources ");
794
        int countDest = destination.getUniqueInteger("SELECT count(*) FROM Source s WHERE s."+ origErms);  // +1 for the source reference "erms" but this has no OriginalDB
795
        boolean success = equals("Reference count ", countSrc, countDest, "-1");
796
        return success;
797
    }
798

    
799
    private String normalizeYear(String yearStr) {
800
        if (StringUtils.isBlank(yearStr)){
801
            return yearStr;
802
        }
803
        yearStr = yearStr.trim();
804
        if (yearStr.matches("\\d{4}-\\d{2}")){
805
            yearStr = yearStr.substring(0, 5)+yearStr.substring(0, 2)+yearStr.substring(5);
806
        }
807
        return yearStr;
808
    }
809

    
810
    private boolean isNull(String attrName, ResultSet destRS) throws SQLException {
811
        Object value = destRS.getObject(attrName);
812
        if (value != null){
813
            String message = attrName + " was expected to be null but was: " + value.toString();
814
            logger.warn(message);
815
            return false;
816
        }else{
817
            logger.info(attrName + " was null as expected");
818
            return true;
819
        }
820
    }
821

    
822
    private boolean equals(String messageStart, Timestamp srcDate, Timestamp destDate, String id) {
823
        if (!CdmUtils.nullSafeEqual(srcDate, destDate)){
824
            String message = id + ": " + messageStart + " must be equal, but was not.\n Source: "+  srcDate + "; Destination: " + destDate;
825
            logger.warn(message);
826
            return false;
827
        }else{
828
            logger.info(messageStart + " were equal: " + srcDate);
829
            return true;
830
        }
831
    }
832

    
833
    private boolean equals(String messageStart, Integer nSrc, Integer nDest, String id) {
834
        String strId = id.equals("-1")? "": (id+ ": ");
835
        if (!CdmUtils.nullSafeEqual(nSrc,nDest)){
836
            String message = strId+ messageStart + " must be equal, but was not.\n Source: "+  nSrc + "; Destination: " + nDest;
837
            logger.warn(message);
838
            return false;
839
        }else{
840
            logger.info(strId + messageStart + " were equal: " + nSrc);
841
            return true;
842
        }
843
    }
844

    
845
    private boolean equals(String messageStart, String strSrc, String strDest, String id) {
846
        if (StringUtils.isBlank(strSrc)){
847
            strSrc = null;
848
        }else{
849
            strSrc = strSrc.trim();
850
        }
851
        //we do not trim strDest here because this should be done during import already. If not it should be shown here
852
        if (!CdmUtils.nullSafeEqual(strSrc, strDest)){
853
            int index = CdmUtils.diffIndex(strSrc, strDest);
854
            String message = id+ ": " + messageStart + " must be equal, but was not at "+index+".\n  Source:      "+  strSrc + "\n  Destination: " + strDest;
855
            logger.warn(message);
856
            return false;
857
        }else{
858
            logger.info(id+ ": " + messageStart + " were equal: " + strSrc);
859
            return true;
860
        }
861
    }
862

    
863
    protected Integer nullSafeInt(ResultSet rs, String columnName) throws SQLException {
864
        Object intObject = rs.getObject(columnName);
865
        if (intObject == null){
866
            return null;
867
        }else{
868
            return Integer.valueOf(intObject.toString());
869
        }
870
    }
871

    
872
//** ************* MAIN ********************************************/
873

    
874

    
875

    
876
    public static void main(String[] args){
877
        PesiErmsValidator validator = new PesiErmsValidator();
878
        validator.invoke(defaultSource, defaultDestination);
879
        System.exit(0);
880
    }
881
}
(1-1/2)