Project

General

Profile

Download (13.4 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
				success &= mapping.invoke(rs, objectsToSave);
125
			}
126
		} catch (SQLException e) {
127
			logger.error("SQLException:" +  e);
128
			return false;
129
		}
130

    
131
		partitioner.startDoSave();
132
		getCommonService().save(objectsToSave);
133
		return success;
134
	}
135

    
136
	protected abstract DbImportMapping<?, ?> getMapping();
137

    
138
	protected abstract String getRecordQuery(ErmsImportConfigurator config);
139

    
140
	protected String getIdQuery(){
141
		String result = " SELECT id FROM " + getTableName();
142
		return result;
143
	}
144

    
145
	@Override
146
    public String getPluralString(){
147
		return pluralString;
148
	}
149

    
150
	protected String getTableName(){
151
		return this.dbTableName;
152
	}
153

    
154
	protected boolean doIdCreatedUpdatedNotes(ErmsImportState state, IdentifiableEntity identifiableEntity, ResultSet rs, long id, String namespace)
155
			throws SQLException{
156
		boolean success = true;
157
		//id
158
		success &= ImportHelper.setOriginalSource(identifiableEntity, state.getConfig().getSourceReference(), id, namespace);
159
		//createdUpdateNotes
160
		success &= doCreatedUpdatedNotes(state, identifiableEntity, rs, namespace);
161
		return success;
162
	}
163

    
164
	protected boolean doCreatedUpdatedNotes(ErmsImportState state, AnnotatableEntity annotatableEntity, ResultSet rs, String namespace)
165
			throws SQLException{
166

    
167
		ErmsImportConfigurator config = state.getConfig();
168
		Object createdWhen = rs.getObject("Created_When");
169
		String createdWho = rs.getString("Created_Who");
170
		Object updatedWhen = null;
171
		String updatedWho = null;
172
		try {
173
			updatedWhen = rs.getObject("Updated_When");
174
			updatedWho = rs.getString("Updated_who");
175
		} catch (SQLException e) {
176
			//Table "Name" has no updated when/who
177
		}
178
		String notes = rs.getString("notes");
179

    
180
		boolean success  = true;
181

    
182
		//Created When, Who, Updated When Who
183
		if (config.getEditor() == null || config.getEditor().equals(EDITOR.NO_EDITORS)){
184
			//do nothing
185
		}else if (config.getEditor().equals(EDITOR.EDITOR_AS_ANNOTATION)){
186
			String createdAnnotationString = "Berlin Model record was created By: " + String.valueOf(createdWho) + " (" + String.valueOf(createdWhen) + ") ";
187
			if (updatedWhen != null && updatedWho != null){
188
				createdAnnotationString += " and updated By: " + String.valueOf(updatedWho) + " (" + String.valueOf(updatedWhen) + ")";
189
			}
190
			Annotation annotation = Annotation.NewInstance(createdAnnotationString, Language.DEFAULT());
191
			annotation.setCommentator(config.getCommentator());
192
			annotation.setAnnotationType(AnnotationType.TECHNICAL());
193
			annotatableEntity.addAnnotation(annotation);
194
		}else if (config.getEditor().equals(EDITOR.EDITOR_AS_EDITOR)){
195
			User creator = getUser(createdWho, state);
196
			User updator = getUser(updatedWho, state);
197
			DateTime created = getDateTime(createdWhen);
198
			DateTime updated = getDateTime(updatedWhen);
199
			annotatableEntity.setCreatedBy(creator);
200
			annotatableEntity.setUpdatedBy(updator);
201
			annotatableEntity.setCreated(created);
202
			annotatableEntity.setUpdated(updated);
203
		}else {
204
			logger.warn("Editor type not yet implemented: " + config.getEditor());
205
		}
206

    
207

    
208
		//notes
209
		if (StringUtils.isNotBlank(notes)){
210
			String notesString = String.valueOf(notes);
211
			if (notesString.length() > 65530 ){
212
				notesString = notesString.substring(0, 65530) + "...";
213
				logger.warn("Notes string is longer than 65530 and was truncated: " + annotatableEntity);
214
			}
215
			Annotation notesAnnotation = Annotation.NewInstance(notesString, null);
216
			//notesAnnotation.setAnnotationType(AnnotationType.EDITORIAL());
217
			//notes.setCommentator(bmiConfig.getCommentator());
218
			annotatableEntity.addAnnotation(notesAnnotation);
219
		}
220
		return success;
221
	}
222

    
223
	private User getUser(String userString, ErmsImportState state){
224
		if (StringUtils.isBlank(userString)){
225
			return null;
226
		}
227
		userString = userString.trim();
228

    
229
		User user = state.getUser(userString);
230
		if (user == null){
231
			user = getTransformedUser(userString,state);
232
		}
233
		if (user == null){
234
			user = makeNewUser(userString, state);
235
		}
236
		if (user == null){
237
			logger.warn("User is null");
238
		}
239
		return user;
240
	}
241

    
242
	private User getTransformedUser(String userString, ErmsImportState state){
243
		Method method = state.getConfig().getUserTransformationMethod();
244
		if (method == null){
245
			return null;
246
		}
247
		try {
248
			userString = (String)state.getConfig().getUserTransformationMethod().invoke(null, userString);
249
		} catch (Exception e) {
250
			logger.warn("Error when trying to transform userString " +  userString + ". No transformation done.");
251
		}
252
		User user = state.getUser(userString);
253
		return user;
254
	}
255

    
256
	private User makeNewUser(String userString, ErmsImportState state){
257
		String pwd = getPassword();
258
		User user = User.NewInstance(userString, pwd);
259
		state.putUser(userString, user);
260
		getUserService().save(user);
261
		logger.info("Added new user: " + userString);
262
		return user;
263
	}
264

    
265
	private String getPassword(){
266
		String result = UUID.randomUUID().toString();
267
		return result;
268
	}
269

    
270
	private DateTime getDateTime(Object timeString){
271
		if (timeString == null){
272
			return null;
273
		}
274
		DateTime dateTime = null;
275
		if (timeString instanceof Timestamp){
276
			Timestamp timestamp = (Timestamp)timeString;
277
			dateTime = new DateTime(timestamp);
278
		}else{
279
			logger.warn("time ("+timeString+") is not a timestamp. Datetime set to current date. ");
280
			dateTime = new DateTime();
281
		}
282
		return dateTime;
283
	}
284

    
285
	protected boolean resultSetHasColumn(ResultSet rs, String columnName){
286
		try {
287
			ResultSetMetaData metaData = rs.getMetaData();
288
			for (int i = 0; i < metaData.getColumnCount(); i++){
289
				if (metaData.getColumnName(i + 1).equalsIgnoreCase(columnName)){
290
					return true;
291
				}
292
			}
293
			return false;
294
		} catch (SQLException e) {
295
            logger.warn("Exception in resultSetHasColumn");
296
            return false;
297
		}
298
	}
299

    
300
	protected boolean checkSqlServerColumnExists(Source source, String tableName, String columnName){
301
		String strQuery = "SELECT  Count(t.id) as n " +
302
				" FROM sysobjects AS t " +
303
				" INNER JOIN syscolumns AS c ON t.id = c.id " +
304
				" WHERE (t.xtype = 'U') AND " +
305
				" (t.name = '" + tableName + "') AND " +
306
				" (c.name = '" + columnName + "')";
307
		ResultSet rs = source.getResultSet(strQuery) ;
308
		int n;
309
		try {
310
			rs.next();
311
			n = rs.getInt("n");
312
			return n>0;
313
		} catch (SQLException e) {
314
			e.printStackTrace();
315
			return false;
316
		}
317
	}
318

    
319
	/**
320
	 * Returns a map that holds all values of a ResultSet. This is needed if a value needs to
321
	 * be accessed twice
322
	 */
323
	protected Map<String, Object> getValueMap(ResultSet rs) throws SQLException{
324
		try{
325
			Map<String, Object> valueMap = new HashMap<>();
326
			int colCount = rs.getMetaData().getColumnCount();
327
			for (int c = 0; c < colCount ; c++){
328
				Object value = rs.getObject(c+1);
329
				String label = rs.getMetaData().getColumnLabel(c+1).toLowerCase();
330
				if (value != null && ! CdmUtils.Nz(value.toString()).trim().equals("")){
331
					valueMap.put(label, value);
332
				}
333
			}
334
			return valueMap;
335
		}catch(SQLException e){
336
			throw e;
337
		}
338
	}
339

    
340
	protected ExtensionType getExtensionType(UUID uuid, String label, String text, String labelAbbrev){
341
		ExtensionType extensionType = (ExtensionType)getTermService().find(uuid);
342
		if (extensionType == null){
343
			extensionType = ExtensionType.NewInstance(text, label, labelAbbrev);
344
			extensionType.setUuid(uuid);
345
			getTermService().save(extensionType);
346
		}
347
		return extensionType;
348
	}
349

    
350
	protected MarkerType getMarkerType(UUID uuid, String label, String text, String labelAbbrev){
351
		MarkerType markerType = (MarkerType)getTermService().find(uuid);
352
		if (markerType == null){
353
			markerType = MarkerType.NewInstance(label, text, labelAbbrev);
354
			markerType.setUuid(uuid);
355
			getTermService().save(markerType);
356
		}
357
		return markerType;
358
	}
359

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

    
370
	/**
371
	 * Reads a foreign key field from the result set and adds its value to the idSet.
372
	 */
373
	protected void handleForeignKey(ResultSet rs, Set<String> idSet, String attributeName)
374
			throws SQLException {
375
		Object idObj = rs.getObject(attributeName);
376
		if (idObj != null){
377
			String id  = String.valueOf(idObj);
378
			idSet.add(id);
379
		}
380
	}
381

    
382
	protected int divideCountBy() { return 1;}
383

    
384
	/**
385
	 * Returns true if i is a multiple of recordsPerTransaction
386
	 */
387
	protected boolean loopNeedsHandling(int i, int recordsPerLoop) {
388
		startTransaction();
389
		return (i % recordsPerLoop) == 0;
390
	}
391

    
392
	protected void doLogPerLoop(int count, int recordsPerLog, String pluralString){
393
		if ((count % recordsPerLog ) == 0 && count!= 0 ){ logger.info(pluralString + " handled: " + (count));}
394
	}
395
}
(4-4/17)