<commit_before>package gov.nih.nci.cabig.caaers.domain.repository;

import gov.nih.nci.cabig.caaers.CaaersSystemException;
import gov.nih.nci.cabig.caaers.RoleMembership;
import gov.nih.nci.cabig.caaers.dao._UserDao;
import gov.nih.nci.cabig.caaers.domain.UserGroupType;
import gov.nih.nci.cabig.caaers.domain._User;
import gov.nih.nci.cabig.ctms.suite.authorization.ProvisioningSession;
import gov.nih.nci.cabig.ctms.suite.authorization.ProvisioningSessionFactory;
import gov.nih.nci.cabig.ctms.suite.authorization.SuiteRole;
import gov.nih.nci.cabig.ctms.suite.authorization.SuiteRoleMembership;
import gov.nih.nci.security.UserProvisioningManager;
import gov.nih.nci.security.authorization.domainobjects.Group;
import gov.nih.nci.security.dao.UserSearchCriteria;
import gov.nih.nci.security.exceptions.CSObjectNotFoundException;
import gov.nih.nci.security.exceptions.CSTransactionException;
import gov.nih.nci.security.util.StringEncrypter;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.context.MessageSource;
import org.springframework.mail.MailException;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

public class UserRepositoryImpl implements UserRepository {

	private Logger logger = Logger.getLogger(UserRepositoryImpl.class);
	private _UserDao userDao;
	private UserProvisioningManager userProvisioningManager;
    private ProvisioningSessionFactory provisioningSessionFactory;
    
    private MailSender mailSender;
    private String authenticationMode;
    private MessageSource messageSource;
    
	
    @SuppressWarnings("unchecked")
	public List searchCsmUser(String firstName, String lastName, String userName) {
    	if(StringUtils.isEmpty(firstName) && StringUtils.isEmpty(lastName) && StringUtils.isEmpty(userName)) firstName = "%";
    	
    	gov.nih.nci.security.authorization.domainobjects.User example = new gov.nih.nci.security.authorization.domainobjects.User();
    	if(StringUtils.isNotEmpty(firstName)) example.setFirstName(firstName);
    	if(StringUtils.isNotEmpty(lastName)) example.setLastName(lastName);
    	if(StringUtils.isNotEmpty(userName)) example.setLoginName(userName);
    	UserSearchCriteria userSearchCriteria = new UserSearchCriteria(example);
    	return userProvisioningManager.getObjects(userSearchCriteria);	
	}
	
    @Transactional(readOnly = false)
    public void save(_User user){
    	userDao.save(user);
    }
    
    @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW, noRollbackFor = MailException.class)
	public void createOrUpdateUser(_User user,String changeURL){
		if(user.getCsmUser().getUserId() == null){
			createCSMUser(user);
			save(user);
			sendCreateAccountEmail(user,changeURL);
		}else{
			updateCSMUser(user);
			sendUpdateAccountEmail(user);
		}
	}

    /**
     * Will fetch the user from the DB, along with the CSM related information properly populated. 
     * @param loginName
     * @return
     */
    @Transactional(readOnly = true)
	public _User getUserByLoginName(String loginName) {
		_User _user = userDao.getByLoginName(loginName);
        gov.nih.nci.security.authorization.domainobjects.User csmUser = userProvisioningManager.getUser(loginName);
        if(_user == null && csmUser == null) return null; // may be login-id supplied is incorrect.
        if(csmUser == null){
            logger.error("CSM User with loginName [" + loginName +"] don't exist, a data integrity issue as user exist in caAERS");
            throw new CaaersSystemException("caAERS user exists and relevant CSM user does not exist : Data Integrity issue");
        }
        if(_user == null){
            _user = new _User(csmUser);
        }else{
            _user.setCsmUser(csmUser);
        }

        //populate the role membership
        ProvisioningSession session = provisioningSessionFactory.createSession(csmUser.getUserId());
        for(SuiteRole suiteRole : SuiteRole.values()){
            UserGroupType role = UserGroupType.getByCSMName(suiteRole.name());
            RoleMembership roleMembership = _user.findRoleMembership(role);
            if(suiteRole.isScoped()){
               SuiteRoleMembership suiteRoleMembership = session.getProvisionableRoleMembership(suiteRole);
               if(suiteRoleMembership.isAllSites()){
            	   roleMembership.setAllSite(suiteRoleMembership.isAllSites());
               }else{
            	   roleMembership.getOrganizationNCICodes().addAll(suiteRoleMembership.getSiteIdentifiers());
               }
               if(suiteRoleMembership.isAllStudies()){
            	   roleMembership.setAllStudy(suiteRoleMembership.isAllStudies());
               }else{
            	   roleMembership.getStudyIdentifiers().addAll(suiteRoleMembership.getStudyIdentifiers());
               }
            }
        }
		return _user;
	}	
	
    /**
     * Fetches the groups associated to users.  
     * @param loginName
     * @return
     */
    public List<UserGroupType> getUserGroups(String loginName) {
    	List<UserGroupType> userGroups = new ArrayList<UserGroupType>();
    	try {
			Set groups = userProvisioningManager.getGroups(loginName);
			if(groups != null){
				for(Object obj : groups){
					Group group = (Group) obj;
					UserGroupType userGroupType = UserGroupType.valueOf(group.getGroupName());
					if(userGroupType != null) userGroups.add(userGroupType);
				}
			}
		} catch (CSObjectNotFoundException e) {
			logger.warn("unable to fetch groups for CSM user (" + loginName + "), something is wrong", e);
		}
    	return userGroups;
    }<commit_msg>CAAERS-4506 - Refactor user provisioning to support all sites Changes to User data migration and Importing<commit_after>package gov.nih.nci.cabig.caaers.domain.repository;

import edu.nwu.bioinformatics.commons.CollectionUtils;
import gov.nih.nci.cabig.caaers.CaaersSystemException;
import gov.nih.nci.cabig.caaers.RoleMembership;
import gov.nih.nci.cabig.caaers.dao._UserDao;
import gov.nih.nci.cabig.caaers.domain.UserGroupType;
import gov.nih.nci.cabig.caaers.domain._User;
import gov.nih.nci.cabig.ctms.suite.authorization.ProvisioningSession;
import gov.nih.nci.cabig.ctms.suite.authorization.ProvisioningSessionFactory;
import gov.nih.nci.cabig.ctms.suite.authorization.SuiteRole;
import gov.nih.nci.cabig.ctms.suite.authorization.SuiteRoleMembership;
import gov.nih.nci.security.UserProvisioningManager;
import gov.nih.nci.security.authorization.domainobjects.Group;
import gov.nih.nci.security.dao.UserSearchCriteria;
import gov.nih.nci.security.exceptions.CSObjectNotFoundException;
import gov.nih.nci.security.exceptions.CSTransactionException;
import gov.nih.nci.security.util.StringEncrypter;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.context.MessageSource;
import org.springframework.mail.MailException;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

public class UserRepositoryImpl implements UserRepository {

	private Logger logger = Logger.getLogger(UserRepositoryImpl.class);
	private _UserDao userDao;
	private UserProvisioningManager userProvisioningManager;
    private ProvisioningSessionFactory provisioningSessionFactory;
    
    private MailSender mailSender;
    private String authenticationMode;
    private MessageSource messageSource;
    
	
    @SuppressWarnings("unchecked")
	public List searchCsmUser(String firstName, String lastName, String userName) {
    	if(StringUtils.isEmpty(firstName) && StringUtils.isEmpty(lastName) && StringUtils.isEmpty(userName)) firstName = "%";
    	
    	gov.nih.nci.security.authorization.domainobjects.User example = new gov.nih.nci.security.authorization.domainobjects.User();
    	if(StringUtils.isNotEmpty(firstName)) example.setFirstName(firstName);
    	if(StringUtils.isNotEmpty(lastName)) example.setLastName(lastName);
    	if(StringUtils.isNotEmpty(userName)) example.setLoginName(userName);
    	UserSearchCriteria userSearchCriteria = new UserSearchCriteria(example);
    	return userProvisioningManager.getObjects(userSearchCriteria);	
	}
	
    @Transactional(readOnly = false)
    public void save(_User user){
    	userDao.save(user);
    }
    
    @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW, noRollbackFor = MailException.class)
	public void createOrUpdateUser(_User user,String changeURL){
		if(user.getCsmUser().getUserId() == null){
			createCSMUser(user);
			save(user);
			sendCreateAccountEmail(user,changeURL);
		}else{
			updateCSMUser(user);
			sendUpdateAccountEmail(user);
		}
	}

    /**
     * Will fetch the user from the DB, along with the CSM related information properly populated. 
     * @param loginName
     * @return
     */
    @Transactional(readOnly = true)
	public _User getUserByLoginName(String loginName) {
		_User _user = userDao.getByLoginName(loginName);
        gov.nih.nci.security.authorization.domainobjects.User csmUser = userProvisioningManager.getUser(loginName);
        if(_user == null && csmUser == null) return null; // may be login-id supplied is incorrect.
        if(csmUser == null){
            logger.error("CSM User with loginName [" + loginName +"] don't exist, a data integrity issue as user exist in caAERS");
            throw new CaaersSystemException("caAERS user exists and relevant CSM user does not exist : Data Integrity issue");
        }
        if(_user == null){
            _user = new _User(csmUser);
        }else{
            _user.setCsmUser(csmUser);
        }

        //populate the role membership
        List<UserGroupType> groups = getUserGroups(loginName);
        if(!CollectionUtils.isEmpty(groups)){
           ProvisioningSession session = provisioningSessionFactory.createSession(csmUser.getUserId());
           for(UserGroupType role : groups){
               SuiteRole suiteRole = SuiteRole.valueOf(role.getCsmName());
               if(!suiteRole.isScoped()){
                     _user.findRoleMembership(role);
               }else{
                   SuiteRoleMembership suiteRoleMembership = session.getProvisionableRoleMembership(suiteRole);
                   RoleMembership roleMembership = _user.findRoleMembership(role);
                   if(suiteRoleMembership.isAllSites()){
                       roleMembership.setAllSite(suiteRoleMembership.isAllSites());
                   }else{
                       roleMembership.getOrganizationNCICodes().addAll(suiteRoleMembership.getSiteIdentifiers());
                   }
                   if(suiteRole.isStudyScoped()){
                      if(suiteRoleMembership.isAllStudies()){
                            roleMembership.setAllStudy(suiteRoleMembership.isAllStudies());
                       }else{
                           roleMembership.getStudyIdentifiers().addAll(suiteRoleMembership.getStudyIdentifiers());
                       }
                   }

               }
           }
        }

		return _user;
	}	
	
    /**
     * Fetches the groups associated to users.  
     * @param loginName
     * @return
     */
    public List<UserGroupType> getUserGroups(String loginName) {
    	List<UserGroupType> userGroups = new ArrayList<UserGroupType>();
    	try {
			Set groups = userProvisioningManager.getGroups(loginName);
			if(groups != null){
				for(Object obj : groups){
					Group group = (Group) obj;
					UserGroupType userGroupType = UserGroupType.valueOf(group.getGroupName());
					if(userGroupType != null) userGroups.add(userGroupType);
				}
			}
		} catch (CSObjectNotFoundException e) {
			logger.warn("unable to fetch groups for CSM user (" + loginName + "), something is wrong", e);
		}
    	return userGroups;
    }
{'fraction_non_alphanumeric': 0.09792118147523879, 'fraction_numerical': 0.0004815795810257645, 'mean_word_length': 3.675422138836773, 'pattern_counts': {'":': 0, '<': 10, '<?xml version=': 0, '>': 10, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '836132', 'n_tokens_mistral': 3767, 'n_tokens_neox': 3649, 'n_words': 645}