Project

General

Profile

Download (14 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.pesi.erms;
11

    
12
import java.lang.reflect.Method;
13
import java.sql.ResultSet;
14
import java.sql.ResultSetMetaData;
15
import java.sql.SQLException;
16
import java.sql.Timestamp;
17
import java.util.HashMap;
18
import java.util.HashSet;
19
import java.util.Map;
20
import java.util.Set;
21
import java.util.UUID;
22

    
23
import org.apache.commons.lang3.StringUtils;
24
import org.apache.log4j.Logger;
25
import org.joda.time.DateTime;
26

    
27
import eu.etaxonomy.cdm.common.CdmUtils;
28
import eu.etaxonomy.cdm.io.common.CdmImportBase;
29
import eu.etaxonomy.cdm.io.common.ICdmIO;
30
import eu.etaxonomy.cdm.io.common.IImportConfigurator.EDITOR;
31
import eu.etaxonomy.cdm.io.common.IPartitionedIO;
32
import eu.etaxonomy.cdm.io.common.ImportHelper;
33
import eu.etaxonomy.cdm.io.common.ResultSetPartitioner;
34
import eu.etaxonomy.cdm.io.common.Source;
35
import eu.etaxonomy.cdm.io.common.mapping.DbImportMapping;
36
import eu.etaxonomy.cdm.model.common.AnnotatableEntity;
37
import eu.etaxonomy.cdm.model.common.Annotation;
38
import eu.etaxonomy.cdm.model.common.AnnotationType;
39
import eu.etaxonomy.cdm.model.common.CdmBase;
40
import eu.etaxonomy.cdm.model.common.ExtensionType;
41
import eu.etaxonomy.cdm.model.common.IdentifiableEntity;
42
import eu.etaxonomy.cdm.model.common.Language;
43
import eu.etaxonomy.cdm.model.common.MarkerType;
44
import eu.etaxonomy.cdm.model.permission.User;
45

    
46
/**
47
 * @author a.mueller
48
 * @since 20.03.2008
49
 */
50
public abstract class ErmsImportBase<CDM_BASE extends CdmBase>
51
             extends CdmImportBase<ErmsImportConfigurator, ErmsImportState>
52
             implements ICdmIO<ErmsImportState>, IPartitionedIO<ErmsImportState> {
53

    
54
    private static final long serialVersionUID = 3856605408484122428L;
55
    private static final Logger logger = Logger.getLogger(ErmsImportBase.class);
56

    
57
	public static final UUID ID_IN_SOURCE_EXT_UUID = UUID.fromString("23dac094-e793-40a4-bad9-649fc4fcfd44");
58

    
59
	//NAMESPACES
60

    
61
	protected static final String AREA_NAMESPACE = "gu";
62
	protected static final String DR_NAMESPACE = "dr";
63
	protected static final String IMAGE_NAMESPACE = "Images";
64
	protected static final String LINKS_NAMESPACE = "Links";
65
	protected static final String NOTES_NAMESPACE = "Notes";
66
	protected static final String LANGUAGE_NAMESPACE = "Language";
67
	protected static final String REFERENCE_NAMESPACE = "Source";
68
	protected static final String SOURCEUSE_NAMESPACE = "tu_sources";
69
	protected static final String TAXON_NAMESPACE = "Taxon";
70
	protected static final String NAME_NAMESPACE = "TaxonName";
71
	protected static final String VERNACULAR_NAMESPACE = "Vernaculars";
72
	protected static final String FEATURE_NAMESPACE = "note.type";
73
	protected static final String EXTENSION_TYPE_NAMESPACE = "ExtensionType";
74

    
75
	private String pluralString;
76
	private String dbTableName;
77
	//TODO needed?
78
	private Class cdmTargetClass;
79

    
80
	public ErmsImportBase(String pluralString, String dbTableName, Class cdmTargetClass) {
81
		this.pluralString = pluralString;
82
		this.dbTableName = dbTableName;
83
		this.cdmTargetClass = cdmTargetClass;
84
	}
85

    
86
	@Override
87
    protected void doInvoke(ErmsImportState state){
88
		logger.info("start make " + getPluralString() + " ...");
89
		ErmsImportConfigurator config = state.getConfig();
90
		Source source = config.getSource();
91

    
92
		String strIdQuery = getIdQuery();
93
		String strRecordQuery = getRecordQuery(config);
94

    
95
		int recordsPerTransaction = config.getRecordsPerTransaction();
96
		recordsPerTransaction = recordsPerTransaction / divideCountBy();
97

    
98
		try{
99
			ResultSetPartitioner<ErmsImportState> partitioner = ResultSetPartitioner.NewInstance(source, strIdQuery, strRecordQuery, recordsPerTransaction);
100
			while (partitioner.nextPartition()){
101
				partitioner.doPartition(this, state);
102
			}
103
		} catch (SQLException e) {
104
			logger.error("SQLException:" +  e);
105
			state.setUnsuccessfull();
106
			return;
107
		}
108

    
109
		logger.info("end make " + getPluralString() + " ... " + getSuccessString(true));
110
		return;
111
	}
112

    
113
	@Override
114
    public boolean doPartition(@SuppressWarnings("rawtypes") ResultSetPartitioner partitioner, ErmsImportState state) {
115
		boolean success = true ;
116
		Set<CdmBase> objectsToSave = new HashSet<>();
117

    
118
 		DbImportMapping<?, ?> mapping = getMapping();
119
		mapping.initialize(state, cdmTargetClass);
120

    
121
		ResultSet rs = partitioner.getResultSet();
122
		try{
123
			while (rs.next()){
124
			    if (!ignoreRecord(rs)) {
125
                    success &= mapping.invoke(rs, objectsToSave);
126
                }
127
			}
128
		} catch (SQLException e) {
129
			logger.error("SQLException:" +  e);
130
			return false;
131
		}
132

    
133
		partitioner.startDoSave();
134
		getCommonService().save(objectsToSave);
135
		return success;
136
	}
137

    
138

    
139
    /**
140
     * Returns <code>true</code> if the current
141
     * record should be ignored. Should be overriden
142
     * if a subclass does not want to handle all records.
143
     * This is primarily important for those subclasses
144
     * handling last action information which create multiple
145
     * records per base record.
146
     * @throws SQLException
147
     */
148
    protected boolean ignoreRecord(@SuppressWarnings("unused") ResultSet rs) throws SQLException {
149
        return false;
150
    }
151

    
152
    protected abstract DbImportMapping<?, ?> getMapping();
153

    
154
	protected abstract String getRecordQuery(ErmsImportConfigurator config);
155

    
156
	protected String getIdQuery(){
157
		String result = " SELECT id FROM " + getTableName();
158
		return result;
159
	}
160

    
161
	@Override
162
    public String getPluralString(){
163
		return pluralString;
164
	}
165

    
166
	protected String getTableName(){
167
		return this.dbTableName;
168
	}
169

    
170
	protected boolean doIdCreatedUpdatedNotes(ErmsImportState state, IdentifiableEntity identifiableEntity, ResultSet rs, long id, String namespace)
171
			throws SQLException{
172
		boolean success = true;
173
		//id
174
		success &= ImportHelper.setOriginalSource(identifiableEntity, state.getConfig().getSourceReference(), id, namespace);
175
		//createdUpdateNotes
176
		success &= doCreatedUpdatedNotes(state, identifiableEntity, rs, namespace);
177
		return success;
178
	}
179

    
180
	protected boolean doCreatedUpdatedNotes(ErmsImportState state, AnnotatableEntity annotatableEntity, ResultSet rs, String namespace)
181
			throws SQLException{
182

    
183
		ErmsImportConfigurator config = state.getConfig();
184
		Object createdWhen = rs.getObject("Created_When");
185
		String createdWho = rs.getString("Created_Who");
186
		Object updatedWhen = null;
187
		String updatedWho = null;
188
		try {
189
			updatedWhen = rs.getObject("Updated_When");
190
			updatedWho = rs.getString("Updated_who");
191
		} catch (SQLException e) {
192
			//Table "Name" has no updated when/who
193
		}
194
		String notes = rs.getString("notes");
195

    
196
		boolean success  = true;
197

    
198
		//Created When, Who, Updated When Who
199
		if (config.getEditor() == null || config.getEditor().equals(EDITOR.NO_EDITORS)){
200
			//do nothing
201
		}else if (config.getEditor().equals(EDITOR.EDITOR_AS_ANNOTATION)){
202
			String createdAnnotationString = "Berlin Model record was created By: " + String.valueOf(createdWho) + " (" + String.valueOf(createdWhen) + ") ";
203
			if (updatedWhen != null && updatedWho != null){
204
				createdAnnotationString += " and updated By: " + String.valueOf(updatedWho) + " (" + String.valueOf(updatedWhen) + ")";
205
			}
206
			Annotation annotation = Annotation.NewInstance(createdAnnotationString, Language.DEFAULT());
207
			annotation.setCommentator(config.getCommentator());
208
			annotation.setAnnotationType(AnnotationType.TECHNICAL());
209
			annotatableEntity.addAnnotation(annotation);
210
		}else if (config.getEditor().equals(EDITOR.EDITOR_AS_EDITOR)){
211
			User creator = getUser(createdWho, state);
212
			User updator = getUser(updatedWho, state);
213
			DateTime created = getDateTime(createdWhen);
214
			DateTime updated = getDateTime(updatedWhen);
215
			annotatableEntity.setCreatedBy(creator);
216
			annotatableEntity.setUpdatedBy(updator);
217
			annotatableEntity.setCreated(created);
218
			annotatableEntity.setUpdated(updated);
219
		}else {
220
			logger.warn("Editor type not yet implemented: " + config.getEditor());
221
		}
222

    
223

    
224
		//notes
225
		if (StringUtils.isNotBlank(notes)){
226
			String notesString = String.valueOf(notes);
227
			if (notesString.length() > 65530 ){
228
				notesString = notesString.substring(0, 65530) + "...";
229
				logger.warn("Notes string is longer than 65530 and was truncated: " + annotatableEntity);
230
			}
231
			Annotation notesAnnotation = Annotation.NewInstance(notesString, null);
232
			//notesAnnotation.setAnnotationType(AnnotationType.EDITORIAL());
233
			//notes.setCommentator(bmiConfig.getCommentator());
234
			annotatableEntity.addAnnotation(notesAnnotation);
235
		}
236
		return success;
237
	}
238

    
239
	private User getUser(String userString, ErmsImportState state){
240
		if (StringUtils.isBlank(userString)){
241
			return null;
242
		}
243
		userString = userString.trim();
244

    
245
		User user = state.getUser(userString);
246
		if (user == null){
247
			user = getTransformedUser(userString,state);
248
		}
249
		if (user == null){
250
			user = makeNewUser(userString, state);
251
		}
252
		if (user == null){
253
			logger.warn("User is null");
254
		}
255
		return user;
256
	}
257

    
258
	private User getTransformedUser(String userString, ErmsImportState state){
259
		Method method = state.getConfig().getUserTransformationMethod();
260
		if (method == null){
261
			return null;
262
		}
263
		try {
264
			userString = (String)state.getConfig().getUserTransformationMethod().invoke(null, userString);
265
		} catch (Exception e) {
266
			logger.warn("Error when trying to transform userString " +  userString + ". No transformation done.");
267
		}
268
		User user = state.getUser(userString);
269
		return user;
270
	}
271

    
272
	private User makeNewUser(String userString, ErmsImportState state){
273
		String pwd = getPassword();
274
		User user = User.NewInstance(userString, pwd);
275
		state.putUser(userString, user);
276
		getUserService().save(user);
277
		logger.info("Added new user: " + userString);
278
		return user;
279
	}
280

    
281
	private String getPassword(){
282
		String result = UUID.randomUUID().toString();
283
		return result;
284
	}
285

    
286
	private DateTime getDateTime(Object timeString){
287
		if (timeString == null){
288
			return null;
289
		}
290
		DateTime dateTime = null;
291
		if (timeString instanceof Timestamp){
292
			Timestamp timestamp = (Timestamp)timeString;
293
			dateTime = new DateTime(timestamp);
294
		}else{
295
			logger.warn("time ("+timeString+") is not a timestamp. Datetime set to current date. ");
296
			dateTime = new DateTime();
297
		}
298
		return dateTime;
299
	}
300

    
301
	protected boolean resultSetHasColumn(ResultSet rs, String columnName){
302
		try {
303
			ResultSetMetaData metaData = rs.getMetaData();
304
			for (int i = 0; i < metaData.getColumnCount(); i++){
305
				if (metaData.getColumnName(i + 1).equalsIgnoreCase(columnName)){
306
					return true;
307
				}
308
			}
309
			return false;
310
		} catch (SQLException e) {
311
            logger.warn("Exception in resultSetHasColumn");
312
            return false;
313
		}
314
	}
315

    
316
	protected boolean checkSqlServerColumnExists(Source source, String tableName, String columnName){
317
		String strQuery = "SELECT  Count(t.id) as n " +
318
				" FROM sysobjects AS t " +
319
				" INNER JOIN syscolumns AS c ON t.id = c.id " +
320
				" WHERE (t.xtype = 'U') AND " +
321
				" (t.name = '" + tableName + "') AND " +
322
				" (c.name = '" + columnName + "')";
323
		ResultSet rs = source.getResultSet(strQuery) ;
324
		int n;
325
		try {
326
			rs.next();
327
			n = rs.getInt("n");
328
			return n>0;
329
		} catch (SQLException e) {
330
			e.printStackTrace();
331
			return false;
332
		}
333
	}
334

    
335
	/**
336
	 * Returns a map that holds all values of a ResultSet. This is needed if a value needs to
337
	 * be accessed twice
338
	 */
339
	protected Map<String, Object> getValueMap(ResultSet rs) throws SQLException{
340
		try{
341
			Map<String, Object> valueMap = new HashMap<>();
342
			int colCount = rs.getMetaData().getColumnCount();
343
			for (int c = 0; c < colCount ; c++){
344
				Object value = rs.getObject(c+1);
345
				String label = rs.getMetaData().getColumnLabel(c+1).toLowerCase();
346
				if (value != null && ! CdmUtils.Nz(value.toString()).trim().equals("")){
347
					valueMap.put(label, value);
348
				}
349
			}
350
			return valueMap;
351
		}catch(SQLException e){
352
			throw e;
353
		}
354
	}
355

    
356
	protected ExtensionType getExtensionType(UUID uuid, String label, String text, String labelAbbrev){
357
		ExtensionType extensionType = (ExtensionType)getTermService().find(uuid);
358
		if (extensionType == null){
359
			extensionType = ExtensionType.NewInstance(text, label, labelAbbrev);
360
			extensionType.setUuid(uuid);
361
			getTermService().save(extensionType);
362
		}
363
		return extensionType;
364
	}
365

    
366
	protected MarkerType getMarkerType(UUID uuid, String label, String text, String labelAbbrev){
367
		MarkerType markerType = (MarkerType)getTermService().find(uuid);
368
		if (markerType == null){
369
			markerType = MarkerType.NewInstance(label, text, labelAbbrev);
370
			markerType.setUuid(uuid);
371
			getTermService().save(markerType);
372
		}
373
		return markerType;
374
	}
375

    
376
    protected AnnotationType getAnnotationType(UUID uuid, String label, String text, String labelAbbrev){
377
        AnnotationType annotationType = (AnnotationType)getTermService().find(uuid);
378
        if (annotationType == null){
379
            annotationType = AnnotationType.NewInstance(label, text, labelAbbrev);
380
            annotationType.setUuid(uuid);
381
            getTermService().save(annotationType);
382
        }
383
        return annotationType;
384
    }
385

    
386
	/**
387
	 * Reads a foreign key field from the result set and adds its value to the idSet.
388
	 */
389
	protected void handleForeignKey(ResultSet rs, Set<String> idSet, String attributeName)
390
			throws SQLException {
391
		Object idObj = rs.getObject(attributeName);
392
		if (idObj != null){
393
			String id  = String.valueOf(idObj);
394
			idSet.add(id);
395
		}
396
	}
397

    
398
	protected int divideCountBy() { return 1;}
399

    
400
	/**
401
	 * Returns true if i is a multiple of recordsPerTransaction
402
	 */
403
	protected boolean loopNeedsHandling(int i, int recordsPerLoop) {
404
		startTransaction();
405
		return (i % recordsPerLoop) == 0;
406
	}
407

    
408
	protected void doLogPerLoop(int count, int recordsPerLog, String pluralString){
409
		if ((count % recordsPerLog ) == 0 && count!= 0 ){ logger.info(pluralString + " handled: " + (count));}
410
	}
411
}
(4-4/17)