Project

General

Profile

Download (13.3 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
	/**
81
	 * @param dbTableName
82
	 * @param dbTableName2
83
	 */
84
	public ErmsImportBase(String pluralString, String dbTableName, Class cdmTargetClass) {
85
		this.pluralString = pluralString;
86
		this.dbTableName = dbTableName;
87
		this.cdmTargetClass = cdmTargetClass;
88
	}
89

    
90
	@Override
91
    protected void doInvoke(ErmsImportState state){
92
		logger.info("start make " + getPluralString() + " ...");
93
		ErmsImportConfigurator config = state.getConfig();
94
		Source source = config.getSource();
95

    
96
		String strIdQuery = getIdQuery();
97
		String strRecordQuery = getRecordQuery(config);
98

    
99
		int recordsPerTransaction = config.getRecordsPerTransaction();
100
		recordsPerTransaction = recordsPerTransaction / divideCountBy();
101

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

    
113
		logger.info("end make " + getPluralString() + " ... " + getSuccessString(true));
114
		return;
115
	}
116

    
117
	@Override
118
    public boolean doPartition(@SuppressWarnings("rawtypes") ResultSetPartitioner partitioner, ErmsImportState state) {
119
		boolean success = true ;
120
		Set<CdmBase> objectsToSave = new HashSet<>();
121

    
122
 		DbImportMapping<?, ?> mapping = getMapping();
123
		mapping.initialize(state, cdmTargetClass);
124

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

    
135
		partitioner.startDoSave();
136
		getCommonService().save(objectsToSave);
137
		return success;
138
	}
139

    
140
	/**
141
	 * @return
142
	 */
143
	protected abstract DbImportMapping<?, ?> getMapping();
144

    
145
	/**
146
	 * @return
147
	 */
148
	protected abstract String getRecordQuery(ErmsImportConfigurator config);
149

    
150
	/**
151
	 * @return
152
	 */
153
	protected String getIdQuery(){
154
		String result = " SELECT id FROM " + getTableName();
155
		return result;
156
	}
157

    
158
	@Override
159
    public String getPluralString(){
160
		return pluralString;
161
	}
162

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

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

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

    
380

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

    
396
	protected int divideCountBy() { return 1;}
397

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

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

    
413
}
(4-4/17)