easycare.load.util.db.loader.UserDataLoader.java Source code

Java tutorial

Introduction

Here is the source code for easycare.load.util.db.loader.UserDataLoader.java

Source

package easycare.load.util.db.loader;

import static com.google.common.collect.Lists.newArrayList;
import static easycare.model.security.RoleEnum.ROLE_ADMIN;
import static easycare.model.security.RoleEnum.ROLE_CLINICIAN;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.apache.commons.lang.StringUtils;
import org.hibernate.ScrollableResults;
import org.hibernate.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import easycare.load.util.db.ContextOfCurrentLoad;
import easycare.load.util.db.SeedData;
import easycare.model.AccountStatus;
import easycare.model.ContactInformation;
import easycare.model.Location;
import easycare.model.Organisation;
import easycare.model.Title;
import easycare.model.User;
import easycare.model.security.Role;
import easycare.model.security.RoleEnum;
import easycare.service.UserService;
import easycare.service.ids.CertificateFactory;
import easycare.service.ids.Ids;
import easycare.service.ids.IdsServiceException;
import easycare.service.ids.pki.CertRequest;
import easycare.service.ids.pki.CertResponse;
import easycare.service.ids.pki.Idspki;
import easycare.util.db.generator.UserGeneratorHelper;

@Component
public class UserDataLoader {

    private static final int _THREE = 3;

    private static final int _SIX = 6;

    private static final Logger log = LoggerFactory.getLogger(UserDataLoader.class);

    private static final int SMALL_CHUNK = 20;
    public static final BigDecimal PADDING_FACTOR = BigDecimal.valueOf(50);

    @PersistenceContext(unitName = "easycare")
    private EntityManager em;

    @Autowired
    private UserService userService;

    @Autowired
    private SeedData seedData;

    @Autowired
    private CertificateFactory certificateFactory;

    @Value("${ids.services.certificatePasscodePath}")
    private String idsCertificatePasscodePath;

    @Value("${ids.services.applicationId}")
    private String applicationId;

    @Value("${ids.services.numberOfCertificatesToGenerate:5}")
    private int numberOfCertificatesToGenerate;

    @Autowired
    @Qualifier("idsPkiService")
    private Idspki idsPkiService;

    @Transactional
    public void buildAllUsers(ContextOfCurrentLoad context) {

        log.info("starting to load users ");
        Session session = (Session) em.getDelegate();
        ScrollableResults scrollableResults = session
                .createQuery("from Organisation where name != 'ResMed' order by accountNumber").scroll();

        int numberOfOrganisationsWithAddedUsers = 0;
        while (scrollableResults.next()) {

            Organisation organisation = (Organisation) scrollableResults.get(0);
            String organisationNumber = StringUtils.remove(organisation.getAccountNumber(), "APT");

            loadOrgUsers(context, organisation, organisationNumber);

            if (++numberOfOrganisationsWithAddedUsers % SMALL_CHUNK == 0) {
                em.flush();
                em.clear();
                log.debug("finished small chunk of orgs with users up to " + numberOfOrganisationsWithAddedUsers
                        + "org");
            }
            log.info("Finished users for org " + organisation);
        }
        log.info("Finished to load users ");
    }

    @Transactional
    public void loadOrgUsers(ContextOfCurrentLoad context, Organisation organisation, String organisationNumber) {
        em.merge(organisation);

        if (log.isTraceEnabled()) {
            log.trace(String.format("Index: [%s], User", organisationNumber));
        }

        createAdmins(context, organisation, organisationNumber);
        createUsersWithAllLocations(context, organisation, organisationNumber);
        createUsersWithSpecificLocations(context, organisation, organisationNumber);
        createUsersWithSubsetLocations(context, organisation, organisationNumber);
        createPaddingUsers(context, organisation, organisationNumber);
    }

    private void createAdmins(ContextOfCurrentLoad context, Organisation organisation, String organisationNumber) {
        List<Role> roles = newArrayList(seedData.getRole(ROLE_ADMIN));

        String userName = String.format("ireneA%s", organisationNumber);
        buildUser(context, userName, "Irene", "AdminA", organisation, roles, organisationNumber);

        String userName1 = String.format("ireneB%s", organisationNumber);
        buildUser(context, userName1, "Irene", "AdminB", organisation, roles, organisationNumber);
    }

    private void createUsersWithAllLocations(ContextOfCurrentLoad context, Organisation organisation,
            String organisationNumber) {
        List<Role> roles = newArrayList(seedData.getRole(ROLE_CLINICIAN));
        buildUser(context, String.format("careyA%s", organisationNumber), "Carey", "EverywhereA", organisation,
                roles, organisationNumber);
        buildUser(context, String.format("careyB%s", organisationNumber), "Carey", "EverywhereB", organisation,
                roles, organisationNumber);
    }

    private void createUsersWithSpecificLocations(ContextOfCurrentLoad context, Organisation organisation,
            String organisationNumber) {
        int locationNumber = 0;
        List<Location> locations = organisation.activeLocations();
        for (Location location : locations) {
            List<Role> roles = newArrayList(seedData.getRole(ROLE_CLINICIAN));
            String uniquePrefix = String.format("%s-%d", organisationNumber, ++locationNumber);
            buildUser(context, "remy" + uniquePrefix, "Remy", "Local" + uniquePrefix, organisation, roles,
                    uniquePrefix, location);
        }
    }

    private void createUsersWithSubsetLocations(ContextOfCurrentLoad context, Organisation organisation,
            String organisationNumber) {
        List<Location> locations = organisation.activeLocations();
        BigDecimal totalLocations = BigDecimal.valueOf(locations.size());
        BigDecimal twoThirdLocations = totalLocations
                .divide(BigDecimal.valueOf(_THREE), _SIX, RoundingMode.HALF_EVEN).multiply(BigDecimal.valueOf(2))
                .setScale(0, RoundingMode.CEILING);
        Location[] locationsToAdd = locations.subList(0, twoThirdLocations.intValue()).toArray(new Location[0]);
        List<Role> roles = newArrayList(seedData.getRole(ROLE_CLINICIAN));
        buildUser(context, "remy" + organisationNumber, "Remy", "Roam", organisation, roles, organisationNumber,
                locationsToAdd);
    }

    private void createPaddingUsers(ContextOfCurrentLoad context, Organisation organisation,
            String organisationNumber) {
        BigDecimal numberOfPatientsPerOrg = context.numberOfPatientsInPassedOrg(organisation, organisationNumber);

        int numberOfPaddingUsers = numberOfPatientsPerOrg.divide(PADDING_FACTOR).setScale(0, RoundingMode.FLOOR)
                .intValue();

        List<Role> roles = newArrayList(seedData.getRole(RoleEnum.ROLE_CLINICIAN));
        for (int i = 0; i < numberOfPaddingUsers; i++) {
            buildUser(context, String.format("paddy%s-%d", organisationNumber, i), context.getFaker().firstName(),
                    context.getFaker().lastName(), organisation, roles, organisationNumber);
        }
    }

    private String createIdsCertificateRequest(ContextOfCurrentLoad context, User userWhoNeedsCert) {
        final String IDS_CREATE_CERTIFICATE_COMMENT = "User %s created certificate for new user %s";
        final byte IDS_AUTHENTICATION_BITMASK_BROWSER_CERT_STORE = 0x08;
        final int IDS_PRIVILEGE_NOT_USED_BY_EASYCARE = 0;
        final int IDS_PROFILE_PLACEHOLDER = 0;
        final int IDS_CERTIFICATE_VALIDITY_DURATION_DAYS = 1095;

        int authMask = IDS_AUTHENTICATION_BITMASK_BROWSER_CERT_STORE;
        String comment = String.format(IDS_CREATE_CERTIFICATE_COMMENT, context.getLoggedInUsername(),
                userWhoNeedsCert.getUsername());

        CertRequest certRequest = new CertRequest();
        certRequest.setApplication(applicationId);
        certRequest.setRequester(Ids.createRequesterFromUsername(context.getLoggedInUsername()));
        certRequest.setAuthCookie(context.getIDSAuthCookieSessionId());
        certRequest.setOrganizationUnit(userWhoNeedsCert.getOrganisation().getName());
        certRequest.setOwner(Ids.createRequesterFromUsername(userWhoNeedsCert.getUsername()));
        certRequest.setIdentifier(userWhoNeedsCert.getUsername());
        certRequest.setPrivilege(IDS_PRIVILEGE_NOT_USED_BY_EASYCARE);
        certRequest.setProfile(IDS_PROFILE_PLACEHOLDER);
        certRequest.setDuration(IDS_CERTIFICATE_VALIDITY_DURATION_DAYS);
        certRequest.setAuthenticationMask(authMask);
        certRequest.setNumber(numberOfCertificatesToGenerate);
        certRequest.setComment(comment);

        CertResponse certResponse;
        try {
            certResponse = idsPkiService.certRequest(certRequest);
        } catch (Exception e) {
            throw new IdsServiceException(
                    "Unable to create IDS certificate for user " + userWhoNeedsCert.getUsername(), e);
        }

        return certResponse.getOTP();
    }

    private void requestIDSCertificateForUser(ContextOfCurrentLoad context, User userWhoNeedsCert) {
        /*
         * If BulkDataLoader is configured to also create IDS certificate
         * request for the created user, this section will create a CSV file
         * storing the username and IDS certificate retrieval passcode. The
         * passcode is then used to manually retrieve the corresponding
         * certificate to be packaged into the keystore uses by JMeter for
         * performance test. This poses no security threats as the user are test
         * users and the file is stored within the network of IDS & ECO.
         */
        if (context != null) {
            if (context.isIDSCertificateRequestToBeCreated() && !idsCertificatePasscodePath.isEmpty()) {
                String certificateRetrievalPasscode;
                try {
                    certificateRetrievalPasscode = createIdsCertificateRequest(context, userWhoNeedsCert);
                } catch (IdsServiceException e) {
                    log.error(e.getMessage(), e);
                    certificateRetrievalPasscode = e.getMessage();
                }

                try {
                    log.info("Appending IDS certificate retrieval passcode for user: "
                            + userWhoNeedsCert.getUsername() + " to CSV file at location: "
                            + idsCertificatePasscodePath);
                    File file = new File(idsCertificatePasscodePath);
                    if (!file.exists()) {
                        file.createNewFile();
                    }
                    PrintWriter pWriter = new PrintWriter(
                            new BufferedWriter(new FileWriter(file.getAbsoluteFile(), true)));
                    pWriter.println(userWhoNeedsCert.getUsername() + "," + certificateRetrievalPasscode);
                    pWriter.close();
                } catch (IOException e) {
                    log.error(e.getMessage(), e);
                }
            }
        }
    }

    public void buildUser(ContextOfCurrentLoad context, String userName, Title title, String firstName,
            String lastName, String email, String password, Organisation organisation, List<Role> roles,
            ContactInformation contactInformation, Location... locations) {
        User user = UserGeneratorHelper.createUserWithDetails(title, firstName, lastName, userName, organisation,
                roles, AccountStatus.ENABLED, email);
        if (locations.length > 0) {
            user.addLocations(locations);
        }

        if (contactInformation == null) {
            UserGeneratorHelper.addContactInformationToUser(user);
        } else {
            user.setContactInformation(contactInformation);
        }

        user = userService.createUserWithManualPassword(user);
        user = userService.changePassword(user, password);
        user = userService.acceptLicenseAgreement(user);

        requestIDSCertificateForUser(context, user);
    }

    public void buildUser(ContextOfCurrentLoad context, String userName, Title title, String firstName,
            String lastName, String email, String password, Organisation organisation, List<Role> roles,
            Location... locations) {
        buildUser(context, userName, title, firstName, lastName, email, password, organisation, roles, null,
                locations);
    }

    public void buildUser(ContextOfCurrentLoad context, String userName, Title title, String firstName,
            String lastName, Organisation organisation, List<Role> roles, Location... locations) {

        String organisationNumber = StringUtils.remove(organisation.getAccountNumber(), "APT");
        String email = userName + "@" + organisationNumber + ".com";
        buildUser(context, userName, title, firstName, lastName, email, UserGeneratorHelper.DEFAULT_PASSWORD,
                organisation, roles, locations);
    }

    public void buildUser(ContextOfCurrentLoad context, String userName, String firstName, String lastName,
            Organisation organisation, List<Role> roles, String organisationNumber, Location... locations) {
        buildUser(context, userName, Title.MRS, firstName, lastName, organisation, roles, locations);
    }

    @Transactional
    public void loadDefaultClinicalAndAdminUsersForOrg(Organisation organisation) {
        // TODO Auto-generated method stub
    }
}