Project

General

Profile

Download (49.5 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.*, tu1.tu_name tu1_name, r.rank_name, acc.tu_sp as acc_sp, st.status_name, "
265
                + "        type.tu_displayname typename, type.tu_authority typeauthor, "
266
                + "        fo.fossil_name, qs.qualitystatus_name "
267
                + " FROM tu t "
268
                + " LEFT JOIN tu as tu1 on t.tu_parent = tu1.id "
269
                + " 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 "
270
                + " LEFT JOIN tu acc ON acc.id = t.tu_accfinal "
271
                + " LEFT JOIN status st ON st.status_id = t.tu_status "
272
                + " LEFT JOIN tu type ON type.id = t.tu_typetaxon "
273
                + " LEFT JOIN fossil fo ON t.tu_fossil = fo.fossil_id "
274
                + " LEFT JOIN qualitystatus qs ON t.tu_qualitystatus = qs.id "
275
                + " WHERE t.id " + moneraFilter
276
                + " ORDER BY CAST(t.id as nvarchar(20)) ");
277
        ResultSet destRS = destination.getResultSet("SELECT t.*, "
278
                + "     pt.GenusOrUninomial p_GenusOrUninomial, pt.InfraGenericEpithet p_InfraGenericEpithet, pt.SpecificEpithet p_SpecificEpithet, "
279
                + "     pt.treeIndex pTreeIndex, "
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
            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
    private boolean testSingleTaxon(ResultSet srcRS, ResultSet destRS) throws SQLException {
306
        String id = String.valueOf(srcRS.getInt("id"));
307
        //complete
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

    
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
//TODO webShowName  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 nameStatusFk       success &= equals("Taxon NameStatusFk", toNameStatus(nullSafeInt(srcRS, "tu_status")),nullSafeInt( destRS,"NameStatusFk"), id);
324
//TODO nameStatusCache    success &= equals("Taxon NameStatusCache", srcRS.getString("status_name"), destRS.getString("NameStatusCache"), id);
325

    
326
       success &= equals("Taxon TaxonStatusFk", makePesiTaxonStatus(srcRS, "tu_status"),nullSafeInt( destRS,"TaxonStatusFk"), id);
327
/*//TODO taxonStatusCache  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
        success &= testTreeIndex(destRS, ("TreeIndex"), ("pTreeIndex"), id);
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
    private Integer makePesiTaxonStatus(ResultSet srcRS, String string) throws SQLException {
351
        Integer status = nullSafeInt(srcRS, "tu_status");
352
        if(status == 1 || status == 2){   //accepted, unaccepted
353
            return status;
354
        }else if (status == 3 || status == 6 || status == 7){  //nomen nudum, nomen dubium, temporary name
355
            return 2;
356
        }
357
        return -1;
358
    }
359

    
360
    private boolean testTreeIndex(ResultSet destRS, String childIndexAttr, String parentIndexAttr, String id) throws SQLException {
361
        boolean result;
362
        int taxonStatusFk = destRS.getInt("TaxonStatusFk");
363
        String parentTaxonId = destRS.getString("parentTaxonFk");
364
        int rankFk = destRS.getInt("RankFk");
365
        if (taxonStatusFk == 2 || taxonStatusFk == 4 || rankFk <= 10){  //synonym; pro parte syn; kingdom and higher
366
            result = isNull(childIndexAttr, destRS);
367
        }else{
368
            String childIndex = destRS.getString(childIndexAttr);
369
            String parentIndex = destRS.getString(parentIndexAttr);
370
            parentIndex = parentIndex == null? "#": parentIndex;
371
            result = equals("Tree index", childIndex, parentIndex + parentTaxonId + "#", id);
372
        }
373
        return result;
374
    }
375

    
376
    boolean namePartsFirst = true;
377
    private boolean compareNameParts(ResultSet srcRS, ResultSet destRS, String id) throws SQLException {
378
        if (namePartsFirst){
379
            logger.warn("Validation of name parts not fully implemented (difficult). Currently validated via fullname");
380
            namePartsFirst = false;
381
        }
382
        int rankFk = srcRS.getInt("tu_rank");
383
        String genusOrUninomial = null;
384
        String infraGenericEpithet = null;
385
        String specificEpithet = null;
386
        String infraSpecificEpithet = null;
387
        if (rankFk <= 180){
388
            genusOrUninomial = srcRS.getString("tu_name");
389
        }else if (rankFk == 190){
390
            genusOrUninomial = srcRS.getString("tu1_name");
391
            infraGenericEpithet =  srcRS.getString("tu_name");
392
            //TODO compareNameParts does not work this way
393
//        }else if (rankFk == 220){
394
//            genusOrUninomial = destRS.getString("p_GenusOrUninomial");
395
//            infraGenericEpithet = destRS.getString("p_InfraGenericEpithet");
396
//            specificEpithet = srcRS.getString("tu_name");
397
        }else{
398
            //TODO exception (compare name parts)
399
            return false;
400
        }
401
        boolean result = testEpis(destRS, genusOrUninomial, infraGenericEpithet,
402
                specificEpithet, infraSpecificEpithet, id);
403
        return result;
404
    }
405

    
406
    private boolean testEpis(ResultSet destRS, String genusOrUninomial, String infraGenericEpithet, String specificEpithet,
407
            String infraSpecificEpithet, String id) throws SQLException {
408
        boolean result = equals("Taxon genusOrUninomial", genusOrUninomial, destRS.getString("GenusOrUninomial"), id) ;
409
        result &= equals("Taxon infraGenericEpithet", infraGenericEpithet, destRS.getString("InfraGenericEpithet"), id) ;
410
        result &= equals("Taxon specificEpithet", specificEpithet, destRS.getString("SpecificEpithet"), id) ;
411
        result &= equals("Taxon infraSpecificEpithet", infraSpecificEpithet, destRS.getString("InfraSpecificEpithet"), id) ;
412
        return result;
413
    }
414

    
415
    private String normalizeRank(String string, ResultSet srcRS, String id) throws SQLException {
416
        String result = string
417
                .replace("Subforma", "Subform")
418
                .replace("Forma", "Form");
419
        int kingdomFk = Integer.valueOf(getSourceKingdomFk(srcRS, id));
420
        if (kingdomFk == 3 || kingdomFk == 4){
421
            result = result.replace("Subphylum", "Subdivision");
422
            result = result.replace("Phylum", "Division");
423
        }
424
        return result;
425
    }
426

    
427
    //see also ErmsTaxonImport.getExpectedTitleCache()
428
    private String srcFullName(ResultSet srcRs) throws SQLException {
429
        String result = null;
430
        String epi = srcRs.getString("tu_name");
431
        String display = srcRs.getString("tu_displayname");
432
        String sp = srcRs.getString("tu_sp");
433
        if (display.indexOf(epi) != display.lastIndexOf(epi) && !sp.startsWith("#2#")){ //autonym, !animal
434
            String authority = srcRs.getString("tu_authority");
435
            result = srcRs.getString("tu_displayname").replaceFirst(epi+" ", CdmUtils.concat(" ", epi, authority)+" ");
436
        }else{
437
            result = CdmUtils.concat(" ", srcRs.getString("tu_displayname"), srcRs.getString("tu_authority"));
438
        }
439
        return result;
440
    }
441

    
442
    private String srcDisplayName(ResultSet srcRs) throws SQLException {
443
        String result = null;
444
        String epi = srcRs.getString("tu_name");
445
        epi = " a" + epi;
446
        String display = "<i>"+srcRs.getString("tu_displayname")+"</i>";
447
        display = display.replace(" var. ", "</i> var. <i>").replace(" f. ", "</i> f. <i>");
448
        String sp = srcRs.getString("tu_sp");
449
        if (display.indexOf(epi) != display.lastIndexOf(epi) && !sp.startsWith("#2#")){ //homonym, animal
450
            result = display.replaceFirst(epi+" ", CdmUtils.concat(" ", " "+epi, srcRs.getString("tu_authority")))+" ";
451
        }else{
452
            result = CdmUtils.concat(" ", display, srcRs.getString("tu_authority"));
453
        }
454
        return result;
455
    }
456

    
457
    String lastLastActionId = "-1";
458
    private boolean testLastAction(ResultSet srcRsLastAction, ResultSet destRs, String id, String table) throws SQLException {
459
        try {
460
            boolean success = true;
461
            String srcId = null;
462
            while (srcRsLastAction.next()){
463
                srcId = String.valueOf(srcRsLastAction.getInt("id"));
464
                if (!lastLastActionId.equals(srcId)){
465
                    lastLastActionId = srcId;
466
                    break;
467
                }
468
            }
469
            if(!id.equals(srcId)){
470
                logger.warn("Last Action SourceIDs are not equal: id: " +id + ", la-id: " + srcId);
471
            }
472
            String destStr = destRs.getString("LastAction");
473
            success &= equals(table + " SpeciesExpertName", srcRsLastAction.getString("ExpertName"), destRs.getString("SpeciesExpertName"), id);  //mapping ExpertName => SpeciesExpertName according to SQL script
474
            success &= equals(table + " Last Action", srcRsLastAction.getString("action_name"), destStr == null? null : destStr, id);
475
            success &= equals(table + " Last Action Date", srcRsLastAction.getTimestamp("sessiondate"), destRs.getTimestamp("LastActionDate"), id);
476

    
477
            return success;
478
        } catch (Exception e) {
479
            e.printStackTrace();
480
            throw e;
481
        }
482
    }
483

    
484
    private boolean compareKingdom(String messageStart, ResultSet srcRS, ResultSet destRS, String id) throws SQLException {
485
        String srcKingdom = getSourceKingdomFk(srcRS, id);
486
        Integer intDest = nullSafeInt(destRS, "KingdomFk");
487
        if (intDest == null){
488
            logger.warn(id +": " + messageStart + " must never be null for destination. Biota needs to be 0, all the rest needs to have >0 int value.");
489
            return false;
490
        }else{
491
            return equals(messageStart, srcKingdom, String.valueOf(intDest), id);
492
        }
493
    }
494

    
495
    private String getSourceKingdomFk(ResultSet srcRS, String id) throws SQLException {
496
        String strSrc = srcRS.getString("acc_sp");
497
        if (strSrc == null){
498
            strSrc = srcRS.getString("tu_sp");
499
        }
500
        if (strSrc == null){
501
            if ("1".equals(id)){
502
                strSrc = "0";  //Biota
503
            }else if ("147415".equals(id)){
504
                strSrc = "6";  //Monera is synonym of Bacteria
505
            }else{
506
                strSrc = id;
507
            }
508
        }else{
509
            strSrc = strSrc.substring(1);
510
            strSrc = strSrc.substring(0, strSrc.indexOf("#"));
511
        }
512
        return strSrc;
513
    }
514

    
515
    private boolean testSingleTaxonRelations(int n) throws SQLException {
516
        boolean success = true;
517
        ResultSet srcRS = source.getResultSet(""
518
                + " SELECT t.* "
519
                + " FROM tu t "
520
                + " WHERE t.id "+ moneraFilter + " AND tu_accfinal <> id "
521
                + " ORDER BY CAST(t.id as nvarchar(20)) ");
522
        ResultSet destRS = destination.getResultSet("SELECT rel.*, t1.IdInSource t1Id, t2.IdInSource t2Id "
523
                + " FROM RelTaxon rel "
524
                + "    LEFT JOIN Taxon t1 ON t1.TaxonId = rel.TaxonFk1 "
525
                + "    LEFT JOIN Taxon t2 ON t2.TaxonId = rel.TaxonFk2 "
526
                + " WHERE t1."+origErms+" AND t2." + origErms
527
                + " ORDER BY t1.IdInSource");
528
        int i = 0;
529
        while (srcRS.next() && destRS.next()){
530
            success &= testSingleTaxonRelation(srcRS, destRS);
531
            i++;
532
        }
533
        success &= equals("Taxon relation count for single compare", n, i, String.valueOf(-1));
534
        return success;
535
    }
536

    
537
    private boolean testSingleTaxonRelation(ResultSet srcRS, ResultSet destRS) throws SQLException {
538
        String id = String.valueOf(srcRS.getInt("id"));
539
        boolean success = equals("Taxon relation taxon1", "tu_id: " + srcRS.getInt("id"), destRS.getString("t1Id"), id);
540
        success &= equals("Taxon relation taxon2", "tu_id: " + srcRS.getInt("tu_accfinal"), destRS.getString("t2Id"), id);
541
        success &= equals("Taxon relation qualifier fk", PesiTransformer.IS_SYNONYM_OF, destRS.getInt("RelTaxonQualifierFk"), id);
542
        success &= equals("Taxon relation qualifier cache", "is synonym of", destRS.getString("RelQualifierCache"), id);
543
        success &= isNull("notes", destRS);
544
        //complete if no further relations need to be added
545
        return success;
546
    }
547

    
548
    private boolean testSingleAdditionalTaxonSources(int n) throws SQLException {
549
        boolean success = true;
550
        ResultSet srcRs = source.getResultSet("SELECT CAST(tu.id as nvarchar(20)) tuId, MN.*, s.*, su.sourceuse_name "
551
                + " FROM tu_sources MN INNER JOIN tu ON MN.tu_id = tu.id "
552
                + "    LEFT JOIN sources s ON s.id = MN.source_id "
553
                + "    LEFT JOIN sourceuses su ON MN.sourceuse_id = su.sourceuse_id "
554
                + " WHERE MN.tu_id  " + moneraFilter
555
                + " ORDER BY CAST(tu.id as nvarchar(20)), MN.sourceuse_id, s.id ");  //, no.note (not possible because ntext
556
        ResultSet destRs = destination.getResultSet("SELECT t.IdInSource, ats.*, s.*, su.* "
557
                + " FROM AdditionalTaxonSource ats INNER JOIN Taxon t ON t.TaxonId = ats.TaxonFk "
558
                + "    INNER JOIN Source s ON s.SourceId = ats.SourceFk "
559
                + "    LEFT JOIN SourceUse su ON su.SourceUseId = ats.SourceUseFk "
560
                + " WHERE t."+origErms
561
                + " ORDER BY t.IdInSource, su.SourceUseId, s.RefIdInSource ");
562
        int count = 0;
563
        while (srcRs.next() && destRs.next()){
564
            success &= testSingleAdditionalTaxonSource(srcRs, destRs);
565
            count++;
566
        }
567
        success &= equals("Notes count differs", n, count, "-1");
568
        return success;
569
    }
570

    
571
    private boolean testSingleAdditionalTaxonSource(ResultSet srcRs, ResultSet destRs) throws SQLException {
572
        String id = String.valueOf(srcRs.getInt("tuId") + "-" + srcRs.getString("sourceuse_name"));
573
        boolean success = equals("Additional taxon source taxonID ", "tu_id: " + String.valueOf(srcRs.getInt("tuId")), destRs.getString("IdInSource"), id);
574
        success &= equals("Additional taxon source fk ", srcRs.getString("source_id"), destRs.getString("RefIdInSource"), id);  //currently we use the same id in ERMS and PESI
575
        success &= equals("Additional taxon source use fk ", srcRs.getString("sourceuse_id"), destRs.getString("SourceUseFk"), id);
576
        success &= equals("Additional taxon source use cache ", srcRs.getString("sourceuse_name"), destRs.getString("SourceUseCache"), id);
577
        //TODO some records are still truncated ~ >820 characters
578
        success &= equals("Additional taxon source name cache ", srcRs.getString("source_name"), destRs.getString("SourceNameCache"), id);
579
        success &= equals("Additional taxon source detail ", srcRs.getString("pagenr"), destRs.getString("SourceDetail"), id);
580
        //Complete
581
        return success;
582
    }
583

    
584
    private boolean testSingleNotes(int n) throws SQLException {
585
        boolean success = true;
586
        ResultSet srcRs = source.getResultSet("SELECT CAST(tu.id as nvarchar(20)) tuId, no.*, l.LanName "
587
                + " FROM notes no INNER JOIN tu ON no.tu_id = tu.id "
588
                + "    LEFT JOIN languages l ON l.LanID = no.lan_id "
589
                + " ORDER BY CAST(tu.id as nvarchar(20)), no.type, no.noteSortable ");  //, no.note (not possible because ntext
590
        ResultSet destRs = destination.getResultSet("SELECT t.IdInSource, no.*, cat.NoteCategory, l.Language "
591
                + " FROM Note no INNER JOIN Taxon t ON t.TaxonId = no.TaxonFk "
592
                + "    LEFT JOIN NoteCategory cat ON cat.NoteCategoryId = no.NoteCategoryFk "
593
                + "    LEFT JOIN Language l ON l.LanguageId = no.LanguageFk "
594
                + " WHERE t." + origErms
595
                + "      AND NOT (NoteCategoryFk = 4 AND no.LastAction IS NULL) AND NOT NoteCategoryFk IN (22,23,24) "
596
                + " ORDER BY t.IdInSource, no.NoteCategoryCache, Note_1  ");
597
        int count = 0;
598
        ResultSet srcRsLastAction = source.getResultSet(""
599
                + " SELECT no.id, s.sessiondate, a.action_name, s.ExpertName "
600
                + " FROM notes no "
601
                + "   INNER JOIN tu ON tu.id = no.tu_id "
602
                + "   LEFT JOIN languages l ON l.LanID = no.lan_id"
603
                + "   LEFT JOIN notes_sessions MN ON no.id = MN.note_id "
604
                + "   LEFT JOIN actions a ON a.id = MN.action_id "
605
                + "   LEFT JOIN sessions s ON s.id = MN.session_id  "
606
                + " ORDER BY CAST(tu.id as nvarchar(20)), no.type, no.noteSortable, s.sessiondate DESC, a.id DESC ");
607

    
608
        while (srcRs.next() && destRs.next()){
609
            success &= testSingleNote(srcRs, destRs);
610
            success &= testLastAction(srcRsLastAction, destRs, String.valueOf(srcRs.getInt("id")), "Note");
611
            count++;
612
        }
613
        success &= equals("Notes count differs", n, count, "-1");
614
        return success;
615
    }
616

    
617
    private boolean testSingleNote(ResultSet srcRs, ResultSet destRs) throws SQLException {
618
        String id = String.valueOf(srcRs.getInt("tuId") + "-" + srcRs.getString("type"));
619
        boolean success = equals("Note taxonID ", "tu_id: " + String.valueOf(srcRs.getInt("tuId")), destRs.getString("IdInSource"), id);
620
        success &= equals("Note Note_1 ", srcRs.getString("note"), destRs.getString("Note_1"), id);
621
        success &= isNull("Note_2", destRs);
622
        success &= equals("Note category cache", normalizeNoteCatCache(srcRs.getString("type")), destRs.getString("NoteCategoryCache"), id);
623
        success &= equals("Note language ", srcRs.getString("LanName"), destRs.getString("Language"), id);
624
        success &= isNull("Region", destRs);
625
        success &= isNull("SpeciesExpertGUID", destRs);
626
        //SpeciesExpertName, LastAction, LastActionDate handled in separate method
627
        //complete
628
        return success;
629
    }
630

    
631
    private String normalizeNoteCatCache(String string) {
632
        return StringUtils.capitalize(string)
633
                .replace("Original Combination", "Original combination")
634
                .replace("Taxonomic remark", "Taxonomic Remark");
635
    }
636

    
637
    private boolean testSingleDistributions(int n) throws SQLException {
638
        boolean success = true;
639
        ResultSet srcRs = source.getResultSet("SELECT CAST(ISNULL(tu.tu_accfinal, tu.id) as nvarchar(20)) tuId,"
640
                + " gu.gazetteer_id, dr.*, gu.id guId, gu.gu_name "
641
                + " FROM dr INNER JOIN tu ON dr.tu_id = tu.id "
642
                + "    LEFT JOIN gu ON gu.id = dr.gu_id "
643
                + " 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
644
        ResultSet destRs = destination.getResultSet("SELECT t.IdInSource, a.AreaERMSGazetteerId, oc.*, a.AreaName "
645
                + " FROM Occurrence oc INNER JOIN Taxon t ON t.TaxonId = oc.TaxonFk "
646
                + "    LEFT JOIN Area a ON a.AreaId = oc.AreaFk "
647
                + " WHERE t." + origErms
648
                + " ORDER BY t.IdInSource, a.AreaERMSGazetteerId, a.AreaName, oc.Notes ");
649
        ResultSet srcRsLastAction = source.getResultSet(""
650
                + " SELECT dr.id, s.sessiondate, a.action_name, s.ExpertName "
651
                + " FROM dr "
652
                + "   INNER JOIN tu ON tu.id = dr.tu_id "
653
                + "   LEFT JOIN gu ON gu.id = dr.gu_id "
654
                + "   LEFT JOIN dr_sessions MN ON dr.id = MN.dr_id "
655
                + "   LEFT JOIN actions a ON a.id = MN.action_id "
656
                + "   LEFT JOIN sessions s ON s.id = MN.session_id  "
657
                + " ORDER BY CAST(tu.id as nvarchar(20)), gu.gazetteer_id, gu.gu_name, s.sessiondate DESC, a.id DESC ");
658
        int count = 0;
659
        while (srcRs.next() && destRs.next()){
660
            success &= testSingleDistribution(srcRs, destRs);
661
            //there are >1000 duplicates in dr, therefore this creates lots of warnings
662
            success &= testLastAction(srcRsLastAction, destRs, String.valueOf(srcRs.getInt("id")), "Distribution");
663
            count++;
664
        }
665
        success &= equals("Distribution count differs", n, count, "-1");
666
        return success;
667
    }
668

    
669
    private boolean testSingleDistribution(ResultSet srcRs, ResultSet destRs) throws SQLException {
670
        String id = String.valueOf(srcRs.getInt("tuId") + "-" + srcRs.getString("gu_name"));
671
        boolean success = equals("Distribution taxonID ", "tu_id: " + String.valueOf(srcRs.getInt("tuId")), destRs.getString("IdInSource"), id);
672
        success &= equals("Distribution gazetteer_id ", srcRs.getString("gazetteer_id"), destRs.getString("AreaERMSGazetteerId"), id);
673
        success &= equals("Distribution area name ", srcRs.getString("gu_name"), destRs.getString("AreaName"), id);
674
        success &= equals("Distribution area name cache", srcRs.getString("gu_name"), destRs.getString("AreaNameCache"), id);
675
        success &= equals("Distribution OccurrenceStatusFk", 1, destRs.getInt("OccurrenceStatusFk"), id);
676
        success &= equals("Distribution OccurrenceStatusCache", "Present", destRs.getString("OccurrenceStatusCache"), id);
677
        //TODO see comments
678
        success &= isNull("SourceFk", destRs);  //sources should be moved to extra table only, check with script and PESI 2014 (=> has values for ERMS)
679
        success &= isNull("SourceCache", destRs);  //sources should be moved to extra table, check with script and PESI 2014 (=> has values for ERMS)
680
        success &= equals("Distribution notes ", srcRs.getString("note"), destRs.getString("Notes"), id);
681
        success &= isNull("SpeciesExpertGUID", destRs);  //SpeciesExpertGUID does not exist in ERMS
682
        //SpeciesExpertName,LastAction,LastActionDate handled in separate method
683
        return success;
684
    }
685

    
686
    private boolean testSingleCommonNames(int n) throws SQLException {
687
        boolean success = true;
688
        ResultSet srcRs = source.getResultSet("SELECT v.*, ISNULL([639_3],[639_2]) iso, l.LanName, tu.id tuId "
689
                + " FROM vernaculars v LEFT JOIN tu ON v.tu_id = tu.id LEFT JOIN languages l ON l.LanID = v.lan_id "
690
                + " ORDER BY CAST(tu.id as nvarchar(20)), ISNULL([639_3],[639_2]), v.vername, v.id ");
691
        ResultSet destRs = destination.getResultSet("SELECT cn.*, t.IdInSource, l.ISO639_2, l.ISO639_3 "
692
                + " FROM CommonName cn INNER JOIN Taxon t ON t.TaxonId = cn.TaxonFk LEFT JOIN Language l ON l.LanguageId = cn.LanguageFk "
693
                + " WHERE t." + origErms
694
                + " ORDER BY t.IdInSource, ISNULL("+preferredISO639+", "+alternativeISO639+"), cn.CommonName, cn.LastActionDate ");  //sorting also lastActionDate results in a minimum of exact duplicate problems
695
        ResultSet srcRsLastAction = source.getResultSet(""
696
                + " SELECT v.id, s.sessiondate, a.action_name, s.ExpertName "
697
                + " FROM vernaculars v "
698
                + "   INNER JOIN tu ON tu.id = v.tu_id "
699
                + "   LEFT JOIN languages l ON l.LanID = v.lan_id"
700
                + "   LEFT JOIN vernaculars_sessions MN ON v.id = MN.vernacular_id "
701
                + "   LEFT JOIN actions a ON a.id = MN.action_id "
702
                + "   LEFT JOIN sessions s ON s.id = MN.session_id  "
703
                + " ORDER BY CAST(tu.id as nvarchar(20)), ISNULL([639_3],[639_2]), v.vername, v.id, s.sessiondate DESC, a.id DESC ");
704
        int count = 0;
705
        while (srcRs.next() && destRs.next()){
706
            success &= testSingleCommonName(srcRs, destRs);
707
            success &= testLastAction(srcRsLastAction, destRs, String.valueOf(srcRs.getInt("id")), "CommonName");
708
            count++;
709
        }
710
        success &= equals("Common name count differs", n, count, "-1");
711
        return success;
712
    }
713

    
714
    boolean prefer639_3 = true;
715
    String preferredISO639 = prefer639_3? "ISO639_3":"ISO639_2";
716
    String alternativeISO639 = prefer639_3? "ISO639_2":"ISO639_3";
717

    
718
    private boolean testSingleCommonName(ResultSet srcRs, ResultSet destRs) throws SQLException {
719
        String id = String.valueOf(srcRs.getInt("tuId") + "-" + srcRs.getString("lan_id"));
720
        boolean success = equals("Common name taxonID ", "tu_id: " + String.valueOf(srcRs.getInt("tuId")), destRs.getString("IdInSource"), id);
721
        success &= equals("CommonName name ", srcRs.getString("vername"), destRs.getString("CommonName"), id);
722
        success &= equals("Common name languageFk ", srcRs.getString("iso"), getLanguageIso(destRs), id);
723
        success = equals("CommonName LanguageCache ", normalizeLang(srcRs.getString("LanName")), destRs.getString("LanguageCache"), id);
724
        //TODO needed? success = equals("CommonName language code ", srcRs.getString("lan_id"), destRs.getString("LanguageFk"), id);
725
        success &= isNull("Region", destRs);  //region does not seem to exist in ERMS
726
        //TODO see comments
727
//        success &= isNull("SourceFk", destRs);  //sources should be moved to extra table, check with PESI 2014
728
//        success &= isNull("SourceNameCache", destRs);  //sources should be moved to extra table, check with PESI 2014
729
        success &= isNull("SpeciesExpertGUID", destRs);  //SpeciesExpertGUID does not exist in ERMS
730
        //SpeciesExpertName,LastAction,LastActionDate handled in separate method
731
        //complete
732
        return success;
733
    }
734

    
735
    private String normalizeLang(String string) {
736
        if ("Spanish".equals(string)){
737
            return "Spanish, Castillian";
738
        }else if ("Modern Greek (1453-)".equals(string)){
739
            return "Greek";
740
        }else if ("Malay (individual language)".equals(string)){
741
            return "Malay";
742
        }else if ("Swahili (individual language)".equals(string)){
743
            return "Swahili";
744
        }
745

    
746
        return string;
747
    }
748

    
749
    private String getLanguageIso(ResultSet destRs) throws SQLException {
750
        String result = destRs.getString(preferredISO639);
751
        if (result == null){
752
            result = destRs.getString(alternativeISO639);
753
        }
754
        return result;
755
    }
756

    
757
    private boolean testSingleReferences() throws SQLException {
758
        boolean success = true;
759
        ResultSet srcRS = source.getResultSet("SELECT s.* FROM sources s ORDER BY s.id ");
760
        ResultSet destRS = destination.getResultSet("SELECT s.* FROM Source s "
761
                + " WHERE s." + origErms
762
                + " ORDER BY s.RefIdInSource ");  // +1 for the source reference "erms" but this has no OriginalDB
763
        while (srcRS.next() && destRS.next()){
764
            success &= testSingleReference(srcRS, destRS);
765
        }
766
        return success;
767
    }
768

    
769
    private boolean testSingleReference(ResultSet srcRS, ResultSet destRS) throws SQLException {
770
        String id = String.valueOf(srcRS.getInt("id"));
771
        boolean success = equals("Reference ID ", srcRS.getInt("id"), destRS.getInt("RefIdInSource"), id);
772
        success &= equals("Reference IMIS_id ", srcRS.getString("imis_id"), destRS.getString("IMIS_Id"), id);
773
        success &= equals("Reference SourceCategoryFk ", convertSourceTypeFk(srcRS.getString("source_type")), destRS.getInt("SourceCategoryFk"), id);
774
        success &= equals("Reference SourceCategoryCache ", convertSourceTypeCache(srcRS.getString("source_type")), destRS.getString("SourceCategoryCache"), id);
775
        success &= equals("Reference name ", srcRS.getString("source_name"), destRS.getString("Name"), id);
776
        success &= equals("Reference abstract ", srcRS.getString("source_abstract"), destRS.getString("Abstract"), id);
777
        success &= equals("Reference title ", srcRS.getString("source_title"), destRS.getString("Title"), id);
778
        success &= equals("Reference author string ", srcRS.getString("source_author"), destRS.getString("AuthorString"), id);
779
        success &= equals("Reference year ", normalizeYear(srcRS.getString("source_year")), destRS.getString("RefYear"), id);
780
        success &= isNull("NomRefCache", destRS);  //for ERMS no other value was found in 2014 value
781
        success &= equals("Reference link ", srcRS.getString("source_link"), destRS.getString("Link"), id);
782
        success &= equals("Reference note ", srcRS.getString("source_note"), destRS.getString("Notes"), id);
783
        //complete
784
        return success;
785
    }
786

    
787
    private Integer convertSourceTypeFk(String sourceType) {
788
        if (sourceType == null){
789
            return null;
790
        }else if ("d".equals(sourceType)){
791
            return 4;
792
        }else if ("e".equals(sourceType)){
793
            return 5;
794
        }else if ("p".equals(sourceType)){
795
            return 11;
796
        }else if ("i".equals(sourceType)){
797
            return 12;
798
        }
799
        return null;
800
    }
801
    private String convertSourceTypeCache(String sourceType) {
802
        if (sourceType == null){
803
            return null;
804
        }else if ("d".equals(sourceType)){
805
            return "database";
806
        }else if ("e".equals(sourceType)){
807
            return "informal reference";
808
        }else if ("p".equals(sourceType)){
809
            return "publication";
810
        }
811
        return null;
812
    }
813

    
814
    private boolean testReferenceCount() {
815
        int countSrc = source.getUniqueInteger("SELECT count(*) FROM sources ");
816
        int countDest = destination.getUniqueInteger("SELECT count(*) FROM Source s WHERE s."+ origErms);  // +1 for the source reference "erms" but this has no OriginalDB
817
        boolean success = equals("Reference count ", countSrc, countDest, "-1");
818
        return success;
819
    }
820

    
821
    //NOTE: there could be better parsing of source_year during import, this may also need better normalizing in the database
822
    private String normalizeYear(String yearStr) {
823
        if (StringUtils.isBlank(yearStr)){
824
            return yearStr;
825
        }
826
        yearStr = yearStr.trim();
827
        if (yearStr.matches("\\d{4}-\\d{2}")){
828
            yearStr = yearStr.substring(0, 5)+yearStr.substring(0, 2)+yearStr.substring(5);
829
        }
830
        if (yearStr.equals("20 Mar 1891")){
831
            yearStr = "20.3.1891";
832
        }
833
        if (yearStr.equals("July 1900")){
834
            yearStr = "7.1900";
835
        }
836
        return yearStr;
837
    }
838

    
839
    private boolean isNull(String attrName, ResultSet destRS) throws SQLException {
840
        Object value = destRS.getObject(attrName);
841
        if (value != null){
842
            String message = attrName + " was expected to be null but was: " + value.toString();
843
            logger.warn(message);
844
            return false;
845
        }else{
846
            logger.info(attrName + " was null as expected");
847
            return true;
848
        }
849
    }
850

    
851
    private boolean equals(String messageStart, Timestamp srcDate, Timestamp destDate, String id) {
852
        if (!CdmUtils.nullSafeEqual(srcDate, destDate)){
853
            String message = id + ": " + messageStart + " must be equal, but was not.\n Source: "+  srcDate + "; Destination: " + destDate;
854
            logger.warn(message);
855
            return false;
856
        }else{
857
            logger.info(messageStart + " were equal: " + srcDate);
858
            return true;
859
        }
860
    }
861

    
862
    private boolean equals(String messageStart, Integer nSrc, Integer nDest, String id) {
863
        String strId = id.equals("-1")? "": (id+ ": ");
864
        if (!CdmUtils.nullSafeEqual(nSrc,nDest)){
865
            String message = strId+ messageStart + " must be equal, but was not.\n Source: "+  nSrc + "; Destination: " + nDest;
866
            logger.warn(message);
867
            return false;
868
        }else{
869
            logger.info(strId + messageStart + " were equal: " + nSrc);
870
            return true;
871
        }
872
    }
873

    
874
    private boolean equals(String messageStart, String strSrc, String strDest, String id) {
875
        if (StringUtils.isBlank(strSrc)){
876
            strSrc = null;
877
        }else{
878
            strSrc = strSrc.trim();
879
        }
880
        //we do not trim strDest here because this should be done during import already. If not it should be shown here
881
        if (!CdmUtils.nullSafeEqual(strSrc, strDest)){
882
            int index = CdmUtils.diffIndex(strSrc, strDest);
883
            String message = id+ ": " + messageStart + " must be equal, but was not at "+index+".\n  Source:      "+  strSrc + "\n  Destination: " + strDest;
884
            logger.warn(message);
885
            return false;
886
        }else{
887
            logger.info(id+ ": " + messageStart + " were equal: " + strSrc);
888
            return true;
889
        }
890
    }
891

    
892
    protected Integer nullSafeInt(ResultSet rs, String columnName) throws SQLException {
893
        Object intObject = rs.getObject(columnName);
894
        if (intObject == null){
895
            return null;
896
        }else{
897
            return Integer.valueOf(intObject.toString());
898
        }
899
    }
900

    
901
//** ************* MAIN ********************************************/
902

    
903

    
904

    
905
    public static void main(String[] args){
906
        PesiErmsValidator validator = new PesiErmsValidator();
907
        validator.invoke(defaultSource, defaultDestination);
908
        System.exit(0);
909
    }
910
}
(1-1/2)