Project

General

Profile

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

    
10
package eu.etaxonomy.cdm.io.berlinModel.in;
11

    
12
import java.net.URI;
13
import java.sql.ResultSet;
14
import java.sql.SQLException;
15
import java.util.HashMap;
16
import java.util.Map;
17
import java.util.UUID;
18

    
19
import org.apache.commons.lang.StringUtils;
20
import org.apache.log4j.Logger;
21
import org.springframework.stereotype.Component;
22
import org.springframework.transaction.TransactionStatus;
23

    
24
import eu.etaxonomy.cdm.io.berlinModel.BerlinModelTransformer;
25
import eu.etaxonomy.cdm.io.berlinModel.in.validation.BerlinModelAreaImportValidator;
26
import eu.etaxonomy.cdm.io.common.CdmImportBase;
27
import eu.etaxonomy.cdm.io.common.IOValidator;
28
import eu.etaxonomy.cdm.io.common.ResultSetPartitioner;
29
import eu.etaxonomy.cdm.io.common.Source;
30
import eu.etaxonomy.cdm.model.common.Annotation;
31
import eu.etaxonomy.cdm.model.common.AnnotationType;
32
import eu.etaxonomy.cdm.model.common.CdmBase;
33
import eu.etaxonomy.cdm.model.common.ExtensionType;
34
import eu.etaxonomy.cdm.model.common.Language;
35
import eu.etaxonomy.cdm.model.common.Marker;
36
import eu.etaxonomy.cdm.model.common.MarkerType;
37
import eu.etaxonomy.cdm.model.common.OrderedTermVocabulary;
38
import eu.etaxonomy.cdm.model.common.OriginalSourceType;
39
import eu.etaxonomy.cdm.model.common.TermType;
40
import eu.etaxonomy.cdm.model.common.TermVocabulary;
41
import eu.etaxonomy.cdm.model.location.NamedArea;
42
import eu.etaxonomy.cdm.model.location.NamedAreaLevel;
43
import eu.etaxonomy.cdm.model.location.NamedAreaType;
44
import eu.etaxonomy.cdm.model.reference.Reference;
45

    
46

    
47
/**
48
 * @author a.mueller
49
 * @since 20.03.2008
50
 */
51
@Component
52
public class BerlinModelAreaImport  extends BerlinModelImportBase {
53

    
54
    private static final long serialVersionUID = -2810052908318645219L;
55
    private static final Logger logger = Logger.getLogger(BerlinModelAreaImport.class);
56

    
57
	public static final String NAMESPACE = "emArea";
58

    
59
	private static final String pluralString = "areas";
60
	private static final String dbTableName = "emArea";  //??
61

    
62
	public BerlinModelAreaImport(){
63
		super(dbTableName, pluralString);
64
	}
65

    
66
	@Override
67
	protected String getIdQuery(BerlinModelImportState state) {
68
		String result = " SELECT AreaId FROM " + getTableName();
69
//		if (StringUtils.isNotBlank(state.getConfig().getOccurrenceFilter())){
70
//			result += " WHERE " +  state.getConfig().getOccurrenceFilter();
71
//		}
72
		return result;
73
	}
74

    
75
	@Override
76
	protected String getRecordQuery(BerlinModelImportConfigurator config) {
77
		String strQuery =
78
		          " SELECT * "
79
		        + " FROM emArea a "
80
                + " WHERE (a.AreaId IN (" + ID_LIST_TOKEN + ")  )"
81
//		        + " ORDER BY PTaxon.RIdentifier"
82
                ;
83
		return strQuery;
84
	}
85

    
86
	private Map<Integer, NamedArea> euroMedAreas = new HashMap<>();
87

    
88

    
89
	private TermVocabulary<NamedArea> createEuroMedAreas(BerlinModelImportState state) throws SQLException {
90

    
91

    
92
	    logger.warn("Start creating E+M areas");
93
		Source source = state.getConfig().getSource();
94
		Reference sourceReference = state.getConfig().getSourceReference();
95

    
96
		TransactionStatus txStatus = this.startTransaction();
97

    
98
		sourceReference = getSourceReference(sourceReference);
99

    
100
		TermVocabulary<NamedArea> euroMedAreasVoc = makeEmptyEuroMedVocabulary();
101

    
102
		MarkerType eurMarkerType = getMarkerType(state, BerlinModelTransformer.uuidEurArea, "eur", "eur Area", "eur", getEuroMedMarkerTypeVoc());
103
		MarkerType euroMedAreaMarkerType = getMarkerType(state, BerlinModelTransformer.uuidEurMedArea, "EuroMedArea", "EuroMedArea", "EuroMedArea", getEuroMedMarkerTypeVoc());
104
		ExtensionType isoCodeExtType = getExtensionType(state, BerlinModelTransformer.uuidIsoCode, "IsoCode", "IsoCode", "iso");
105
		ExtensionType tdwgCodeExtType = getExtensionType(state, BerlinModelTransformer.uuidTdwgAreaCode, "TDWG code", "TDWG Area code", "tdwg");
106
		ExtensionType mclCodeExtType = getExtensionType(state, BerlinModelTransformer.uuidMclCode, "MCL code", "MedCheckList code", "mcl");
107
		NamedAreaLevel areaLevelTop = getNamedAreaLevel(state, BerlinModelTransformer.uuidEuroMedAreaLevelTop, "Euro+Med top area level", "Euro+Med top area level. This level is only to be used for the area representing the complete Euro+Med area", "e+m top", null);
108
		NamedAreaLevel areaLevelEm1 = getNamedAreaLevel(state, BerlinModelTransformer.uuidEuroMedAreaLevelFirst, "Euro+Med 1. area level", "Euro+Med 1. area level", "e+m 1.", null);
109
		NamedAreaLevel areaLevelEm2 = getNamedAreaLevel(state, BerlinModelTransformer.uuidEuroMedAreaLevelSecond, "Euro+Med 2. area level", "Euro+Med 2. area level", "Euro+Med 1. area level", null);
110

    
111

    
112
		String sql = "SELECT * , CASE WHEN EMCode = 'EM' THEN 'a' ELSE 'b' END as isEM " +
113
				" FROM emArea " +
114
				" ORDER BY isEM, EMCode";
115
		ResultSet rs = source.getResultSet(sql);
116

    
117
		NamedArea euroMedArea = null;
118
		NamedArea lastLevel1Area = null;
119

    
120
		//euroMedArea (EMCode = 'EM')
121
		rs.next();
122
		euroMedArea = makeSingleEuroMedArea(rs, eurMarkerType, euroMedAreaMarkerType, isoCodeExtType, tdwgCodeExtType, mclCodeExtType,
123
				areaLevelTop, areaLevelEm1 , areaLevelEm2, sourceReference, euroMedArea, lastLevel1Area);
124
		euroMedAreasVoc.addTerm(euroMedArea);
125

    
126
		//all other areas
127
		while (rs.next()){
128
			NamedArea newArea = makeSingleEuroMedArea(rs, eurMarkerType, euroMedAreaMarkerType,
129
					isoCodeExtType, tdwgCodeExtType, mclCodeExtType,
130
					areaLevelTop, areaLevelEm1 , areaLevelEm2, sourceReference, euroMedArea, lastLevel1Area);
131
			if (newArea != null){
132
    			euroMedAreasVoc.addTerm(newArea);
133
    			if (newArea.getPartOf().equals(euroMedArea)){
134
    				lastLevel1Area = newArea;
135
    			}
136
			}
137
		}
138
		emAreaFinetuning(euroMedAreasVoc, areaLevelEm2);
139

    
140
		markAreasAsHidden(state, euroMedAreasVoc);
141

    
142
	    getVocabularyService().saveOrUpdate(euroMedAreasVoc);
143

    
144
		try {
145
            commitTransaction(txStatus);
146
        } catch (Exception e) {
147
             e.printStackTrace();
148
             logger.error("An exception occurred when trying to commit E+M Areas");
149
        }
150
		logger.warn("Created E+M areas");
151

    
152
		return euroMedAreasVoc;
153
	}
154

    
155
	/**
156
     * @param areaLevelEm2
157
	 * @param euroMedAreas2
158
     */
159
    private void emAreaFinetuning(TermVocabulary<NamedArea> euroMedAreas, NamedAreaLevel areaLevelEm2) {
160
        //CZ
161
        NamedArea oldArea = euroMedAreas.getTermByIdInvocabulary("Cz");
162
        makeSubterm(oldArea, euroMedAreas.getTermByIdInvocabulary("Cs"), areaLevelEm2);
163
        makeSubterm(oldArea, euroMedAreas.getTermByIdInvocabulary("Sk"), areaLevelEm2);
164

    
165
        //Ju
166
        oldArea = euroMedAreas.getTermByIdInvocabulary("Ju");
167
        makeSubterm(oldArea, euroMedAreas.getTermByIdInvocabulary("BH"), areaLevelEm2);
168
        makeSubterm(oldArea, euroMedAreas.getTermByIdInvocabulary("Cg"), areaLevelEm2);
169
        makeSubterm(oldArea, euroMedAreas.getTermByIdInvocabulary("Ct"), areaLevelEm2);
170
        makeSubterm(oldArea, euroMedAreas.getTermByIdInvocabulary("Mk"), areaLevelEm2);
171
        makeSubterm(oldArea, euroMedAreas.getTermByIdInvocabulary("Sl"), areaLevelEm2);
172
        makeSubterm(oldArea, euroMedAreas.getTermByIdInvocabulary("Sr"), areaLevelEm2);
173

    
174
        //IJ
175
        oldArea = euroMedAreas.getTermByIdInvocabulary("IJ");
176
        makeSubterm(oldArea, euroMedAreas.getTermByIdInvocabulary("Ir"), areaLevelEm2);
177
        makeSubterm(oldArea, euroMedAreas.getTermByIdInvocabulary("Jo"), areaLevelEm2);
178

    
179
        //LS
180
        oldArea = euroMedAreas.getTermByIdInvocabulary("LS");
181
        makeSubterm(oldArea, euroMedAreas.getTermByIdInvocabulary("Le"), areaLevelEm2);
182
        makeSubterm(oldArea, euroMedAreas.getTermByIdInvocabulary("Sy"), areaLevelEm2);
183

    
184
    }
185

    
186
    //5.Mark areas to be hidden #3979 .5
187
    private void markAreasAsHidden(BerlinModelImportState state, TermVocabulary<NamedArea> euroMedAreasVoc) {
188

    
189
        try {
190

    
191
            @SuppressWarnings("unchecked")
192
            TermVocabulary<MarkerType> vocUserDefinedMarkerTypes = getVocabularyService().find(CdmImportBase.uuidUserDefinedMarkerTypeVocabulary);
193
            if (vocUserDefinedMarkerTypes == null){
194
                String message = "Marker type vocabulary could not be found. Hidden areas not added.";
195
                logger.error(message);
196
                System.out.println(message);
197
            }
198
            MarkerType hiddenAreaMarkerType = getMarkerType(state, BerlinModelTransformer.uuidHiddenArea,
199
                    "Hidden Area","Used to hide distributions for the named areas in publications", null, getEuroMedMarkerTypeVoc());
200

    
201
            //Add hidden area marker to Rs(C) and Rs(N)
202
            hideArea(euroMedAreasVoc, hiddenAreaMarkerType, BerlinModelTransformer.uuidRs);
203
            hideArea(euroMedAreasVoc, hiddenAreaMarkerType, BerlinModelTransformer.uuidRs_B);
204
            hideArea(euroMedAreasVoc, hiddenAreaMarkerType, BerlinModelTransformer.uuidRs_C);
205
            hideArea(euroMedAreasVoc, hiddenAreaMarkerType, BerlinModelTransformer.uuidRs_E);
206
            hideArea(euroMedAreasVoc, hiddenAreaMarkerType, BerlinModelTransformer.uuidRs_N);
207
            hideArea(euroMedAreasVoc, hiddenAreaMarkerType, BerlinModelTransformer.uuidRs_K);
208
            hideArea(euroMedAreasVoc, hiddenAreaMarkerType, BerlinModelTransformer.uuidRs_W);
209
        } catch (Exception e) {
210
            e.printStackTrace();
211
            logger.error("Exception in markAreasAsHidden: " + e.getMessage());
212
        }
213

    
214
    }
215

    
216
    private void hideArea(TermVocabulary<NamedArea> euroMedAreasVoc, MarkerType hiddenAreaMarkerType, UUID areaUuid) {
217
        for (NamedArea namedArea : euroMedAreasVoc){
218
            if (namedArea.getUuid().equals(areaUuid)){
219
                namedArea.addMarker(Marker.NewInstance(hiddenAreaMarkerType, true));
220
                return;
221
            }
222
        }
223
    }
224

    
225
    /**
226
     * @param oldArea
227
     * @param namedArea
228
     * @param areaLevelEm2
229
     */
230
    private void makeSubterm(NamedArea oldArea, NamedArea namedArea, NamedAreaLevel areaLevelEm2) {
231
        namedArea.setLevel(areaLevelEm2);
232
        namedArea.setPartOf(oldArea);
233
    }
234

    
235

    
236
	/**
237
	 * @param eurMarkerType
238
	 * @param euroMedAreaMarkerType
239
	 * @param isoCodeExtType
240
	 * @param tdwgCodeExtType
241
	 * @param mclCodeExtType
242
	 * @param rs
243
	 * @param areaLevelEm2
244
	 * @param areaLevelEm1
245
	 * @param areaLevelTop
246
	 * @throws SQLException
247
	 */
248
	private NamedArea makeSingleEuroMedArea(ResultSet rs, MarkerType eurMarkerType,
249
			MarkerType euroMedAreaMarkerType, ExtensionType isoCodeExtType,
250
			ExtensionType tdwgCodeExtType, ExtensionType mclCodeExtType,
251
			NamedAreaLevel areaLevelTop, NamedAreaLevel areaLevelEm1, NamedAreaLevel areaLevelEm2,
252
			Reference sourceReference, NamedArea euroMedArea, NamedArea level1Area) throws SQLException {
253

    
254
	    Integer areaId = rs.getInt("AreaId");
255
		String emCode = nullSafeTrim(rs.getString("EMCode"));
256
		String isoCode = nullSafeTrim(rs.getString("ISOCode"));
257
		String tdwgCode = nullSafeTrim(rs.getString("TDWGCode"));
258
		String unit = nullSafeTrim(rs.getString("Unit"));
259
//				      ,[Status]
260
//				      ,[OutputOrder]
261
		boolean eurMarker = rs.getBoolean("eur");
262
		boolean euroMedAreaMarker = rs.getBoolean("EuroMedArea");
263
		String notes = nullSafeTrim(rs.getString("Notes"));
264
		String mclCode = nullSafeTrim(rs.getString("MCLCode"));
265
		String geoSearch = nullSafeTrim(rs.getString("NameForGeoSearch"));
266

    
267

    
268
		if (isBlank(emCode)){
269
			emCode = unit;
270
		}
271

    
272
		//uuid
273
		UUID uuid = BerlinModelTransformer.getEMAreaUuid(emCode);
274
		NamedArea area = (NamedArea)getTermService().find(uuid);
275
		if (area == null){
276
			//label
277
			area = NamedArea.NewInstance(geoSearch, unit, emCode);
278
			if (uuid != null){
279
				area.setUuid(uuid);
280
			}else{
281
			    if (areaId == 211 || areaId == 213){  //Additional Azores and Canary Is. area are merged into primary area, see also area.addSource part below
282
			        return null;
283
			    }
284
				logger.warn("Uuid for emCode could not be defined: " + emCode);
285
			}
286
		}
287

    
288

    
289
		//code
290
		area.setIdInVocabulary(emCode);
291
		//notes
292
		if (StringUtils.isNotEmpty(notes)){
293
			area.addAnnotation(Annotation.NewInstance(notes, AnnotationType.EDITORIAL(), Language.DEFAULT()));
294
		}
295
		//markers
296
		area.addMarker(Marker.NewInstance(eurMarkerType, eurMarker));
297
		area.addMarker(Marker.NewInstance(euroMedAreaMarkerType, euroMedAreaMarker));
298

    
299
		//extensions
300
		if (isNotBlank(isoCode)){
301
			area.addExtension(isoCode, isoCodeExtType);
302
		}
303
		if (isNotBlank(tdwgCode)){
304
			area.addExtension(tdwgCode, tdwgCodeExtType);
305
		}
306
		if (isNotBlank(mclCode)){
307
			area.addExtension(mclCode, mclCodeExtType);
308
		}
309

    
310
		//type
311
		area.setType(NamedAreaType.ADMINISTRATION_AREA());
312

    
313
		//source
314
		area.addSource(OriginalSourceType.Import, String.valueOf(areaId), NAMESPACE, sourceReference, null);
315
		//add duplicate area ids for canary
316
		if (areaId == 624){ //Canary Is.
317
		    area.addSource(OriginalSourceType.Import, String.valueOf(213), NAMESPACE, sourceReference, null);
318
		}
319
		if (areaId == 210){//Azores
320
            area.addSource(OriginalSourceType.Import, String.valueOf(211), NAMESPACE, sourceReference, null);
321
        }
322

    
323
		//parent
324
		if (euroMedArea != null){
325
			if (emCode.contains("(")){
326
				area.setPartOf(level1Area);
327
				area.setLevel(areaLevelEm2);
328
			}else{
329
				area.setPartOf(euroMedArea);
330
				area.setLevel(areaLevelEm1);
331
			}
332
		}else{
333
			area.setLevel(areaLevelTop);
334
		}
335
		this.euroMedAreas.put(areaId, area);
336

    
337
		//save
338
		getTermService().saveOrUpdate(area);
339

    
340
		return area;
341
	}
342

    
343
	private String nullSafeTrim(String string) {
344
		if (string == null){
345
			return null;
346
		}else{
347
			return string.trim();
348
		}
349
	}
350

    
351
	/**
352
	 *
353
	 */
354
	private TermVocabulary<NamedArea> makeEmptyEuroMedVocabulary() {
355
		TermType type = TermType.NamedArea;
356
		String description = "Euro+Med area vocabulary";
357
		String label = "E+M areas";
358
		String abbrev = null;
359
		URI termSourceUri = null;
360
		OrderedTermVocabulary<NamedArea> result = OrderedTermVocabulary.NewInstance(type, description, label, abbrev, termSourceUri);
361

    
362
		result.setUuid(BerlinModelTransformer.uuidVocEuroMedAreas);
363
		getVocabularyService().save(result);
364
		return result;
365
	}
366

    
367
	@Override
368
	public boolean doPartition(@SuppressWarnings("rawtypes") ResultSetPartitioner partitioner, BerlinModelImportState state)  {
369
	    TermVocabulary<?> voc = getVocabularyService().find(BerlinModelTransformer.uuidVocEuroMedAreas);
370
	    if (voc == null){
371
	        try {
372
	            createEuroMedAreas(state);
373
	        } catch (SQLException e) {
374
	            logger.warn("Exception when creating areas: " + e.getMessage());
375
	            e.printStackTrace();
376
	        }
377
        }
378
	    return true;
379
	}
380

    
381

    
382
	@Override
383
	public Map<Object, Map<String, ? extends CdmBase>> getRelatedObjectsForPartition(ResultSet rs, BerlinModelImportState state) {
384

    
385
		Map<Object, Map<String, ? extends CdmBase>> result = new HashMap<>();
386
		return result;
387
	}
388

    
389
	@Override
390
	protected boolean doCheck(BerlinModelImportState state){
391
		IOValidator<BerlinModelImportState> validator = new BerlinModelAreaImportValidator();
392
		return validator.validate(state);
393
	}
394

    
395

    
396
	@Override
397
	protected boolean isIgnore(BerlinModelImportState state){
398
		if (! (state.getConfig().isDoOccurrence() || state.getConfig().isDoCommonNames())){
399
			return true;
400
		}else{
401
			if (!this.checkSqlServerColumnExists(state.getConfig().getSource(), "emArea", "AreaId")){
402
				logger.error("emArea table or AreaId column do not exist. Must ignore area import");
403
				return true;
404
			}else{
405
				return false;
406
			}
407
		}
408
	}
409

    
410
}
(1-1/22)