*/
private void _loadUserCSVFiles(ActionForm form, ActionRequest req, ActionResponse res) throws Exception {
User systemUser = APILocator.getUserAPI().getSystemUser();
UserManagerListSearchForm userForm = (UserManagerListSearchForm) form;
UploadPortletRequest uploadReq = PortalUtil.getUploadPortletRequest(req);
java.io.File uploadedFile = uploadReq.getFile("newUsersFile");
StringBuffer returnMessage = new StringBuffer();
User userLoader = PortalUtil.getUser(req);
boolean someError = false;
String companyId = com.dotmarketing.cms.factories.PublicCompanyFactory.getDefaultCompany().getCompanyId();
// read permission
String[] readPermissions = req.getParameterValues("readRole");
// write permission
String[] writePermissions = req.getParameterValues("writeRole");
int userCreated = 0;
int countUserDuplicated = 0;
int userTaged = 0;
int numberGenericVariables = Config.getIntProperty("MAX_NUMBER_VARIABLES_TO_SHOW");
List<String> arrayUserIds = new ArrayList<String>();
// creating tags
if (UtilMethods.isSet(userForm.getTagName())) {
StringTokenizer tagNameToken = new StringTokenizer(userForm.getTagName(), ",");
if (tagNameToken.hasMoreTokens()) {
for (; tagNameToken.hasMoreTokens();) {
String tagTokenized = tagNameToken.nextToken().trim();
TagFactory.getTag(tagTokenized, userLoader.getUserId());
}
}
}
if (uploadedFile.exists() && uploadedFile.length() > 0) {
//get the groups
String groupsStr = req.getParameter("groups");
//get the roles
String rolesStr = req.getParameter("roles");
String token;
StringTokenizer tokens = new StringTokenizer(groupsStr, ",");
HashSet<String> groups = new HashSet<String>();
for (; tokens.hasMoreTokens();) {
if (!((token = tokens.nextToken().trim()).equals("")))
groups.add(token);
}
tokens = new StringTokenizer(rolesStr, ",");
HashSet<String> roles = new HashSet<String>();
for (; tokens.hasMoreTokens();) {
if (!((token = tokens.nextToken().trim()).equals("")))
roles.add(token);
}
int lineNumber = 0;
BufferedReader input = new BufferedReader(new FileReader(uploadedFile));
try {
if (userForm.isIgnoreHeaders()) {
input.readLine();
lineNumber++;
}
String line = null;
Company comp = com.dotmarketing.cms.factories.PublicCompanyFactory.getDefaultCompany();
HibernateUtil.startTransaction();
while ((line = input.readLine()) != null) {
lineNumber++;
if (lineNumber % 100 == 0) {
HibernateUtil.commitTransaction();
HibernateUtil.startTransaction();
}
String[] lineTok = UtilMethods.specialSplit(line, ",", "\"");
String firstName = "";
String middleName = "";
String lastName = "";
String email = "";
String password = "";
String dateOfBirthday = "";
String street1 = "";
String street2 = "";
String city = "";
String state = "";
String zip = "";
String country = "";
String phone = "";
String fax = "";
String cell = "";
String userId = "";
try {
int i = 0;
try {
firstName = lineTok[i++];
} catch (Exception e) {
}
try {
middleName = lineTok[i++];
} catch (Exception e) {
}
try {
lastName = lineTok[i++];
} catch (Exception e) {
}
try {
email = lineTok[i++];
} catch (Exception e) {
}
if (UtilMethods.isValidEmail(email)) {
try {
password = lineTok[i++];
} catch (Exception e) {
}
Date birthday = null;
String validationBirthdayString;
try {
dateOfBirthday = lineTok[i++];
birthday = UtilMethods.htmlToDate(dateOfBirthday);
validationBirthdayString = UtilMethods.dateToHTMLDate(birthday);
if (!dateOfBirthday.startsWith(validationBirthdayString) || (9999 < birthday.getYear()))
birthday = null;
} catch (Exception e) {
}
try {
street1 = lineTok[i++];
} catch (Exception e) {
}
try {
street2 = lineTok[i++];
} catch (Exception e) {
}
try {
city = lineTok[i++];
} catch (Exception e) {
}
try {
state = lineTok[i++];
} catch (Exception e) {
}
try {
zip = lineTok[i++];
} catch (Exception e) {
}
try {
country = lineTok[i++];
} catch (Exception e) {
}
try {
phone = lineTok[i++];
} catch (Exception e) {
}
try {
fax = lineTok[i++];
} catch (Exception e) {
}
try {
cell = lineTok[i++];
} catch (Exception e) {
}
if (comp.getAuthType().equals(Company.AUTH_TYPE_ID)) {
try {
userId = lineTok[i++];
} catch (Exception e) {
Logger.info(this, e.getMessage());
}
}
if (firstName.equalsIgnoreCase("")) {
if (!someError) {
returnMessage.append( LanguageUtil.get(com.liferay.portal.util.PortalUtil.getUser(req), "Errors-loading-users-br-br") );
someError = true;
}
returnMessage.append( LanguageUtil.get(com.liferay.portal.util.PortalUtil.getUser(req), "Missing-First-Name-on-line") +" "+ lineNumber + "<br>");
continue;
}
if (lastName.equalsIgnoreCase("")) {
if (!someError) {
returnMessage.append(LanguageUtil.get(com.liferay.portal.util.PortalUtil.getUser(req), "Errors-loading-users-br-br"));
someError = true;
}
returnMessage.append(LanguageUtil.get(com.liferay.portal.util.PortalUtil.getUser(req), "Missing-Last-Name-on-line")+" " + lineNumber + "<br>");
continue;
}
if (email.equalsIgnoreCase("")) {
if (!someError) {
returnMessage.append(LanguageUtil.get(com.liferay.portal.util.PortalUtil.getUser(req), "Errors-loading-users-br-br"));
someError = true;
}
returnMessage.append(LanguageUtil.get(com.liferay.portal.util.PortalUtil.getUser(req), "Missing-Email-Address-on-line") +" "+ lineNumber + "<br>");
continue;
}
User userDuplicated = null;
try {
if (comp.getAuthType().equals(Company.AUTH_TYPE_ID)) {
userDuplicated = APILocator.getUserAPI().loadUserById(userId,APILocator.getUserAPI().getSystemUser(),false);
} else {
userDuplicated = APILocator.getUserAPI().loadByUserByEmail(email, APILocator.getUserAPI().getSystemUser(), false);
}
} catch (Exception e) {
}
if (userDuplicated == null) {
User user = null;
// Check company authorization type to set user id.
if (comp.getAuthType().equals(Company.AUTH_TYPE_ID)) {
if(userId.equalsIgnoreCase("")) {
if (!someError) {
returnMessage.append(LanguageUtil.get(com.liferay.portal.util.PortalUtil.getUser(req), "Errors-loading-users-br-br"));
someError = true;
}
returnMessage.append(LanguageUtil.get(com.liferay.portal.util.PortalUtil.getUser(req), "Missing-User-ID-on-line")+" " + lineNumber + "<br>");
continue;
}
try {
user = APILocator.getUserAPI().createUser(userId, null);
} catch (IndexOutOfBoundsException ie) {
Logger.error(this.getClass(), ie.getMessage(), ie);
}
}else {
user = APILocator.getUserAPI().createUser(null, null);
}
user.setCreateDate(new Date());
user.setGreeting("Welcome, " + firstName + " " + lastName + "!");
user.setFirstName(firstName);
user.setMiddleName(middleName);
user.setLastName(lastName);
user.setNickName("");
user.setEmailAddress(email.trim().toLowerCase());
user.setBirthday(birthday);
if (!UtilMethods.isSet(password)) {
password = PublicEncryptionFactory.getRandomPassword();
user.setActive(false);
} else {
user.setActive(true);
}
user.setPassword(PublicEncryptionFactory.digestString(password));
user.setPasswordEncrypted(true);
APILocator.getUserAPI().save(user, APILocator.getUserAPI().getSystemUser(), false);
UserProxy userProxy = com.dotmarketing.business.APILocator.getUserProxyAPI().getUserProxy(user,APILocator.getUserAPI().getSystemUser(), false);
String userProxyInode = userProxy.getInode();
userProxy = (UserProxy) InodeFactory.getInode(userProxyInode, UserProxy.class);
userProxy.setInode(userProxyInode);
userProxy.setUserId(user.getUserId());
// getting and saving the user
// additional info
String userAdditionalInfo = "";
for (int j = 1; j <= numberGenericVariables; j++) {
try {
userAdditionalInfo = lineTok[i++];
} catch (Exception e) {
userAdditionalInfo = "";
}
if (!userAdditionalInfo.equalsIgnoreCase("")) {
userProxy.setVar(j, userAdditionalInfo);
}
}
com.dotmarketing.business.APILocator.getUserProxyAPI().saveUserProxy(userProxy,APILocator.getUserAPI().getSystemUser(), false);
userProxyInode = userProxy.getInode();
// adding roles to user
Permission permission = null;
if (readPermissions != null) {
for (int n = 0; n < readPermissions.length; n++) {
permission = new Permission(userProxyInode, readPermissions[n], PERMISSION_READ);
permissionAPI.save(permission, userProxy, systemUser, false);
}
}
if (writePermissions != null) {
for (int n = 0; n < writePermissions.length; n++) {
permission = new Permission(userProxyInode, writePermissions[n], PERMISSION_WRITE);
permissionAPI.save(permission, userProxy, systemUser, false);
}
}
Date today = new Date();
Address address = PublicAddressFactory.getInstance();
address.setUserName(user.getFullName());
address.setCompanyId(companyId);
address.setUserId(user.getUserId());
address.setCreateDate(today);
address.setModifiedDate(today);
address.setPriority(1);
address.setClassName(user.getClass().getName());
address.setClassPK(user.getUserId());
address.setDescription("Primary");
address.setStreet1(street1);
address.setStreet2(street2);
address.setCountry(country);
address.setCity(city);
address.setState(state);
address.setZip(zip);
address.setPhone(phone);
address.setFax(fax);
address.setCell(cell);
PublicAddressFactory.save(address);
// creating tag users
if (UtilMethods.isSet(userForm.getTagName())) {
StringTokenizer tagNameToken = new StringTokenizer(userForm.getTagName(), ",");
if (tagNameToken.hasMoreTokens()) {
for (; tagNameToken.hasMoreTokens();) {
String tagTokenized = tagNameToken.nextToken().trim();
TagFactory.addTag(tagTokenized, user.getUserId(),"");
}
}
}
for (String roleId : roles) {
com.dotmarketing.business.APILocator.getRoleAPI().addRoleToUser(roleId, user);
}
userCreated++;
userTaged++;
arrayUserIds.add(user.getUserId());
} else {
// email duplicated
if (userForm.isUpdateDuplicatedUsers()) {
if (UtilMethods.isSet(firstName))
userDuplicated.setFirstName(firstName);
if (UtilMethods.isSet(middleName))
userDuplicated.setMiddleName(middleName);
if (UtilMethods.isSet(lastName))
userDuplicated.setLastName(lastName);
userDuplicated
.setGreeting("Welcome, " + userDuplicated.getFirstName() + " " + userDuplicated.getLastName() + "!");
if (UtilMethods.isSet(email))
userDuplicated.setEmailAddress(email.trim().toLowerCase());
if (UtilMethods.isSet(birthday))
userDuplicated.setBirthday(birthday);
if (UtilMethods.isSet(password)) {
userDuplicated.setPassword(PublicEncryptionFactory.digestString(password));
userDuplicated.setPasswordEncrypted(true);
}
APILocator.getUserAPI().save(userDuplicated,APILocator.getUserAPI().getSystemUser(),false);
UserProxy userProxy = com.dotmarketing.business.APILocator.getUserProxyAPI().getUserProxy(userDuplicated,APILocator.getUserAPI().getSystemUser(), false);
// getting and saving the user
// additional info
String userAdditionalInfo = "";
for (int j = 1; j <= numberGenericVariables; j++) {
try {
userAdditionalInfo = lineTok[i++];
} catch (Exception e) {
userAdditionalInfo = "";
}
if (!userAdditionalInfo.equalsIgnoreCase("")) {
userProxy.setVar(j, userAdditionalInfo);
}
}
com.dotmarketing.business.APILocator.getUserProxyAPI().saveUserProxy(userProxy,APILocator.getUserAPI().getSystemUser(), false);
String userProxyInode = userProxy.getInode();
permissionAPI.removePermissions(userProxy);
// adding roles to user
if (readPermissions != null) {
for (int n = 0; n < readPermissions.length; n++) {
permissionAPI.save(new Permission(userProxyInode, readPermissions[n], PERMISSION_READ), userProxy, systemUser, false);
}
}
if (writePermissions != null) {
for (int n = 0; n < writePermissions.length; n++) {
permissionAPI.save(new Permission(userProxyInode, writePermissions[n], PERMISSION_WRITE), userProxy, systemUser, false);
}
}
Address address = null;
List<Address> addresses = PublicAddressFactory.getAddressesByUserId(userDuplicated.getUserId());
for (int pos = 0; pos < addresses.size(); ++pos) {
if ((addresses.get(pos).getDescription() != null) && (addresses.get(pos).getDescription().equals("Primary"))) {
address = addresses.get(pos);
break;
}
}
Date today = new Date();
if (address == null) {
address = PublicAddressFactory.getInstance();
address.setUserName(userDuplicated.getFullName());
address.setCompanyId(companyId);
address.setUserId(userDuplicated.getUserId());
address.setCreateDate(today);
address.setModifiedDate(today);
address.setPriority(1);
address.setClassName(userDuplicated.getClass().getName());
address.setClassPK(userDuplicated.getUserId());
address.setDescription("Primary");
address.setStreet1(street1);
address.setStreet2(street2);
address.setCountry(country);
address.setCity(city);
address.setState(state);
address.setZip(zip);
address.setPhone(phone);
address.setFax(fax);
address.setCell(cell);
} else {
address.setModifiedDate(today);
if (UtilMethods.isSet(street1))
address.setStreet1(street1);
if (UtilMethods.isSet(street2))
address.setStreet2(street2);
if (UtilMethods.isSet(country))
address.setCountry(country);
if (UtilMethods.isSet(city))
address.setCity(city);
if (UtilMethods.isSet(state))
address.setState(state);
if (UtilMethods.isSet(zip))
address.setZip(zip);
if (UtilMethods.isSet(phone))
address.setPhone(phone);
if (UtilMethods.isSet(fax))
address.setFax(fax);
if (UtilMethods.isSet(cell))
address.setCell(cell);
}
PublicAddressFactory.save(address);
for (String roleId : roles) {
com.dotmarketing.business.APILocator.getRoleAPI().addRoleToUser(roleId, userDuplicated);
}
countUserDuplicated++;
} else {
if (!someError) {
returnMessage.append(LanguageUtil.get(com.liferay.portal.util.PortalUtil.getUser(req), "Errors-loading-users-br-br"));
someError = true;
}
returnMessage.append(LanguageUtil.get(com.liferay.portal.util.PortalUtil.getUser(req), "Duplicated-Email")+": " + email + " "+LanguageUtil.get(com.liferay.portal.util.PortalUtil.getUser(req), "user.duplicated.email.line")+" " + lineNumber + "<br>");
}
if (UtilMethods.isSet(userForm.getTagName())) {
StringTokenizer tagNameToken = new StringTokenizer(userForm.getTagName(), ",");
if (tagNameToken.hasMoreTokens()) {
UserProxy userProxy = com.dotmarketing.business.APILocator.getUserProxyAPI().getUserProxy(userDuplicated,APILocator.getUserAPI().getSystemUser(), false);
for (; tagNameToken.hasMoreTokens();) {
String tagTokenized = tagNameToken.nextToken().trim();
TagFactory.addTagInode(tagTokenized, String.valueOf(userProxy.getUserId()), "");
}
}
}
arrayUserIds.add(userDuplicated.getUserId());
userTaged++;
}
} else {
// invalid email
if (!someError) {
returnMessage.append(LanguageUtil.get(com.liferay.portal.util.PortalUtil.getUser(req), "Errors-loading-users-br-br"));
someError = true;
}
returnMessage.append(LanguageUtil.get(com.liferay.portal.util.PortalUtil.getUser(req), "Invalid-Email")+": " + email + " "+LanguageUtil.get(com.liferay.portal.util.PortalUtil.getUser(req), "user.duplicated.email.line")+" " + lineNumber + "<br>");
}
} catch (Exception e) {
if (!someError) {
returnMessage.append(LanguageUtil.get(com.liferay.portal.util.PortalUtil.getUser(req), "Errors-loading-users-br-br"));
someError = true;
}
returnMessage.append(LanguageUtil.get(com.liferay.portal.util.PortalUtil.getUser(req), "Error-creating-user-with-email")+": " + email + " "+LanguageUtil.get(com.liferay.portal.util.PortalUtil.getUser(req), "user.duplicated.email.line")+" " + lineNumber + "<br>");
}
}
CacheLocator.getCmsRoleCache().clearCache();
} catch (Exception e) {
Logger.error(this.getClass(), e.getMessage(), e);
}
if (someError) {
returnMessage.append("<br><br>");
} else {
returnMessage.append(LanguageUtil.get(com.liferay.portal.util.PortalUtil.getUser(req), "Users-uploaded-successfully-br-br"));
}
HibernateUtil.commitTransaction();
returnMessage.append(userCreated + " "+LanguageUtil.get(com.liferay.portal.util.PortalUtil.getUser(req), "new-user-accounts-created<br>")+" " + countUserDuplicated +" "+LanguageUtil.get(com.liferay.portal.util.PortalUtil.getUser(req), "user-accounts-updated"));
if (UtilMethods.isSet(userForm.getTagName())) {
returnMessage.append("<br>" + userTaged +" "+ LanguageUtil.get(com.liferay.portal.util.PortalUtil.getUser(req), "users-tagged-as>")+" " + userForm.getTagName());
}
SessionMessages.add(req, "message", returnMessage.toString());
userForm.setArrayUserIds((String[]) arrayUserIds.toArray(new String[0]));
HibernateUtil.flush();
}
}