com.stoxx.service.business.registration.RegistrationServiceImpl.java Source code

Java tutorial

Introduction

Here is the source code for com.stoxx.service.business.registration.RegistrationServiceImpl.java

Source

package com.stoxx.service.business.registration;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.dao.DataAccessException;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.util.StringPool;
import com.liferay.portal.kernel.util.Validator;
import com.liferay.portal.model.Address;
import com.liferay.portal.model.Contact;
import com.liferay.portal.model.Country;
import com.liferay.portal.model.Group;
import com.liferay.portal.model.ListType;
import com.liferay.portal.model.ListTypeConstants;
import com.liferay.portal.model.Phone;
import com.liferay.portal.model.Role;
import com.liferay.portal.model.RoleConstants;
import com.liferay.portal.model.User;
import com.liferay.portal.model.UserGroup;
import com.liferay.portal.security.auth.PrincipalThreadLocal;
import com.liferay.portal.security.permission.PermissionChecker;
import com.liferay.portal.security.permission.PermissionCheckerFactoryUtil;
import com.liferay.portal.security.permission.PermissionThreadLocal;
import com.liferay.portal.service.AddressLocalServiceUtil;
import com.liferay.portal.service.AddressServiceUtil;
import com.liferay.portal.service.ContactLocalServiceUtil;
import com.liferay.portal.service.CountryServiceUtil;
import com.liferay.portal.service.GroupLocalServiceUtil;
import com.liferay.portal.service.ListTypeServiceUtil;
import com.liferay.portal.service.PhoneLocalServiceUtil;
import com.liferay.portal.service.PhoneServiceUtil;
import com.liferay.portal.service.RoleLocalServiceUtil;
import com.liferay.portal.service.ServiceContext;
import com.liferay.portal.service.UserGroupLocalServiceUtil;
import com.liferay.portal.service.UserLocalServiceUtil;
import com.liferay.portal.theme.ThemeDisplay;
import com.stoxx.digital.platform.model.SalesEntry;
import com.stoxx.digital.platform.service.SalesEntryLocalServiceUtil;
import com.stoxx.service.constant.STOXXConstants;
import com.stoxx.service.dao.registration.RegistrationDAO;
import com.stoxx.service.domain.TranslatorAgency;
import com.stoxx.service.domain.userprofile.UserPreferencesDetails;
import com.stoxx.service.domain.userprofile.UserProfileDetails;
import com.stoxx.service.exception.STOXXException;

public class RegistrationServiceImpl implements RegistrationService, Serializable {

    private static final String EMAIL_ADDRESS_IS = "email address is ";
    private static final long serialVersionUID = 1L;
    private static final Logger logger = Logger.getLogger(RegistrationServiceImpl.class);
    private RegistrationDAO registrationDAO;

    public void setRegistrationDAO(RegistrationDAO registrationDAO) {
        this.registrationDAO = registrationDAO;
    }

    public RegistrationDAO getRegistrationDAO() {
        return registrationDAO;
    }

    @Override
    public void addUserRegistration(UserProfileDetails userProfileDetails)
            throws STOXXException, DataAccessException {
        logger.info("**************From serviceIMPL***********");
        registrationDAO.addUserRegistration(userProfileDetails);
    }

    @Override
    public Contact saveContactToLiferayDB(Contact contact) throws STOXXException {
        try {
            return ContactLocalServiceUtil.addContact(contact);
        } catch (SystemException e) {
            logger.error(e.getMessage(), e);
            throw new STOXXException(e.getMessage(), e);
        }
    }

    @Override
    public void deleteUserOnRollBack(String businessEmailaddress, long companyId) throws STOXXException {
        registrationDAO.deleteUserFromCustomDb(businessEmailaddress);
        User user = null;
        try {
            user = UserLocalServiceUtil.getUserByEmailAddress(companyId, businessEmailaddress);
            if (null != user) {
                UserLocalServiceUtil.deleteUser(user.getUserId());
                PhoneLocalServiceUtil.deletePhones(user.getCompanyId(), Contact.class.getName(),
                        user.getContactId());
                AddressLocalServiceUtil.deleteAddresses(user.getUserId(), Contact.class.getName(),
                        user.getContactId());
            }
        } catch (PortalException e) {
            logger.error(e.getMessage(), e);
        } catch (SystemException e) {
            logger.error(e.getMessage(), e);
        }

    }

    public User updateExistingLiferayUser(UserProfileDetails userProfileDetails) throws STOXXException {
        logger.info("the ****************************>COMPANY id is " + userProfileDetails.getCompanyId()
                + EMAIL_ADDRESS_IS + userProfileDetails.getCompanyId());
        User user = null;
        try {
            user = UserLocalServiceUtil.getUserByEmailAddress(userProfileDetails.getCompanyId(),
                    userProfileDetails.getEmailAddress());
            if (Validator.isNotNull(user)) {
                user.setFirstName(userProfileDetails.getFirstName());
                user.setLastName(userProfileDetails.getLastName());
                user.setJobTitle(userProfileDetails.getJobTitle());
                user.setCreateDate(new Date());
            }
            user = UserLocalServiceUtil.updateUser(user);
            user = UserLocalServiceUtil.updatePassword(user.getUserId(), userProfileDetails.getPassword(),
                    userProfileDetails.getPassword(), Boolean.FALSE);
        } catch (PortalException e) {
            logger.error(e.getMessage(), e);
            throw new STOXXException(e.getMessage(), e);
        } catch (SystemException e) {
            logger.error(e.getMessage(), e);
            throw new STOXXException(e.getMessage(), e);
        }
        logger.info("the user returned with userId " + user.getUserId());
        return user;
    }

    private void assignRolesForReRegisteredUser(UserProfileDetails userProfileDetails, ThemeDisplay themeDisplay,
            ServiceContext serviceContext, TranslatorAgency translatorAgency, User user) throws STOXXException {
        try {
            if (userProfileDetails.getUserType().equalsIgnoreCase(STOXXConstants.STOXX_REGISTERED_USER)) {
                if (null != userProfileDetails.getSalesEntryId()) {

                    List<Long> roleList = new ArrayList<Long>();
                    Long salesEntryID = userProfileDetails.getSalesEntryId();
                    SalesEntry salesEntry = SalesEntryLocalServiceUtil.getSalesEntry(salesEntryID);
                    if (!(salesEntry.getPackageNames().contains(StringPool.COMMA))) {
                        Role packageRole = RoleLocalServiceUtil.getRole(themeDisplay.getCompanyId(),
                                salesEntry.getPackageNames().trim());
                        long packageRoleId = packageRole.getRoleId();
                        roleList.add(packageRoleId);
                    } else {
                        for (String packageName : salesEntry.getPackageNames().split(StringPool.COMMA)) {
                            Role packageRole = RoleLocalServiceUtil.getRole(themeDisplay.getCompanyId(),
                                    packageName.trim());
                            long packageRoleId = packageRole.getRoleId();
                            roleList.add(packageRoleId);
                        }
                    }

                    if (StringUtils.isNotBlank(salesEntry.getKeyEmailAddress()) && salesEntry.getKeyEmailAddress()
                            .trim().equalsIgnoreCase(userProfileDetails.getEmailAddress())) {
                        if (isLicensedUser(userProfileDetails.getEmailAddress())) {
                            Role keyAccntHolderUserRole = RoleLocalServiceUtil.getRole(themeDisplay.getCompanyId(),
                                    STOXXConstants.STOXX_KEY_ACCOUNT_HOLDER_ROLE);
                            long roleKeyAccntHolder = keyAccntHolderUserRole.getRoleId();
                            roleList.add(roleKeyAccntHolder);
                        }
                    }

                    long roleLicensed[] = ArrayUtils.toPrimitive(roleList.toArray(new Long[roleList.size()]));
                    RoleLocalServiceUtil.addUserRoles(user.getUserId(), roleLicensed);
                }
            } else if (userProfileDetails.getUserType().equalsIgnoreCase(STOXXConstants.STOXX_VENDOR_USER)) {
                if (translatorAgency != null) {

                    StringBuilder userGroupNameTemp = new StringBuilder();
                    String userGroupName = StringPool.BLANK;
                    List<Long> translatorRoles = null;
                    if (translatorAgency.getCompanyName().trim().contains(StringPool.SPACE)) {

                        for (String word : translatorAgency.getCompanyName().trim().split(StringPool.SPACE)) {
                            userGroupNameTemp.append(word).append(StringPool.UNDERLINE);
                        }
                        userGroupName = userGroupNameTemp.substring(0, userGroupNameTemp.length() - 1);
                        translatorRoles = assignTranslatorRole(userGroupName, translatorAgency, themeDisplay);
                    } else {
                        userGroupName = translatorAgency.getCompanyName().trim();
                        translatorRoles = assignTranslatorRole(userGroupName, translatorAgency, themeDisplay);
                    }
                    UserGroup translatorGroup = UserGroupLocalServiceUtil.getUserGroup(themeDisplay.getCompanyId(),
                            userGroupName);
                    long translatorGroupId[] = { translatorGroup.getUserGroupId() };
                    long translatorRoleId[] = ArrayUtils
                            .toPrimitive(translatorRoles.toArray(new Long[translatorRoles.size()]));
                    if (translatorAgency.getAgencyManagerEmailId()
                            .equalsIgnoreCase(userProfileDetails.getEmailAddress())) {
                        RoleLocalServiceUtil.addUserRoles(user.getUserId(), translatorRoleId);
                        UserGroupLocalServiceUtil.addUserUserGroups(user.getUserId(),
                                UserGroupLocalServiceUtil.getUserGroups(translatorGroupId));
                    }

                }
            }

            Role powerUserRole = RoleLocalServiceUtil.getRole(themeDisplay.getCompanyId(),
                    RoleConstants.POWER_USER);
            if (Validator.isNotNull(powerUserRole)) {
                long rolePower[] = { powerUserRole.getRoleId() };
                if (Validator.isNotNull(user) && rolePower.length > 0) {
                    RoleLocalServiceUtil.unsetUserRoles(user.getUserId(), rolePower);
                }
            }
        } catch (PortalException e) {
            logger.error(e.getMessage(), e);
            throw new STOXXException(e.getMessage(), e);
        } catch (SystemException e) {
            logger.error(e.getMessage(), e);
            throw new STOXXException(e.getMessage(), e);
        }

    }

    public User updateReRegisteredLiferayUser(UserProfileDetails userProfileDetails, ThemeDisplay themeDisplay,
            ServiceContext serviceContext, TranslatorAgency translatorAgency) throws STOXXException {
        logger.info("the ****************************>COMPANY id is " + userProfileDetails.getCompanyId()
                + EMAIL_ADDRESS_IS + userProfileDetails.getCompanyId());
        User user = null;
        try {
            user = UserLocalServiceUtil.getUserByEmailAddress(userProfileDetails.getCompanyId(),
                    userProfileDetails.getEmailAddress());
            if (Validator.isNotNull(user)) {
                user.setFirstName(userProfileDetails.getFirstName());
                user.setLastName(userProfileDetails.getLastName());
                user.setJobTitle(userProfileDetails.getJobTitle());
                user.setCreateDate(new Date());
            }

            assignRolesForReRegisteredUser(userProfileDetails, themeDisplay, serviceContext, translatorAgency,
                    user);

            //user = UserLocalServiceUtil.updateUser(user);
            user = UserLocalServiceUtil.updatePassword(user.getUserId(), userProfileDetails.getPassword(),
                    userProfileDetails.getPassword(), Boolean.FALSE);
        } catch (PortalException e) {
            logger.error(e.getMessage(), e);
            throw new STOXXException(e.getMessage(), e);
        } catch (SystemException e) {
            logger.error(e.getMessage(), e);
            throw new STOXXException(e.getMessage(), e);
        }
        logger.info("the user returned with userId " + user.getUserId());
        return user;
    }

    public User saveUserToLiferayDB(UserProfileDetails userProfileDetails, ThemeDisplay themeDisplay,
            ServiceContext serviceContext) throws STOXXException {
        try {
            Group stoxxNetgroup = GroupLocalServiceUtil.getGroup(themeDisplay.getCompanyId(),
                    STOXXConstants.STOXXNET_SITE_NAME);
            Group stoxxgroup = GroupLocalServiceUtil.getGroup(themeDisplay.getCompanyId(),
                    STOXXConstants.STOXX_SITE_NAME);
            User adminDefaultUser = UserLocalServiceUtil.getDefaultUser(themeDisplay.getCompanyId());
            logger.info("the ****************************>default user id is " + adminDefaultUser.getUserId()
                    + EMAIL_ADDRESS_IS + adminDefaultUser.getEmailAddresses());
            long[] groupIds = null;
            if (userProfileDetails.getUserType().equalsIgnoreCase(STOXXConstants.STOXX_VENDOR_USER)) {
                groupIds = new long[] { stoxxNetgroup.getGroupId() };
            } else if (userProfileDetails.getUserType().equalsIgnoreCase(STOXXConstants.STOXX_GENERAL_USER)
                    || userProfileDetails.getUserType().equalsIgnoreCase(STOXXConstants.STOXX_REGISTERED_USER)) {
                groupIds = new long[] { stoxxgroup.getGroupId() };
            } else if (userProfileDetails.getUserType().equalsIgnoreCase(STOXXConstants.STOXX_STAFF_USER)) {
                groupIds = new long[] { stoxxNetgroup.getGroupId(), stoxxgroup.getGroupId() };
            }
            User user = null;
            if (!(userProfileDetails.getUserType().equalsIgnoreCase(STOXXConstants.STOXX_VENDOR_USER))) {
                if (userProfileDetails.getUserType().equalsIgnoreCase(STOXXConstants.STOXX_REGISTERED_USER)) {
                    if (null != userProfileDetails.getSalesEntryId()) {

                        List<Long> roleList = new ArrayList<Long>();
                        Long salesEntryID = userProfileDetails.getSalesEntryId();
                        SalesEntry salesEntry = SalesEntryLocalServiceUtil.getSalesEntry(salesEntryID);
                        if (!(salesEntry.getPackageNames().contains(StringPool.COMMA))) {
                            Role packageRole = RoleLocalServiceUtil.getRole(themeDisplay.getCompanyId(),
                                    salesEntry.getPackageNames().trim());
                            long packageRoleId = packageRole.getRoleId();
                            roleList.add(packageRoleId);
                        } else {
                            for (String packageName : salesEntry.getPackageNames().split(StringPool.COMMA)) {
                                Role packageRole = RoleLocalServiceUtil.getRole(themeDisplay.getCompanyId(),
                                        packageName.trim());
                                long packageRoleId = packageRole.getRoleId();
                                roleList.add(packageRoleId);
                            }
                        }

                        if (StringUtils.isNotBlank(salesEntry.getKeyEmailAddress())
                                && salesEntry.getKeyEmailAddress().trim()
                                        .equalsIgnoreCase(userProfileDetails.getEmailAddress())) {
                            if (isLicensedUser(userProfileDetails.getEmailAddress())) {
                                Role keyAccntHolderUserRole = RoleLocalServiceUtil.getRole(
                                        themeDisplay.getCompanyId(), STOXXConstants.STOXX_KEY_ACCOUNT_HOLDER_ROLE);
                                long roleKeyAccntHolder = keyAccntHolderUserRole.getRoleId();
                                roleList.add(roleKeyAccntHolder);
                            }
                        }

                        long roleLicensed[] = ArrayUtils.toPrimitive(roleList.toArray(new Long[roleList.size()]));
                        user = UserLocalServiceUtil.addUser(adminDefaultUser.getUserId(),
                                themeDisplay.getCompanyId(), false, userProfileDetails.getPassword(),
                                userProfileDetails.getPassword(), true, StringPool.BLANK,
                                userProfileDetails.getEmailAddress(), 0, StringPool.BLANK, themeDisplay.getLocale(),
                                userProfileDetails.getFirstName(), StringPool.BLANK,
                                userProfileDetails.getLastName(), userProfileDetails.getPrefixId(), 0,
                                userProfileDetails.isGender(), userProfileDetails.getBirthMonth(),
                                userProfileDetails.getBirthDay(), userProfileDetails.getBirthYear(),
                                userProfileDetails.getJobTitle(), groupIds, null, roleLicensed, null, false,
                                serviceContext);
                    }
                } else {
                    user = UserLocalServiceUtil.addUser(adminDefaultUser.getUserId(), themeDisplay.getCompanyId(),
                            false, userProfileDetails.getPassword(), userProfileDetails.getPassword(), true,
                            StringPool.BLANK, userProfileDetails.getEmailAddress(), 0, StringPool.BLANK,
                            themeDisplay.getLocale(), userProfileDetails.getFirstName(), StringPool.BLANK,
                            userProfileDetails.getLastName(), userProfileDetails.getPrefixId(), 0,
                            userProfileDetails.isGender(), userProfileDetails.getBirthMonth(),
                            userProfileDetails.getBirthDay(), userProfileDetails.getBirthYear(),
                            userProfileDetails.getJobTitle(), groupIds, null, null, null, false, serviceContext);
                }
            }
            Role powerUserRole = RoleLocalServiceUtil.getRole(themeDisplay.getCompanyId(),
                    RoleConstants.POWER_USER);
            if (Validator.isNotNull(powerUserRole)) {
                long rolePower[] = { powerUserRole.getRoleId() };
                if (Validator.isNotNull(user) && rolePower.length > 0) {
                    RoleLocalServiceUtil.unsetUserRoles(user.getUserId(), rolePower);
                }
            }
            return user;
        } catch (PortalException e) {
            logger.error(e.getMessage(), e);
            throw new STOXXException(e.getMessage(), e);
        } catch (SystemException e) {
            logger.error(e.getMessage(), e);
            throw new STOXXException(e.getMessage(), e);
        }
    }

    // To save User Details those who are translator
    @Override
    public User saveUserToLiferayDBForTranslator(UserProfileDetails userProfileDetails, ThemeDisplay themeDisplay,
            ServiceContext serviceContext, TranslatorAgency translatorAgency) throws STOXXException {
        try {
            Group stoxxNetgroup = GroupLocalServiceUtil.getGroup(themeDisplay.getCompanyId(),
                    STOXXConstants.STOXXNET_SITE_NAME);
            User adminDefaultUser = UserLocalServiceUtil.getDefaultUser(themeDisplay.getCompanyId());
            logger.info("the ****************************>default user id is " + adminDefaultUser.getUserId()
                    + EMAIL_ADDRESS_IS + adminDefaultUser.getEmailAddresses());
            long[] groupIds = null;
            if (userProfileDetails.getUserType().equalsIgnoreCase(STOXXConstants.STOXX_VENDOR_USER)) {
                groupIds = new long[] { stoxxNetgroup.getGroupId() };
            }
            User user = null;
            if (userProfileDetails.getUserType().equalsIgnoreCase(STOXXConstants.STOXX_VENDOR_USER)) {
                StringBuilder userGroupNameTemp = new StringBuilder();
                String userGroupName = StringPool.BLANK;
                List<Long> translatorRoles = null;
                if (translatorAgency.getCompanyName().trim().contains(StringPool.SPACE)) {

                    for (String word : translatorAgency.getCompanyName().trim().split(StringPool.SPACE)) {
                        userGroupNameTemp.append(word).append(StringPool.UNDERLINE);
                    }
                    userGroupName = userGroupNameTemp.substring(0, userGroupNameTemp.length() - 1);
                    translatorRoles = assignTranslatorRole(userGroupName, translatorAgency, themeDisplay);
                } else {
                    userGroupName = translatorAgency.getCompanyName().trim();
                    translatorRoles = assignTranslatorRole(userGroupName, translatorAgency, themeDisplay);
                }
                UserGroup translatorGroup = UserGroupLocalServiceUtil.getUserGroup(themeDisplay.getCompanyId(),
                        userGroupName);
                long translatorGroupId[] = { translatorGroup.getUserGroupId() };
                long translatorRoleId[] = ArrayUtils
                        .toPrimitive(translatorRoles.toArray(new Long[translatorRoles.size()]));
                if (translatorAgency.getAgencyManagerEmailId()
                        .equalsIgnoreCase(userProfileDetails.getEmailAddress())) {
                    user = UserLocalServiceUtil.addUser(adminDefaultUser.getUserId(), themeDisplay.getCompanyId(),
                            false, userProfileDetails.getPassword(), userProfileDetails.getPassword(), true,
                            StringPool.BLANK, userProfileDetails.getEmailAddress(), 0, StringPool.BLANK,
                            themeDisplay.getLocale(), userProfileDetails.getFirstName(), StringPool.BLANK,
                            userProfileDetails.getLastName(), userProfileDetails.getPrefixId(), 0,
                            userProfileDetails.isGender(), userProfileDetails.getBirthMonth(),
                            userProfileDetails.getBirthDay(), userProfileDetails.getBirthYear(),
                            userProfileDetails.getJobTitle(), groupIds, null, translatorRoleId, translatorGroupId,
                            false, serviceContext);
                } else {
                    user = UserLocalServiceUtil.addUser(adminDefaultUser.getUserId(), themeDisplay.getCompanyId(),
                            false, userProfileDetails.getPassword(), userProfileDetails.getPassword(), true,
                            StringPool.BLANK, userProfileDetails.getEmailAddress(), 0, StringPool.BLANK,
                            themeDisplay.getLocale(), userProfileDetails.getFirstName(), StringPool.BLANK,
                            userProfileDetails.getLastName(), userProfileDetails.getPrefixId(), 0,
                            userProfileDetails.isGender(), userProfileDetails.getBirthMonth(),
                            userProfileDetails.getBirthDay(), userProfileDetails.getBirthYear(),
                            userProfileDetails.getJobTitle(), groupIds, null, null, translatorGroupId, false,
                            serviceContext);
                }
            }
            Role powerUserRole = RoleLocalServiceUtil.getRole(themeDisplay.getCompanyId(),
                    RoleConstants.POWER_USER);
            if (Validator.isNotNull(powerUserRole)) {
                long rolePower[] = { powerUserRole.getRoleId() };
                if (Validator.isNotNull(user) && rolePower.length > 0) {
                    RoleLocalServiceUtil.unsetUserRoles(user.getUserId(), rolePower);
                }
            }

            return user;
        } catch (PortalException e) {
            logger.error(e.getMessage(), e);
            throw new STOXXException(e.getMessage(), e);
        } catch (SystemException e) {
            logger.error(e.getMessage(), e);
            throw new STOXXException(e.getMessage(), e);
        }
    }

    private List<Long> assignTranslatorRole(String userGroupName, TranslatorAgency translatorAgency,
            ThemeDisplay themeDisplay) {
        List<Long> roleList = new ArrayList<Long>();
        try {
            if (translatorAgency.getTranslatorLanguage().trim().contains(StringPool.COMMA)) {
                for (String language : translatorAgency.getTranslatorLanguage().trim().split(StringPool.COMMA)) {
                    Role translatorRole = RoleLocalServiceUtil.getRole(themeDisplay.getCompanyId(),
                            userGroupName.concat(StringPool.UNDERLINE.concat(language)));
                    long translatorRoleId = translatorRole.getRoleId();
                    roleList.add(translatorRoleId);
                }
            } else {
                Role translatorRole = RoleLocalServiceUtil.getRole(themeDisplay.getCompanyId(), userGroupName
                        .concat(StringPool.UNDERLINE.concat(translatorAgency.getTranslatorLanguage().trim())));
                long translatorRoleId = translatorRole.getRoleId();
                roleList.add(translatorRoleId);
            }
        }

        catch (PortalException e) {
            logger.error(e.getMessage(), e);
        } catch (SystemException e) {
            logger.error(e.getMessage(), e);
        }
        return roleList;
    }

    @Override
    public void saveAddressToLiferayDB(UserProfileDetails userProfileDetails, User user, ThemeDisplay themeDisplay,
            ServiceContext serviceContext) throws STOXXException {

        try {
            List<ListType> listTypeAddress = ListTypeServiceUtil
                    .getListTypes(Contact.class.getName() + ListTypeConstants.ADDRESS);
            AddressLocalServiceUtil.addAddress(user.getUserId(), Contact.class.getName(), user.getContactId(),
                    userProfileDetails.getStreet1(), userProfileDetails.getStreet2(), "",
                    userProfileDetails.getCity(), userProfileDetails.getZip(), 0, userProfileDetails.getCountryId(),
                    listTypeAddress.get(0).getListTypeId(), Boolean.FALSE, Boolean.TRUE, serviceContext);
        } catch (SystemException e) {
            logger.error(e.getMessage(), e);
        } catch (PortalException e) {
            logger.error(e.getMessage(), e);
        }

    }

    @Override
    public void updateMigratedUserAddressToLiferayDB(UserProfileDetails userProfileDetails, User user,
            ThemeDisplay themeDisplay, ServiceContext serviceContext) throws STOXXException {
        try {
            permissionSetter(user);
            List<ListType> listTypeAddress = ListTypeServiceUtil
                    .getListTypes(Contact.class.getName() + ListTypeConstants.ADDRESS);
            List<Address> addresses = AddressServiceUtil.getAddresses(Contact.class.getName(), user.getContactId());
            for (Address address : addresses) {
                if (address.getType().getName().equalsIgnoreCase(STOXXConstants.ADDRESS_TYPE_BUSINESS)) {
                    AddressLocalServiceUtil.updateAddress(address.getAddressId(), userProfileDetails.getStreet1(),
                            userProfileDetails.getStreet2(), StringPool.BLANK, userProfileDetails.getCity(),
                            userProfileDetails.getZip(), 0, userProfileDetails.getCountryId(),
                            listTypeAddress.get(0).getListTypeId(), Boolean.TRUE, Boolean.TRUE);
                    break;
                }
            }
            logger.info("addresse updated");
        } catch (STOXXException e) {
            logger.error(e.getMessage(), e);
            throw e;
        } catch (PortalException e) {
            logger.error(e.getMessage(), e);
            throw new STOXXException(e.getMessage(), e);
        } catch (SystemException e) {
            logger.error(e.getMessage(), e);
            throw new STOXXException(e.getMessage(), e);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new STOXXException(e.getMessage(), e);
        }

    }

    @Override
    public void savePhoneToLiferayDB(UserProfileDetails userProfileDetails, User user, ThemeDisplay themeDisplay,
            ServiceContext serviceContext) throws STOXXException {
        try {
            PhoneLocalServiceUtil.addPhone(user.getUserId(), Contact.class.getName(), user.getContactId(),
                    userProfileDetails.getNumber(), "", userProfileDetails.getTypeId(), Boolean.TRUE,
                    serviceContext);
        } catch (PortalException e) {
            logger.error(e.getMessage(), e);
            throw new STOXXException(e.getMessage(), e);
        } catch (SystemException e) {
            logger.error(e.getMessage(), e);
            throw new STOXXException(e.getMessage(), e);
        }
    }

    @Override
    public void updateMigratedUserPhoneToLiferayDB(UserProfileDetails userProfileDetails, User user,
            ThemeDisplay themeDisplay, ServiceContext serviceContext) throws STOXXException {
        try {
            permissionSetter(user);
            List<Phone> phones = PhoneServiceUtil.getPhones(Contact.class.getName(), user.getContactId());
            for (Phone phone : phones) {
                if (phone.getType().getName().equalsIgnoreCase(STOXXConstants.PHONE_TYPE_BUSINESS)) {
                    PhoneLocalServiceUtil.updatePhone(phone.getPhoneId(), userProfileDetails.getNumber(),
                            StringPool.BLANK, userProfileDetails.getTypeId(), Boolean.TRUE);
                    break;
                }

            }
            logger.info("Phone updated");
        } catch (SystemException e) {
            logger.error("RegistrationServiceImpl.updateMigratedUserPhoneToLiferayDB", e);
        } catch (PortalException e) {
            logger.error("PortalException.updateMigratedUserPhoneToLiferayDB", e);
        } catch (Exception e) {
            logger.error("Exception.updateMigratedUserPhoneToLiferayDB", e);
        }
    }

    /**
     * @param user
     * @throws Exception
     * @throws PortalException
     * @throws SystemException
     */
    public void permissionSetter(User user) throws Exception, PortalException, SystemException {
        PrincipalThreadLocal.setName(user.getUserId());
        PermissionChecker permissionChecker = PermissionCheckerFactoryUtil
                .create(UserLocalServiceUtil.getUser(user.getUserId()));
        PermissionThreadLocal.setPermissionChecker(permissionChecker);
    }

    // UserPreference Table details
    @Override
    public void addUserPrefRegistration(List<UserPreferencesDetails> userPreferencesDetails)
            throws STOXXException, DataAccessException {
        registrationDAO.addUserPrefRegistration(userPreferencesDetails);

    }

    @Override
    public void deleteUserPrefRegistration(List<UserPreferencesDetails> userPreferencesDetails)
            throws STOXXException, DataAccessException {
        registrationDAO.deleteUserPrefRegistration(userPreferencesDetails);

    }

    @Override
    public UserProfileDetails getUserFromCustomDB(UserProfileDetails userProfileDetails) throws STOXXException {
        try {
            if (null != userProfileDetails && null != userProfileDetails.getEmailAddress()) {
                return registrationDAO.getUserProfile(userProfileDetails.getEmailAddress());
            }
        } catch (Exception e) {
            logger.error("Exception in getUserFromCustomDB", e);
        }
        return userProfileDetails;
    }

    @Override
    public void saveUserUserGroupToLiferayDB(UserProfileDetails userProfileDetails, User user)
            throws STOXXException {

        try {
            if (userProfileDetails.getUserType().equalsIgnoreCase(STOXXConstants.STOXX_VENDOR_USER)) {
                UserGroupLocalServiceUtil.addUserUserGroup(user.getUserId(), UserGroupLocalServiceUtil
                        .getUserGroup(user.getCompanyId(), STOXXConstants.STOXX_TRANSLATOR));
            } else if (userProfileDetails.getUserType().equalsIgnoreCase(STOXXConstants.STOXX_STAFF_USER)) {
                UserGroupLocalServiceUtil.addUserUserGroup(user.getUserId(), UserGroupLocalServiceUtil
                        .getUserGroup(user.getCompanyId(), STOXXConstants.STOXX_STAFF_USER));
            } else if (userProfileDetails.getUserType().equalsIgnoreCase(STOXXConstants.STOXX_GENERAL_USER)
                    || userProfileDetails.getUserType().equalsIgnoreCase(STOXXConstants.STOXX_REGISTERED_USER)) {
                UserGroupLocalServiceUtil.addUserUserGroup(user.getUserId(),
                        UserGroupLocalServiceUtil.getUserGroup(user.getCompanyId(), STOXXConstants.STOXX_CUSTOMER));
                if (userProfileDetails.getUserType().equalsIgnoreCase(STOXXConstants.STOXX_REGISTERED_USER)) {
                    UserGroupLocalServiceUtil.addUserUserGroup(user.getUserId(), UserGroupLocalServiceUtil
                            .getUserGroup(user.getCompanyId(), STOXXConstants.STOXX_SALES_ENTRY));
                }
            }
        }

        catch (PortalException e) {
            logger.error("Portal exception in saveUserUserGroupToLiferayDB", e);
            throw new STOXXException(e.getMessage(), e);
        } catch (SystemException e) {
            logger.error(e.getMessage(), e);
            throw new STOXXException(e.getMessage(), e);
        }

    }

    @Override
    public boolean checkIfUserExistsInLiferay(UserProfileDetails userProfileDetails) throws STOXXException {
        boolean exists;

        UserProfileDetails userProfileDetails1 = registrationDAO
                .getUserProfile(userProfileDetails.getEmailAddress());
        if (null != userProfileDetails1) {
            exists = Boolean.TRUE;
        } else {
            exists = Boolean.FALSE;
        }

        return exists;
    }

    @Override
    public boolean checkIfUserExistsInLiferayDB(UserProfileDetails userProfileDetails) throws STOXXException {
        boolean exists;
        try {
            User stoxxUser = UserLocalServiceUtil.getUserByEmailAddress(userProfileDetails.getCompanyId(),
                    userProfileDetails.getEmailAddress());
            if (null != stoxxUser) {
                exists = Boolean.TRUE;
            } else {
                exists = Boolean.FALSE;
            }
        }

        catch (PortalException e) {
            logger.error(e.getMessage());
            exists = Boolean.FALSE;
        } catch (SystemException e) {
            logger.error(e.getMessage());
            exists = Boolean.FALSE;
        }
        return exists;
    }

    @SuppressWarnings("unchecked")
    @Override
    public Map<Long, String> getCountryMap(Locale locale) throws STOXXException {
        try {
            HashMap<Long, String> countryMap = new HashMap<Long, String>();
            Map<Long, String> sortedCountryMap = new HashMap<Long, String>();
            List<Country> countryList = CountryServiceUtil.getCountries();
            List<String> sortedCountryList = new ArrayList<String>();
            for (Country country : countryList) {
                sortedCountryList.add(country.getName());
            }
            Collections.sort(sortedCountryList);
            for (String countryName : sortedCountryList) {
                if (null != CountryServiceUtil.getCountryByName(countryName)
                        && 0 != CountryServiceUtil.getCountryByName(countryName).getCountryId()) {
                    countryMap.put(CountryServiceUtil.getCountryByName(countryName).getCountryId(),
                            CountryServiceUtil.getCountryByName(countryName).getName(locale));
                }
                sortedCountryMap = sortByValues(countryMap);

            }
            return sortedCountryMap;
        } catch (PortalException e) {
            logger.error(e.getMessage(), e);
            throw new STOXXException(e.getMessage(), e);
        } catch (SystemException e) {
            logger.error(e.getMessage(), e);
            throw new STOXXException(e.getMessage(), e);
        }
    }

    @SuppressWarnings({ "rawtypes", "unchecked" })
    private static Map sortByValues(Map map) {
        List list = new LinkedList(map.entrySet());
        // Defined Custom Comparator here
        Collections.sort(list, new Comparator() {

            public int compare(Object o1, Object o2) {
                return ((Comparable) ((Map.Entry) (o1)).getValue()).compareTo(((Map.Entry) (o2)).getValue());
            }
        });

        // Here I am copying the sorted list in HashMap
        // using LinkedHashMap to preserve the insertion order
        Map sortedHashMap = new LinkedHashMap();
        for (Iterator it = list.iterator(); it.hasNext();) {
            Map.Entry entry = (Map.Entry) it.next();
            sortedHashMap.put(entry.getKey(), entry.getValue());
        }
        return sortedHashMap;
    }

    public boolean isLicensedUser(String businessEmailaddress) {
        boolean registerFlag = Boolean.FALSE;
        try {
            UserProfileDetails userProfileDetails = registrationDAO.getUserProfile(businessEmailaddress);
            if (null != userProfileDetails) {
                if (userProfileDetails.getSalesEntryId() != 0) {
                    registerFlag = Boolean.TRUE;
                } else {
                    registerFlag = Boolean.FALSE;
                }
            }
        } catch (Exception e) {
            registerFlag = Boolean.FALSE;
        }

        return registerFlag;
    }

    public String getPackageDetails(Long salesEntryId) {
        String packageDetails = StringPool.BLANK;
        try {
            packageDetails = SalesEntryLocalServiceUtil.getSalesEntry(salesEntryId).getPackageNames();
        } catch (PortalException e) {
            logger.error(e.getMessage(), e);
        } catch (SystemException e) {
            logger.error(e.getMessage(), e);
        }
        return packageDetails;
    }

    @Override
    public List<UserPreferencesDetails> getUserPreferenceDetails(String emailAddress, String searchParam)
            throws STOXXException {
        return registrationDAO.getUserPrefDetails(emailAddress, searchParam);
    }

    @Override
    public List<UserPreferencesDetails> getUserPreferenceDetails(String emailAddress) throws STOXXException {
        return registrationDAO.getUserPrefDetails(emailAddress);
    }

    @Override
    public void updateUserType(String emailAddress, String userType) throws STOXXException {
        registrationDAO.updateUserType(emailAddress, userType);
    }

    @Override
    public boolean isInactiveUser(long companyId, String emailAddress) {
        logger.info("companyId : " + companyId + "emailAddress : " + emailAddress);
        boolean inactiveUser = Boolean.FALSE;
        try {
            User user = UserLocalServiceUtil.getUserByEmailAddress(companyId, emailAddress);
            if (user != null) {
                logger.info("user.toString() : " + user.getStatus());
                if (user.getStatus() == 1) {
                    inactiveUser = Boolean.TRUE;
                }
            }
            logger.info("inactiveUser : " + inactiveUser);
        } catch (Exception e) {
            logger.info("User didn't exist in liferay DB");
        }
        return inactiveUser;
    }

}