Java tutorial
package easycare.load.util.db.loader; import easycare.dao.CountryRepository; import easycare.dao.OrganisationRepository; import easycare.load.util.db.ContextOfCurrentLoad; import easycare.load.util.db.DeterministicFaker; import easycare.load.util.db.SeedData; import easycare.model.ContactInformation; import easycare.model.Country; import easycare.model.Image; import easycare.model.ImageTypeEnum; import easycare.model.Location; import easycare.model.Organisation; import easycare.model.OrganisationType; import easycare.model.PatientGroupLayout; import easycare.model.SubscriptionLevel; import easycare.model.User; import easycare.model.security.Role; import easycare.service.UserService; import easycare.util.db.generator.UserGeneratorHelper; import easycare.util.fixture.FixtureUtil; import org.apache.commons.lang.builder.ToStringBuilder; 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.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import java.util.ArrayList; import java.util.List; import static easycare.model.OrganisationType.ROOT; import static easycare.model.Title.MRS; import static easycare.model.security.RoleEnum.ROLE_RESMED_CS; @Component public class OrganisationDataLoader { private static final int THREE = 3; private static final Logger log = LoggerFactory.getLogger(OrganisationDataLoader.class); private static final int SMALL_CHUNK = 20; @Autowired private OrganisationRepository organisationRepository; @Autowired private CountryRepository countryRepository; @Autowired private ContactDetailsDataLoader contactDetailsDataLoader; @Autowired private UserService userService; @Autowired private SeedData seedData; @PersistenceContext(unitName = "easycare") private EntityManager em; @Transactional public void buildHazel(ContextOfCurrentLoad context) { buildHazel(context, UserGeneratorHelper.DEFAULT_PASSWORD); } @Transactional public void buildHazel(DeterministicFaker faker, String countryOfHazel, String password) { buildHazel(faker, countryRepository.findByCountryCode(countryOfHazel), password); } @Transactional public void buildHazel(ContextOfCurrentLoad context, String password) { buildHazel(context.getFaker(), countryRepository.findByCountryCode(context.getCountryCode()), password); } @Transactional public void buildAllOrgsAndLocations(ContextOfCurrentLoad context, int start, int batchSize) { validateContextForBuildingOrgs(context); for (int i = start; i < start + batchSize && i < context.getTotalNumberOfOrgs(); i++) { Organisation organisation = buildOrgFromOrgNumber(context, i); em.persist(organisation); if (i % SMALL_CHUNK == 0) { em.flush(); em.clear(); log.debug("just finshed small chunk of orgs , up to " + i + "th org"); } } } private void validateContextForBuildingOrgs(ContextOfCurrentLoad context) { if (context.getNumberOfSmallOrgs() > 0 && context.getNumberOfPatientsPerSmallOrg() == 0) { throw new IllegalStateException( "if you have any small orgs (short hand -s) you require at least 1 patient per small org (short hand -P)"); } } private Organisation buildOrgFromOrgNumber(ContextOfCurrentLoad context, int orgNumber) { int humanReadableOrgNumber = orgNumber + 1; String organisationName = createOrganisationName(context, humanReadableOrgNumber); Organisation organisation = createOrganisation(context.getFaker(), countryRepository.findByCountryCode(context.getCountryCode()), String.format("%s %d", organisationName, humanReadableOrgNumber), String.format("APT%06d", humanReadableOrgNumber), OrganisationType.HME, // integrated sleep lab? "resmed-usa-logo.gif", null); if (log.isTraceEnabled()) { log.trace(String.format("Index: [%d], Org: [%s]", orgNumber, ToStringBuilder.reflectionToString(organisation))); } return organisation; } private String createOrganisationName(ContextOfCurrentLoad context, int i) { String fakerCompanyName = context.getFaker().company(); return isStandardOrg(context, i) ? fakerCompanyName : fakerCompanyName + "_Small"; } public Organisation createOrganisation(DeterministicFaker faker, Country country, String name, String accountNumber, OrganisationType orgType, String logoPath, PatientGroupLayout patientGroupLayout) { return createOrganisation(faker, country, name, accountNumber, orgType, logoPath, SubscriptionLevel.PREMIUM, null, patientGroupLayout); } public Organisation createOrganisation(DeterministicFaker faker, Country country, String name, String accountNumber, OrganisationType orgType, String logoPath, SubscriptionLevel chosenSubscriptionLevel, ContactInformation contact, PatientGroupLayout patientGroupLayout) { Organisation organisation = new Organisation(name, orgType, accountNumber); organisation.setCountry(country); organisation.setPrimaryContact(contactDetailsDataLoader.createPrimaryContact(faker, country, contact)); organisation.setSubscriptionLevel(chosenSubscriptionLevel); organisation.setPasswordResetRequired(true); organisation.setPasswordResetDurationMonths(THREE); organisation.setPatientGroupLayout(patientGroupLayout); // This causes another query if (logoPath != null) { Image logo = new Image(); String logoName = "USA " + name; if (logoName.length() > Image.MAX_NAME_LENGTH) { logoName = logoName.substring(0, Image.MAX_NAME_LENGTH); } logo.setName(logoName); logo.setDescription("USA Logo " + name); logo.setType(ImageTypeEnum.ORGANIZATION); logo.setImage(FixtureUtil.getFixture(logoPath)); organisation.setLogo(logo); } return organisation; } @Transactional public void buildAllLocations(ContextOfCurrentLoad context) { log.info("starting to load locations"); Session session = (Session) em.getDelegate(); ScrollableResults scrollableResults = session .createQuery("from Organisation where name != 'ResMed' order by accountNumber").scroll(); int numberOfLoadedLocations = 0; int numberOfLoadedStdOrgLocations = 0; int numberOfLocationsToCreateInStandardOrg = context.getInitialNumOfLocationsInStdOrg(); int numberOfUpdatedOrganisations = 0; int numberOfPatientsPlacedIntoLocations = 0; while (scrollableResults.next()) { Organisation organisation = (Organisation) scrollableResults.get(0); if (isStandardOrg(context, numberOfUpdatedOrganisations)) { log.info("creating locations for org " + (numberOfUpdatedOrganisations + 1)); for (int i = 0; i < numberOfLocationsToCreateInStandardOrg && numberOfLoadedStdOrgLocations < context.getTotalNumberOfLocationsInStandardOrgs(); i++) { int oldPatientsInOrg = numberOfPatientsPlacedIntoLocations; numberOfPatientsPlacedIntoLocations += (context.getNumberOfPatientsInStandardOrgLocation()); log.info("creating location " + (i + 1) + "with patients from " + (oldPatientsInOrg + 1) + " to " + (numberOfPatientsPlacedIntoLocations + 1)); createAndAddLocationToOrganisation(context, i, organisation); numberOfLoadedStdOrgLocations++; numberOfLoadedLocations++; } session.update(organisation); em.flush(); em.clear(); numberOfLocationsToCreateInStandardOrg++; } else { int oldPatientsInOrg = numberOfPatientsPlacedIntoLocations; numberOfPatientsPlacedIntoLocations += context.getNumberOfPatientsPerSmallOrg(); log.info( "creating org " + (numberOfUpdatedOrganisations + 1) + " as a small org with patients from " + (oldPatientsInOrg + 1) + " to " + (numberOfPatientsPlacedIntoLocations + 1)); createAndAddLocationToOrganisation(context, ContextOfCurrentLoad.NUMBER_OF_LOCATIONS_IN_SMALL_ORG, organisation); numberOfLoadedLocations++; } numberOfUpdatedOrganisations++; if (numberOfLoadedLocations % SMALL_CHUNK == 0) { em.flush(); em.clear(); log.debug("finished small chunk of locations up to " + numberOfLoadedLocations + "the location"); } } log.info("finished to load locations "); } private boolean isStandardOrg(ContextOfCurrentLoad context, int numberOfUpdatedOrganisations) { return numberOfUpdatedOrganisations <= context.getTotalNumberOfStandardOrgs(); } public void createAndAddLocationToOrganisation(ContextOfCurrentLoad context, int currentLocationNumber, Organisation organisation) { int humanReadableLocationNumber = currentLocationNumber + 1; String locationName = String.format("%s-L%04d", organisation.getName(), humanReadableLocationNumber); Location location = createAndAddLocationToOrganisation(context.getFaker(), locationName, organisation); if (log.isTraceEnabled()) { String locationStr = ToStringBuilder.reflectionToString(location); log.trace(String.format("Index: [%d], Location: [%s]", currentLocationNumber, locationStr)); } } public Location createAndAddLocationToOrganisation(DeterministicFaker faker, String locationName, Organisation organisation) { return createAndAddLocationToOrganisation(faker, locationName, organisation, null); } public Location createAndAddLocationToOrganisation(DeterministicFaker faker, String locationName, Organisation organisation, ContactInformation contactInformation) { Location location = organisation.assignNewLocation(locationName); location.setContactInformation(contactInformation == null ? contactDetailsDataLoader.createContactInformation(faker, seedData.getUs()) : contactInformation); location.setActive(true); return location; } private void buildHazel(DeterministicFaker faker, Country country, String password) { log.info("building hazel"); Organisation resMedOrg = createOrganisation(faker, country, "ResMed", null, ROOT, "resmed-usa-logo.gif", null); resMedOrg = organisationRepository.save(resMedOrg); List<Role> roles = new ArrayList<Role>(); roles.add(seedData.getRole(ROLE_RESMED_CS)); User user = UserGeneratorHelper.createUser(MRS, "Hazel", "Resmed", "hazelr", resMedOrg, roles); user = userService.createUserWithManualPassword(user); user = userService.changePassword(user, password); user = userService.acceptLicenseAgreement(user); } }