no.abmu.user.service.AbstractUserImportService.java Source code

Java tutorial

Introduction

Here is the source code for no.abmu.user.service.AbstractUserImportService.java

Source

/*$Id: AbstractUserImportService.java 13614 2009-04-03 07:17:16Z jens $*/
/*
 ****************************************************************************
 *                                                                          *
 *                   (c) Copyright 2008 ABM-utvikling                       *
 *                                                                          *
 *                                                                          *
 * This program is free software; you can redistribute it and/or modify it  *
 * under the terms of the GNU General Public License as published by the    *
 * Free Software Foundation; either version 2 of the License, or (at your   *
 * option) any later version.                                               *
 *                                                                          *
 * This program is distributed in the hope that it will be useful, but      *
 * WITHOUT ANY WARRANTY; without even the implied warranty of               *
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General *
 * Public License for more details. http://www.gnu.org/licenses/gpl.html    *
 *                                                                          *
 ****************************************************************************
 */

package no.abmu.user.service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import no.abmu.common.domain.Entity;
import no.abmu.organisationregister.domain.OrganisationTypeNameConst;
import no.abmu.organisationregister.domain.OrganisationUnit;
import no.abmu.organisationregister.finders.organisationunit.OrgUnitFinderSpecificationBean;
import no.abmu.organisationregister.finders.organisationunit.OrgUnitQueryFinderSpecification;
import no.abmu.organisationregister.service.OrganisationRegisterBaseService;
import no.abmu.organisationregister.util.OrganisationUnitImportExcelParser;
import no.abmu.user.domain.ContactInfo;
import no.abmu.user.domain.GroupOrgUnitMapping;
import no.abmu.user.domain.Role;
import no.abmu.user.domain.RoleRelation;
import no.abmu.user.domain.User;
import no.abmu.user.domain.UserGroup;
import no.abmu.user.domain.UserRoleNameConst;
import no.abmu.user.finders.role.RoleFinderSpecification;
import no.abmu.user.finders.user.UserFinderSpecification;
import no.abmu.user.util.UserUtil;
import no.abmu.util.date.DateUtil;
import no.abmu.util.string.StringUtil;
import no.abmu.util.test.Assert;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * <code>AbstractUserImportService</code> implements interface
 * UserImportService. 
 * 
 * @author Jens Vindvad, Jens.Vindvad@abm-utvikling.no
 * @author $Author: jens $
 * @version $Rev: 13614 $
 * $Date: 2009-04-03 09:17:16 +0200 (Fri, 03 Apr 2009) $
 * copyright ABM-Utvikling
 *
 */
public abstract class AbstractUserImportService implements UserImportService {

    private static final Log logger = (Log) LogFactory.getLog(AbstractUserImportService.class);

    private ReportingDeadlineService reportingDeadlineService;
    private OrganisationRegisterBaseService organisationRegisterBaseService;
    private UserService userService;

    public void setReportingDeadlineService(ReportingDeadlineService reportingDeadlineService) {
        this.reportingDeadlineService = reportingDeadlineService;
    }

    public void setOrganisationRegisterBaseService(OrganisationRegisterBaseService baseService) {
        this.organisationRegisterBaseService = baseService;
    }

    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    public UserService getUserService() {
        return userService;
    }

    //    @Override
    public abstract boolean importFromExcelFile(String fileName, String sheetName, boolean doRollback);

    protected OrganisationUnitImportExcelParser createExcelParser(String fileName, String sheetName) {
        Assert.checkRequiredArgument("fileName", fileName);
        Assert.checkRequiredArgument("sheetName", sheetName);

        logger.info("Opening file " + fileName + " and using sheet " + sheetName);

        OrganisationUnitImportExcelParser excelParser = new OrganisationUnitImportExcelParser();
        excelParser.setExcelFileName(fileName);
        excelParser.setSheetName(sheetName);
        excelParser.setOrganisationRegisterBaseService(organisationRegisterBaseService);
        excelParser.load();

        return excelParser;
    }
    /*
        protected int countNonExistentOrToManyOrgUnits(OrganisationUnitImportExcelParser excelParser) {
        
    int numberOfNonExistentOrToManyOrganisationUnits = 0;
        
    excelParser.load();
    for (; excelParser.hasNext(); excelParser.next()) {
        Long user = excelParser.getUser();
        if (user != null && user.equals(Long.valueOf(1))) {
            String orgUnitName = excelParser.getBokmaalName();
            if (DataLoaderUtils.checkForAndGetOneAndOnlyOneOrganisationUnitWithName(
                    organisationRegisterBaseService, orgUnitName) == null) {
                numberOfNonExistentOrToManyOrganisationUnits++;
            }
        }
        
    }
    return numberOfNonExistentOrToManyOrganisationUnits;
        }
    */

    protected boolean checkExistanceOfRolesForOrganisationUnits(OrganisationUnitImportExcelParser excelParser) {
        Assert.checkRequiredArgument("excelParser", excelParser);

        boolean allRolesExist = true;
        excelParser.load();
        List<OrganisationUnit> organisationUnits = new ArrayList<OrganisationUnit>();
        for (; excelParser.hasNext(); excelParser.next()) {
            Long user = excelParser.getUser();
            if (user != null && user.equals(Long.valueOf(1))) {
                String orgUnitName = excelParser.getBokmaalName();
                String abmuId = excelParser.getABMU_ID();
                OrganisationUnit organisationUnit = getSingleOrganisationUnit(abmuId, orgUnitName);
                organisationUnits.add(organisationUnit);
            }
        }

        Set<String> roleNames = new HashSet<String>();
        for (OrganisationUnit organisationUnit : organisationUnits) {
            String organisationTypeName = getMainOrganisationType(organisationUnit);
            Set<String> roleNamesForMainOrgType = getRoleNames(organisationUnit, organisationTypeName);
            roleNames.addAll(roleNamesForMainOrgType);
        }

        Map<String, Role> rolesFromDbInMap = rolesFromDbInMap();
        for (String roleName : roleNames) {
            if (!rolesFromDbInMap.containsKey(roleName)) {
                String warningMessage = "Role does not exist in RoleRegister RoleName : '" + roleName + "'.";
                logger.warn(warningMessage);
                // System.out.println(warningMessage);
                allRolesExist = false;
            }
        }
        return allRolesExist;
    }

    protected List<Entity> createUserStoreList(String orgUnitName) {
        return createUserStoreList(null, orgUnitName);
    }

    protected List<Entity> createUserStoreList(String abmuId, String orgUnitName) {
        Assert.checkRequiredArgument("orgUnitName", orgUnitName);

        OrganisationUnit organisationUnit = getSingleOrganisationUnit(abmuId, orgUnitName);
        String mainOrganisationTypeName = getMainOrganisationType(organisationUnit);

        Set<String> roleNamesForMainOrgType = getRoleNames(organisationUnit, mainOrganisationTypeName);
        if (roleNamesForMainOrgType == null || roleNamesForMainOrgType.size() == 0) {
            logger.warn("Can not create user for organisationUnit with name: '" + orgUnitName
                    + "' rollback and no import.");
            return null;
        }

        Map<String, Role> rolesFromDbInMap = rolesFromDbInMap();
        Set<Role> rolesForNewUser = new HashSet<Role>();
        for (String roleName : roleNamesForMainOrgType) {
            if (rolesFromDbInMap.containsKey(roleName)) {
                Role role = rolesFromDbInMap.get(roleName);
                rolesForNewUser.add(role);
            } else {
                // We should never get here.
                String errorMessage = "RoleName '" + roleName + "' does not exist in DB";
                logger.error(errorMessage);
                throw new IllegalStateException(errorMessage);
            }
        }

        if (rolesForNewUser == null || rolesForNewUser.size() == 0) {
            logger.error("Cant find any role for organisationUnit ==> " + organisationUnit);
            return null;
        }

        return createEntityStorList(organisationUnit, mainOrganisationTypeName, rolesForNewUser);

    }

    protected boolean checkThatOrganisationUnitsHasNoUser(OrganisationUnitImportExcelParser excelParser) {

        boolean checkWentOK = true;
        excelParser.load();
        for (; excelParser.hasNext(); excelParser.next()) {
            Long user = excelParser.getUser();
            if (user != null && user.equals(Long.valueOf(1))) {
                String orgUnitName = excelParser.getBokmaalName();
                String abmuId = excelParser.getABMU_ID();
                OrganisationUnit organisationUnit = getSingleOrganisationUnit(abmuId, orgUnitName);
                Long orgUnitId = organisationUnit.getId();
                UserFinderSpecification finder = new UserFinderSpecification(orgUnitId);
                Collection<User> users = userService.find(finder);
                if (users.size() > 0) {
                    logger.warn("OrganisationUnit id='" + orgUnitId + "' name='"
                            + organisationUnit.getName().getReference() + "' has allready '" + users.size()
                            + "' user(s).");
                    checkWentOK = false;
                }
            }
        }
        return checkWentOK;
    }

    protected Map<String, Role> rolesFromDbInMap() {
        RoleFinderSpecification finderSpecification = new RoleFinderSpecification();
        Collection<Role> rolesInList = userService.find(finderSpecification);
        Map<String, Role> roleMap = new HashMap<String, Role>();
        for (Role role : rolesInList) {
            roleMap.put(role.getName(), role);
        }
        return roleMap;
    }

    private Collection<OrganisationUnit> getOrganisationUnits(String orgUnitName) {

        OrgUnitFinderSpecificationBean finderBean = new OrgUnitFinderSpecificationBean();
        finderBean.setOrganisationUnitRefName(orgUnitName);

        OrgUnitQueryFinderSpecification finderSpecification = new OrgUnitQueryFinderSpecification(finderBean);

        Collection<OrganisationUnit> orgUnits = organisationRegisterBaseService.find(finderSpecification);

        return orgUnits;
    }

    private Collection<OrganisationUnit> getOrganisationUnitsByAbmuId(String abmuId) {

        OrgUnitFinderSpecificationBean finderBean = new OrgUnitFinderSpecificationBean();
        finderBean.setAbmuId(abmuId);

        OrgUnitQueryFinderSpecification finderSpecification = new OrgUnitQueryFinderSpecification(finderBean);

        Collection<OrganisationUnit> orgUnits = organisationRegisterBaseService.find(finderSpecification);

        return orgUnits;
    }

    private OrganisationUnit getSingleOrganisationUnit(String abmuId, String orgUnitName) {

        if (abmuId == null || "".equals(abmuId)) {
            return getSingleOrganisationUnit(orgUnitName);
        }

        Collection<OrganisationUnit> orgUnits = getOrganisationUnitsByAbmuId(abmuId);

        if (orgUnits.size() == 0) {
            // We should never get here.
            String errorMessage = "Can not find organisationUnit with ABMU id: '" + abmuId + "'.";
            logger.error(errorMessage);
            throw new IllegalStateException(errorMessage);
        }

        if (orgUnits.size() > 1) {
            // We should never get here.
            String errorMessage = orgUnits.size() + " organisationUnits has the ABMU id: '" + abmuId + "'.";
            logger.error(errorMessage);
            throw new IllegalStateException(errorMessage);
        }

        return orgUnits.iterator().next();
    }

    private OrganisationUnit getSingleOrganisationUnit(String orgUnitName) {

        Collection<OrganisationUnit> orgUnits = getOrganisationUnits(orgUnitName);

        if (orgUnits.size() == 0) {
            // We should never get here.
            String errorMessage = "Can not find organisationUnit with name: '" + orgUnitName + "'.";
            logger.error(errorMessage);
            throw new IllegalStateException(errorMessage);
        }

        if (orgUnits.size() > 1) {
            // We should never get here.
            String errorMessage = orgUnits.size() + " organisationUnits has the name: '" + orgUnitName + "'.";
            logger.error(errorMessage);
            throw new IllegalStateException(errorMessage);
        }

        return orgUnits.iterator().next();
    }

    private String getMainOrganisationType(OrganisationUnit organisationUnit) {

        String organisationTypeName = "";
        if (organisationUnit.hasType(OrganisationTypeNameConst.ARCHIVE_COMPLETE)) {
            organisationTypeName = OrganisationTypeNameConst.ARCHIVE_COMPLETE;
        } else if (organisationUnit.hasType(OrganisationTypeNameConst.ARCHIVE_LIGHT)) {
            organisationTypeName = OrganisationTypeNameConst.ARCHIVE_LIGHT;
        } else if (organisationUnit.hasType(OrganisationTypeNameConst.FAG_LIBRARY)) {
            organisationTypeName = OrganisationTypeNameConst.FAG_LIBRARY;
        } else if (organisationUnit.hasType(OrganisationTypeNameConst.REPORTINGMUSEUM)) {
            organisationTypeName = OrganisationTypeNameConst.REPORTINGMUSEUM;
        } else if (organisationUnit.hasType(OrganisationTypeNameConst.MUSEUM)) {
            organisationTypeName = OrganisationTypeNameConst.MUSEUM;
        } else if (organisationUnit.hasType(OrganisationTypeNameConst.FYLKES_LIBRARY)) {
            organisationTypeName = OrganisationTypeNameConst.FYLKES_LIBRARY;
        } else if (organisationUnit.hasType(OrganisationTypeNameConst.KOMMUNE)) {
            organisationTypeName = OrganisationTypeNameConst.KOMMUNE;
        } else if (organisationUnit.hasType(OrganisationTypeNameConst.FYLKE)) {
            organisationTypeName = OrganisationTypeNameConst.FYLKE;
        } else if (organisationUnit.hasType(OrganisationTypeNameConst.PUBLIC_LIBRARY)) {
            organisationTypeName = OrganisationTypeNameConst.PUBLIC_LIBRARY;
        } else if (organisationUnit.hasType(OrganisationTypeNameConst.HIGH_SCHOOL_LIBRARY)) {
            organisationTypeName = OrganisationTypeNameConst.HIGH_SCHOOL_LIBRARY;
        } else if (organisationUnit.hasType(OrganisationTypeNameConst.HOSPITAL_LIBRARY)) {
            organisationTypeName = OrganisationTypeNameConst.HOSPITAL_LIBRARY;
        } else if (organisationUnit.hasType(OrganisationTypeNameConst.PRISON_LIBRARY)) {
            organisationTypeName = OrganisationTypeNameConst.PRISON_LIBRARY;
        } else if (organisationUnit.hasType(OrganisationTypeNameConst.MOBILE_LIBRARY)) {
            organisationTypeName = OrganisationTypeNameConst.MOBILE_LIBRARY;
        } else if (organisationUnit.hasType(OrganisationTypeNameConst.PRIMARY_SCHOOL_LIBRARY)) {
            organisationTypeName = OrganisationTypeNameConst.PRIMARY_SCHOOL_LIBRARY;
        } else if (organisationUnit.hasType(OrganisationTypeNameConst.KKD_GENERAL_ARTS)) {
            organisationTypeName = OrganisationTypeNameConst.KKD_GENERAL_ARTS;
        } else if (organisationUnit.hasType(OrganisationTypeNameConst.KKD_VISUAL_ARTS)) {
            organisationTypeName = OrganisationTypeNameConst.KKD_VISUAL_ARTS;
        } else if (organisationUnit.hasType(OrganisationTypeNameConst.KKD_DRAMATIC_ART)) {
            organisationTypeName = OrganisationTypeNameConst.KKD_DRAMATIC_ART;
        } else if (organisationUnit.hasType(OrganisationTypeNameConst.KKD_DRAMATIC_ART_70)) {
            organisationTypeName = OrganisationTypeNameConst.KKD_DRAMATIC_ART_70;
        } else if (organisationUnit.hasType(OrganisationTypeNameConst.KKD_KNUTEPUNKT)) {
            organisationTypeName = OrganisationTypeNameConst.KKD_KNUTEPUNKT;
        } else if (organisationUnit.hasType(OrganisationTypeNameConst.KKD_MUSIC)) {
            organisationTypeName = OrganisationTypeNameConst.KKD_MUSIC;
        } else if (organisationUnit.hasType(OrganisationTypeNameConst.KKD_MUSIC_70)) {
            organisationTypeName = OrganisationTypeNameConst.KKD_MUSIC_70;
        }

        return organisationTypeName;
    }

    private Set<String> getRoleNamesForMainOrganisationType(String organisationTypeName) {

        Set<String> roleNames = new HashSet<String>();

        /* All users should have this */
        roleNames.add(UserRoleNameConst.ROLE_ABMSTATISTIKK_USER);

        if (organisationTypeName == OrganisationTypeNameConst.ARCHIVE_COMPLETE) {
            roleNames.add(UserRoleNameConst.ROLE_ARCHIVE_USER);
            roleNames.add(UserRoleNameConst.ROLE_ARCHIVE_COMPLETE_REGISTRATOR);
            return roleNames;
        }

        if (organisationTypeName == OrganisationTypeNameConst.FYLKES_LIBRARY) {
            roleNames.add(UserRoleNameConst.ROLE_FOLKEBIB_FYLKESBIB_REGISTRATOR);
            roleNames.add(UserRoleNameConst.ROLE_FOLKEBIB_FOLKEBIB_REGISTRATOR);
            roleNames.add(UserRoleNameConst.ROLE_FOLKEBIB_GRUNNSKOLE_REGISTRATOR);
            roleNames.add(UserRoleNameConst.ROLE_FOLKEBIB_VIDEREGAENDE_SKOLE_REGISTRATOR);
            roleNames.add(UserRoleNameConst.ROLE_FOLKEBIB_MOBIL_REGISTRATOR);
            roleNames.add(UserRoleNameConst.ROLE_FOLKEBIB_KOMMUNE_REGISTRATOR);
            roleNames.add(UserRoleNameConst.ROLE_FOLKEBIB_FYLKESKOMMUNE_REGISTRATOR);
            return roleNames;
        }

        if (organisationTypeName == OrganisationTypeNameConst.KOMMUNE) {
            roleNames.add(UserRoleNameConst.ROLE_FOLKEBIB_KOMMUNE_REGISTRATOR);
            roleNames.add(UserRoleNameConst.ROLE_FOLKEBIB_GRUNNSKOLE_REGISTRATOR);
            return roleNames;
        }

        if (organisationTypeName == OrganisationTypeNameConst.FYLKE) {
            roleNames.add(UserRoleNameConst.ROLE_FOLKEBIB_FYLKESKOMMUNE_REGISTRATOR);
            roleNames.add(UserRoleNameConst.ROLE_FOLKEBIB_VIDEREGAENDE_SKOLE_REGISTRATOR);
            return roleNames;
        }

        if (organisationTypeName == OrganisationTypeNameConst.PUBLIC_LIBRARY
                || organisationTypeName == OrganisationTypeNameConst.FOLKEBIBLIOTEK_SVALBARD) {
            roleNames.add(UserRoleNameConst.ROLE_FOLKEBIB_FOLKEBIB_REGISTRATOR);
            //            roleNames.add(UserRoleNameConst.ROLE_FOLKEBIB_MOBIL_REGISTRATOR);
            return roleNames;
        }

        if (organisationTypeName == OrganisationTypeNameConst.FAG_LIBRARY
                || organisationTypeName == OrganisationTypeNameConst.NATIONAL_LIBRARY
                || organisationTypeName == OrganisationTypeNameConst.UNIVERITY_OF_OSLO
                || organisationTypeName == OrganisationTypeNameConst.UNIVERITY_OF_BERGEN
                || organisationTypeName == OrganisationTypeNameConst.UNIVERITY_OF_TRONDHEIM
                || organisationTypeName == OrganisationTypeNameConst.UNIVERITY_OF_TROMSOE
                || organisationTypeName == OrganisationTypeNameConst.SPECIALISED_UNIVERISTY_LIBRARY
                || organisationTypeName == OrganisationTypeNameConst.PUBLIC_COLLEGE_LIBRARY
                || organisationTypeName == OrganisationTypeNameConst.PRIVATE_COLLEGE_LIBRARY
                || organisationTypeName == OrganisationTypeNameConst.PUBLIC_SPECIAL_LIBRARY
                || organisationTypeName == OrganisationTypeNameConst.PRIVATE_SPECIAL_LIBRARY
                || organisationTypeName == OrganisationTypeNameConst.FAG_BIBLIOTEK_LEVEL_1
                || organisationTypeName == OrganisationTypeNameConst.FAG_BIBLIOTEK_LEVEL_2
                || organisationTypeName == OrganisationTypeNameConst.FAG_BIBLIOTEK_LEVEL_3) {
            roleNames.add(UserRoleNameConst.ROLE_FAGBIB_REGISTRATOR);
            return roleNames;
        }

        if (organisationTypeName == OrganisationTypeNameConst.REPORTINGMUSEUM) {
            roleNames.add(UserRoleNameConst.ROLE_REPORTING_MUSEUM_REGISTRATOR);
            roleNames.add(UserRoleNameConst.ROLE_KKD_FINANCE_APPLICATION_REGISTRATOR);
            return roleNames;
        }

        if (organisationTypeName == OrganisationTypeNameConst.MUSEUM) {
            roleNames.add(UserRoleNameConst.ROLE_MUSEUM_REGISTRATOR);
            return roleNames;
        }

        if (organisationTypeName == OrganisationTypeNameConst.HIGH_SCHOOL_LIBRARY) {
            roleNames.add(UserRoleNameConst.ROLE_FOLKEBIB_VIDEREGAENDE_SKOLE_REGISTRATOR);
            return roleNames;
        }
        if (organisationTypeName == OrganisationTypeNameConst.HOSPITAL_LIBRARY) {
            roleNames.add(UserRoleNameConst.ROLE_FOLKEBIB_PASIENT_REGISTRATOR);
            return roleNames;
        }

        if (organisationTypeName == OrganisationTypeNameConst.PRISON_LIBRARY) {
            roleNames.add(UserRoleNameConst.ROLE_FOLKEBIB_FENGSEL_REGISTRATOR);
            return roleNames;
        }
        if (organisationTypeName == OrganisationTypeNameConst.MOBILE_LIBRARY) {
            roleNames.add(UserRoleNameConst.ROLE_FOLKEBIB_MOBIL_REGISTRATOR);
            return roleNames;
        }

        if (organisationTypeName == OrganisationTypeNameConst.PRIMARY_SCHOOL_LIBRARY
                || organisationTypeName == OrganisationTypeNameConst.GRUNNSKOLEBIBLIOTEK_SVALBARD) {
            roleNames.add(UserRoleNameConst.ROLE_FOLKEBIB_GRUNNSKOLE_REGISTRATOR);
            return roleNames;
        }

        if (organisationTypeName == OrganisationTypeNameConst.KKD_GENERAL_ARTS) {
            roleNames.add(UserRoleNameConst.ROLE_KKD_GENERAL_ARTS_USER);
            roleNames.add(UserRoleNameConst.ROLE_KKD_GENERAL_ARTS_REGISTRATOR);
            roleNames.add(UserRoleNameConst.ROLE_KKD_FINANCE_APPLICATION_REGISTRATOR);
            return roleNames;
        }
        if (organisationTypeName == OrganisationTypeNameConst.KKD_VISUAL_ARTS) {
            roleNames.add(UserRoleNameConst.ROLE_KKD_VISUAL_ARTS_USER);
            roleNames.add(UserRoleNameConst.ROLE_KKD_VISUAL_ARTS_REGISTRATOR);
            roleNames.add(UserRoleNameConst.ROLE_KKD_FINANCE_APPLICATION_REGISTRATOR);
            return roleNames;
        }
        if (organisationTypeName == OrganisationTypeNameConst.KKD_DRAMATIC_ART) {
            roleNames.add(UserRoleNameConst.ROLE_KKD_DRAMATIC_ART_USER);
            roleNames.add(UserRoleNameConst.ROLE_KKD_DRAMATIC_ART_REGISTRATOR);
            roleNames.add(UserRoleNameConst.ROLE_KKD_FINANCE_APPLICATION_REGISTRATOR);
            return roleNames;
        }
        if (organisationTypeName == OrganisationTypeNameConst.KKD_DRAMATIC_ART_70) {
            roleNames.add(UserRoleNameConst.ROLE_KKD_DRAMATIC_ART_70_USER);
            roleNames.add(UserRoleNameConst.ROLE_KKD_DRAMATIC_ART_70_REGISTRATOR);
            roleNames.add(UserRoleNameConst.ROLE_KKD_FINANCE_APPLICATION_REGISTRATOR);
            return roleNames;
        }
        if (organisationTypeName == OrganisationTypeNameConst.KKD_KNUTEPUNKT) {
            roleNames.add(UserRoleNameConst.ROLE_KKD_KNUTEPUNKT_USER);
            roleNames.add(UserRoleNameConst.ROLE_KKD_KNUTEPUNKT_REGISTRATOR);
            roleNames.add(UserRoleNameConst.ROLE_KKD_FINANCE_APPLICATION_REGISTRATOR);
            return roleNames;
        }
        if (organisationTypeName == OrganisationTypeNameConst.KKD_MUSIC) {
            roleNames.add(UserRoleNameConst.ROLE_KKD_MUSIC_USER);
            roleNames.add(UserRoleNameConst.ROLE_KKD_MUSIC_REGISTRATOR);
            roleNames.add(UserRoleNameConst.ROLE_KKD_FINANCE_APPLICATION_REGISTRATOR);
            return roleNames;
        }
        if (organisationTypeName == OrganisationTypeNameConst.KKD_MUSIC_70) {
            roleNames.add(UserRoleNameConst.ROLE_KKD_MUSIC_70_USER);
            roleNames.add(UserRoleNameConst.ROLE_KKD_MUSIC_70_REGISTRATOR);
            roleNames.add(UserRoleNameConst.ROLE_KKD_FINANCE_APPLICATION_REGISTRATOR);
            return roleNames;
        }

        return roleNames;
    }

    private Set<String> getRoleNames(OrganisationUnit organisationUnit, String organisationTypeName) {

        if (StringUtil.isEmpty(organisationTypeName)) {
            logger.error("Cant find organisationUnitTypeName for organisationUnit id='" + organisationUnit.getId()
                    + "' name='" + organisationUnit.getName().getReference());
            return null;
        }
        Set<String> roleNames = getRoleNamesForMainOrganisationType(organisationTypeName);
        if (roleNames == null || roleNames.size() < 1) {
            logger.error("Cant find any rolenames for organisationUnitTypeName='" + organisationTypeName + "'");
            return null;
        }

        return roleNames;
    }

    private List<Entity> createEntityStorList(OrganisationUnit organisationUnit, String organisationTypeName,
            Set<Role> roles) {

        Long orgUnitId = organisationUnit.getId();
        UserFinderSpecification finder = new UserFinderSpecification(orgUnitId);
        Collection<User> users = userService.find(finder);
        if (users.size() > 0) {
            logger.warn("Skipping organisationUnit (has allready one or more users) " + "id='" + orgUnitId
                    + "' name='" + organisationUnit.getName().getReference() + "'");
            return null;
        }

        List<Entity> entityStoreList = new ArrayList<Entity>();
        //        List<Object> sessionStoreList = new ArrayList<Object>();

        Set<RoleRelation> roleRelations = new HashSet<RoleRelation>();
        for (Role role : roles) {
            String roleName = role.getName();

            if (roleName.contains("_REGISTRATOR")) {
                String deadlineAsText = reportingDeadlineService.getActualDeadline(organisationTypeName, roleName);
                String opningDateAsText = reportingDeadlineService.getOpningDate(organisationTypeName, roleName);
                Date deadline = DateUtil.parseISODate(deadlineAsText);
                Date opningDate = DateUtil.parseISODate(opningDateAsText);
                roleRelations.add(new RoleRelation(role, opningDate, deadline));
            } else {
                roleRelations.add(new RoleRelation(role, null, null));
            }
        }
        UserGroup userGroup = new UserGroup("group" + organisationUnit.getId());

        //A null name will set the user name to the same as the user id.
        User user = new User(null, UserUtil.generatePassword());

        ContactInfo contactInfo = new ContactInfo();
        Object obj = organisationUnit.getName() != null ? organisationUnit.getName().getDefault() : "unknown";
        String str = obj == null ? "noname" : obj.toString();
        contactInfo.setLastName(str);
        user.setContactInfo(contactInfo);

        // Tag this user, to enable sql to turn off of the enabled flag later on.
        user.setTemporaryUser(true);

        // Adding roleRelations to user.
        user.addRoles(roleRelations);

        entityStoreList.add(user);
        userGroup.addPrincipalChildren(user);
        entityStoreList.add(userGroup);

        GroupOrgUnitMapping mapping = new GroupOrgUnitMapping(userGroup, organisationUnit.getId());
        entityStoreList.add(mapping);

        List<RoleRelation> roleRels = user.getRoles();
        StringBuffer sb = new StringBuffer();
        sb.append("For organisationUnit id='");
        sb.append(organisationUnit.getId());
        sb.append("' name='");
        sb.append(organisationUnit.getName().getReference());
        sb.append("' created user name='");
        sb.append(user.getName());
        sb.append("' and roles:");
        for (RoleRelation rr : roleRels) {
            sb.append(" " + rr.getRole().getName());
        }
        logger.info(sb.toString());

        return entityStoreList;
    }
}