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.excel.common;
|
11
|
|
12
|
import java.io.ByteArrayInputStream;
|
13
|
import java.io.FileNotFoundException;
|
14
|
import java.net.URI;
|
15
|
import java.util.ArrayList;
|
16
|
import java.util.HashMap;
|
17
|
import java.util.Map;
|
18
|
import java.util.UUID;
|
19
|
|
20
|
import org.apache.commons.lang.StringUtils;
|
21
|
import org.apache.log4j.Logger;
|
22
|
import org.springframework.transaction.TransactionStatus;
|
23
|
|
24
|
import eu.etaxonomy.cdm.common.CdmUtils;
|
25
|
import eu.etaxonomy.cdm.common.ExcelUtils;
|
26
|
import eu.etaxonomy.cdm.io.common.CdmImportBase;
|
27
|
import eu.etaxonomy.cdm.io.distribution.excelupdate.ExcelDistributionUpdateConfigurator;
|
28
|
import eu.etaxonomy.cdm.io.excel.taxa.NormalExplicitImportConfigurator;
|
29
|
import eu.etaxonomy.cdm.io.excel.taxa.TaxonListImportConfigurator;
|
30
|
import eu.etaxonomy.cdm.model.agent.TeamOrPersonBase;
|
31
|
import eu.etaxonomy.cdm.model.common.CdmBase;
|
32
|
import eu.etaxonomy.cdm.model.common.TimePeriod;
|
33
|
import eu.etaxonomy.cdm.model.name.NomenclaturalCode;
|
34
|
import eu.etaxonomy.cdm.model.reference.Reference;
|
35
|
import eu.etaxonomy.cdm.model.reference.ReferenceFactory;
|
36
|
import eu.etaxonomy.cdm.model.taxon.TaxonBase;
|
37
|
import eu.etaxonomy.cdm.strategy.parser.TimePeriodParser;
|
38
|
|
39
|
/**
|
40
|
* @author a.babadshanjan
|
41
|
* @since 17.12.2008
|
42
|
*/
|
43
|
public abstract class ExcelImportBase<STATE extends ExcelImportState<CONFIG, ROW>, CONFIG extends ExcelImportConfiguratorBase, ROW extends ExcelRowBase>
|
44
|
extends CdmImportBase<CONFIG, STATE> {
|
45
|
|
46
|
private static final long serialVersionUID = 2759164811664484732L;
|
47
|
private static final Logger logger = Logger.getLogger(ExcelImportBase.class);
|
48
|
|
49
|
protected static final String SCIENTIFIC_NAME_COLUMN = "ScientificName";
|
50
|
|
51
|
private ArrayList<HashMap<String, String>> recordList = null;
|
52
|
|
53
|
private ExcelImportConfiguratorBase configurator = null;
|
54
|
|
55
|
|
56
|
/** Reads data from an Excel file and stores them into a CDM DB.
|
57
|
*
|
58
|
* @param config
|
59
|
* @param stores (not used)
|
60
|
*/
|
61
|
@Override
|
62
|
protected void doInvoke(STATE state){
|
63
|
|
64
|
logger.debug("Importing excel data");
|
65
|
|
66
|
configurator = state.getConfig();
|
67
|
|
68
|
NomenclaturalCode nc = getConfigurator().getNomenclaturalCode();
|
69
|
if (nc == null && needsNomenclaturalCode()) {
|
70
|
logger.error("Nomenclatural code could not be determined. Skip invoke.");
|
71
|
state.setUnsuccessfull();
|
72
|
return;
|
73
|
}
|
74
|
URI source = null;
|
75
|
|
76
|
byte[] data = null;
|
77
|
// read and save all rows of the excel worksheet
|
78
|
if ((state.getConfig() instanceof NormalExplicitImportConfigurator || state.getConfig() instanceof ExcelDistributionUpdateConfigurator || state.getConfig() instanceof TaxonListImportConfigurator) &&
|
79
|
(state.getConfig().getStream() != null || state.getConfig().getStream() != null)){
|
80
|
data = state.getConfig().getStream();
|
81
|
} else{
|
82
|
source = state.getConfig().getSource();
|
83
|
}
|
84
|
|
85
|
|
86
|
|
87
|
String sheetName = getWorksheetName();
|
88
|
|
89
|
|
90
|
if (data != null){
|
91
|
try {
|
92
|
ByteArrayInputStream stream = new ByteArrayInputStream(data);
|
93
|
recordList = ExcelUtils.parseXLS(stream, sheetName);
|
94
|
} catch (FileNotFoundException e) {
|
95
|
throw new RuntimeException(e);
|
96
|
}
|
97
|
}else{
|
98
|
try {
|
99
|
recordList = ExcelUtils.parseXLS(source, sheetName);
|
100
|
} catch (FileNotFoundException e) {
|
101
|
String message = "File not found: " + source;
|
102
|
warnProgress(state, message, e);
|
103
|
logger.error(message);
|
104
|
state.setUnsuccessfull();
|
105
|
return;
|
106
|
}
|
107
|
}
|
108
|
|
109
|
handleRecordList(state, source);
|
110
|
logger.debug("End excel data import");
|
111
|
return;
|
112
|
}
|
113
|
|
114
|
protected boolean needsNomenclaturalCode() {
|
115
|
return true;
|
116
|
}
|
117
|
|
118
|
/**
|
119
|
* @param state
|
120
|
* @param success
|
121
|
* @param source
|
122
|
* @return
|
123
|
*/
|
124
|
private void handleRecordList(STATE state, URI source) {
|
125
|
Integer startingLine = 2;
|
126
|
if (recordList != null) {
|
127
|
HashMap<String,String> record = null;
|
128
|
|
129
|
TransactionStatus txStatus = startTransaction();
|
130
|
|
131
|
//first pass
|
132
|
state.setCurrentLine(startingLine);
|
133
|
for (int i = 0; i < recordList.size(); i++) {
|
134
|
record = recordList.get(i);
|
135
|
analyzeRecord(record, state);
|
136
|
state.setOriginalRecord(record);
|
137
|
try {
|
138
|
firstPass(state);
|
139
|
} catch (Exception e) {
|
140
|
e.printStackTrace();
|
141
|
}finally{
|
142
|
state.incCurrentLine();
|
143
|
}
|
144
|
}
|
145
|
//second pass
|
146
|
state.setCurrentLine(startingLine);
|
147
|
for (int i = 0; i < recordList.size(); i++) {
|
148
|
record = recordList.get(i);
|
149
|
analyzeRecord(record, state);
|
150
|
state.setOriginalRecord(record);
|
151
|
secondPass(state);
|
152
|
state.incCurrentLine();
|
153
|
}
|
154
|
if (configurator.isDeduplicateReferences()){
|
155
|
getReferenceService().deduplicate(Reference.class, null, null);
|
156
|
}
|
157
|
if (configurator.isDeduplicateAuthors()){
|
158
|
getAgentService().deduplicate(TeamOrPersonBase.class, null, null);
|
159
|
}
|
160
|
commitTransaction(txStatus);
|
161
|
}else{
|
162
|
logger.warn("No records found in " + source);
|
163
|
}
|
164
|
return;
|
165
|
}
|
166
|
|
167
|
/**
|
168
|
* To define a worksheet name override this method. Otherwise the first worksheet is taken.
|
169
|
* @return worksheet name. <code>null</null> if not worksheet is defined.
|
170
|
*/
|
171
|
protected String getWorksheetName() {
|
172
|
return null;
|
173
|
}
|
174
|
|
175
|
@Override
|
176
|
protected boolean doCheck(STATE state) {
|
177
|
boolean result = true;
|
178
|
logger.warn("No check implemented for Excel import");
|
179
|
return result;
|
180
|
}
|
181
|
|
182
|
/**
|
183
|
*
|
184
|
*
|
185
|
* @param record
|
186
|
* @return
|
187
|
*/
|
188
|
protected abstract void analyzeRecord(HashMap<String,String> record, STATE state);
|
189
|
|
190
|
protected abstract void firstPass(STATE state);
|
191
|
protected abstract void secondPass(STATE state);
|
192
|
|
193
|
|
194
|
public ExcelImportConfiguratorBase getConfigurator() {
|
195
|
return configurator;
|
196
|
}
|
197
|
|
198
|
|
199
|
protected int floatString2IntValue(String value) {
|
200
|
int intValue = 0;
|
201
|
try {
|
202
|
Float fobj = new Float(Float.parseFloat(value));
|
203
|
intValue = fobj.intValue();
|
204
|
if (logger.isDebugEnabled()) { logger.debug("Value formatted: " + intValue); }
|
205
|
} catch (NumberFormatException ex) {
|
206
|
logger.error(value + " is not an integer");
|
207
|
}
|
208
|
return intValue;
|
209
|
}
|
210
|
|
211
|
protected String floatString2IntStringValue(String value) {
|
212
|
int i = floatString2IntValue(value);
|
213
|
return String.valueOf(i);
|
214
|
}
|
215
|
|
216
|
|
217
|
/**
|
218
|
* @param start
|
219
|
* @param end
|
220
|
* @return
|
221
|
*/
|
222
|
protected TimePeriod getTimePeriod(String start, String end) {
|
223
|
String strPeriod = CdmUtils.concat(" - ", start, end);
|
224
|
TimePeriod result = TimePeriodParser.parseString(strPeriod);
|
225
|
return result;
|
226
|
}
|
227
|
|
228
|
/**
|
229
|
* Returns the value of the record map for the given key.
|
230
|
* The value is trimmed and empty values are set to <code>null</code>.
|
231
|
* @param record
|
232
|
* @param originalKey
|
233
|
* @return the value
|
234
|
*/
|
235
|
protected String getValue(Map<String, String> record, String originalKey) {
|
236
|
String value = record.get(originalKey);
|
237
|
if (! StringUtils.isBlank(value)) {
|
238
|
if (logger.isDebugEnabled()) { logger.debug(originalKey + ": " + value); }
|
239
|
value = CdmUtils.removeDuplicateWhitespace(value.trim()).toString();
|
240
|
return value;
|
241
|
}else{
|
242
|
return null;
|
243
|
}
|
244
|
}
|
245
|
|
246
|
|
247
|
/**
|
248
|
* Returns the taxon for the given CDM uuid. If no taxon exists for the given id
|
249
|
* no record is returned. If a name cache, name title cache (full name) or
|
250
|
* taxon title cache column is given the name is checked against the given columns.
|
251
|
* If they don't manage it is logged as a warning in import result.
|
252
|
* <BR>If clazz is given, only objects of the given class are loaded.
|
253
|
*
|
254
|
*
|
255
|
* @param state
|
256
|
* @param colTaxonUuid taxon uuid column
|
257
|
* @param colNameCache name cache column (if exists)
|
258
|
* @param colNameTitleCache name title cache column (if exists)
|
259
|
* @param colTaxonTitleCache taxon title cache column (if exists)
|
260
|
* @param clazz the clazz null
|
261
|
* @param line the row, for debug information
|
262
|
* @return the taxon to load
|
263
|
*/
|
264
|
protected <T extends TaxonBase<?>> T getTaxonByCdmId(STATE state, String colTaxonUuid,
|
265
|
String colNameCache, String colNameTitleCache, String colTaxonTitleCache,
|
266
|
Class<T> clazz, String line) {
|
267
|
|
268
|
HashMap<String, String> record = state.getOriginalRecord();
|
269
|
String strUuidTaxon = record.get(colTaxonUuid);
|
270
|
if (strUuidTaxon != null){
|
271
|
UUID uuidTaxon;
|
272
|
try {
|
273
|
uuidTaxon = UUID.fromString(strUuidTaxon);
|
274
|
} catch (Exception e) {
|
275
|
state.getResult().addError("Taxon uuid has incorrect format. Taxon could not be loaded. Data not imported.", null, line);
|
276
|
return null;
|
277
|
}
|
278
|
TaxonBase<?> result = getTaxonService().find(uuidTaxon);
|
279
|
//TODO load only objects of correct class
|
280
|
if (result != null && clazz != null && !result.isInstanceOf(clazz)){
|
281
|
result = null;
|
282
|
}
|
283
|
|
284
|
|
285
|
if (result == null){
|
286
|
state.getResult().addError("Taxon for uuid "+strUuidTaxon+" could not be found in database. "
|
287
|
+ "Taxon could not be loaded. Data not imported.", null, line);
|
288
|
}else{
|
289
|
verifyName(state, colNameCache, colNameTitleCache, colTaxonTitleCache, line, record, result);
|
290
|
}
|
291
|
result = CdmBase.deproxy(result, clazz);
|
292
|
|
293
|
|
294
|
return CdmBase.deproxy(result, clazz);
|
295
|
}else{
|
296
|
String message = "No taxon identifier found";
|
297
|
state.getResult().addWarning(message, null, line);
|
298
|
return null;
|
299
|
}
|
300
|
}
|
301
|
|
302
|
|
303
|
/**
|
304
|
* @see #getTaxonByCdmId(ExcelImportState, String, String, String, String, Class, String)
|
305
|
*/
|
306
|
protected void verifyName(STATE state, String colNameCache, String colNameTitleCache, String colTaxonTitleCache,
|
307
|
String line, HashMap<String, String> record, TaxonBase<?> result) {
|
308
|
//nameCache
|
309
|
String strExpectedNameCache = record.get(colNameCache);
|
310
|
String nameCache = result.getName() == null ? null : result.getName().getNameCache();
|
311
|
if (isNotBlank(strExpectedNameCache) && (!strExpectedNameCache.equals(nameCache))){
|
312
|
String message = "Name cache (%s) does not match expected name (%s)";
|
313
|
message = String.format(message, nameCache==null? "null":nameCache, strExpectedNameCache);
|
314
|
state.getResult().addWarning(message, null, line);
|
315
|
}
|
316
|
//name title
|
317
|
String strExpectedNameTitleCache = record.get(colNameTitleCache);
|
318
|
String nameTitleCache = result.getName() == null ? null : result.getName().getTitleCache();
|
319
|
if (isNotBlank(strExpectedNameTitleCache) && (!strExpectedNameTitleCache.equals(nameTitleCache))){
|
320
|
String message = "Name title cache (%s) does not match expected name (%s)";
|
321
|
message = String.format(message, nameTitleCache==null? "null":nameTitleCache, strExpectedNameTitleCache);
|
322
|
state.getResult().addWarning(message, null, line);
|
323
|
}
|
324
|
//taxon title cache
|
325
|
String strExpectedTaxonTitleCache = record.get(colTaxonTitleCache);
|
326
|
String taxonTitleCache = result.getTitleCache();
|
327
|
if (isNotBlank(strExpectedTaxonTitleCache) && (!strExpectedTaxonTitleCache.equals(taxonTitleCache))){
|
328
|
String message = "Name cache (%s) does not match expected name (%s)";
|
329
|
message = String.format(message, taxonTitleCache==null? "null":taxonTitleCache, strExpectedTaxonTitleCache);
|
330
|
state.getResult().addWarning(message, null, line);
|
331
|
}
|
332
|
}
|
333
|
|
334
|
|
335
|
/**
|
336
|
* Non transaction save method to retrieve the source reference
|
337
|
* if either existent or not in the database (uses check for uuid).
|
338
|
*
|
339
|
* @param state
|
340
|
* @return the source reference
|
341
|
*/
|
342
|
protected Reference getSourceReference(STATE state) {
|
343
|
|
344
|
Reference sourceRef = state.getSourceReference();
|
345
|
if (sourceRef != null){
|
346
|
return sourceRef;
|
347
|
}
|
348
|
UUID uuid = state.getConfig().getSourceRefUuid();
|
349
|
if (uuid == null){
|
350
|
sourceRef = state.getConfig().getSourceReference();
|
351
|
if (sourceRef != null){
|
352
|
uuid = sourceRef.getUuid();
|
353
|
}
|
354
|
}
|
355
|
if (uuid != null){
|
356
|
Reference existingRef = getReferenceService().find(uuid);
|
357
|
if (existingRef != null){
|
358
|
sourceRef = existingRef;
|
359
|
}
|
360
|
// else if (sourceRef != null){
|
361
|
// getReferenceService().save(sourceRef);
|
362
|
// }
|
363
|
}
|
364
|
if (sourceRef == null){
|
365
|
sourceRef = ReferenceFactory.newGeneric();
|
366
|
String title = state.getConfig().getSourceNameString();
|
367
|
sourceRef.setTitle(title);
|
368
|
state.getConfig().setSourceReference(sourceRef);
|
369
|
}
|
370
|
state.setSourceReference(sourceRef);
|
371
|
|
372
|
return sourceRef;
|
373
|
}
|
374
|
}
|