Example usage for org.hibernate StatelessSession createQuery

List of usage examples for org.hibernate StatelessSession createQuery

Introduction

In this page you can find the example usage for org.hibernate StatelessSession createQuery.

Prototype

@Override
    org.hibernate.query.Query createQuery(String queryString);

Source Link

Usage

From source file:edu.psu.iam.cpr.core.database.batch.AccessAccountStatus.java

License:Creative Commons License

/**
 * This method is used to determine whether an account is new or not.
 * @param personId contains the person identifier to be searched for.
 * @param userid contains the userid to be searched for.
 * @return will return true if the account is new, otherwise it will return false.
 *///from  w  w  w  . j a v  a 2 s . co  m
public boolean isAccountNew(final long personId, final String userid) {
    final StatelessSession session = getDatabaseSession();
    final Query query = session
            .createQuery("from UserServiceStatus where personId = :person_id AND userid = :userid");
    query.setParameter("person_id", personId);
    query.setParameter("userid", userid);
    return query.list().size() == 0;
}

From source file:edu.psu.iam.cpr.core.database.batch.EmployeeInfo.java

License:Creative Commons License

/**
 * Update an employee in the CPR./*from   w w  w . j  a  v  a 2  s.  com*/
 *
 * @param jobTitleShort The short job title
 * @param alternateJobTitle The alternate job title
 * @param hireDate The date the employee was hired
 * @param terminatedDate The date the employee was terminated
 * @param lastDatePaid The date the was last paid
 * @param appointmentCode The appointment code
 * @param appointmentCodeType The appointment code type
 * @param adminArea The employee's administrative area
 * @param adminAreaCode The code for the admin area
 * @param department The employee's department
 * @param campusCode The employee's campus
 * @param statusCode The employee's employment status code
 * @param classCode The employee's employment class code
 * @param layoffFlag Indicates if the employee has been laid off. Should be "Y" or "N".
 * @param benefitsRate The employee's benefits rate
 * @param visaType Visa code
 * @param studentStatus The employee's student status
 * @param specialStatus Special status code
 * @param directPhoneCode Is the phone a direct phone
 * @param eduPersonPrimaryAffiliation the EduPersonPrimaryAffiliation (will be null except for Hershey)
 * @param payFreqCode Contains the employee's pay frequency code.
 * @throws CprException On any error.
 */
public void updateEmployee(final String jobTitleShort, final String alternateJobTitle, final Date hireDate,
        final Date terminatedDate, final Date lastDatePaid, final String appointmentCode,
        final String appointmentCodeType, final String adminArea, final String adminAreaCode,
        final String department, final String campusCode, final String statusCode, final String classCode,
        final String layoffFlag, final String benefitsRate, final String visaType, final String studentStatus,
        final String specialStatus, final String directPhoneCode, final String eduPersonPrimaryAffiliation,
        final String payFreqCode) throws CprException {

    // check for mandatory fields
    if (getBatchDataSource() == BatchDataSource.IBIS && ValidateHelper.isFieldEmpty(appointmentCode)) {
        return;
    }

    boolean matchFound = false;
    boolean changeFound = false;
    boolean lastPaidChangeFound = false;

    boolean processingSecondary = false;
    boolean changedTermDate = false;

    final Date updateDate = getUpdateDate();
    final String updatedBy = getBatchDataSource().toString();

    // look for any employees
    final StatelessSession session = getDatabaseSession();

    // switch between transEmpl/transHershey's format (P = Primary; S = Secondary) to Employee's format (a yes/no field for primary appt)
    String primaryAppt;
    if ("P".equals(appointmentCodeType)) {
        primaryAppt = "Y";
    } else {
        primaryAppt = "N";
    }

    Query query = null;

    // we use different logic for IBIS vs HMC updates
    // because they pass different values
    String localDepartment = null;
    if (department != null) {
        localDepartment = department.toUpperCase();
    }
    if (getBatchDataSource() == BatchDataSource.IBIS || getBatchDataSource() == BatchDataSource.UNIT_TEST) {
        if (Utility.isOptionYes(primaryAppt)) {
            query = session.createQuery(
                    "from Employee where personId = :person_id and primaryApptFlag = :primary_appt_flag");
            query.setParameter("person_id", getPersonId());
            query.setParameter("primary_appt_flag", primaryAppt);
        } else {
            processingSecondary = true;

            // Make sure we are doing a case insensitive compare when we are doing a compare using department.
            query = session.createQuery(
                    "from Employee where personId = :person_id and primaryApptFlag = :primary_appt_flag and apptCode = :appt_code and statusCode = :status_code and upper(department) = :department and alternateJobTitle = :alt_job_title");
            query.setParameter("person_id", getPersonId());
            query.setParameter("primary_appt_flag", primaryAppt);
            query.setParameter("appt_code", appointmentCode);
            query.setParameter("status_code", statusCode);
            query.setParameter("department", localDepartment);
            query.setParameter("alt_job_title", alternateJobTitle);
        }
    } else if (getBatchDataSource() == BatchDataSource.HMC) {

        // Make sure we are doing a case insensitive compare for the department.
        query = session.createQuery(
                "from Employee where personId = :person_id and upper(department) = :department and jobTitle = :job_title");
        query.setParameter("person_id", getPersonId());
        query.setParameter("department", localDepartment);
        query.setParameter("job_title", jobTitleShort);
    }

    for (final Iterator<?> it = query.list().iterator(); it.hasNext();) {
        matchFound = true;

        final Employee employee = (Employee) it.next();
        setOldEmployee(new Employee(employee));
        setNewEmployee(new Employee(employee));

        // since we don't match on primary/secondary appt for HMC,
        // update the record here
        if (getBatchDataSource() == BatchDataSource.HMC && appointmentCodeType != null
                && !Utility.areStringFieldsEqual(employee.getPrimaryApptFlag(), primaryAppt)) {
            changeFound = true;
            newEmployee.setPrimaryApptFlag(primaryAppt);
        }

        // compare string fields

        if (!Utility.areStringFieldsEqual(employee.getJobTitle(), jobTitleShort)) {
            changeFound = true;
            newEmployee.setJobTitle(jobTitleShort);
        }

        if (!Utility.areStringFieldsEqual(employee.getAlternateJobTitle(), alternateJobTitle)) {
            changeFound = true;
            newEmployee.setAlternateJobTitle(alternateJobTitle);
        }

        if (!Utility.areStringFieldsEqual(employee.getBenefitsRate(), benefitsRate)) {
            changeFound = true;
            newEmployee.setAlternateJobTitle(benefitsRate);
        }

        final String tempLayoffFlag = Validate.isValidYesNo(layoffFlag);
        final String tempEmpLayoffFlag = Validate.isValidYesNo(employee.getLayoffFlag());
        if (!Utility.areStringFieldsEqual(tempEmpLayoffFlag, tempLayoffFlag)) {
            changeFound = true;
            newEmployee.setLayoffFlag(layoffFlag);
        }

        if (!Utility.areStringFieldsEqual(employee.getAdminArea(), adminArea)) {
            changeFound = true;
            newEmployee.setAdminArea(adminArea);
        }

        if (!Utility.areStringFieldsEqual(employee.getAdminAreaCode(), adminAreaCode)) {
            changeFound = true;
            newEmployee.setAdminAreaCode(adminAreaCode);
        }

        // Ignore case for department compares.
        if (!Utility.areStringFieldsEqualIgnoreCase(employee.getDepartment(), department)) {
            changeFound = true;
            newEmployee.setDepartment(department);
        }

        if (!Utility.areStringFieldsEqual(employee.getStudentStatus(), studentStatus)) {
            changeFound = true;
            newEmployee.setStudentStatus(studentStatus);
        }

        if (!Utility.areStringFieldsEqual(employee.getStatusCode(), statusCode)) {
            changeFound = true;
            newEmployee.setStatusCode(statusCode);

            // HMC doesn't pass us a termination date. If this is the first
            // time we've seen an HMC term for this record, insert a term date.
            if (getBatchDataSource() == BatchDataSource.HMC && employee.getTerminatedDate() == null) {
                newEmployee.setTerminatedDate(getUpdateDate());
            }
        }

        if (!Utility.areStringFieldsEqual(employee.getClassCode(), classCode)) {
            changeFound = true;
            newEmployee.setClassCode(classCode);
        }

        if (!Utility.areStringFieldsEqual(employee.getVisaType(), visaType)) {
            changeFound = true;
            newEmployee.setVisaType(visaType);
        }

        if (!Utility.areStringFieldsEqual(employee.getPayFreqCode(), payFreqCode)) {
            changeFound = true;
            newEmployee.setPayFreqCode(payFreqCode);
        }

        if (!ValidateHelper.isFieldEmpty(campusCode)) {
            try {
                final CampusCs campusCsBean = getCampusBean(campusCode);
                final Long newCampusCode = campusCsBean.getCampusCodeKey();
                final Long oldCampusCode = employee.getCampusCodeKey();
                if (!Utility.areLongFieldsEqual(oldCampusCode, newCampusCode)) {
                    changeFound = true;
                    newEmployee.setCampusCodeKey(newCampusCode);
                }
            } catch (final CprException ex) {
                LOG4J_LOGGER.warn("Unknown campus code: " + campusCode + " for record " + transEmplKey, ex);
            }
        }

        final boolean oldEmployeeShowDir = Utility.isOptionYes(employee.getShowInDirectoryFlag());
        final boolean newEmployeeShowDir = showEmployeeInDirectory(directPhoneCode);
        if (oldEmployeeShowDir != newEmployeeShowDir) {
            changeFound = true;
            if (newEmployeeShowDir) {
                newEmployee.setShowInDirectoryFlag("Y");
            } else {
                newEmployee.setShowInDirectoryFlag("N");
            }
        }

        // compare date fields
        if (lastDatePaid != null && !lastDatePaid.equals(oldEmployee.getLastDatePaid())) {
            lastPaidChangeFound = true;
            oldEmployee.setLastDatePaid(lastDatePaid);
            newEmployee.setLastDatePaid(lastDatePaid);
        }

        if (hireDate != null && !hireDate.equals(oldEmployee.getHireDate())) {
            changeFound = true;
            newEmployee.setHireDate(hireDate);
        }

        if (terminatedDate != null && !terminatedDate.equals(oldEmployee.getTerminatedDate())) {
            //changeFound = true;
            changedTermDate = true;
            newEmployee.setTerminatedDate(terminatedDate);
        }

        // special case logic for people
        // with multiple secondary appts and a term date change
        // on one of the secondary appts.
        if (!changeFound && changedTermDate && processingSecondary) {
            LOG4J_LOGGER.error("Unable to determine which record to update. Trans_empl_key: " + transEmplKey);
        }

        // save changes to the database
        if (changeFound || lastPaidChangeFound) {

            // If all that changed was the last date paid, update in place.
            // Since last date paid changes frequently,
            // we don't save a history record if it's the only thing that changed.
            if (!changeFound && lastPaidChangeFound) {
                getDatabaseSession().update(oldEmployee);
            }

            // archive the old bean
            if (changeFound) {
                saveEmployeeHistory(oldEmployee);
            }

            newEmployee.setStartDate(updateDate);

            newEmployee.setLastUpdateBy(updatedBy);
            newEmployee.setLastUpdateOn(updateDate);

            newEmployee.setImportFrom(updatedBy);
            newEmployee.setImportDate(updateDate);

            getDatabaseSession().update(newEmployee);
        } else {
            // Employee was found, but there was no changes, so we need to reset the employee beans.
            setOldEmployee(null);
            setNewEmployee(null);
        }
    }

    if (!matchFound) {
        addEmployee(jobTitleShort, alternateJobTitle, hireDate, terminatedDate, lastDatePaid, appointmentCode,
                appointmentCodeType, adminArea, adminAreaCode, department, campusCode, statusCode, classCode,
                layoffFlag, benefitsRate, visaType, studentStatus, specialStatus, directPhoneCode, payFreqCode);
    }
}

From source file:edu.psu.iam.cpr.core.database.batch.PersonBio.java

License:Creative Commons License

/**
 * This method is used to update a PSU ID record or add a new one.
 * @param psuId contains the PSU ID to be updated.
 *///from   www.  ja v a  2s  .c  o m
public void updatePsuId(final String psuId) {

    // Do not attempt to update null PSU IDs.
    if (ValidateHelper.isFieldEmpty(psuId)) {
        return;
    }

    boolean matchFound = false;

    // Perform a query to find the active PSU IDs for the user, there should only ever be one.
    final StatelessSession session = getDatabaseSession();
    final Date d = getUpdateDate();
    final String updatedBy = getBatchDataSource().toString();

    final Query query = session.createQuery("from PsuId where personId = :person_id and endDate is null");
    query.setParameter(PERSON_ID, getPersonId());
    for (final Iterator<?> it = query.list().iterator(); it.hasNext();) {
        final PsuId bean = (PsuId) it.next();

        // Does the bean's PSU ID, equal the incoming psu id, if so we can ignore the update.
        if (bean.getPsuId().equals(psuId)) {
            matchFound = true;
        }

        // PSU ID change, so expire the existing one.
        else {
            bean.setEndDate(d);
            bean.setLastUpdateBy(updatedBy);
            bean.setLastUpdateOn(d);
            session.update(bean);
            setOldPsuId(bean);
        }
    }

    // If we did not find a match, we need to add the new PSU ID.
    if (!matchFound) {
        addPsuId(psuId);
    }
}

From source file:edu.psu.iam.cpr.core.database.batch.PersonBio.java

License:Creative Commons License

/**
 * This method is used to update gender record with a new gender if one differs from what's stored in the database.
 * @param genderType contains the incoming gender type.
 *///from   www  . jav  a  2 s .co m
public void updateGender(final GenderType genderType) {

    // do not attempt to store a null gender type.
    if (genderType == null) {
        return;
    }

    boolean matchFound = false;

    // Perform a query to find the active genders for the user, there should only ever be one.
    final StatelessSession session = getDatabaseSession();
    final Date d = getUpdateDate();
    final String updatedBy = getBatchDataSource().toString();

    final Query query = session
            .createQuery("from PersonGender where personId = :person_id and endDate is null");
    query.setParameter(PERSON_ID, getPersonId());
    for (final Iterator<?> it = query.list().iterator(); it.hasNext();) {
        final PersonGender bean = (PersonGender) it.next();

        // Does the bean's Gender, equal the incoming gender, if so we can ignore the update.
        if (bean.getDataTypeKey().equals(genderType.index())) {
            matchFound = true;
        }

        // Gender change, so expire the existing one.
        else {
            bean.setEndDate(d);
            bean.setLastUpdateBy(updatedBy);
            bean.setLastUpdateOn(d);
            session.update(bean);
            setOldPersonGender(bean);
        }
    }

    // If we did not find a match, we need to add the new gender.
    if (!matchFound) {
        addGender(genderType);
    }

}

From source file:edu.psu.iam.cpr.core.database.batch.PersonBio.java

License:Creative Commons License

/**
 * This method is used to update/add a date of birth record.  The input is a dob string formatted as MMDDYYYY string.
 * A check will be made to ensure the DOB does not already exist.  Otherwise, it will expire the existing on and add
 * a new one./* w w  w.  j a v a 2  s . c  o m*/
 * @param dobString contains the date of birth string formatted as MMDDYYYY.
 * @throws ParseException will be thrown if the Date of Birth cannot be parsed.
 */
public void updateDateOfBirth(final String dobString) throws ParseException {

    // do not attempt to store a null date of birth.
    if (ValidateHelper.isFieldEmpty(dobString)) {
        return;
    }

    boolean matchFound = false;

    // Perform a query to find the active date of births for the user, there should only ever be one.
    final StatelessSession session = getDatabaseSession();
    final Date d = getUpdateDate();
    final String updatedBy = getBatchDataSource().toString();

    final Query query = session.createQuery("from DateOfBirth where personId = :person_id and endDate is null");
    query.setParameter(PERSON_ID, getPersonId());
    for (final Iterator<?> it = query.list().iterator(); it.hasNext();) {
        final DateOfBirth bean = (DateOfBirth) it.next();

        // Does the bean's dobString, equal the incoming dobString, if so we can ignore the update.
        if (bean.getDobChar().equals(dobString)) {
            matchFound = true;
        }

        // Date of birth change, so expire the existing one.
        else {
            bean.setEndDate(d);
            bean.setLastUpdateBy(updatedBy);
            bean.setLastUpdateOn(d);
            session.update(bean);
            setOldDateOfBirth(bean);
        }
    }

    // If we did not find a match, we need to add the new date of birth.
    if (!matchFound) {
        addDateOfBirth(dobString);
    }
}

From source file:edu.psu.iam.cpr.core.database.batch.PersonBio.java

License:Creative Commons License

/**
 * This method is used to determine how to process an email address update.  It will search to see if there is an email address
 * that matches the incoming email address.  If so the update is ignored.  Otherwise, the existing one is expired and the new one
 * is added./*from ww  w .ja v a2 s  . co m*/
 * @param emailAddress contains the email address to be added.
 */
public void updateEmailAddress(final String emailAddress) {

    // If the email address is null, ignore the update.
    if (ValidateHelper.isFieldEmpty(emailAddress)) {
        return;
    }

    final Date d = getUpdateDate();
    final String updatedBy = getBatchDataSource().toString();
    final StatelessSession session = getDatabaseSession();
    final EmailAddressType emailAddressType = getEmailAddressType(emailAddress);
    boolean matchFound = false;

    // Perform a query to find the active email addresses for the user, there should only ever be one.
    final Query query = session.createQuery(
            "from EmailAddress where personId = :person_id and endDate is null and dataTypeKey = :data_type_key");
    query.setParameter(PERSON_ID, getPersonId());
    query.setParameter(DATA_TYPE_KEY, emailAddressType.index());
    for (final Iterator<?> it = query.list().iterator(); it.hasNext();) {
        final EmailAddress bean = (EmailAddress) it.next();

        // Does the bean's email address equal the incoming email address, if so we can ignore the update.
        if (bean.getEmailAddress().equalsIgnoreCase(emailAddress)) {
            matchFound = true;
        }

        // Date of birth change, so expire the existing one.
        else {
            bean.setEndDate(d);
            bean.setLastUpdateBy(updatedBy);
            bean.setLastUpdateOn(d);
            session.update(bean);
            setOldEmailAddress(bean);
        }
    }

    // If we did not find a match, we need to add the new email address.
    if (!matchFound) {
        addEmailAddress(emailAddress);
    }
}

From source file:edu.psu.iam.cpr.core.database.batch.PersonBio.java

License:Creative Commons License

/**
 * This method is used to update a name within the CPR.  A check is made to ensure that the name does not already exist, if it
 * does not, the current name is expired and a new name is added.
 * @param firstName contains the first name to be added.
 * @param middleNames contains the middle name to be added.
 * @param lastName contains the last name to be added.
 * @param suffix contains the suffix to be added.
 *///ww w .  j  a  va2  s  .  c  o  m
public void updateName(final String firstName, final String middleNames, final String lastName,
        final String suffix) {

    // Make sure we have a last name.
    if (ValidateHelper.isFieldEmpty(lastName)) {
        return;
    }

    final String updatedBy = getBatchDataSource().toString();
    final StatelessSession session = getDatabaseSession();
    final DataQualityService dq = getDataQualityService();

    boolean skipAdd = false;

    final Query query = session
            .createQuery("from NamesStaging where personId = :person_id AND importFrom = :import_from");
    query.setParameter(PERSON_ID, getPersonId());
    query.setParameter(IMPORT_FROM, updatedBy);

    // Get the match code for the input name.
    String nameMatchCode = null;
    if (CprProperties.INSTANCE.getProperties().getProperty(CprPropertyName.CPR_MATCHING_ALGORITHM.toString())
            .equals(MatchingAlgorithmType.PENN_STATE.toString())) {
        final MatchCodeServiceReturn nameMatchCodeReturn = dq.getNameMatchCode(firstName, middleNames,
                lastName);
        nameMatchCode = nameMatchCodeReturn.getMatchCode();
    }

    // This iterator will return at most zero or one records.  If it returns most, we have a problem, Houston!
    for (final Iterator<?> it = query.list().iterator(); it.hasNext();) {
        final NamesStaging bean = (NamesStaging) it.next();
        skipAdd = true;

        // If the data source is ISIS, we cannot do a match code compare, we just do an exact one.
        if (getBatchDataSource() == BatchDataSource.ISIS) {
            if (!(Utility.areStringFieldsEqualIgnoreCase(bean.getFirstName(), firstName)
                    && Utility.areStringFieldsEqualIgnoreCase(bean.getMiddleNames(), middleNames)
                    && Utility.areStringFieldsEqualIgnoreCase(bean.getLastName(), lastName)
                    && Utility.areStringFieldsEqualIgnoreCase(bean.getSuffix(), suffix))) {
                updateStagingName(bean, firstName, middleNames, lastName, suffix, nameMatchCode);
            }
        }

        // For other data sources we can do a match code compare.
        else {
            // If the name match codes differ, we need to do an update because the names do not match.
            if (CprProperties.INSTANCE.getProperties()
                    .getProperty(CprPropertyName.CPR_MATCHING_ALGORITHM.toString())
                    .equals(MatchingAlgorithmType.PENN_STATE.toString())) {
                if (!nameMatchCode.equals(bean.getNameMatchCode())) {
                    updateStagingName(bean, firstName, middleNames, lastName, suffix, nameMatchCode);
                } else {
                    updateStagingName(bean, firstName, middleNames, lastName, suffix, nameMatchCode);
                }
            }
        }
    }

    // No name was found, so we need to add one.
    if (!skipAdd) {
        addStagingName(firstName, middleNames, lastName, suffix, nameMatchCode);
    }
}

From source file:edu.psu.iam.cpr.core.database.batch.PersonBio.java

License:Creative Commons License

/**
 * This method is used to update a telephone number.
 * @param phoneType contains the type of telephone number to be updated.
 * @param phoneNumber contains the actual telephone number.
 * @param extension contains the extension.
 *//*  w w w. j a  va2  s.c o m*/
public void updatePhone(final PhoneType phoneType, final String phoneNumber, final String extension) {

    // Only do an update if we have a phone #.
    if (ValidateHelper.isFieldEmpty(phoneNumber)) {
        return;
    }

    final String localPhoneNumber = phoneNumber.replaceAll("\\s", "");
    final StatelessSession session = getDatabaseSession();
    final Date d = getUpdateDate();
    final String updatedBy = getBatchDataSource().toString();
    boolean matchFound = false;

    final Query query = session.createQuery(
            "from Phones where personId = :person_id AND dataTypeKey = :data_type_key AND endDate IS NULL");
    query.setParameter(PERSON_ID, getPersonId());
    query.setParameter(DATA_TYPE_KEY, phoneType.index());
    for (final Iterator<?> it = query.list().iterator(); it.hasNext();) {
        final Phones bean = (Phones) it.next();
        if (Utility.areStringFieldsEqual(localPhoneNumber, bean.getPhoneNumber())) {
            matchFound = true;
        }

        // Based on the data we are receiving from the feeds this is the best we can do at this time.  Not sure what to do about
        // the home phone.
        else if (phoneType == PhoneType.LOCAL_PHONE || phoneType == PhoneType.WORK_PHONE) {
            bean.setEndDate(d);
            bean.setLastUpdateBy(updatedBy);
            bean.setLastUpdateOn(d);
            session.update(bean);
            setOldPhone(bean);
        }
    }

    // If we did not find a match, we need to determine what the new group id will be.
    if (!matchFound) {

        Long groupId = null;
        final Query maxQuery = session.createQuery(
                "select max(groupId) from Phones where personId = :person_id and dataTypeKey = :data_type_key");
        maxQuery.setParameter(PERSON_ID, getPersonId());
        maxQuery.setParameter(DATA_TYPE_KEY, phoneType.index());
        groupId = (Long) maxQuery.list().get(0);
        if (groupId == null) {
            groupId = 1L;
        } else {
            groupId++;
        }

        addPhone(phoneType, localPhoneNumber, extension, groupId);
    }
}

From source file:edu.psu.iam.cpr.core.database.batch.PersonBio.java

License:Creative Commons License

/**
 * This method is used to update a userid record in the database.
 * @param userid contains the userid to be updated.
 * @throws CprException will be thrown if there are any problems.
 *//*from   w w  w  .j a  va2  s  .  c  o  m*/
public void updateUserid(final String userid) throws CprException {

    if (ValidateHelper.isFieldEmpty(userid)) {
        return;
    }

    final StatelessSession session = getDatabaseSession();
    boolean matchFound = false;

    // do a query to see if the userid to be added is not already active.
    Query query = session.createQuery("from Userid where userid = :userid AND endDate is NULL");
    query.setParameter("userid", userid);
    for (final Iterator<?> it = query.list().iterator(); it.hasNext();) {
        final Userid bean = (Userid) it.next();

        // If the userid matches the current person - great!
        if (bean.getPersonId().equals(getPersonId())) {
            matchFound = true;
        }

        // Otherwise we have a problem and cannot add this new userid.
        else {
            throw new CprException(ReturnType.RECORD_ALREADY_EXISTS, "Userid");
        }
    }

    // Determine if the user already has a userid, if so we need to add this one as a secondary userid, not a primary one.
    String primaryFlag = "Y";
    query = session.createQuery("from Userid where personId = :person_id AND endDate IS NULL");
    query.setParameter(PERSON_ID, getPersonId());
    if (query.list().size() > 0) {
        primaryFlag = "N";
    }

    if (!matchFound) {
        addUseridPrimaryFlag(userid, primaryFlag);
    }
}

From source file:edu.psu.iam.cpr.core.database.batch.PersonBio.java

License:Creative Commons License

/**
 * This method is used to update or add a new address record.  It does a check to ensure that address does not already exist
 * for the address1 and city./*from   w w  w . j a va 2  s  . co m*/
 * @param addressType contains the type of address.
 * @param address1 contains address line #1.
 * @param address2 contains address line #2.
 * @param address3 contains address line #3.
 * @param city contains the city.
 * @param state contains the state.
 * @param postalCode contains the postal code.
 * @param countryCode contains the country code.
 * @param campusCode contains the campus code.
 * @throws CprException  will be thrown if there is a CPR releated problem.
 */
public void updateAddress(final AddressType addressType, final String address1, final String address2,
        final String address3, final String city, final String state, final String postalCode,
        final String countryCode, final String campusCode) throws CprException {

    // Only do an update if we have an address1, and city.
    if (ValidateHelper.isFieldEmpty(address1) || ValidateHelper.isFieldEmpty(city)) {
        return;
    }

    final StatelessSession session = getDatabaseSession();
    final String updatedBy = getBatchDataSource().toString();
    final DataQualityService dq = getDataQualityService();
    boolean skipAdd = false;

    // Save off the fields, they will be updated with the transformed values if possible
    String transAddress1 = address1;
    String transAddress2 = address2;
    String transAddress3 = address3;
    String transCity = city;
    String transState = state;
    String transPostalCode = postalCode;
    String transCountryCode = countryCode;

    String addressMatchCode = null;
    String cityMatchCode = null;

    if (CprProperties.INSTANCE.getProperties().getProperty(CprPropertyName.CPR_MATCHING_ALGORITHM.toString())
            .equals(MatchingAlgorithmType.PENN_STATE.toString())) {
        // Transform the address.
        final TransformServiceReturn transformAddressReturn = dq.transformAddress(address1, address2, address3,
                city, state, postalCode, countryCode);

        // If possible use the transformed values
        if (transformAddressReturn.getStatusCode() == ReturnType.SUCCESS.index()) {
            transAddress1 = transformAddressReturn.getAddress1();
            transAddress2 = transformAddressReturn.getAddress2();
            transAddress3 = null;
            transCity = transformAddressReturn.getCity();
            transState = transformAddressReturn.getStateOrProvince();
            transPostalCode = transformAddressReturn.getPostalCode();
            transCountryCode = transformAddressReturn.getCountryCode();
        }

        // Obtain match codes for city and address.
        final MatchCodeServiceReturn addressMatch = dq.getAddressMatchCode(transAddress1, transAddress2,
                transAddress3);
        final MatchCodeServiceReturn cityMatch = dq.getCityMatchCode(transCity);

        if (addressMatch.getStatusCode() != ReturnType.SUCCESS.index()
                || cityMatch.getStatusCode() != ReturnType.SUCCESS.index()) {
            throw new CprException(ReturnType.GENERAL_DATABASE_EXCEPTION, "Unable to obtain match codes");
        }
        addressMatchCode = addressMatch.getMatchCode();
        cityMatchCode = cityMatch.getMatchCode();
    }

    final Query query = session.createQuery(
            "from AddressStaging where personId = :person_id AND importFrom = :import_from AND dataTypeKey = :data_type_key");
    query.setParameter(PERSON_ID, getPersonId());
    query.setParameter(IMPORT_FROM, updatedBy);
    query.setParameter(DATA_TYPE_KEY, addressType.index());

    for (final Iterator<?> it = query.list().iterator(); it.hasNext();) {
        final AddressStaging bean = (AddressStaging) it.next();
        skipAdd = true;

        // Check to see if the match codes or any fields that are not part of a match code have changed.
        if (CprProperties.INSTANCE.getProperties()
                .getProperty(CprPropertyName.CPR_MATCHING_ALGORITHM.toString())
                .equals(MatchingAlgorithmType.PENN_STATE.toString())) {
            if (!(Utility.areStringFieldsEqual(addressMatchCode, bean.getAddressMatchCode())
                    && Utility.areStringFieldsEqual(cityMatchCode, bean.getCityMatchCode())
                    && Utility.areStringFieldsEqualIgnoreCase(campusCode, bean.getCampusCode())
                    && Utility.areStringFieldsEqualIgnoreCase(transPostalCode, bean.getPostalCode())
                    && isStateOrProvinceEqual(transState, bean.getState(), bean.getProvince()))) {
                updateStagingAddress(bean, addressType, transAddress1, transAddress2, transAddress3, transCity,
                        transState, transPostalCode, transCountryCode, campusCode, addressMatchCode,
                        cityMatchCode);
            }
        } else {
            if (!(Utility.areStringFieldsEqual(address1, bean.getAddress1())
                    && Utility.areStringFieldsEqual(city, bean.getCity())
                    && Utility.areStringFieldsEqualIgnoreCase(campusCode, bean.getCampusCode())
                    && Utility.areStringFieldsEqualIgnoreCase(transPostalCode, bean.getPostalCode())
                    && isStateOrProvinceEqual(transState, bean.getState(), bean.getProvince()))) {
                updateStagingAddress(bean, addressType, transAddress1, transAddress2, transAddress3, transCity,
                        transState, transPostalCode, transCountryCode, campusCode, addressMatchCode,
                        cityMatchCode);
            }
        }
    }
    // No address was found, so we need to add one.
    if (!skipAdd) {
        addStagingAddress(addressType, transAddress1, transAddress2, transAddress3, transCity, transState,
                transPostalCode, transCountryCode, campusCode, addressMatchCode, cityMatchCode);
    }
}