Project

General

Profile

Download (11.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.faunaEuropaea;
11

    
12
import java.net.URI;
13
import java.sql.ResultSet;
14
import java.sql.SQLException;
15
import java.util.Collection;
16
import java.util.HashMap;
17
import java.util.HashSet;
18
import java.util.Iterator;
19
import java.util.Map;
20
import java.util.Map.Entry;
21
import java.util.UUID;
22

    
23
import org.apache.commons.lang.StringUtils;
24
import org.apache.log4j.Logger;
25
import org.springframework.stereotype.Component;
26
import org.springframework.transaction.TransactionStatus;
27
import org.springframework.transaction.support.DefaultTransactionDefinition;
28

    
29
import eu.etaxonomy.cdm.io.common.IImportConfigurator;
30
import eu.etaxonomy.cdm.io.common.ImportHelper;
31
import eu.etaxonomy.cdm.io.common.Source;
32
import eu.etaxonomy.cdm.model.agent.AgentBase;
33
import eu.etaxonomy.cdm.model.agent.Contact;
34
import eu.etaxonomy.cdm.model.agent.Institution;
35
import eu.etaxonomy.cdm.model.agent.Person;
36
import eu.etaxonomy.cdm.model.common.OriginalSourceBase;
37
import eu.etaxonomy.cdm.model.common.User;
38

    
39

    
40
/**
41
 * @author a.babadshanjan
42
 * @created 23.08.2010
43
 */
44
@Component
45
public class FaunaEuropaeaUsersImport extends FaunaEuropaeaImportBase {
46
	private static final Logger logger = Logger.getLogger(FaunaEuropaeaUsersImport.class);
47

    
48
	/* Interval for progress info message when retrieving taxa */
49
	private final int modCount = 10000;
50

    
51
	 protected DefaultTransactionDefinition txDefinition = new DefaultTransactionDefinition();
52

    
53
	/* (non-Javadoc)
54
	 * @see eu.etaxonomy.cdm.io.common.CdmIoBase#doCheck(eu.etaxonomy.cdm.io.common.IImportConfigurator)
55
	 */
56
	@Override
57
	protected boolean doCheck(FaunaEuropaeaImportState state) {
58
		boolean result = true;
59
		FaunaEuropaeaImportConfigurator fauEuConfig = state.getConfig();
60
		logger.warn("Checking for References not yet fully implemented");
61
		result &= checkReferenceStatus(fauEuConfig);
62

    
63
		return result;
64
	}
65

    
66
	private boolean checkReferenceStatus(FaunaEuropaeaImportConfigurator fauEuConfig) {
67
		boolean result = true;
68
//		try {
69
		Source source = fauEuConfig.getSource();
70
		String sqlStr = "";
71
//		ResultSet rs = source.getResultSet(sqlStr);
72
		return result;
73
//		} catch (SQLException e) {
74
//		e.printStackTrace();
75
//		return false;
76
//		}
77
	}
78

    
79
	/* (non-Javadoc)
80
	 * @see eu.etaxonomy.cdm.io.common.CdmIoBase#doInvoke(eu.etaxonomy.cdm.io.common.IImportConfigurator, eu.etaxonomy.cdm.api.application.CdmApplicationController, java.util.Map)
81
	 */
82
	@Override
83
	protected void doInvoke(FaunaEuropaeaImportState state) {
84
		/*
85
		logger.warn("Start User doInvoke");
86
		ProfilerController.memorySnapshot();
87
		*/
88
		
89
		
90
		TransactionStatus txStatus = null;
91
		Map<String, Person> persons = null;
92
		Map<String, User> users= null;
93

    
94
		Map<Integer, UUID> userUuids = new HashMap<Integer, UUID>();
95
		Map<Integer, Institution> institiutions= new HashMap<Integer, Institution>();
96
		Collection<Institution> institutionsToSave = new HashSet<Institution>();
97
		int limit = state.getConfig().getLimitSave();
98
		//this.authenticate("admin", "00000");
99

    
100
		FaunaEuropaeaImportConfigurator fauEuConfig = state.getConfig();
101
		Source source = fauEuConfig.getSource();
102

    
103
		String namespace = "User";
104
		int i = 0;
105

    
106
		String selectCountUsers =
107
			" SELECT count(*) FROM Users";
108

    
109
		String selectColumnsUsers =
110
			" SELECT u.usr_id as userId, u.usr_title as title, u.usr_firstname as firstname, u.usr_lastname as lastname, u.usr_createdat as created, u.usr_password as password, u.usr_cou_id as country, u.usr_email as mail, "
111
			+ "u.usr_homepage as homepage, u.usr_description as description, u.usr_active as active, o.org_name as organisationName, o.org_homepage as organisationHomepage, o.org_id as institutionId FROM Users u LEFT JOIN Organisation o ON o.org_id= u.usr_org_id";
112

    
113
		int count;
114
		if(logger.isInfoEnabled()) { logger.info("Start making References (Users)..."); }
115

    
116
		try {
117
			ResultSet rsUser = source.getResultSet(selectCountUsers);
118
			rsUser.next();
119
			count = rsUser.getInt(1);
120

    
121
			rsUser= source.getResultSet(selectColumnsUsers);
122

    
123
	        if (logger.isInfoEnabled()) {
124
	        	logger.info("Get all References...");
125
				logger.info("Number of rows: " + count);
126
				logger.info("Count Query: " + selectCountUsers);
127
				logger.info("Select Query: " + selectColumnsUsers);
128
			}
129

    
130
	        while (rsUser.next()){//usr_country_id, usr_org_id, usr_email, usr_homepage, usr_groupname, usr_groupicon, usr_groupnote, usr_description, usr_active)
131
	        	int refId = rsUser.getInt("userId");
132
				String userTitle = rsUser.getString("title");
133
				String userFirstname = rsUser.getString("firstname");
134
				String userLastname = rsUser.getString("lastname");
135
				String createdDate = rsUser.getString("created");
136
				String userPwd = rsUser.getString("password");
137
				String userCountry = rsUser.getString("country");
138

    
139
				String userMail = rsUser.getString("mail");
140
				String userHomepage = rsUser.getString("homepage");
141
				//String userGroupName = rsUser.getString("u.usr_groupname");
142
				String userDescription = rsUser.getString("description");
143
				int userActive = rsUser.getInt("active");
144
				String orgName = rsUser.getString("organisationName");
145
				String orgHomepage = rsUser.getString("organisationHomepage");
146
				int institutionId = rsUser.getInt("institutionId");
147

    
148
				// build person
149
				String userPerson = "";
150
				if (userTitle != null) {
151
					userPerson = userTitle;
152
					if (! userTitle.endsWith(".")) {
153
						userPerson += ".";
154
					}
155
				}
156
				userPerson += userTitle == null ? NullToEmpty(userFirstname) : " " + NullToEmpty(userFirstname);
157
				if ((userTitle != null || userFirstname != null) && userLastname != null) {
158
					userPerson += " " + userLastname;
159
				}
160
				this.authenticate("admin", "00000");
161
				// build year
162
				String year = null;
163
				if (createdDate != null) {
164
					year = createdDate.substring(0, createdDate.indexOf("-"));
165
				}
166

    
167
				if ((i++ % limit) == 0) {
168

    
169
					txStatus = startTransaction();
170
					persons= new HashMap<String,Person>(limit);
171
					users = new HashMap<String,User>(limit);
172

    
173

    
174
					if(logger.isInfoEnabled()) {
175
						logger.info("i = " + i + " - User import transaction started");
176
					}
177
				}
178

    
179
				Person person = null;
180
				User user = null;
181

    
182
				person= Person.NewTitledInstance(userPerson);
183

    
184
				person.addEmailAddress(userMail);
185
				try{
186
				    if (!StringUtils.isBlank(userHomepage)){
187
				        person.addUrl(URI.create(userHomepage));
188
				    }
189
				}catch(IllegalArgumentException e){
190
				    logger.debug(e.getMessage());
191
				}
192
				if (institutionId != 1){//1 = private
193
				    Institution institution ;
194
				    if (!institiutions.containsKey(institutionId)){
195
				        institution = Institution.NewInstance();
196
				        institution.setName(orgName);
197
				        Contact contact = Contact.NewInstance();
198
	                    try{
199
	                        if (!StringUtils.isBlank(orgHomepage)){
200
	                            contact.addUrl(URI.create(orgHomepage));
201
	                        }
202
	                    }catch(IllegalArgumentException e){
203
	                        logger.debug(e.getMessage());
204
	                    }
205
	                    institution.setContact(contact);
206
	                    institutionsToSave.add(institution);
207
				    } else {
208
				        institution = institiutions.get(institutionId);
209
				    }
210

    
211

    
212
    				person.addInstitutionalMembership(institution, null, null, null);
213
				}
214
				user = User.NewInstance(userPerson, userPwd);
215
				user.setPerson(person);
216
				if (userActive == FaunaEuropaeaTransformer.U_ACTIVE){
217
				    user.setAccountNonLocked(false);
218
				} else{
219
				    user.setAccountNonLocked(true);
220
				}
221

    
222
				if (!persons.containsKey(userPerson)) {
223
					if (userPerson == null) {
224
						logger.warn("User is null");
225
					}
226

    
227
					persons.put(userPerson, person);
228
					if (logger.isTraceEnabled()) {
229
						logger.trace("Stored user (" + userPerson + ")");
230
					}
231
				//}
232

    
233
				} else {
234
					person = persons.get(userPerson);
235
					if (logger.isDebugEnabled()) {
236
						logger.debug("Not imported user with duplicated ref_id (" + refId +
237
							") " + userPerson);
238
					}
239
				}
240

    
241
				// set protected titleCache
242
				StringBuilder referenceTitleCache = new StringBuilder(person.getTitleCache() + ".");
243
				if (year != null) {
244
					referenceTitleCache.append(" " + year);
245
				}
246

    
247

    
248
				//ImportHelper.setOriginalSource(user, fauEuConfig.getSourceReference(), userId, namespace);
249
				ImportHelper.setOriginalSource(person, fauEuConfig.getSourceReference(), refId, namespace);
250

    
251

    
252
				// Store persons
253
				if (!users.containsKey(userPerson.toLowerCase())) {
254

    
255
					if (user == null) {
256
						logger.warn("User is null");
257
					}
258
					users.put(userPerson.toLowerCase(), user);
259
					if (logger.isTraceEnabled()) {
260
						logger.trace("Stored user (" + userPerson + ")");
261
					}
262
				} else {
263
					//if (logger.isDebugEnabled()) {
264
						logger.info("Duplicated user(" + userPerson +")");
265
					//}
266
					//continue;
267
				}
268

    
269
				if (((i % limit) == 0 && i > 1 ) || i == count ) {
270

    
271
					commitUsers(txStatus, persons, users,
272
							state.getAgentMap(),institutionsToSave, i);
273

    
274
					users = null;
275
					persons= null;
276
				}
277

    
278
	        }
279
	        if (users != null){
280
	        	commitUsers(txStatus, persons, users,  state.getAgentMap(), institutionsToSave,i);
281
	        	users = null;
282
				persons= null;
283
	        }
284
		}catch(SQLException e) {
285
			logger.error("SQLException:" +  e);
286
			state.setUnsuccessfull();
287
		}
288
		/*
289
		logger.warn("End User doInvoke");
290
		ProfilerController.memorySnapshot();
291
		*/
292
		if(logger.isInfoEnabled()) { logger.info("End making References (Users) ..."); }
293

    
294
		return;
295
	}
296

    
297
	private void commitUsers(TransactionStatus txStatus,
298
			Map<String, Person> persons,
299
			Map<String, User> users,
300
			Map<Integer, UUID> agentsUUID,
301
			Collection<Institution> institutionsToSave,
302
			int i) {
303

    
304
	    Map<UUID, AgentBase> instMap = getAgentService().save((Collection)institutionsToSave);
305
		Map<UUID, AgentBase> userMap = getAgentService().save((Collection)persons.values());
306
		logger.info("i = " + i + " - persons saved");
307

    
308

    
309

    
310
		Iterator<Entry<UUID, AgentBase>> it = userMap.entrySet().iterator();
311
		while (it.hasNext()){
312
			AgentBase person = it.next().getValue();
313
			int userID = Integer.valueOf(((OriginalSourceBase)person.getSources().iterator().next()).getIdInSource());
314
			UUID uuid = person.getUuid();
315
			agentsUUID.put(userID, uuid);
316
		}
317

    
318
		getUserService().save(users.values());
319
		logger.info("i = " + users.size() + " - users saved");
320
		//getReferenceService().save(references.values());
321
		//logger.info("i = " +references.size() + " - references saved");
322
		commitTransaction(txStatus);
323
	}
324

    
325
	/**
326
	 * Returns an empty string in case of a null string.
327
	 * This avoids having the string "null" when using StringBuilder.append(null);
328
	 * @param string
329
	 * @return
330
	 */
331
	private String NullToEmpty(String string) {
332
		if (string == null) {
333
			return "";
334
		} else {
335
			return string;
336
		}
337
	}
338

    
339
	/* (non-Javadoc)
340
	 * @see eu.etaxonomy.cdm.io.common.CdmIoBase#isIgnore(eu.etaxonomy.cdm.io.common.IImportConfigurator)
341
	 */
342
	@Override
343
    protected boolean isIgnore(FaunaEuropaeaImportState state){
344
		return (state.getConfig().getDoReferences() == IImportConfigurator.DO_REFERENCES.NONE);
345
	}
346

    
347
}
(17-17/20)