cognition.pipeline.data.PatientDao.java Source code

Java tutorial

Introduction

Here is the source code for cognition.pipeline.data.PatientDao.java

Source

/*
Designed and developed by Ismail E. Kartoglu
Copyright 2015 King's College London
    
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    
    http://www.apache.org/licenses/LICENSE-2.0
    
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
 */

package cognition.pipeline.data;

import cognition.pipeline.data.helper.ClobHelper;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.hibernate.transform.Transformers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Repository;
import cognition.common.data.BaseDao;
import cognition.common.data.SessionWrapper;
import cognition.common.model.Individual;
import cognition.common.model.PatientAddress;
import cognition.common.model.PatientCarer;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Repository
public class PatientDao extends BaseDao {

    @Autowired
    private ClobHelper clobHelper;

    private static Logger logger = Logger.getLogger(PatientDao.class);

    /**
     * Returns the patient with the given id.
     * Returns the patient from the cache if it's been fetched once.
     *
     * @param id
     * @return a patient object of the patient with the given id.
     */
    @Cacheable(value = "patients", key = "#id")
    public Individual getPatient(Long id) {
        SessionWrapper sessionWrapper = createSourceSession();
        try {
            Query getPatient = sessionWrapper.getNamedQuery("getPatient");
            getPatient.setParameter("patientId", id);
            logger.info("Loading patient " + id);
            Individual individual = (Individual) getPatient.setFirstResult(0).setMaxResults(1)
                    .setResultTransformer(Transformers.aliasToBean(Individual.class)).uniqueResult();

            setNames(individual);
            setPhoneNumbers(individual);
            setAddresses(individual);
            setCarers(individual);
            setNhsNumbers(individual);
            setDateOfBirths(individual);

            return individual;
        } finally {
            sessionWrapper.closeSession();
        }
    }

    private void setNhsNumbers(Individual individual) {
        SessionWrapper sessionWrapper = createSourceSession();
        try {
            Query getNhsNumbers = sessionWrapper.getNamedQuery("getNhsNumbers");
            getNhsNumbers.setParameter("patientId", individual.getId());
            List nhsNumbers = getNhsNumbers.list();
            nhsNumbers.forEach(object -> {
                String number;
                if (object instanceof String) {
                    number = (String) object;
                } else {
                    Object[] nhsNumberRow = (Object[]) object;
                    number = clobHelper.getStringFromExpectedClob(nhsNumberRow[0]);
                }
                if (!StringUtils.isBlank(number)) {
                    individual.addNhsNumber(number);
                }
            });
        } catch (Exception ex) {
            logger.warn("Error while loading NHS Numbers of patient " + individual.getId()
                    + ". Does the specified table exist? " + ex.getMessage());
        } finally {
            sessionWrapper.closeSession();
        }
    }

    private void setDateOfBirths(Individual individual) {
        SessionWrapper sessionWrapper = createSourceSession();
        try {
            Query getDateOfBirths = sessionWrapper.getNamedQuery("getDateOfBirths");
            getDateOfBirths.setParameter("patientId", individual.getId());
            List dateOfBirths = getDateOfBirths.list();
            dateOfBirths.forEach(object -> {
                Date dateOfBirth;
                if (object instanceof Date) {
                    dateOfBirth = (Date) object;
                } else {
                    Object[] dateOfBirthRow = (Object[]) object;
                    dateOfBirth = (Date) dateOfBirthRow[0];
                }
                if (dateOfBirth != null) {
                    individual.addDateOfBirth(dateOfBirth);
                }
            });
        } catch (Exception ex) {
            logger.warn("Error while loading date of births of patient " + individual.getId()
                    + ". Does the specified table exist? " + ex.getMessage());
        } finally {
            sessionWrapper.closeSession();
        }
    }

    private void setCarers(Individual individual) {
        SessionWrapper sessionWrapper = createSourceSession();
        try {
            Query getCarers = sessionWrapper.getNamedQuery("getCarers");
            getCarers.setParameter("patientId", individual.getId());
            List carerObjects = getCarers.list();
            carerObjects.forEach(object -> {
                Object[] carerRow = (Object[]) object;
                String name = clobHelper.getStringFromExpectedClob(carerRow[0]);
                String lastName = clobHelper.getStringFromExpectedClob(carerRow[1]);
                PatientCarer carer = new PatientCarer(name, lastName);
                individual.addCarer(carer);
            });
        } catch (Exception ex) {
            logger.warn("Error while loading carers of patient " + individual.getId()
                    + ". Does the specified carer table exist? " + ex.getMessage());
        } finally {
            sessionWrapper.closeSession();
        }
    }

    private void setPhoneNumbers(Individual individual) {
        SessionWrapper sessionWrapper = createSourceSession();
        try {
            Query getPhoneNumbers = sessionWrapper.getNamedQuery("getPhoneNumbers");
            getPhoneNumbers.setParameter("patientId", individual.getId());
            List list = getPhoneNumbers.list();
            List<String> phoneNumbers = new ArrayList<>();
            list.forEach(object -> {
                String phone = clobHelper.getStringFromExpectedClob(object);
                if (!StringUtils.isBlank(phone)) {
                    phoneNumbers.add(phone);
                }
            });
            individual.setPhoneNumbers(phoneNumbers);
        } finally {
            sessionWrapper.closeSession();
        }
    }

    /**
     * Fetches the addresses of the patient from the DB and assigns them to the given patient.
     *
     * @param individual
     */
    private void setAddresses(Individual individual) {
        SessionWrapper sessionWrapper = createSourceSession();
        try {
            Query getAddresses = sessionWrapper.getNamedQuery("getAddresses");
            getAddresses.setParameter("patientId", individual.getId());
            List addressObjects = getAddresses.list();
            addressObjects.forEach(object -> {
                Object[] addressRow = (Object[]) object;
                String addressStr = clobHelper.getStringFromExpectedClob(addressRow[0]);
                String postCode = "";
                if (addressRow.length > 1) {
                    postCode = clobHelper.getStringFromExpectedClob(addressRow[1]);
                }
                PatientAddress address = PatientAddress.newAddressPostCode(addressStr, postCode);
                individual.addAddress(address);
            });
        } catch (Exception ex) {
            logger.warn("Error while loading addresses of patient " + individual.getId()
                    + ". Does the specified address table exist? " + ex.getMessage());
        } finally {
            sessionWrapper.closeSession();
        }
    }

    /**
     * Fetches the names of the patient from the DB and assigns them to the given patient.
     *
     * @param individual
     */
    private void setNames(Individual individual) {
        SessionWrapper sessionWrapper = createSourceSession();
        try {
            Query getForeNames = sessionWrapper.getNamedQuery("getPatientNames");
            getForeNames.setParameter("patientId", individual.getId());
            List foreNames = getForeNames.list();
            if (CollectionUtils.isEmpty(foreNames)) {
                logger.warn("!! No name/surname was found for patient with id " + individual.getId());
                return;
            }
            for (Object dbObject : foreNames) {
                Object[] namePair = (Object[]) dbObject;
                String name = clobHelper.getStringFromExpectedClob(namePair[0]);
                String lastName = clobHelper.getStringFromExpectedClob(namePair[1]);
                if (!StringUtils.isBlank(name)) {
                    individual.addForeName(name);
                }
                if (!StringUtils.isBlank(lastName)) {
                    individual.addSurname(lastName);
                }
            }
        } catch (Exception ex) {
            logger.warn("Error while loading names of patient " + individual.getId()
                    + ". Does the specified address table exist? " + ex.getMessage());
        } finally {
            sessionWrapper.closeSession();
        }
    }

}