repo
stringlengths
1
191
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/validate/MedicationBeanValidator.java
package edu.ncsu.csc.itrust.model.old.validate; import edu.ncsu.csc.itrust.action.UpdateNDCodeListAction; import edu.ncsu.csc.itrust.exception.ErrorList; import edu.ncsu.csc.itrust.exception.FormValidationException; import edu.ncsu.csc.itrust.model.old.beans.MedicationBean; /** * Validates ND code beans, from {@link UpdateNDCodeListAction} * * * */ public class MedicationBeanValidator extends BeanValidator<MedicationBean> { /** * The default constructor. */ public MedicationBeanValidator() { } /** * Performs the act of validating the bean in question, which varies depending on the * type of validator. If the validation does not succeed, a {@link FormValidationException} is thrown. * * @param p A bean of the type to be validated. */ @Override public void validate(MedicationBean m) throws FormValidationException { ErrorList errorList = new ErrorList(); errorList.addIfNotNull(checkFormat("ND Code", m.getNDCode(), ValidationFormat.ND, false)); errorList.addIfNotNull(checkFormat("Description", m.getDescription(), ValidationFormat.ND_CODE_DESCRIPTION, false)); if (errorList.hasErrors()) throw new FormValidationException(errorList); } }
1,198
31.405405
104
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/validate/MessageValidator.java
package edu.ncsu.csc.itrust.model.old.validate; import edu.ncsu.csc.itrust.exception.ErrorList; import edu.ncsu.csc.itrust.exception.FormValidationException; import edu.ncsu.csc.itrust.model.old.beans.MessageBean; /** * Used to validate updating an office visit, by {@link EditOfficeVisitAction} * * * */ public class MessageValidator extends BeanValidator<MessageBean> { public MessageValidator() { } @Override public void validate(MessageBean mBean) throws FormValidationException { ErrorList errorList = new ErrorList(); errorList.addIfNotNull(checkFormat("body", mBean.getBody(), ValidationFormat.MESSAGES_BODY, false)); errorList.addIfNotNull(checkFormat("subject", mBean.getSubject(), ValidationFormat.MESSAGES_SUBJECT, false)); if (errorList.hasErrors()) throw new FormValidationException(errorList); } }
846
28.206897
111
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/validate/OverrideReasonBeanValidator.java
package edu.ncsu.csc.itrust.model.old.validate; import edu.ncsu.csc.itrust.exception.ErrorList; import edu.ncsu.csc.itrust.exception.FormValidationException; import edu.ncsu.csc.itrust.model.old.beans.OverrideReasonBean; /** * Validates reason code beans, from {@link UpdateReasonCodeListAction} * */ public class OverrideReasonBeanValidator extends BeanValidator<OverrideReasonBean> { /** * The default constructor. */ public OverrideReasonBeanValidator() { } /** * Performs the act of validating the bean in question, which varies depending on the * type of validator. If the validation does not succeed, a {@link FormValidationException} is thrown. * * @param p A bean of the type to be validated. */ @Override public void validate(OverrideReasonBean orc) throws FormValidationException { ErrorList errorList = new ErrorList(); errorList.addIfNotNull(checkFormat("Reason Code", orc.getORCode(), ValidationFormat.ORC, false)); errorList.addIfNotNull(checkFormat("Description", orc.getDescription(), ValidationFormat.OR_CODE_DESCRIPTION, false)); if (errorList.hasErrors()) throw new FormValidationException(errorList); } }
1,170
33.441176
104
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/validate/PatientValidator.java
package edu.ncsu.csc.itrust.model.old.validate; import edu.ncsu.csc.itrust.action.EditPatientAction; import edu.ncsu.csc.itrust.exception.ErrorList; import edu.ncsu.csc.itrust.exception.FormValidationException; import edu.ncsu.csc.itrust.model.old.beans.PatientBean; import org.apache.commons.validator.CreditCardValidator; import java.util.Date; /** * Validates a patient bean, from {@link EditPatientAction} * * * */ public class PatientValidator extends BeanValidator<PatientBean> { /** * The default constructor. */ public PatientValidator() { } @Override public void validate(PatientBean p) throws FormValidationException{ ErrorList errorList = new ErrorList(); //First name, last name, and email are all required errorList.addIfNotNull(checkFormat("First name", p.getFirstName(), ValidationFormat.NAME, false)); errorList.addIfNotNull(checkFormat("Last name", p.getLastName(), ValidationFormat.NAME, false)); errorList.addIfNotNull(checkFormat("Email", p.getEmail(), ValidationFormat.EMAIL, false)); if(!p.getDateOfBirthStr().isEmpty()){ errorList.addIfNotNull(checkFormat("Date of Birth", p.getDateOfBirthStr(), ValidationFormat.DATE, false)); } if(!p.getDateOfDeathStr().isEmpty()){ errorList.addIfNotNull(checkFormat("Date of Death", p.getDateOfDeathStr(), ValidationFormat.DATE, true)); } try { if ("".equals(p.getDateOfDeathStr()) || p.getDateOfDeath() == null) { if (!p.getCauseOfDeath().equals("")){ errorList.addIfNotNull("Cause of Death cannot be specified without Date of Death!"); } } else { if (p.getDateOfDeath().before(p.getDateOfBirth())) errorList.addIfNotNull("Death date cannot be before birth date!"); if( p.getDateOfDeath().after(new Date())){ errorList.addIfNotNull("Death date cannot be in the future!"); } } if( p.getDateOfBirth().after(new Date())){ errorList.addIfNotNull("Birth date cannot be in the future!"); } } catch (NullPointerException e) { // ignore this } if(!p.getCauseOfDeath().isEmpty()){ boolean deathCauseNull = (null == p.getDateOfDeathStr() || p.getDateOfDeathStr().equals("")); errorList.addIfNotNull(checkFormat("Cause of Death", p.getCauseOfDeath(), ValidationFormat.ICD9CM, deathCauseNull)); } if(!p.getStreetAddress1().isEmpty()){ errorList.addIfNotNull(checkFormat("Street Address 1", p.getStreetAddress1(), ValidationFormat.ADDRESS, false)); } if(!p.getStreetAddress2().isEmpty()){ errorList.addIfNotNull(checkFormat("Street Address 2", p.getStreetAddress2(), ValidationFormat.ADDRESS, true)); } if(!p.getCity().isEmpty()){ errorList.addIfNotNull(checkFormat("City", p.getCity(), ValidationFormat.CITY, false)); } if(!p.getState().isEmpty()){ errorList.addIfNotNull(checkFormat("State", p.getState(), ValidationFormat.STATE, false)); } if(!p.getZip().isEmpty()){ errorList.addIfNotNull(checkFormat("Zip Code", p.getZip(), ValidationFormat.ZIPCODE, false)); } if(!p.getPhone().isEmpty()){ errorList.addIfNotNull(checkFormat("Phone Number", p.getPhone(), ValidationFormat.PHONE_NUMBER, false)); } if(!p.getEmergencyName().isEmpty()){ errorList.addIfNotNull(checkFormat("Emergency Contact Name", p.getEmergencyName(), ValidationFormat.NAME, false)); } if(!p.getEmergencyPhone().isEmpty()){ errorList.addIfNotNull(checkFormat("Emergency Contact Phone", p.getEmergencyPhone(), ValidationFormat.PHONE_NUMBER, false)); } if(!p.getIcName().isEmpty()){ errorList.addIfNotNull(checkFormat("Insurance Company Name", p.getIcName(), ValidationFormat.NAME, false)); } if(!p.getIcAddress1().isEmpty()){ errorList.addIfNotNull(checkFormat("Insurance Company Address 1", p.getIcAddress1(), ValidationFormat.ADDRESS, false)); } if(!p.getIcAddress2().isEmpty()){ errorList.addIfNotNull(checkFormat("Insurance Company Address 2", p.getIcAddress2(), ValidationFormat.ADDRESS, true)); } if(!p.getIcCity().isEmpty()){ errorList.addIfNotNull(checkFormat("Insurance Company City", p.getIcCity(), ValidationFormat.CITY, false)); } if(!p.getIcState().isEmpty()){ errorList.addIfNotNull(checkFormat("Insurance Company State", p.getIcState(), ValidationFormat.STATE, false)); } if(!p.getIcZip().isEmpty()){ errorList.addIfNotNull(checkFormat("Insurance Company Zip", p.getIcZip(), ValidationFormat.ZIPCODE, false)); } if(!p.getIcPhone().isEmpty()){ errorList.addIfNotNull(checkFormat("Insurance Company Phone", p.getIcPhone(), ValidationFormat.PHONE_NUMBER, false)); } if(!p.getIcID().isEmpty()){ errorList.addIfNotNull(checkFormat("Insurance Company ID", p.getIcID(), ValidationFormat.INSURANCE_ID, false)); } if(!p.getMotherMID().isEmpty()){ errorList.addIfNotNull(checkFormat("Mother MID", p.getMotherMID(), ValidationFormat.NPMID, true)); } if(!p.getFatherMID().isEmpty()){ errorList.addIfNotNull(checkFormat("Father MID", p.getFatherMID(), ValidationFormat.NPMID, true)); } if(!p.getTopicalNotes().isEmpty()){ errorList.addIfNotNull(checkFormat("Topical Notes", p.getTopicalNotes(), ValidationFormat.NOTES, true)); } /* This block was added for Theme 5 by Tyler Arehart */ if(!p.getCreditCardNumber().isEmpty()){ if (!(p.getCreditCardNumber().equals("") && p.getCreditCardType().equals(""))) { String s = null; CreditCardValidator c; int type = -1; if (p.getCreditCardType().equals("VISA")) type = CreditCardValidator.VISA; if (p.getCreditCardType().equals("MASTERCARD")) type = CreditCardValidator.MASTERCARD; if (p.getCreditCardType().equals("DISCOVER")) type = CreditCardValidator.DISCOVER; if (p.getCreditCardType().equals("AMEX")) type = CreditCardValidator.AMEX; if (type != -1) { c = new CreditCardValidator(type); if (!c.isValid(p.getCreditCardNumber())) { s = "Credit Card Number"; } } else { s = "Credit Card Type"; } errorList.addIfNotNull(s); } } if(!p.getDirectionsToHome().isEmpty()){ errorList.addIfNotNull(checkFormat("Directions to Home", p.getDirectionsToHome(), ValidationFormat.COMMENTS, true)); } if(!p.getReligion().isEmpty()){ errorList.addIfNotNull(checkFormat("Religion", p.getReligion(), ValidationFormat.NAME, true)); } if(!p.getLanguage().isEmpty()){ errorList.addIfNotNull(checkFormat("Language", p.getLanguage(), ValidationFormat.NAME, true)); } if(!p.getSpiritualPractices().isEmpty()){ errorList.addIfNotNull(checkFormat("Spiritual Practices", p.getSpiritualPractices(), ValidationFormat.COMMENTS, true)); } if(!p.getAlternateName().isEmpty()){ errorList.addIfNotNull(checkFormat("Alternate Name", p.getAlternateName(), ValidationFormat.NAME, true)); } if (errorList.hasErrors()) throw new FormValidationException(errorList); } }
6,881
34.474227
127
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/validate/PersonnelValidator.java
package edu.ncsu.csc.itrust.model.old.validate; import edu.ncsu.csc.itrust.action.EditPersonnelAction; import edu.ncsu.csc.itrust.exception.ErrorList; import edu.ncsu.csc.itrust.exception.FormValidationException; import edu.ncsu.csc.itrust.model.old.beans.PersonnelBean; /** * Validates a personnel bean, from {@link EditPersonnelAction} * * * */ public class PersonnelValidator extends BeanValidator<PersonnelBean> { /** * The default constructor. */ public PersonnelValidator() { } /** * Performs the act of validating the bean in question, which varies depending on the * type of validator. If the validation does not succeed, a {@link FormValidationException} is thrown. * * @param p A bean of the type to be validated. */ @Override public void validate(PersonnelBean p) throws FormValidationException { ErrorList errorList = new ErrorList(); errorList.addIfNotNull(checkFormat("First name", p.getFirstName(), ValidationFormat.NAME, false)); errorList.addIfNotNull(checkFormat("Last name", p.getLastName(), ValidationFormat.NAME, false)); errorList.addIfNotNull(checkFormat("Street Address 1", p.getStreetAddress1(), ValidationFormat.ADDRESS, false)); errorList.addIfNotNull(checkFormat("Street Address 2", p.getStreetAddress2(), ValidationFormat.ADDRESS, true)); errorList.addIfNotNull(checkFormat("City", p.getCity(), ValidationFormat.CITY, false)); errorList.addIfNotNull(checkFormat("State", p.getState(), ValidationFormat.STATE, false)); errorList.addIfNotNull(checkFormat("Zip Code", p.getZip(), ValidationFormat.ZIPCODE, false)); errorList.addIfNotNull(checkFormat("Phone Number", p.getPhone(), ValidationFormat.PHONE_NUMBER, false)); errorList.addIfNotNull(checkFormat("Email", p.getEmail(), ValidationFormat.EMAIL, true)); if (errorList.hasErrors()) throw new FormValidationException(errorList); } }
1,874
41.613636
114
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/validate/RecordsReleaseFormValidator.java
package edu.ncsu.csc.itrust.model.old.validate; import edu.ncsu.csc.itrust.exception.ErrorList; import edu.ncsu.csc.itrust.exception.FormValidationException; import edu.ncsu.csc.itrust.model.old.beans.forms.RecordsReleaseForm; public class RecordsReleaseFormValidator extends BeanValidator<RecordsReleaseForm> { /** * Performs the act of validating the bean in question, which varies depending on the * type of validator. If the validation does not succeed, a {@link FormValidationException} is thrown. * * @param p A bean of the type to be validated. */ @Override public void validate(RecordsReleaseForm bean) throws FormValidationException { ErrorList errorList = new ErrorList(); errorList.addIfNotNull(checkFormat("Release Hospital ID", bean.getReleaseHospitalID(), ValidationFormat.HOSPITAL_ID, false)); errorList.addIfNotNull(checkFormat("Recipient hospital name", bean.getRecipientHospitalName(), ValidationFormat.HOSPITAL_NAME, false)); errorList.addIfNotNull(checkFormat("Recipient hospital address", bean.getRecipientHospitalAddress(), ValidationFormat.FULL_ADDRESS, false)); errorList.addIfNotNull(checkFormat("Doctor's first name", bean.getRecipientFirstName(), ValidationFormat.NAME, false)); errorList.addIfNotNull(checkFormat("Doctor's last name", bean.getRecipientLastName(), ValidationFormat.NAME, false)); errorList.addIfNotNull(checkFormat("Doctor's phone number", bean.getRecipientPhone(), ValidationFormat.PHONE_NUMBER, false)); errorList.addIfNotNull(checkFormat("Doctor's email address", bean.getRecipientEmail(), ValidationFormat.EMAIL, false)); errorList.addIfNotNull(checkFormat("Release request justification", bean.getRequestJustification(), ValidationFormat.NOTES, true)); errorList.addIfNotNull(checkBoolean("Digital Signature", bean.getDigitalSignature().toString())); if (errorList.hasErrors()) throw new FormValidationException(errorList); } }
1,925
57.363636
142
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/validate/RemoteMonitoringDataBeanValidator.java
package edu.ncsu.csc.itrust.model.old.validate; import edu.ncsu.csc.itrust.action.AddRemoteMonitoringDataAction; import edu.ncsu.csc.itrust.exception.ErrorList; import edu.ncsu.csc.itrust.exception.FormValidationException; import edu.ncsu.csc.itrust.model.old.beans.RemoteMonitoringDataBean; /** * Validator used to validate adding new remote monitoring data in {@link AddRemoteMonitoringDataAction} * */ public class RemoteMonitoringDataBeanValidator extends BeanValidator<RemoteMonitoringDataBean> { /** * The default constructor. */ public RemoteMonitoringDataBeanValidator() {} /** * Performs the act of validating the bean in question, which varies depending on the * type of validator. If the validation does not succeed, a {@link FormValidationException} is thrown. * * @param p A bean of the type to be validated. */ @Override public void validate(RemoteMonitoringDataBean m) throws FormValidationException { ErrorList errorList = new ErrorList(); // Skip validation if values were not submitted (0 or -1) if (!(m.getSystolicBloodPressure() == 0 || m.getSystolicBloodPressure() == -1)) errorList.addIfNotNull(checkFormat("Systolic Blood Pressure", "" + m.getSystolicBloodPressure(), ValidationFormat.SYSTOLIC_BLOOD_PRESSURE, true)); if (!(m.getDiastolicBloodPressure() == 0 || m.getDiastolicBloodPressure() == -1)) errorList.addIfNotNull(checkFormat("Diastolic Blood Pressure", "" + m.getDiastolicBloodPressure(), ValidationFormat.DIASTOLIC_BLOOD_PRESSURE, true)); if (!(m.getGlucoseLevel() == 0 || m.getGlucoseLevel() == -1)) errorList.addIfNotNull(checkFormat("Glucose Level", "" + m.getGlucoseLevel(), ValidationFormat.GLUCOSE_LEVEL, true)); if (!(m.getPedometerReading() == 0 || m.getPedometerReading() == -1)) errorList.addIfNotNull(checkFormat("Pedometer Reading", "" + m.getPedometerReading(), ValidationFormat.PEDOMETER_READING, true)); if (!(m.getHeight() == 0 || m.getHeight() == -1)) errorList.addIfNotNull(checkFormat("Height", "" + m.getHeight(), ValidationFormat.HEIGHT, true)); if (!(m.getWeight() == 0 || m.getWeight() == -1)) errorList.addIfNotNull(checkFormat("Weight", "" + m.getWeight(), ValidationFormat.WEIGHT, true)); if (errorList.hasErrors()){ throw new FormValidationException(errorList); } } }
2,333
43.884615
104
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/validate/SecurityQAValidator.java
package edu.ncsu.csc.itrust.model.old.validate; import edu.ncsu.csc.itrust.action.SetSecurityQuestionAction; import edu.ncsu.csc.itrust.exception.ErrorList; import edu.ncsu.csc.itrust.exception.FormValidationException; import edu.ncsu.csc.itrust.model.old.beans.SecurityQA; /** * Validates the security question and answer. This doesn't follow the same format as the others because this * validator is used for the various states of reset password, {@link SetSecurityQuestionAction} * * * */ public class SecurityQAValidator extends BeanValidator<SecurityQA> { /** * Performs the act of validating the bean in question, which varies depending on the * type of validator. If the validation does not succeed, a {@link FormValidationException} is thrown. * * @param p A bean of the type to be validated. */ @Override public void validate(SecurityQA bean) throws FormValidationException { ErrorList errorList = new ErrorList(); if (null == bean) throw new FormValidationException("Null form"); if (null == bean.getConfirmAnswer()) throw new FormValidationException("Confirm answer cannot be empty"); if (!bean.getAnswer().equals(bean.getConfirmAnswer())) throw new FormValidationException("Security answers do not match"); errorList.addIfNotNull(checkFormat("Security Question", bean.getQuestion(), ValidationFormat.QUESTION, false)); errorList.addIfNotNull(checkFormat("Security Answer", bean.getAnswer(), ValidationFormat.ANSWER, false)); if (errorList.hasErrors()) throw new FormValidationException(errorList); } }
1,581
34.954545
109
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/validate/SurveySearchValidator.java
package edu.ncsu.csc.itrust.model.old.validate; import edu.ncsu.csc.itrust.exception.ErrorList; import edu.ncsu.csc.itrust.exception.FormValidationException; import edu.ncsu.csc.itrust.model.old.beans.SurveyResultBean; /** * Validator for zip code that is entered when a user searches for HCP survey results. */ public class SurveySearchValidator extends BeanValidator<SurveyResultBean>{ /** * Performs the act of validating the bean in question, which varies depending on the * type of validator. If the validation does not succeed, a {@link FormValidationException} is thrown. * * @param p A bean of the type to be validated. */ @Override public void validate(SurveyResultBean bean) throws FormValidationException { ErrorList errorList = new ErrorList(); errorList.addIfNotNull(checkFormat("Zip Code", bean.getHCPzip(), ValidationFormat.ZIPCODE, false)); if (errorList.hasErrors()) throw new FormValidationException(errorList); } }
968
33.607143
104
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/validate/ValidationFormat.java
package edu.ncsu.csc.itrust.model.old.validate; import java.util.regex.Pattern; /** * Enum with all of the validation formats that fit into a regex. * * * * */ public enum ValidationFormat { NAME("^(?=.*[a-zA-Z])[\\sa-zA-Z'-]{1,20}$", "Up to 20 Letters, space, ' and -"), DATE("[\\d]{2}/[\\d]{2}/[\\d]{4}", "MM/DD/YYYY"), PHONE_NUMBER("[\\d]{3}-[\\d]{3}-[\\d]{4}", "xxx-xxx-xxxx"), MID("[\\d]{1,10}", "Between 1 and 10 digits"), NPMID("[0-8][0-9]{0,9}", "1-10 digit number not beginning with 9"), DATETIME("[\\d]{4}-[\\d]{2}-[\\d]{2}[\\s]{1}[\\d]{2}:[\\d]{2}:[\\d]{2}.[\\d]{1}", "mm/dd/yyyy"), EMAIL(".+@.+\\..+", "Up to 30 alphanumeric characters and symbols . and _ @"), QUESTION("[a-zA-Z0-9?\\-'.\\s]{1,50}", "Up to 50 alphanumeric characters and symbols ?-'."), ANSWER("[a-zA-Z0-9\\s]{1,30}", "Up to 30 alphanumeric characters"), ADDRESS("[a-zA-Z0-9.\\s]{1,30}", "Up to 30 alphanumeric characters, and ."), FULL_ADDRESS("[a-zA-Z0-9.,\\s]{1,100}", "Up to 100 alphanumeric characters, comma, and ."), APPT_COMMENT("[0-9a-zA-Z\\s'\"?!:;\\-._\n\t]{1,1000}", "Between 0 and 1000 alphanumerics with space, and other punctuation"), APPT_TYPE_NAME("[a-zA-Z ]{1,30}", "Between 1 and 30 alpha characters and space"), APPT_TYPE_DURATION("[0-9]{1,5}", "Between 1 and 5 numeric digits"), CITY("[a-zA-Z\\s]{1,15}", "Up to 15 characters"), STATE("[A-Z]{2}", "Two capital letters"), ZIPCODE("([0-9]{5})|([0-9]{5}-[0-9]{4})", "xxxxx or xxxxx-xxxx"), // ^[0-9]{5}(?:-[0-9]{4})?$ BLOODTYPE("((O)|(A)|(B)|(AB))([+-]{1})", "Must be [O,A,B,AB]+/-"), // ^(?:O|A|B|AB)[+-]$ NOTES("[a-zA-Z0-9\\s'\"?!:#;\\-.,_\n\t]{1,300}", "Up to 300 alphanumeric characters, with space, and other punctuation"), MESSAGES_BODY("[a-zA-Z0-9\\s'\"?!:;\\-.,_\n\t()\\\\/]{1,1000}", "Up to 1000 alphanumeric characters, with space, and other punctuation"), MESSAGES_SUBJECT("[a-zA-Z0-9\\s'\"?!:;\\-._\n\t()]{1,100}", "Up to 100 alphanumeric characters, with space, and other punctuation"), PASSWORD("[a-zA-Z0-9]{8,20}", "8-20 alphanumeric characters"), INSURANCE_ID("[\\s\\da-zA-Z'-]{1,20}", "Up to 20 letters, digits, space, ' and -"), HOSPITAL_ID("[\\d]{1,10}", "Between 1 and 10 digits"), HOSPITAL_NAME("[0-9a-zA-Z' .]{1,30}", "Between 1 and 30 alphanumerics, space, ', and ."), ND_CODE_DESCRIPTION("[a-zA-Z0-9\\s]{1,100}", "Up to 100 characters, letters, numbers, and a space"), DRUG_INT_COMMENTS("[a-zA-Z0-9.\\-',!;:()?\\s]{1,500}", "Up to 500 alphanumeric characters and .-',!;:()?"), EMAILS("[a-zA-Z0-9.\\-',!;:()?\\s\\\\/]{1,500}", "Up to 500 alphanumeric characters and .-',!;:()?"), ADVERSE_EVENT_COMMENTS("[a-zA-Z0-9.\\-',!;:()?\\s]{1,2000}", "Up to 2000 alphanumeric characters and .-',!;:()?"), ICD_CODE_DESCRIPTION("[a-zA-Z0-9\\s]{1,30}", "Up to 30 characters, letters, numbers, and a space"), CPT_CODE_DESCRIPTION("[a-zA-Z0-9\\s]{1,30}", "Up to 30 characters, letters, numbers, and a space"), ALLERGY_DESCRIPTION("[a-zA-Z0-9\\s]{1,30}", "Up to 30 characters, letters, numbers, and a space"), ICD9CM("([\\d]{1,3})|([\\d]{1,3}\\.[\\d]{0,2})", "xxx.xx"), CPT("[\\d]{1,4}[A-Za-z0-9]", "Up to four digit integer plus a letter or digit"), HeadCircumference("[\\d]{0,3}(\\.(\\d){0,1}){0,1}", "Up to 3-digit number + up to 1 decimal place"), Height("[\\d]{0,3}(\\.(\\d){0,1}){0,1}", "Up to 3-digit number + up to 1 decimal place"), Weight("[\\d]{0,4}(\\.(\\d){0,1}){0,1}", "Up to 4-digit number + up to 1 decimal place"), YEAR("[\\d]{4}", "Must be 4 digits"), GENDERCOD("(Male)|(Female)|(Not Specified)", "Only Male, Female, or All Patients"), LOINC("[\\d]{1,5}[-]{1}[\\d]{1}", "Must be 1-5 digits followed by a - then another digit"), ND("[\\d]{1,9}", "Up to nine digit integer"), LOINC_ITEM("[^\"]{1,100}", "Up to 100 characters, excluding quotation marks"), COMMENTS("[a-zA-Z0-9.\\s]{1,500}", "Up to 500 alphanumeric characters"), LAB_STATUS("(In Transit)|(Received)|(Testing)|(Pending)|(Completed)", "Only In Transit, Received, Testing, Pending, or Completed"), LAB_RIGHTS("(ALLOWED)|(RESTRICTED)", "Only ALLOWED, or RESTRICTED"), SYSTOLIC_BLOOD_PRESSURE("^([4-9][0-9]|1[0-9][0-9]|2[0-3][0-9]|240)$", "Must be between 40 and 240"), DIASTOLIC_BLOOD_PRESSURE("^([4-9][0-9]|1[0-4][0-9]|150)$", "Must be between 40 and 150"), GLUCOSE_LEVEL("^([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|250)$", "Must be between 0 and 250"), PEDOMETER_READING("^([0-9]{1,10})$", "Up to ten digit integer"), HEIGHT("^([0-9]{1,4}\\.[0-9])$", "Up to 4 digit number and 1 decimal place"), WEIGHT("^([0-9]{1,4}\\.[0-9])$", "Up to 4 digit number and 1 decimal place"), ORC("[\\d]{1,5}", "Up to five digit integer"), OR_CODE_DESCRIPTION("[a-zA-Z0-9\\s]{1,80}", "Up to 80 characters, letters, numbers, and a space"), PATIENT_INSTRUCTIONS_NAME("^[a-zA-Z0-9#;?\\-'.:,!/ \n]{1,100}$", "Up to 100 alphanumeric characters, with space, and other punctuation"), PATIENT_INSTRUCTIONS_COMMENTS("^[a-zA-Z0-9#;?\\-'.:,!/ \n]{1,500}$", "Up to 500 alphanumeric characters, with space, and other punctuation"), PATIENT_INSTRUCTIONS_URL("^.{1,200}$", "Up to 200 characters, as a valid URL"), LABPROCEDURE_NUMRESULT_CONTENT("^[\\-+]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)$", "A number containing an optional minus sign and an optional decimal point."), LABPROCEDURE_NUMRESULT_LENGTH("^.{1,20}$", "A number containing between 1 and 20 characters, including the optional minus sign and decimal point."), LABPROCEDURE_COMMENTS("^[^<>&]{1,500}$", "Up to 500 characters without newline, less than, greater than, or ampersand."), REFERRAL_NOTES("[a-zA-Z0-9\\s'\"?!:;\\-.,_\n\t()\\\\/]{1,500}", "Up to 500 alphanumeric characters, with space, and other punctuation"), PRIORITY("[1-3]", "Priority must be between 1 and 3"), WEEKS_PREGNANT("^([0-9]|[1-3][0-9]|4[0-2])-[0-6]{1}$", "Weeks must be between 0 and 42, Days must be between 0 and 6"), HOURS_LABOR("[\\d]{0,3}.[\\d]{0,2}", "Hours in labor must between 0.0 and 999.99"), FHR("^[0-9]\\d*", "Must be 0 or positive integer."), FHU("^[0-9]*.^[1-9][0-9]*|^[1-9][0-9]*.?[0-9]*$", "Must be a positive double."), WEEKS_PREGNANT_OV("^([0-9]|[1-3][0-9]|4[0-2])-[0-6]{1}$", "The patient chosen is not a current obstetrics patient"), MEALTYPE("^(?:Breakfast|Lunch|Snack|Dinner)$", "must be one of {Breakfast, Lunch, Snack, Dinner}"), EXERCISETYPE("^(?:Cardio|Weight Training)$", "must be one of {Cardio, Weight Training}"), SLEEPTYPE("^(?:Nightly|Nap)$", "must be one of {Nightly, Nap}"), HEIGHT_OV("^[0-9]{0,3}(?:\\.[0-9])?$", "Up to 3 digit number and up to 1 decimal place"), LENGTH_OV("^[0-9]{0,3}(?:\\.[0-9])?$", "Up to 3 digit number and up to 1 decimal place"), WEIGHT_OV("^[0-9]{0,3}(?:\\.[0-9])?$", "Up to 4 digit number and up to 1 decimal place"), HEAD_CIRCUMFERENCE_OV("^[0-9]{0,3}(?:\\.[0-9])?$", "Up to 3 digit number and up to 1 decimal place"), BLOOD_PRESSURE_OV("^[0-9]{1,3}\\/[0-9]{1,3}$", "Up to 3-digit number / Up to 3-digit number"), HDL_OV("^[0-8]?[0-9]$", "integer less than 90"), TRIGLYCERIDE_OV("^(?:[1-5][0-9]{2}|600)$", "integer between 100 and 600"), LDL_OV("^(?:[1-5]?[0-9]{1,2}|600)$", "integer between 0 and 600"), HSS_OV("^[1-3]$","1, 2, or 3, representing household smoking status"), PSS_OV("^[1-59]$","1-5 or 9, representing patient smoking status") ; private Pattern regex; private String description; ValidationFormat(String regex, String errorMessage) { this.regex = Pattern.compile(regex); this.description = errorMessage; } public Pattern getRegex() { return regex; } public String getDescription() { return description; } }
7,612
56.240602
132
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/prescription/Prescription.java
package edu.ncsu.csc.itrust.model.prescription; import java.time.LocalDate; import edu.ncsu.csc.itrust.model.old.beans.MedicationBean; public class Prescription { private long patientMID; private MedicationBean drugCode; private LocalDate startDate; private LocalDate endDate; private long officeVisitId; private long hcpMID; private long id; private String instructions; private long dosage; public Prescription() { drugCode = new MedicationBean(); } public long getPatientMID() { return patientMID; } public void setPatientMID(long patientMID) { this.patientMID = patientMID; } public long getHcpMID() { return hcpMID; } public void setHcpMID(long hcpMID) { this.hcpMID = hcpMID; } public MedicationBean getDrugCode() { return drugCode; } public void setDrugCode(MedicationBean drugCode) { this.drugCode = drugCode; } public LocalDate getStartDate() { return startDate; } public void setStartDate(LocalDate startDate) { this.startDate = startDate; } public LocalDate getEndDate() { return endDate; } public void setEndDate(LocalDate endDate) { this.endDate = endDate; } public long getOfficeVisitId() { return officeVisitId; } public void setOfficeVisitId(long officeVisitId) { this.officeVisitId = officeVisitId; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getCode() { return getDrugCode().getNDCode(); } public String getName() { return getDrugCode().getDescription(); } public String getInstructions() { return instructions; } public void setInstructions(String instructions) { this.instructions = instructions; } public long getDosage() { return dosage; } public void setDosage(long dosage) { this.dosage = dosage; } }
1,795
16.436893
58
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/prescription/PrescriptionMySQL.java
package edu.ncsu.csc.itrust.model.prescription; import java.sql.Connection; import java.sql.Date; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.time.LocalDate; import java.util.ArrayList; import java.util.List; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.sql.DataSource; import edu.ncsu.csc.itrust.exception.DBException; import edu.ncsu.csc.itrust.exception.FormValidationException; import edu.ncsu.csc.itrust.model.old.beans.MedicationBean; import edu.ncsu.csc.itrust.model.old.beans.PatientBean; import edu.ncsu.csc.itrust.model.old.beans.loaders.PatientLoader; public class PrescriptionMySQL { private DataSource ds; private PrescriptionValidator validator; /** * Standard constructor for use in deployment * @throws DBException */ public PrescriptionMySQL() throws DBException { try { this.ds = getDataSource(); this.validator = new PrescriptionValidator(); } catch (NamingException e) { throw new DBException(new SQLException("Context Lookup Naming Exception: " + e.getMessage())); } } protected DataSource getDataSource() throws NamingException { Context ctx = new InitialContext(); return ((DataSource) (((Context) ctx.lookup("java:comp/env"))).lookup("jdbc/itrust")); } /** * Constructor for testing purposes * @param ds The DataSource to use */ public PrescriptionMySQL(DataSource ds) { this.ds = ds; this.validator = new PrescriptionValidator(); } /** * Gets all prescriptions for the patient with the given MID with ending * dates equal to or after the given end date * * @param mid The mid of the patient whose prescriptions we should get * @param endDate The end date to get prescriptions after * @return A List of prescriptions for the given patient that end on or * after the given date. * @throws SQLException */ public List<Prescription> getPrescriptionsForPatientEndingAfter(long mid, LocalDate endDate) throws SQLException{ try (Connection conn = ds.getConnection(); PreparedStatement pstring = createERPreparedStatement(conn, mid, endDate); ResultSet results = pstring.executeQuery()){ return loadRecords(results); } } /** * Adds a Prescription to the database. * * @param p The prescription to add * @return True if the record was successfully added, false otherwise * @throws SQLException */ public boolean add(Prescription p) throws SQLException { try { validator.validate(p); } catch (FormValidationException e) { throw new SQLException(e.getMessage()); } try (Connection conn = ds.getConnection(); PreparedStatement pstring = createAddPreparedStatement(conn, p);){ return pstring.executeUpdate() > 0; } } public Prescription get(long id) throws SQLException { try (Connection conn = ds.getConnection(); PreparedStatement pstring = createGetStatement(conn, id); ResultSet results = pstring.executeQuery()) { List<Prescription> list = loadRecords(results); return list.isEmpty() ? null : list.get(0); } } /** * Get all prescription for the patient with the given MID. * * @param mid * MID of patient * @return list of MID beloning to the given patient * @throws SQLException */ public List<Prescription> getPrescriptionsByMID(long mid) throws SQLException { try (Connection conn = ds.getConnection(); PreparedStatement pstring = createGetByMIDStatement(conn, mid); ResultSet results = pstring.executeQuery()) { return loadRecords(results); } } /** * Removes a Prescription from the database. It will remove the record * with the same id as this one, but will not pay attention to any other * fields. * @param p The Prescription to remove * @return True if the Prescription was successfully removed, false if not * @throws SQLException */ public boolean remove(long id) throws SQLException{ try (Connection conn = ds.getConnection(); PreparedStatement pstring = createRemovePreparedStatement(conn, id);){ return pstring.executeUpdate() > 0; } } /** * Updates a Prescription in the database. * @param p The Prescription to update * @return True if the Prescription was successfully updated, false if not * @throws SQLException */ public boolean update(Prescription p) throws SQLException { try { validator.validate(p); } catch (FormValidationException e) { throw new SQLException(e.getMessage()); } try (Connection conn = ds.getConnection(); PreparedStatement pstring = createUpdatePreparedStatement(conn, p);){ return pstring.executeUpdate() > 0; } } /** * A utility method for creating a PreparedStatement for an update operation * @param conn The connection to use * @param p The Prescription we're updating * @return The generated PreparedStatement * @throws SQLException */ private PreparedStatement createUpdatePreparedStatement(Connection conn, Prescription p) throws SQLException{ PreparedStatement pstring = conn.prepareStatement("UPDATE prescription SET patientMID=?, drugCode=?, startDate=?, endDate=?, officeVisitId=?, instructions=?, hcpMID=?, dosage=? WHERE id=?;"); pstring.setLong(1, p.getPatientMID()); pstring.setString(2, p.getCode()); pstring.setDate(3, Date.valueOf(p.getStartDate())); pstring.setDate(4, Date.valueOf(p.getEndDate())); pstring.setLong(5, p.getOfficeVisitId()); pstring.setString(6, p.getInstructions()); pstring.setLong(7, p.getHcpMID()); pstring.setLong(8, p.getDosage()); pstring.setLong(9, p.getId()); return pstring; } /** * A utility method for creating a PreparedStatement for a remove operation * @param conn The connection to use * @param p The Prescription we're removing * @return The generated PreparedStatement * @throws SQLException */ private PreparedStatement createRemovePreparedStatement(Connection conn, long id) throws SQLException { PreparedStatement pstring = conn.prepareStatement("DELETE FROM prescription WHERE id=?"); pstring.setLong(1, id); return pstring; } /** * Gets all prescriptions associated with the given OfficeVisit ID * @param officeVisitId The ID of the OfficeVisit we should get Prescriptions for * @return A List<Prescription> of all Prescriptions associated with this * OfficeVisit ID * @throws SQLException */ public List<Prescription> getPrescriptionsForOfficeVisit(long officeVisitId) throws SQLException{ try (Connection conn = ds.getConnection(); PreparedStatement pstring = createOVPreparedStatement(conn, officeVisitId); ResultSet results = pstring.executeQuery()){ return loadRecords(results); } } /** * Gets the list of patient that the user represents * @param pid * id of a representer * @return all patients represented by the given representer * @throws SQLException */ public List<PatientBean> getListOfRepresentees(long pid) throws SQLException { try (Connection conn = ds.getConnection(); PreparedStatement pstring = createListOfRepsPreparedStatement(conn, pid); ResultSet rs = pstring.executeQuery()){ return new PatientLoader().loadList(rs); } } /** * Utility method to generate a prepared statement * in order to get the list of representees of a user * * @param conn Connection to use * @param mid mid of representer * @return Prepared statement for getting all representees of a representer * @throws SQLException */ private PreparedStatement createListOfRepsPreparedStatement(Connection conn, long mid) throws SQLException { PreparedStatement pstring = conn.prepareStatement("SELECT patients.* FROM representatives, " + "patients WHERE RepresenterMID=? AND RepresenteeMID=patients.MID"); pstring.setLong(1, mid); return pstring; } /** * Gets a codes actual name * * @param code id to search and get name for * @return string representation of the code * @throws SQLException */ public String getCodeName(String code) throws SQLException { try (Connection conn = ds.getConnection(); PreparedStatement pstring = createGetCodeNamePreparedStatement(conn, code); ResultSet rs = pstring.executeQuery()){ if (!rs.next()) return ""; return rs.getString("Description"); } } /** * A utility method for creating a PreparedStatement for * getting a codes actual name * * @param conn The Connection to use * @param mid The code's unique code to search for * * @return A string representation of the code * @throws SQLException */ private PreparedStatement createGetCodeNamePreparedStatement(Connection conn, String code) throws SQLException { PreparedStatement pstring = conn.prepareStatement("SELECT a.Description FROM ndcodes a JOIN prescription On a.code=?"); pstring.setString(1, code); return pstring; } /** * A utility method that loads all Prescriptions from a ResultSet into a * List<Prescription> and returns it. * @param rs The ResultSet to load * @return A List of all Prescriptions in the ResultSet * @throws SQLException */ public List<Prescription> loadRecords(ResultSet rs) throws SQLException{ List<Prescription> prescriptions = new ArrayList<>(); while (rs.next()){ Prescription newP = new Prescription(); newP.setDrugCode(new MedicationBean(rs.getString("code"), rs.getString("description"))); newP.setEndDate(rs.getDate("endDate").toLocalDate()); newP.setStartDate(rs.getDate("startDate").toLocalDate()); newP.setOfficeVisitId(rs.getLong("officeVisitId")); newP.setPatientMID(rs.getLong("patientMID")); newP.setId(rs.getLong("id")); newP.setInstructions(rs.getString("instructions")); newP.setDosage(rs.getLong("dosage")); newP.setHcpMID(rs.getLong("hcpMID")); prescriptions.add(newP); } return prescriptions; } /** * A utility method for creating a PreparedStatement for an EmergencyRecord * operation. * * @param conn The Connection to use * @param mid The MID of the patient we need the records for * @param endDate All prescriptions for this patient that end after this * date will be returned. * @return A List<Prescription> containing all appropriate Prescriptions for * the EmergencyRecord * @throws SQLException */ private PreparedStatement createERPreparedStatement(Connection conn, long mid, LocalDate endDate) throws SQLException{ PreparedStatement pstring = conn.prepareStatement("SELECT * FROM prescription, ndcodes WHERE drugCode = code AND patientMID=? AND endDate>=? ORDER BY endDate DESC"); pstring.setLong(1, mid); pstring.setDate(2, Date.valueOf(endDate)); return pstring; } /** * A utility method for creating a PreparedStatement for an add operation * @param conn The Connection to use * @param p The Prescription to add * @return The new PreparedStatement * @throws SQLException */ private PreparedStatement createAddPreparedStatement(Connection conn, Prescription p) throws SQLException{ PreparedStatement pstring = conn.prepareStatement("INSERT INTO prescription(patientMID, drugCode, startDate, endDate, officeVisitId, instructions, hcpMID, dosage) " + "VALUES(?, ?, ?, ?, ?, ?, ?, ?)"); pstring.setLong(1, p.getPatientMID()); pstring.setString(2, p.getCode()); pstring.setDate(3, Date.valueOf(p.getStartDate())); pstring.setDate(4, Date.valueOf(p.getEndDate())); pstring.setLong(5, p.getOfficeVisitId()); pstring.setString(6, p.getInstructions()); pstring.setLong(7, p.getHcpMID()); pstring.setLong(8, p.getDosage()); return pstring; } /** * A utility method for creating a PreparedStatement for getting all * Prescriptions for an office visit * @param conn The Connection to use * @param officeVisitId The ID of theOfficeVisit to get Prescriptions for * @return The new PreparedStatement * @throws SQLException */ private PreparedStatement createOVPreparedStatement(Connection conn, long officeVisitId) throws SQLException{ PreparedStatement pstring = conn.prepareStatement("SELECT * FROM prescription, ndcodes WHERE drugCode = code AND officeVisitId=?"); pstring.setLong(1, officeVisitId); return pstring; } /** * Construct a prepared statement to retrieve all prescriptions for a given MID. * * @param conn connection to use * @param patientMID patient's MID * @return PreparedStatement getting all patient's prescriptions * @throws SQLException */ private PreparedStatement createGetByMIDStatement(Connection conn, long patientMID) throws SQLException { PreparedStatement pstring = conn.prepareStatement("SELECT * FROM prescription, ndcodes WHERE drugCode = code AND patientMID=? ORDER BY startDate DESC"); pstring.setLong(1, patientMID); return pstring; } /** * Construct a prepared statement to retrieve prescription for a given id. * * @param conn connection to use * @param id prescription id * @return PreparedStatement getting all patient's prescriptions * @throws SQLException */ private PreparedStatement createGetStatement(Connection conn, long id) throws SQLException { PreparedStatement pstring = conn.prepareStatement("SELECT * FROM prescription, ndcodes WHERE drugCode = code AND id=?"); pstring.setLong(1, id); return pstring; } }
14,711
38.023873
199
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/prescription/PrescriptionValidator.java
package edu.ncsu.csc.itrust.model.prescription; import org.apache.commons.lang3.StringUtils; import edu.ncsu.csc.itrust.exception.ErrorList; import edu.ncsu.csc.itrust.exception.FormValidationException; import edu.ncsu.csc.itrust.model.POJOValidator; import edu.ncsu.csc.itrust.model.ValidationFormat; public class PrescriptionValidator extends POJOValidator<Prescription> { @Override public void validate(Prescription obj) throws FormValidationException { ErrorList errorList = new ErrorList(); if (obj.getDrugCode() == null) { errorList.addIfNotNull("Drug code cannot be empty"); } else { errorList.addIfNotNull(checkFormat("Drug Code", obj.getDrugCode().getNDCode(), ValidationFormat.ND, true)); errorList.addIfNotNull(checkFormat("Drug Code Description", obj.getDrugCode().getDescription(), ValidationFormat.ND_CODE_DESCRIPTION, true)); } if (StringUtils.isEmpty(obj.getInstructions())) { errorList.addIfNotNull("Instruction cannot be empty"); } if (obj.getDosage() <= 0) { errorList.addIfNotNull("Dosage cannot be 0 or negative"); } errorList.addIfNotNull(checkFormat("Special Instructions", obj.getInstructions(), ValidationFormat.ND_CODE_DESCRIPTION, true)); if (obj.getStartDate() == null) { errorList.addIfNotNull("Start date cannot be empty"); } else if (obj.getEndDate() == null) { errorList.addIfNotNull("End date cannot be empty"); } else if (obj.getStartDate().isAfter(obj.getEndDate())) { errorList.addIfNotNull("Start date must precede end date"); } if (errorList.hasErrors()) { throw new FormValidationException(errorList); } } }
1,629
34.434783
144
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/user/User.java
package edu.ncsu.csc.itrust.model.user; import java.io.Serializable; import edu.ncsu.csc.itrust.exception.ITrustException; import edu.ncsu.csc.itrust.model.old.enums.Role; public class User implements Serializable{ /** * */ private static final long serialVersionUID = -4883990864493568300L; private long MID; private String lastName; private String firstName; private Role role; public User(){ } public long getMID() { return MID; } public void setMID(long mid) throws ITrustException { if((mid >= 10000000000L) || (mid<=0L)){ throw new ITrustException("Invalid MID"); } else{ MID = mid; } } public Role getRole() { return role; } public void setRole(Role role) { this.role = role; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } }
996
18.94
68
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/user/UserMySQLConverter.java
package edu.ncsu.csc.itrust.model.user; import java.io.Serializable; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import javax.annotation.Resource; import javax.faces.bean.ManagedBean; import javax.faces.bean.RequestScoped; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.sql.DataSource; import edu.ncsu.csc.itrust.DBUtil; import edu.ncsu.csc.itrust.exception.DBException; import edu.ncsu.csc.itrust.model.DataBean; import edu.ncsu.csc.itrust.model.SQLLoader; import edu.ncsu.csc.itrust.model.old.dao.DAOFactory; import edu.ncsu.csc.itrust.model.old.enums.Role; @ManagedBean @RequestScoped public class UserMySQLConverter implements DataBean<User>, Serializable{ /** * */ private static final long serialVersionUID = -8056934124263634466L; @Resource(name="jdbc/itrust") private static DAOFactory factory; private SQLLoader<User> loader; private DataSource ds; //private transient final ProductionConnectionDriver driver = new ProductionConnectionDriver(); /** * @throws DBException */ public UserMySQLConverter() throws DBException{ loader = new UserSQLConvLoader(); try { Context ctx = new InitialContext(); ds = ((DataSource) (((Context) ctx.lookup("java:comp/env"))).lookup("jdbc/itrust")); } catch (NamingException e) { throw new DBException(new SQLException("Context Lookup Naming Exception: "+e.getMessage())); } } /**Constructor used for unit testing * @param ds * @throws DBException */ public UserMySQLConverter(DataSource ds) throws DBException{ this.ds = ds; loader = new UserSQLConvLoader(); } @Override public List<User> getAll() throws DBException { List<User> list = new ArrayList<User>(); Connection conn = null; PreparedStatement pstring = null; ResultSet results = null; try { conn = ds.getConnection(); pstring = conn.prepareStatement("SELECT * FROM users"); results = pstring.executeQuery(); list = loader.loadList(results); return list; } catch (SQLException e) { throw new DBException(e); } finally { try{ if(results !=null){ results.close(); } } catch (SQLException e) { throw new DBException(e); } finally { DBUtil.closeConnection(conn, pstring); } } } @Override public User getByID(long id) throws DBException { User ret = null; Connection conn = null; PreparedStatement pstring = null; ResultSet results = null; String stmt = ""; Role userRole = getUserRole(id); switch (userRole) { case HCP: case PHA: case ADMIN: case UAP: case ER: case LT: stmt = "SELECT users.MID AS MID, users.Role AS Role, personnel.firstName AS firstName, personnel.lastName AS lastName FROM users INNER JOIN personnel ON users.MID = personnel.MID WHERE users.MID=?;"; break; //ToDo: add back in when needed case PATIENT: stmt = "SELECT users.MID AS MID, users.Role AS Role, patients.firstName AS firstName, patients.lastName AS lastName FROM users INNER JOIN patients ON users.MID = patients.MID WHERE users.MID=?;"; // throw new IllegalStateException("unimplemented"); break; case TESTER: stmt = "SELECT MID AS MID, Role, '' AS firstName, MID AS lastName from Users WHERE MID=?;"; break; default: throw new DBException(new SQLException("Role " + userRole + " not supported")); } try { List<User> list = null; conn=ds.getConnection(); pstring = conn.prepareStatement(stmt); pstring.setString(1, Long.toString(id)); results = pstring.executeQuery(); list = loader.loadList(results); if(!list.isEmpty()){ ret = list.get(0); } return ret; } catch (SQLException e) { throw new DBException(e); } finally { try{ if(results !=null){ results.close(); } } catch (SQLException e) { throw new DBException(e); } finally { DBUtil.closeConnection(conn, pstring); } } } @Override public boolean add(User addObj) throws DBException { throw new IllegalStateException("unimplemented"); // TODO implement as needed } @Override public boolean update(User updateObj) throws DBException { // TODO Implement as needed throw new IllegalStateException("unimplemented"); } private Role getUserRole(long mid) throws DBException{ Role userRole = null; Connection conn = null; PreparedStatement pstring = null; ResultSet results = null; try { conn=ds.getConnection(); pstring = conn.prepareStatement("SELECT Role FROM users WHERE MID = ?;"); pstring.setString(1, Long.toString(mid)); results = pstring.executeQuery(); results.next(); String roleName = results.getString("Role"); userRole = Role.parse(roleName); return userRole; } catch (SQLException e) { throw new DBException(e); } finally{ try{ if(results != null){ results.close(); } } catch (SQLException e) { throw new DBException(e); } finally{ DBUtil.closeConnection(conn, pstring); } } } }
5,115
24.452736
202
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/user/UserSQLConvLoader.java
package edu.ncsu.csc.itrust.model.user; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import edu.ncsu.csc.itrust.exception.ITrustException; import edu.ncsu.csc.itrust.model.SQLLoader; import edu.ncsu.csc.itrust.model.old.enums.Role; public class UserSQLConvLoader implements SQLLoader<User> { @Override public List<User> loadList(ResultSet rs) throws SQLException { List<User> list = new ArrayList<User>(); while (rs.next()) list.add(loadSingle(rs)); return list; } @Override public User loadSingle(ResultSet rs) throws SQLException { User ret = new User(); long mid = rs.getLong("MID"); String roleName = rs.getString("Role"); Role userRole = Role.parse(roleName); String fn = rs.getString("firstName"); String ln = rs.getString("lastName"); //Tester was originally nameless so we'll leave him/her that way if(!(userRole.equals(Role.TESTER))){ ret.setFirstName(fn); ret.setLastName(ln); } ret.setRole(userRole); try { ret.setMID(mid); } catch (ITrustException e) { throw new SQLException("Incorrect value for MID stored in MySQL database"); } return ret; } @Override public PreparedStatement loadParameters(Connection conn, PreparedStatement ps, User insertObject, boolean newInstance) throws SQLException { return null; } }
1,429
24.535714
98
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/user/patient/Patient.java
package edu.ncsu.csc.itrust.model.user.patient; import java.io.Serializable; import edu.ncsu.csc.itrust.model.user.User; /** * Empty class for future use * Needed Patient Data Access/Controllers but * Did not need any information generally available * outside the information available in the user class * */ public class Patient extends User implements Serializable{ /** * */ private static final long serialVersionUID = 1509544768333457536L; // add data when appropriate }
492
21.409091
67
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/user/patient/PatientMySQLConverter.java
package edu.ncsu.csc.itrust.model.user.patient; import java.io.Serializable; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import javax.annotation.Resource; import javax.faces.bean.ManagedBean; import javax.faces.bean.RequestScoped; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.sql.DataSource; import edu.ncsu.csc.itrust.DBUtil; import edu.ncsu.csc.itrust.exception.DBException; import edu.ncsu.csc.itrust.model.DataBean; import edu.ncsu.csc.itrust.model.SQLLoader; import edu.ncsu.csc.itrust.model.old.dao.DAOFactory; @ManagedBean @RequestScoped public class PatientMySQLConverter implements DataBean<Patient>, Serializable{ /** * */ private static final long serialVersionUID = -8056934124263634466L; @Resource(name="jdbc/itrust") private static DAOFactory factory; private SQLLoader<Patient> loader; private DataSource ds; //private transient final ProductionConnectionDriver driver = new ProductionConnectionDriver(); /** * @throws DBException */ public PatientMySQLConverter() throws DBException{ loader = new PatientSQLConvLoader(); try { Context ctx = new InitialContext(); ds = ((DataSource) (((Context) ctx.lookup("java:comp/env"))).lookup("jdbc/itrust")); } catch (NamingException e) { throw new DBException(new SQLException("Context Lookup Naming Exception: "+e.getMessage())); } } /**Constructor used for unit testing * @param ds * @throws DBException */ public PatientMySQLConverter(DataSource ds) throws DBException{ this.ds = ds; loader = new PatientSQLConvLoader(); } @Override public List<Patient> getAll() throws DBException { List<Patient> list = new ArrayList<Patient>(); Connection conn = null; PreparedStatement pstring = null; ResultSet results = null; try { conn = ds.getConnection(); pstring = conn.prepareStatement("SELECT users.MID AS MID, users.Role AS Role, patients.firstName AS firstName, patients.lastName AS lastName FROM users INNER JOIN patients ON users.MID = patients.MID"); results = pstring.executeQuery(); list = loader.loadList(results); return list; } catch (SQLException e) { throw new DBException(e); } finally { try{ if(results !=null){ results.close(); } } catch (SQLException e) { throw new DBException(e); } finally { DBUtil.closeConnection(conn, pstring); } } } @Override public Patient getByID(long id) throws DBException { Patient ret = null; Connection conn = null; PreparedStatement pstring = null; ResultSet results = null; String stmt = ""; stmt = "SELECT users.MID AS MID, users.Role AS Role, patients.firstName AS firstName, patients.lastName AS lastName FROM users INNER JOIN patients ON users.MID = patients.MID WHERE users.MID=?;"; try { List<Patient> list = null; conn=ds.getConnection(); pstring = conn.prepareStatement(stmt); pstring.setString(1, Long.toString(id)); results = pstring.executeQuery(); list = loader.loadList(results); if(!list.isEmpty()){ ret = list.get(0); } return ret; } catch (SQLException e) { throw new DBException(e); } finally { try{ if(results !=null){ results.close(); } } catch (SQLException e) { throw new DBException(e); } finally { DBUtil.closeConnection(conn, pstring); } } } @Override public boolean add(Patient addObj) throws DBException { throw new IllegalStateException("unimplemented"); // TODO implement as needed } @Override public boolean update(Patient updateObj) throws DBException { // TODO Implement as needed throw new IllegalStateException("unimplemented"); } }
3,821
25.358621
205
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/user/patient/PatientSQLConvLoader.java
package edu.ncsu.csc.itrust.model.user.patient; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import edu.ncsu.csc.itrust.exception.ITrustException; import edu.ncsu.csc.itrust.model.SQLLoader; import edu.ncsu.csc.itrust.model.old.enums.Role; public class PatientSQLConvLoader implements SQLLoader<Patient> { @Override public List<Patient> loadList(ResultSet rs) throws SQLException { List<Patient> list = new ArrayList<Patient>(); while (rs.next()) list.add(loadSingle(rs)); return list; } @Override public Patient loadSingle(ResultSet rs) throws SQLException { Patient ret = new Patient(); long mid = rs.getLong("MID"); String roleName = rs.getString("Role"); Role userRole = Role.parse(roleName); String fn = rs.getString("firstName"); String ln = rs.getString("lastName"); ret.setFirstName(fn); ret.setLastName(ln); ret.setRole(userRole); try { ret.setMID(mid); } catch (ITrustException e) { throw new SQLException("Incorrect value for MID stored in MySQL database"); } return ret; } @Override public PreparedStatement loadParameters(Connection conn, PreparedStatement ps, Patient insertObject, boolean newInstance) throws SQLException { return null; } }
1,352
24.528302
101
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/parser/ICDCodeParser.java
package edu.ncsu.csc.itrust.parser; import java.io.BufferedWriter; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Paths; import java.util.stream.Collectors; import edu.ncsu.csc.itrust.model.icdcode.ICDCode; public class ICDCodeParser { private static final int LIMIT = 1000; private static final int NAME_LENGTH = 30; private static final String INPUT_PATH = "src/main/edu/ncsu/csc/itrust/parser/cci_icd10cm_2017.csv"; private static final String OUTPUT_PATH = "sql/data/icdcode.sql"; private static ICDCode processLine(String[] tokens) { return new ICDCode(tokens[0], tokens[1].substring(0, Math.min(tokens[1].length(), NAME_LENGTH)), tokens[2].equals("1")); } private static String convertToSql(ICDCode code) { return String.format("('%s', '%s', %d)", code.getCode(), code.getName(), code.isChronic() ? 1 : 0); } public static void main(String[] args) throws Exception { try (BufferedWriter writer = Files.newBufferedWriter(Paths.get(OUTPUT_PATH))) { writer.write("INSERT INTO icdcode " + "(code, name, is_chronic) VALUES\n"); String valuesSql = Files.lines(Paths.get(INPUT_PATH), Charset.forName("Cp1252")).skip(1).limit(LIMIT) .map(line -> line.replaceAll("\"|'", "").split(",")).map(ICDCodeParser::processLine).map(ICDCodeParser::convertToSql) .collect(Collectors.joining(",\n")); writer.write(valuesSql); writer.write("\nON duplicate key update code=code;"); } } }
1,457
38.405405
122
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/parser/LOINCCodeParser.java
package edu.ncsu.csc.itrust.parser; import java.io.BufferedWriter; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Paths; import java.util.stream.Collectors; import org.apache.commons.lang.StringEscapeUtils; import edu.ncsu.csc.itrust.model.loinccode.LOINCCode; public class LOINCCodeParser { private static final int LIMIT = 1000; private static final String INPUT_PATH = "src/main/edu/ncsu/csc/itrust/parser/LOINC_subset.csv"; private static final String OUTPUT_PATH = "sql/data/loinc.sql"; private static LOINCCode processLine(String[] tokens) { return new LOINCCode(tokens[0], tokens[1], tokens[2], tokens[3], tokens[4], tokens[5], tokens[6]); } private static String convertToSql(LOINCCode code) { return String.format("('%s', '%s', '%s', '%s', '%s', '%s', '%s')", code.getCode(), StringEscapeUtils.escapeSql(code.getComponent()), code.getKindOfProperty(), code.getTimeAspect(), code.getSystem(), code.getScaleType(), code.getMethodType()); } public static void main(String[] args) throws Exception { try (BufferedWriter writer = Files.newBufferedWriter(Paths.get(OUTPUT_PATH))) { writer.write("INSERT INTO loincCode " + "(code, component, kind_of_property, time_aspect, system, scale_type, method_type) VALUES\n"); String valuesSql = Files.lines(Paths.get(INPUT_PATH), Charset.forName("Cp1252")).skip(1).limit(LIMIT) .map(line -> line.split(",")).map(LOINCCodeParser::processLine).map(LOINCCodeParser::convertToSql) .collect(Collectors.joining(",\n")); writer.write(valuesSql); writer.write("\nON duplicate key update code=code;"); } } }
1,637
39.95
104
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/parser/NDCCodeParser.java
package edu.ncsu.csc.itrust.parser; import java.io.BufferedWriter; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Paths; import java.util.stream.Collectors; import org.apache.commons.lang.StringEscapeUtils; import edu.ncsu.csc.itrust.model.ndcode.NDCCode; public class NDCCodeParser { private static final int LIMIT = 1000; private static final int DESCRIPTION_LIMIT = 100; private static final String INPUT_PATH = "src/main/edu/ncsu/csc/itrust/parser/package.csv"; private static final String OUTPUT_PATH = "sql/data/ndcodes1000.sql"; private static NDCCode processLine(String[] tokens) { String description = StringEscapeUtils.escapeSql(tokens[3]); return new NDCCode(tokens[1], description.substring(0, Math.min(description.length(), DESCRIPTION_LIMIT))); } private static String convertToSql(NDCCode code) { return String.format("('%s', '%s')", code.getCode(), code.getDescription()); } public static void main(String[] args) throws Exception { try (BufferedWriter writer = Files.newBufferedWriter(Paths.get(OUTPUT_PATH))) { writer.write("INSERT INTO ndcodes " + "(code, description) VALUES\n"); String valuesSql = Files.lines(Paths.get(INPUT_PATH), Charset.forName("Cp1252")).skip(1).limit(LIMIT) .map(line -> line.split("\t")).map(NDCCodeParser::processLine).map(NDCCodeParser::convertToSql) .collect(Collectors.joining(",\n")); writer.write(valuesSql); writer.write("\nON duplicate key update code=code;"); } } }
1,509
36.75
109
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/report/DemographicReportFilter.java
package edu.ncsu.csc.itrust.report; import java.util.ArrayList; import java.util.List; import edu.ncsu.csc.itrust.model.old.beans.FamilyMemberBean; import edu.ncsu.csc.itrust.model.old.beans.PatientBean; import edu.ncsu.csc.itrust.model.old.dao.DAOFactory; import edu.ncsu.csc.itrust.model.old.dao.mysql.FamilyDAO; /** * * */ public class DemographicReportFilter extends ReportFilter { /** * * */ public enum DemographicReportFilterType { MID("MID"), GENDER("GENDER"), LAST_NAME("LAST NAME"), FIRST_NAME("FIRST NAME"), CONTACT_EMAIL("CONTACT EMAIL"), STREET_ADDR("STREET ADDRESS"), CITY("CITY"), STATE("STATE"), ZIP("ZIPCODE"), PHONE("PHONE #"), EMER_CONTACT_NAME("EMERGENCY CONTACT NAME"), EMER_CONTACT_PHONE("EMERGENCY CONTACT PHONE #"), INSURE_NAME("INSURANCE COMPANY NAME"), INSURE_ADDR("INSURANCE COMPANY ADDRESS"), INSURE_CITY("INSURANCE COMPANY CITY"), INSURE_STATE("INSURANCE COMPANY STATE"), INSURE_ZIP("INSURANCE COMPANY ZIPCODE"), INSURE_PHONE("INSURANCE COMPANY PHONE #"), INSURE_ID("INSURANCE COMPANY ID"), PARENT_FIRST_NAME("PARENT'S FIRST NAME"), PARENT_LAST_NAME("PARENT'S LAST NAME"), CHILD_FIRST_NAME("CHILD'S FIRST NAME"), CHILD_LAST_NAME("CHILD'S LAST NAME"), SIBLING_FIRST_NAME("SIBLING'S FIRST NAME"), SIBLING_LAST_NAME("SIBLING'S LAST NAME"), LOWER_AGE_LIMIT("LOWER AGE LIMIT"), UPPER_AGE_LIMIT("UPPER AGE LIMIT"), DEACTIVATED("DEACTIVATED"); private final String name; /** * * @param name */ private DemographicReportFilterType(String name) { this.name = name; } /** * */ @Override public String toString() { return this.name; } } private DemographicReportFilterType filterType; private String filterValue; private FamilyDAO fDAO; /** * * @param filterType * @param filterValue */ public DemographicReportFilter(DemographicReportFilterType filterType, String filterValue, DAOFactory factory) { this.filterType = filterType; this.filterValue = filterValue; fDAO = factory.getFamilyDAO(); } /** * * @param name * @return */ public static DemographicReportFilterType filterTypeFromString(String name) { for (DemographicReportFilterType type : DemographicReportFilterType.values()) { if (type.name().equalsIgnoreCase(name)) { return type; } } return null; } /** * */ @Override public List<PatientBean> filter(List<PatientBean> patients) { List<PatientBean> prunedList = new ArrayList<PatientBean>(); boolean add = filterValue != null && !filterValue.isEmpty(); if (add) { for (PatientBean patient : patients) { add = false; switch (filterType) { case MID: add = filterValue.equalsIgnoreCase(Long.toString(patient.getMID())); break; case GENDER: add = filterValue.equalsIgnoreCase(patient.getGender().toString()); break; case LAST_NAME: add = patient.getLastName().equalsIgnoreCase(filterValue); break; case FIRST_NAME: add = patient.getFirstName().equalsIgnoreCase(filterValue); break; case CONTACT_EMAIL: add = patient.getEmail().equalsIgnoreCase(filterValue); break; case STREET_ADDR: add = patient.getStreetAddress1().equalsIgnoreCase(filterValue) || patient.getStreetAddress2().equalsIgnoreCase(filterValue) || (patient.getStreetAddress1() + " " + patient.getStreetAddress2()) .equalsIgnoreCase(filterValue); break; case CITY: add = patient.getCity().equalsIgnoreCase(filterValue); break; case STATE: add = patient.getState().equalsIgnoreCase(filterValue); break; case ZIP: add = patient.getZip().contains(filterValue); break; case PHONE: add = patient.getPhone().equalsIgnoreCase(filterValue); break; case EMER_CONTACT_NAME: add = patient.getEmergencyName().equalsIgnoreCase(filterValue); break; case EMER_CONTACT_PHONE: add = patient.getEmergencyPhone().equalsIgnoreCase(filterValue); break; case INSURE_NAME: add = patient.getIcName().equalsIgnoreCase(filterValue); break; case INSURE_ADDR: add = patient.getIcAddress1().equalsIgnoreCase(filterValue) || patient.getIcAddress2().equalsIgnoreCase(filterValue) || (patient.getIcAddress1() + " " + patient.getIcAddress2()) .equalsIgnoreCase(filterValue); break; case INSURE_CITY: add = patient.getIcCity().equalsIgnoreCase(filterValue); break; case INSURE_STATE: add = patient.getIcState().equalsIgnoreCase(filterValue); break; case INSURE_ZIP: add = patient.getIcZip().equalsIgnoreCase(filterValue); break; case INSURE_PHONE: add = patient.getIcPhone().equalsIgnoreCase(filterValue); break; case INSURE_ID: add = patient.getIcID().equalsIgnoreCase(filterValue); break; case PARENT_FIRST_NAME: try { List<FamilyMemberBean> parents = fDAO.getParents(patient.getMID()); for (FamilyMemberBean parent : parents) { if (filterValue.equalsIgnoreCase(parent.getFirstName())) { add = true; break; } } } catch (Exception e) { break; } break; case PARENT_LAST_NAME: try { List<FamilyMemberBean> parents = fDAO.getParents(patient.getMID()); for (FamilyMemberBean parent : parents) { if (parent.getLastName().equals(filterValue)) { add = true; break; } } } catch (Exception e) { break; } break; case CHILD_FIRST_NAME: try { List<FamilyMemberBean> children = fDAO.getChildren(patient.getMID()); for (FamilyMemberBean child : children) { if (child.getFirstName().equals(filterValue)) { add = true; break; } } } catch (Exception e) { break; } break; case CHILD_LAST_NAME: try { List<FamilyMemberBean> children = fDAO.getChildren(patient.getMID()); for (FamilyMemberBean child : children) { if (child.getLastName().equals(filterValue)) { add = true; break; } } } catch (Exception e) { break; } break; case SIBLING_FIRST_NAME: try { List<FamilyMemberBean> siblings = fDAO.getSiblings(patient.getMID()); for (FamilyMemberBean sibling : siblings) { if (sibling.getFirstName().equals(filterValue)) { add = true; break; } } } catch (Exception e) { break; } break; case SIBLING_LAST_NAME: try { List<FamilyMemberBean> siblings = fDAO.getSiblings(patient.getMID()); for (FamilyMemberBean sibling : siblings) { if (sibling.getLastName().equals(filterValue)) { add = true; break; } } } catch (Exception e) { break; } break; case LOWER_AGE_LIMIT: int lalval = Integer.parseInt(filterValue); if(lalval<0){ throw new NumberFormatException("Age must be GTE 0!"); } add = lalval <= patient.getAge(); break; case UPPER_AGE_LIMIT: int ualval = Integer.parseInt(filterValue); if(ualval<0){ throw new NumberFormatException("Age must be GTE 0!"); } add = patient.getAge() > 0 && ualval >= patient.getAge(); break; case DEACTIVATED: if(filterValue.equals("exclude")){ add = patient.getDateOfDeactivationStr().equals(""); }else if(filterValue.equals("only")){ add = !patient.getDateOfDeactivationStr().equals(""); }else{ add=true; } break; default: break; } if (add) { prunedList.add(patient); } } } return prunedList; } /** * * @return */ public DemographicReportFilterType getFilterType() { return filterType; } /** * * @return */ @Override public String getFilterTypeString() { return filterType.toString(); } /** * * @return */ @Override public String getFilterValue() { return filterValue; } /** * */ @Override public String toString() { String out = "Filter by " + filterType.toString() + " with value " + filterValue; return out; } }
8,162
24.272446
91
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/report/MedicalReportFilter.java
package edu.ncsu.csc.itrust.report; import java.util.ArrayList; import java.util.List; import edu.ncsu.csc.itrust.model.old.beans.AllergyBean; import edu.ncsu.csc.itrust.model.old.beans.PatientBean; import edu.ncsu.csc.itrust.model.old.dao.DAOFactory; import edu.ncsu.csc.itrust.model.old.dao.mysql.AllergyDAO; /** * * */ public class MedicalReportFilter extends ReportFilter { /** * * */ public enum MedicalReportFilterType { PROCEDURE("PROCEDURE"), ALLERGY("ALLERGY"), CURRENT_PRESCRIPTIONS("CURRENT PRESCRIPTIONS"), PASTCURRENT_PRESCRIPTIONS("PAST AND CURRENT PRESCRIPTIONS"), DIAGNOSIS_ICD_CODE("DIAGNOSIS"), MISSING_DIAGNOSIS_ICD_CODE("MISSING DIAGNOSIS"), LOWER_OFFICE_VISIT_DATE("LOWER OFFICE VISIT DATE LIMIT"), UPPER_OFFICE_VISIT_DATE("UPPER OFFICE VISIT DATE LIMIT"); private final String name; /** * * @param name */ private MedicalReportFilterType(String name) { this.name = name; } /** * */ @Override public String toString() { return this.name; } } private MedicalReportFilterType filterType; private String filterValue; private AllergyDAO aDAO; /** * * @param filterType * @param filterValue */ public MedicalReportFilter(MedicalReportFilterType filterType, String filterValue, DAOFactory factory) { this.filterType = filterType; this.filterValue = filterValue; aDAO = factory.getAllergyDAO(); } /** * * @param name * @return */ public static MedicalReportFilterType filterTypeFromString(String name) { for(MedicalReportFilterType type : MedicalReportFilterType.values()) { if(type.name().equalsIgnoreCase(name)) { return type; } } return null; } /** * */ @Override public List<PatientBean> filter(List<PatientBean> patients) { List<PatientBean> prunedList = new ArrayList<PatientBean>(); boolean add = filterValue != null && !filterValue.isEmpty(); if (add) { for (PatientBean patient : patients) { add = false; switch (filterType) { case ALLERGY: try { List<AllergyBean> allergies = aDAO.getAllergies(patient.getMID()); for (AllergyBean allergy : allergies) { if (filterValue.equalsIgnoreCase(allergy.getNDCode())) { add = true; break; } } } catch (Exception e) { break; } break; default: break; } if(add) prunedList.add(patient); } } return prunedList; } /** * * @return */ public MedicalReportFilterType getFilterType() { return filterType; } /** * * @return */ @Override public String getFilterTypeString() { return filterType.toString(); } /** * * @return */ @Override public String getFilterValue() { return filterValue; } /** * */ @Override public String toString() { String out = "Filter by " + filterType.toString() + " with value " + filterValue; return out; } }
2,910
18.536913
105
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/report/PersonnelReportFilter.java
package edu.ncsu.csc.itrust.report; import java.util.ArrayList; import java.util.List; import edu.ncsu.csc.itrust.model.old.beans.PatientBean; import edu.ncsu.csc.itrust.model.old.beans.PersonnelBean; import edu.ncsu.csc.itrust.model.old.dao.DAOFactory; import edu.ncsu.csc.itrust.model.old.dao.mysql.PatientDAO; /** * * */ public class PersonnelReportFilter extends ReportFilter { /** * * */ public enum PersonnelReportFilterType { // MID, DLHCP("DECLARED HCP"); private final String name; /** * * @param name */ private PersonnelReportFilterType(String name) { this.name = name; } /** * */ @Override public String toString() { return this.name; } } private PersonnelReportFilterType filterType; private String filterValue; private PatientDAO pDAO; public PersonnelReportFilter(PersonnelReportFilterType filterType, String filterValue, DAOFactory factory) { this.filterType = filterType; this.filterValue = filterValue; pDAO = factory.getPatientDAO(); } /** * * @param name * @return */ public static PersonnelReportFilterType filterTypeFromString(String name) { for(PersonnelReportFilterType type : PersonnelReportFilterType.values()) { if(type.name().equalsIgnoreCase(name)) { return type; } } return null; } /** * */ @Override public List<PatientBean> filter(List<PatientBean> patients) { List<PatientBean> prunedList = new ArrayList<PatientBean>(); boolean add = filterValue != null && !filterValue.isEmpty(); if (add) { for (PatientBean patient : patients) { add = false; switch (filterType) { case DLHCP: try { List<PersonnelBean> dlhcps = pDAO.getDeclaredHCPs(patient.getMID()); for (PersonnelBean dlhcp : dlhcps) { if (filterValue.equalsIgnoreCase(dlhcp.getFullName())) { add = true; break; } } } catch (Exception e) { break; } break; default: break; } if (add) prunedList.add(patient); } } return prunedList; } /** * */ @Override public String toString() { String out = "Filter by " + filterType.toString() + " with value " + filterValue; return out; } /** * */ @Override public String getFilterValue() { return filterValue; } /** * * @return */ public PersonnelReportFilterType getFilterType() { return filterType; } /** * * @return */ @Override public String getFilterTypeString() { return filterType.toString(); } }
2,530
17.474453
109
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/report/ReportFilter.java
package edu.ncsu.csc.itrust.report; import java.util.List; import edu.ncsu.csc.itrust.model.old.beans.PatientBean; /** * * */ public abstract class ReportFilter { /** * * @param patients * @return */ public abstract List<PatientBean> filter(List<PatientBean> patients); /** * */ @Override public abstract String toString(); public abstract String getFilterTypeString(); public abstract String getFilterValue(); }
441
16
70
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/server/FindExpertServlet.java
package edu.ncsu.csc.itrust.server; import java.io.IOException; import java.io.PrintWriter; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import edu.ncsu.csc.itrust.action.SearchUsersAction; import edu.ncsu.csc.itrust.model.old.beans.PersonnelBean; import edu.ncsu.csc.itrust.model.old.dao.DAOFactory; /** * Servlet implementation class FindExpertServlet */ public class FindExpertServlet extends HttpServlet { private SearchUsersAction sua; private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public FindExpertServlet() { super(); //We never use the mid, so we don't need it. sua = new SearchUsersAction(DAOFactory.getProductionInstance(), -1); } protected FindExpertServlet(DAOFactory factory){ super(); sua = new SearchUsersAction(factory, -1); } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/plain"); String q = request.getParameter("query"); PrintWriter pw = response.getWriter(); List<PersonnelBean> exp = sua.fuzzySearchForExperts(q); StringBuffer resp = new StringBuffer("<table class=\"fTable\" width=\"80%\"><tr>" + "<th width=\"30%\">Name</th>" + "<th width=\"30%\">Specialty</th>" + "<th width=\"25%\">Reviews</th></tr>"); for(int i = 0; i < exp.size(); i++){ resp.append("<tr><td>"); resp.append(exp.get(i).getFirstName() + " " + exp.get(i).getLastName()); resp.append("</td><td>"); resp.append(exp.get(i).getSpecialty() == null ? "N/A" : exp.get(i).getSpecialty()); resp.append("</td><td>"); resp.append("<a href='reviewsPage.jsp?expertID=" + exp.get(i).getMID() + "'>View Reviews</a>"); resp.append("</td></tr>"); } resp.append("</table>"); pw.write(resp.toString()); pw.close(); } }
2,136
32.390625
118
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/server/GroupReportGeneratorServlet.java
package edu.ncsu.csc.itrust.server; import java.io.OutputStreamWriter; import java.io.Writer; import java.util.Calendar; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Document; import edu.ncsu.csc.itrust.XmlGenerator; import edu.ncsu.csc.itrust.action.GroupReportGeneratorAction; import edu.ncsu.csc.itrust.exception.DBException; import edu.ncsu.csc.itrust.model.old.dao.DAOFactory; /** * GroupReportGeneratorServlet is a generic servlet that serves a xml document * * */ public class GroupReportGeneratorServlet extends HttpServlet{ /** * GroupReportGeneratorAction to generate the report for download */ GroupReportGeneratorAction grga; /** * factor for the GroupReportGeneratorAction to use */ protected DAOFactory factory = DAOFactory.getProductionInstance(); /** * Document to be served to client */ Document doc; /** * Randomly generated servlet ID */ private static final long serialVersionUID = 4343961065799365553L; /** * doPost method that takes a user request and serves them a downloadable xml based on their defined search criteria. */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response){ try { grga = new GroupReportGeneratorAction(factory, request, 0l); } catch (DBException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try{ grga.generateReport(); doc = XmlGenerator.generateXml(grga.getReportHeaders(), grga.getReportData()); //Set the headers. response.setContentType("application/x-download"); response.setHeader("Content-Disposition", "attachment; filename=patientReport-" + Calendar.getInstance().getTimeInMillis() + ".xml"); DOMSource source = new DOMSource(doc); Transformer transformer = TransformerFactory.newInstance().newTransformer(); Writer writer = new OutputStreamWriter(response.getOutputStream(), "UTF-8"); StreamResult result = new StreamResult(writer); transformer.transform(source, result); }catch(Exception e){ System.out.println(e); } } }
2,328
30.053333
136
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/server/PatientSearchServlet.java
package edu.ncsu.csc.itrust.server; import java.io.IOException; import java.io.PrintWriter; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang.StringEscapeUtils; import edu.ncsu.csc.itrust.action.SearchUsersAction; import edu.ncsu.csc.itrust.model.old.beans.PatientBean; import edu.ncsu.csc.itrust.model.old.dao.DAOFactory; /** * Servlet implementation class PateintSearchServlet */ public class PatientSearchServlet extends HttpServlet { private static final long serialVersionUID = 1L; private SearchUsersAction sua; /** * @see HttpServlet#HttpServlet() */ public PatientSearchServlet() { super(); //We don't ever use the second parameter, so we don't need to give it meaning. sua = new SearchUsersAction(DAOFactory.getProductionInstance(), -1); } /** * @see HttpServlet#HttpServlet() */ protected PatientSearchServlet(DAOFactory factory) { super(); //We don't ever use the second parameter, so we don't need to give it meaning. sua = new SearchUsersAction(factory, -1); } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String query = request.getParameter("q"); if(query == null ){ return; } boolean isAudit = request.getParameter("isAudit") != null && request.getParameter("isAudit").equals("true"); boolean deactivated = request.getParameter("allowDeactivated") != null && request.getParameter("allowDeactivated").equals("checked"); String forward = request.getParameter("forward"); List<PatientBean> search = null; if(query.isEmpty() && deactivated){ search = sua.getDeactivated(); } else { search = sua.fuzzySearchForPatients(query, deactivated); } StringBuffer result = new StringBuffer("<span class=\"searchResults\">Found " + search.size() + " Records</span>"); if(isAudit){ result.append("<table class='fTable' width=80%><tr><th width=10%>MID</th><th width=20%>First Name</th><th width=20%>Last Name</th><th width=30%>Status</th><th width=20%>Action</th></tr>"); for(PatientBean p : search){ boolean isActivated = p.getDateOfDeactivationStr() == null || p.getDateOfDeactivationStr().isEmpty(); String change = isActivated ? "Deactivate" : "Activate"; result.append("<tr>"); result.append("<td>" + p.getMID() + "</td>"); result.append("<td>" + p.getFirstName() + "</td>"); result.append("<td>" + p.getLastName() + "</td>"); if(isActivated){ result.append("<td>" + p.getFirstName() + " " + p.getLastName() + " is activated.</td>"); } else { result.append("<td>" + p.getFirstName() + " " + p.getLastName() + " deactivated on: " + p.getDateOfDeactivationStr() + "</td>"); } result.append("<td>"); result.append("<input type='button' style='width:100px;' onclick=\"parent.location.href='getPatientID.jsp?UID_PATIENTID=" + StringEscapeUtils.escapeHtml("" + p.getMID()) + "&forward=" + StringEscapeUtils.escapeHtml("" + forward ) + "';\" value=" + StringEscapeUtils.escapeHtml("" + change) + " />"); result.append("</td></tr>"); } result.append("<table>"); } else { result.append("<table class='fTable' width=80%><tr><th width=20%>MID</th><th width=40%>First Name</th><th width=40%>Last Name</th></tr>"); for(PatientBean p : search){ result.append("<tr>"); result.append("<td>"); result.append("<input type='button' style='width:100px;' onclick=\"parent.location.href='getPatientID.jsp?UID_PATIENTID=" + StringEscapeUtils.escapeHtml("" + p.getMID()) + "&forward=" + StringEscapeUtils.escapeHtml("" + forward ) +"';\" value=" + StringEscapeUtils.escapeHtml("" + p.getMID()) + " />"); result.append("</td>"); result.append("<td>" + p.getFirstName() + "</td>"); result.append("<td>" + p.getLastName() + "</td>"); result.append("</tr>"); } result.append("</table>"); } response.setContentType("text/plain"); PrintWriter resp = response.getWriter(); resp.write(result.toString()); } }
4,294
42.383838
306
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/server/RecordsReleaseServlet.java
package edu.ncsu.csc.itrust.server; import javax.servlet.*; import javax.servlet.http.*; import edu.ncsu.csc.itrust.action.EventLoggingAction; import edu.ncsu.csc.itrust.action.RequestRecordsReleaseAction; import edu.ncsu.csc.itrust.model.old.beans.forms.RecordsReleaseForm; import edu.ncsu.csc.itrust.model.old.enums.TransactionType; import edu.ncsu.csc.itrust.exception.DBException; import java.io.*; public class RecordsReleaseServlet extends HttpServlet { private static final long serialVersionUID = 1L; private RecordsReleaseForm form; private RequestRecordsReleaseAction releaseAction; private EventLoggingAction loggingAction; private String loggedInName; private String currentMID; private String isRepresentee; private String releaseHospital; private String recFirstName; private String recLastName; private String recPhone; private String recEmail; private String recHospitalName; private String recHospitalAddress1; private String recHospitalAddress2; private String recHospitalCity; private String recHospitalState; private String recHospitalZip; private String releaseJustification; private boolean verifyForm; private String digitalSig; private String patMID; @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException{ try{ releaseAction = (RequestRecordsReleaseAction)request.getSession().getAttribute("releaseAction"); loggingAction = (EventLoggingAction)request.getSession().getAttribute("loggingAction"); loggedInName = (String)request.getSession().getAttribute("loggedInName"); currentMID = request.getParameter("currentMID"); isRepresentee = request.getParameter("isRepresentee"); releaseHospital = request.getParameter("releaseHospital"); recFirstName = request.getParameter("recFirstName"); recLastName = request.getParameter("recLastName"); recPhone = request.getParameter("recPhone"); recEmail = request.getParameter("recEmail"); recHospitalName = request.getParameter("recHospitalName"); recHospitalAddress1 = request.getParameter("recHospitalAddress1"); recHospitalAddress2 = request.getParameter("recHospitalAddress2"); recHospitalCity = request.getParameter("recHospitalCity"); recHospitalState = request.getParameter("recHospitalState"); recHospitalZip = request.getParameter("recHospitalZip"); releaseJustification = request.getParameter("releaseJustification"); verifyForm = Boolean.parseBoolean(request.getParameter("verifyForm")); digitalSig = request.getParameter("digitalSig"); patMID = (String)request.getSession().getAttribute("patMID"); } catch(NullPointerException e){ e.printStackTrace(); } Boolean checksum = false; try { checksum = checkCredentials(digitalSig); } catch (Exception e) { e.printStackTrace(); } try{ form = new RecordsReleaseForm(); form.setReleaseHospitalID(releaseHospital); form.setRecipientFirstName(recFirstName); form.setRecipientLastName(recLastName); form.setRecipientPhone(recPhone); form.setRecipientEmail(recEmail); form.setRecipientHospitalName(recHospitalName); form.setRecipientHospitalAddress(recHospitalAddress1 + recHospitalAddress2 + ", " + recHospitalCity + ", " + recHospitalState + " " + recHospitalZip); form.setRequestJustification(releaseJustification); form.setDigitalSignature(checksum); } catch(NullPointerException e){ e.printStackTrace(); } String message = ""; message = releaseAction.addRecordsRelease(form); if(!message.equals(RequestRecordsReleaseAction.SUCCESS_MESSAGE)){ request.setAttribute("failure", message); request.setAttribute("isRepresentee", isRepresentee); request.getRequestDispatcher("requestRecordsRelease.jsp").forward(request, response); return; } try { if(isRepresentee.equals("false")){ loggingAction.logEvent(TransactionType.PATIENT_RELEASE_HEALTH_RECORDS, Long.parseLong(patMID), Long.parseLong(currentMID), ""); } else if(isRepresentee.equals("true")){ loggingAction.logEvent(TransactionType.PATIENT_REQUEST_DEPEDENT_RECORDS, Long.parseLong(patMID), Long.parseLong(currentMID), ""); } } catch (DBException e) { e.printStackTrace(); } request.setAttribute("currentMID", currentMID); request.setAttribute("status", "Pending"); request.setAttribute("releaseHospital", releaseHospital); request.setAttribute("recFirstName", recFirstName); request.setAttribute("recLastName", recLastName); request.setAttribute("recPhone", recPhone); request.setAttribute("recEmail", recEmail); request.setAttribute("recHospitalName", recHospitalName); request.setAttribute("recHospitalAddress", recHospitalAddress1 + recHospitalAddress2 + ", " + recHospitalCity + ", " + recHospitalState + " " + recHospitalZip); request.setAttribute("recHospitalAddress1", recHospitalAddress1); request.setAttribute("recHospitalAddress2", recHospitalAddress2); request.setAttribute("recHospitalCity", recHospitalCity); request.setAttribute("recHospitalState", recHospitalState); request.setAttribute("recHospitalZip", recHospitalZip); request.setAttribute("releaseJustification", releaseJustification); if(verifyForm){ request.setAttribute("fromServlet", "true"); request.getRequestDispatcher("confirmRecordsReleaseServlet.jsp").forward(request, response); } } private Boolean checkCredentials(String digitalSig) throws Exception{ if(digitalSig.equals(loggedInName)){ return true; } return false; } }
5,603
34.468354
162
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/server/SessionTimeoutListener.java
package edu.ncsu.csc.itrust.server; import javax.servlet.http.HttpSession; import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionListener; import edu.ncsu.csc.itrust.exception.DBException; import edu.ncsu.csc.itrust.logger.TransactionLogger; import edu.ncsu.csc.itrust.model.old.dao.DAOFactory; import edu.ncsu.csc.itrust.model.old.enums.TransactionType; /** * A listener which will time the user out after a pre-specified time limit. */ public class SessionTimeoutListener implements HttpSessionListener { private DAOFactory factory; /** * The default constructor. */ public SessionTimeoutListener() { this.factory = DAOFactory.getProductionInstance(); } /** * The specialized constructor, which takes a particular DAOFactory to be used when checking for the pre-specified * timeout limit. * @param factory The DAOFactory to be used. */ public SessionTimeoutListener(DAOFactory factory) { this.factory = factory; } /** * Called when the HttpSession is created, this method pulls the pre-specified limit from the * database and sets it as a property of the HttpSession. * @param arg0 The HttpSessionEven which just occurred. */ @Override public void sessionCreated(HttpSessionEvent arg0) { HttpSession session = arg0.getSession(); int mins = 20; try { mins = factory.getAccessDAO().getSessionTimeoutMins(); } catch (DBException e) { System.err.println("Unable to set session timeout, defaulting to 20 minutes"); } if (mins < 1) mins = 1; session.setMaxInactiveInterval(mins * 60); } /** * Must be declared for compliance with the interface. Not implemented. * @param arg0 arg0 */ @Override public void sessionDestroyed(HttpSessionEvent arg0) { // nothing to do here HttpSession session = arg0.getSession(); Long mid = (Long) session.getAttribute("loggedInMID"); if (mid != null) { TransactionLogger.getInstance().logTransaction(TransactionType.LOGOUT_INACTIVE, mid, null, ""); } } }
2,005
28.5
115
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/server/WardCRUDServlet.java
package edu.ncsu.csc.itrust.server; import java.io.IOException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import edu.ncsu.csc.itrust.model.old.beans.WardBean; import edu.ncsu.csc.itrust.model.old.dao.DAOFactory; import edu.ncsu.csc.itrust.model.old.dao.mysql.WardDAO; public class WardCRUDServlet extends HttpServlet { /** * */ private static final long serialVersionUID = 1L; /** * WardDao for doing DAO Operations */ protected WardDAO wardDAO = new WardDAO(DAOFactory.getProductionInstance()); @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException{ try{ String reqSpecialty = request.getParameter("requiredSpecialty"); long inHospital = Long.parseLong(request.getParameter("inHospital")); WardBean ward = new WardBean(0, reqSpecialty, inHospital); wardDAO.addWard(ward); } catch(RuntimeException e){ //Send error parameter back to page response.sendRedirect(""); return; } catch(Exception e){ //Send error parameter back to page response.sendRedirect(""); return; } //Redirect back to page response.sendRedirect(""); } @Override protected void doPut(HttpServletRequest request, HttpServletResponse response) throws IOException{ try{ long wardID = Long.parseLong(request.getParameter("wardID")); String reqSpecialty = request.getParameter("requiredSpecialty"); long inHospital = Long.parseLong(request.getParameter("inHospital")); WardBean ward = new WardBean(wardID, reqSpecialty, inHospital); wardDAO.updateWard(ward); } catch(RuntimeException e){ //Send error parameter back to page response.sendRedirect(""); return; } catch(Exception e){ //Send error parameter back to page response.sendRedirect(""); return; } //Redirect back to page response.sendRedirect(""); } @Override protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws IOException{ try{ wardDAO.removeWard(Long.parseLong(request.getParameter("wardID"))); } catch(Exception e){ //Send error parameter back to page response.sendRedirect(""); return; } //Redirect back to page response.sendRedirect(""); } }
2,306
26.795181
102
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/server/WardRoomCRUDServlet.java
package edu.ncsu.csc.itrust.server; import java.io.IOException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import edu.ncsu.csc.itrust.model.old.beans.WardRoomBean; import edu.ncsu.csc.itrust.model.old.dao.DAOFactory; import edu.ncsu.csc.itrust.model.old.dao.mysql.WardDAO; public class WardRoomCRUDServlet extends HttpServlet { /** * */ private static final long serialVersionUID = 1L; /** * WardDao for doing DAO Operations */ protected WardDAO wardDAO = new WardDAO(DAOFactory.getProductionInstance()); @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException{ try{ long inWard = Long.parseLong(request.getParameter("inWard")); String roomName = request.getParameter("roomName"); String status = request.getParameter("status"); WardRoomBean wardRoom = new WardRoomBean(0, 0, inWard, roomName, status); wardDAO.addWardRoom(wardRoom); } catch (RuntimeException e){ //Send error parameter back to page response.sendRedirect(""); return; } catch(Exception e){ //Send error parameter back to page response.sendRedirect(""); return; } //Redirect back to page response.sendRedirect(""); } @Override protected void doPut(HttpServletRequest request, HttpServletResponse response) throws IOException{ try{ long occupiedBy = Long.parseLong(request.getParameter("occupiedBy")); long inWard = Long.parseLong(request.getParameter("inWard")); String roomName = request.getParameter("roomName"); String status = request.getParameter("status"); WardRoomBean wardRoom = new WardRoomBean(0, occupiedBy, inWard, roomName, status); wardDAO.updateWardRoom(wardRoom); } catch(Exception e){ //Send error parameter back to page response.sendRedirect(""); return; } //Redirect back to page response.sendRedirect(""); } @Override protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws IOException{ try{ wardDAO.removeWardRoom(Long.parseLong(request.getParameter("roomID"))); } catch(Exception e){ //Send error parameter back to page response.sendRedirect(""); return; } //Redirect back to page response.sendRedirect(""); } }
2,328
27.402439
102
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/tags/PatientNavigation.java
package edu.ncsu.csc.itrust.tags; import java.io.IOException; import javax.servlet.jsp.JspException; import javax.servlet.jsp.JspWriter; import javax.servlet.jsp.PageContext; import javax.servlet.jsp.tagext.Tag; /** * JSP tag that is used as the patient navigation bar at the bottom of the screen. * * To add a new page, add to the two arrays, and make sure that the page accepts PID */ public class PatientNavigation implements Tag { private PageContext pageContext; private Tag parent; // A more elegant solution here would be to use enums and have a displayName, a name, and url private String pageTitles[] = { "Demographics", "Office Visit"}; private String pageURLs[] = { "editPatient.jsp","viewOfficeVisit.xhtml"}; private String thisTitle; /** * PatientNavigation */ public PatientNavigation() { } /** * doStartTag * @throws JspException */ @Override public int doStartTag() throws JspException { try { JspWriter out = pageContext.getOut(); out.write("<center><span class=\"patient-navigation\">"); for (int i = 0; i < pageTitles.length; i++) { if (pageTitles[i].equals(thisTitle)) { out.write("<span class=\"patient-nav-selected\">" + pageTitles[i] + "</span>"); } else out.write("<a href=\"/iTrust/auth/hcp-uap/" + pageURLs[i] + "\">" + pageTitles[i] + "</a>"); } out.write("<br /></span></center>"); } catch (IOException e) { //TODO } return SKIP_BODY; } /** * doEndTag * @throws JspException */ @Override public int doEndTag() throws JspException { return SKIP_BODY; } /** * release */ @Override public void release() { } /** * setPageContext * @param pageContext pageContext */ @Override public void setPageContext(PageContext pageContext) { this.pageContext = pageContext; } /** * setParent * @param parent parent */ @Override public void setParent(Tag parent) { this.parent = parent; } /** * getParent * @return parent */ @Override public Tag getParent() { return parent; } /** * getThisTitle * @return this title */ public String getThisTitle() { return thisTitle; } /** * setThisTitle * @param thisPage thisPage */ public void setThisTitle(String thisPage) { this.thisTitle = thisPage; } }
2,279
19.540541
94
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/tags/StateSelect.java
package edu.ncsu.csc.itrust.tags; import java.io.IOException; import javax.servlet.jsp.JspException; import javax.servlet.jsp.JspWriter; import javax.servlet.jsp.PageContext; import javax.servlet.jsp.tagext.Tag; import edu.ncsu.csc.itrust.model.old.enums.State; /** * JSP tag that adds an HTML select for states, from the enum. * * @see {@link State} * * Also selects the current state */ public class StateSelect implements Tag { private PageContext pageContext; private Tag parent; private String name; private String value; /** * StateSelect */ public StateSelect() { super(); } /** * doStarTag * @throws JspException */ @Override public int doStartTag() throws JspException { try { JspWriter out = pageContext.getOut(); out.write("<select name=\"" + getName() + "\" >"); if (name == null || "".equals(name)) out.write("<option value=\"\">Select State</option>"); for (State state : State.values()) { String selected = state.toString().equals(getValue()) ? "selected=selected" : ""; out.write("<option value=\"" + state.toString() + "\" " + selected + ">" + state.getName() + "</option>"); } out.write("</select>"); } catch (IOException e) { //TODO } return SKIP_BODY; } /** * doEndTag * @return SKIP_BODY * @throws JspException */ @Override public int doEndTag() throws JspException { return SKIP_BODY; } /** * release */ @Override public void release() { } /** * setPageContext * @param pageContext pageContext */ @Override public void setPageContext(PageContext pageContext) { this.pageContext = pageContext; } /** * setParent * @param parent parent */ @Override public void setParent(Tag parent) { this.parent = parent; } /** * getParent */ @Override public Tag getParent() { return parent; } /** * getName * @return */ public String getName() { return name; } /** * setName * @param name anem */ public void setName(String name) { this.name = name; } /** * getValue * @return value */ public String getValue() { return value; } /** * setValue * @param value value */ public void setValue(String value) { this.value = value; } }
2,228
16.27907
94
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/webutils/LocalDateConverter.java
package edu.ncsu.csc.itrust.webutils; import java.time.DateTimeException; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import javax.faces.application.FacesMessage; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.convert.Converter; import javax.faces.convert.ConverterException; import javax.faces.convert.FacesConverter; @FacesConverter("localDateConverter") public class LocalDateConverter implements Converter { @Override public Object getAsObject(FacesContext context, UIComponent component, String value) { if (value == null || value.isEmpty()) { return null; } try { return LocalDate.parse(value, DateTimeFormatter.ofPattern("M/d/yyyy")); } catch (IllegalArgumentException | DateTimeException e) { FacesMessage throwMsg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Invalid date format", "Date format must be M/d/yyyy"); throw new ConverterException(throwMsg); } } @Override public String getAsString(FacesContext context, UIComponent component, Object value) { if (value == null) { return ""; } if (!(value instanceof LocalDate)) { throw new ConverterException("Invalid LocalDate"); } return DateTimeFormatter.ofPattern("M/d/yyyy").format((LocalDate) value); } }
1,430
32.27907
134
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/webutils/LocalDateTimeConverter.java
package edu.ncsu.csc.itrust.webutils; import java.time.DateTimeException; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import javax.faces.application.FacesMessage; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.convert.Converter; import javax.faces.convert.ConverterException; import javax.faces.convert.FacesConverter; @FacesConverter("localDateTimeConverter") public class LocalDateTimeConverter implements Converter { @Override public Object getAsObject(FacesContext context, UIComponent component, String value) { if (value == null || value.isEmpty()) { return null; } try { return LocalDateTime.parse(value, DateTimeFormatter.ofPattern("M/d/yyyy h:mm a")); } catch (IllegalArgumentException | DateTimeException e) { FacesMessage throwMsg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Invalid date format", "Date format must be M/d/yyyy hh:mm AM/PM"); throw new ConverterException(throwMsg); } } @Override public String getAsString(FacesContext context, UIComponent component, Object value) { if (value == null) { return ""; } if (!(value instanceof LocalDateTime)) { throw new ConverterException("Message"); } return DateTimeFormatter.ofPattern("M/d/yyyy h:mm a").format((LocalDateTime) value); } }
1,470
33.209302
146
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/webutils/SessionUtils.java
package edu.ncsu.csc.itrust.webutils; import java.util.List; import javax.faces.application.FacesMessage; import javax.faces.application.FacesMessage.Severity; import javax.faces.context.FacesContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import edu.ncsu.csc.itrust.model.old.beans.PatientBean; /** * Singleton class containing session-related utility methods. * @author mwreesjo */ public class SessionUtils { /** * Name of representees */ private static final String REPRESENTEES = "representees"; /** * Name of patient role */ private static final String PATIENT = "patient"; /** * HttpSession variable name of the current logged in user role. */ private static final String USER_ROLE = "userRole"; /** * HttpSession variable name of the current logged in patient MID. */ private static final String LOGGED_IN_MID = "loggedInMID"; /** * HttpSession variable name of the HCP selected patient MID. */ private static final String PID = "pid"; /** * Get the current office visit id that the user (HCP) is viewing. */ private static final String OFFICE_VISIT_ID = "officeVisitId"; /** The singleton instance of this class. */ private static SessionUtils singleton = null; private SessionUtils() {} public void setSessionVariable(String varname, Object value){ HttpServletRequest req = getHttpServletRequest(); HttpSession httpSession = req.getSession(false); httpSession.setAttribute(varname, value); } /** * Uses FacesContext to seek a HttpSession variable of a string type within * the FaceContext. * * @param varname * variable name in the HTTP session * @return session variable of any type */ public Object getSessionVariable(String varname) { Object variable = null; HttpServletRequest req = getHttpServletRequest(); if (req == null) { return variable; } HttpSession httpSession = req.getSession(false); if (httpSession == null) { return variable; } variable = httpSession.getAttribute(varname); return variable; } /** * Returns the session variable in string form. * * @param variable * A session variable in Object form, could be of String type or * Long type * @return String representation of the session variable, or null if it is * neither String nor Long */ public String parseString(Object variable) { if (variable instanceof String) { return (String) variable; } else if (variable instanceof Long) { return parseLong(variable).toString(); } else { return null; } } /** * Returns the session variable in Long form. * * @param variable * A session variable in Object form, could be of String type or * Long type * @return Long representation of the session variable, or null if it is not Long */ public Long parseLong(Object variable) { if (variable instanceof Long) { return (Long) variable; } return null; } /** * @return role of the currently logged in user */ public String getSessionUserRole() { return parseString(getSessionVariable(USER_ROLE)); } /** * @return MID of the patient that the HCP selected in the session */ public String getSessionPID() { return parseString(getSessionVariable(PID)); } /** * @return current logged in patient's MID */ public String getSessionLoggedInMID() { return parseString(getSessionVariable(LOGGED_IN_MID)); } /** * @return current logged in patient's MID in Long form */ public Long getSessionLoggedInMIDLong() { Long mid = null; try { mid = Long.parseLong(getSessionLoggedInMID()); } catch(NumberFormatException e) { // Leave mid null } return mid; } /** * Checks whether if a patient is logged in, if so, retrieve this patient's * mid, otherwise, check whether if an HCP selected a patient in his/her * session. * * @return MID of patient, null if no patient is logged in or selected by * HCP */ public String getCurrentPatientMID() { String patientMID = getSessionPID(); String role = getSessionUserRole(); if (role != null && role.equals(PATIENT)) { patientMID = getSessionLoggedInMID(); } return patientMID; } public Long getCurrentPatientMIDLong() { Long mid = null; try { mid = Long.parseLong(getCurrentPatientMID()); } catch(NumberFormatException e) { // Leave mid null } return mid; } /** * @return office visit that the current logged in user (HCP) selected */ public Long getCurrentOfficeVisitId() { return parseLong(getSessionVariable(OFFICE_VISIT_ID)); } public List<PatientBean> getRepresenteeList() { return (List<PatientBean>) getSessionVariable(REPRESENTEES); } public void setRepresenteeList(List<PatientBean> list) { setSessionVariable(REPRESENTEES, list); } /** * Returns the value of a request parameter as a String, or null if the * parameter does not exist. * * @param name a String specifying the name of the parameter * @return a String representing the single value of the parameter */ public String getRequestParameter(String name) { HttpServletRequest req = getHttpServletRequest(); return (req == null) ? null : req.getParameter(name); } /** * @return HTTPRequest in FacesContext, null if no request is found */ private HttpServletRequest getHttpServletRequest() { FacesContext ctx = getCurrentFacesContext(); if (ctx == null) { return null; } return ctx.getExternalContext().getRequest() instanceof HttpServletRequest ? (HttpServletRequest) ctx.getExternalContext().getRequest() : null; } /** * Sends a FacesMessage for FacesContext to display. * * @param severity * severity of the message * @param summary * localized summary message text * @param detail * localized detail message text * @param clientId * The client identifier with which this message is associated * (if any) */ public void printFacesMessage(Severity severity, String summary, String detail, String clientId) { FacesContext ctx = getCurrentFacesContext(); if (ctx == null) { return; } ctx.getExternalContext().getFlash().setKeepMessages(true); ctx.addMessage(clientId, new FacesMessage(severity, summary, detail)); } /** * @return the current instance of FacesContext */ public FacesContext getCurrentFacesContext() { return FacesContext.getCurrentInstance(); } public static SessionUtils getInstance() { if (singleton == null) singleton = new SessionUtils(); return singleton; } }
6,635
24.621622
99
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/cucumber/AuthenticationStepDefs.java
package edu.ncsu.csc.itrust.cucumber; import cucumber.api.java.en.Given; import edu.ncsu.csc.itrust.exception.DBException; import edu.ncsu.csc.itrust.model.old.dao.mysql.AuthDAO; import edu.ncsu.csc.itrust.unit.testutils.TestDAOFactory; import org.junit.Assert; public class AuthenticationStepDefs { private UserDataShared data; public AuthenticationStepDefs(UserDataShared MIDs){ this.data = MIDs; } @Given("^I login as (.*) using (.*)$") public void login_With_MID(String MID, String pwd){ long mid; try{ mid = Long.parseLong(MID); AuthDAO login = new AuthDAO(TestDAOFactory.getTestInstance()); try { if(login.authenticatePassword(mid, pwd)){ data.loginID= mid; } } catch (DBException e) { // TODO Auto-generated catch block Assert.fail("Unable to authenticate Password"); } } catch(NumberFormatException ne){ Assert.fail("Could not parse MID"); } } }
924
22.125
65
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/cucumber/BasicHealthInfoStepDefs.java
package edu.ncsu.csc.itrust.cucumber; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.fail; import java.time.Instant; import java.time.LocalDateTime; import java.time.ZoneOffset; import java.util.Date; import org.junit.Assert; import cucumber.api.java.en.Given; import cucumber.api.java.en.Then; import cucumber.api.java.en.When; import edu.ncsu.csc.itrust.cucumber.util.SharedOfficeVisit; import edu.ncsu.csc.itrust.cucumber.util.SharedPatient; import edu.ncsu.csc.itrust.cucumber.util.SharedPersonnel; import edu.ncsu.csc.itrust.model.officeVisit.OfficeVisit; import edu.ncsu.csc.itrust.model.old.beans.PatientBean; import edu.ncsu.csc.itrust.model.old.beans.PersonnelBean; import edu.ncsu.csc.itrust.model.old.enums.Role; public class BasicHealthInfoStepDefs { private SharedPersonnel sharedPersonnel; private SharedPatient sharedPatient; private SharedOfficeVisit sharedOfficeVisit; public BasicHealthInfoStepDefs(SharedPersonnel sharedPersonnel, SharedPatient sharedPatient, SharedOfficeVisit sharedOfficeVisit) throws Exception { this.sharedPersonnel = sharedPersonnel; this.sharedPatient = sharedPatient; this.sharedOfficeVisit = sharedOfficeVisit; } @Given("^(?:.*) is an HCP with MID: (\\d+)$") public void hcp_is_an_HCP_with_MID(long MID) throws Throwable { PersonnelBean p = sharedPersonnel.getPersonnelDAO().getPersonnel(MID); assertNotNull(String.format("Personnel with MID: %d doesn't exist", MID), p); assertEquals(Role.HCP, p.getRole()); } @Given("^(?:.*) is a patient with MID (\\d+) who is born on (\\S+)$") public void patient_is_a_patient_with_MID_who_is_months_old(long MID, Date birthday) throws Throwable { PatientBean p = sharedPatient.getPatientDAO().getPatient(MID); assertNotNull(String.format("Patient with MID: %d doesn't exist", MID), p); assertEquals("Patient birthday doesn't match", p.getDateOfBirth(), birthday); } @When("^(?:.*) logs in with MID: (\\d+)") public void hcp_logs_in(Long MID) throws Throwable { PersonnelBean p = sharedPersonnel.getPersonnelDAO().getPersonnel(MID); sharedPersonnel.setPersonnel(p); } @When("^Chooses to document an office visit$") public void chooses_to_document_an_office_visit() throws Throwable { sharedOfficeVisit.setOfficeVisit(new OfficeVisit()); } @When("^selects patient (?:.*) with MID (\\d+)$") public void selects_patient_Brynn_McClain_with_MID(long MID) throws Throwable { sharedOfficeVisit.getOfficeVisit().setPatientMID(MID); } @When("^Choose appointment type (?:.*) with id: (\\d+)$") public void choose_appointment_type_General_checkup(long apptID) throws Throwable { sharedOfficeVisit.getOfficeVisit().setApptTypeID(apptID); } @When("^Chooses the date to be (\\S+)$") public void chooses_the_date_to_be(Date date) throws Throwable { sharedOfficeVisit.getOfficeVisit() .setDate(LocalDateTime.ofInstant(Instant.ofEpochMilli(date.getTime()), ZoneOffset.UTC)); } @When("^Select (?:.*) with id: (\\w+) for location$") public void select_Central_Hospital_for_location(String locationId) throws Throwable { sharedOfficeVisit.getOfficeVisit().setLocationID(locationId); } @When("^enters Note “(.+)”$") public void enters_Notes_Brynn_can_start_eating_rice_cereal_mixed_with_breast_milk_or_formula_once_a_day( String notes) throws Throwable { sharedOfficeVisit.getOfficeVisit().setNotes(notes); } @When("^Enters (\\S+) for weight$") public void enters_for_weight(String weightStr) throws Throwable { Float weight = null; try { weight = Float.parseFloat(weightStr); } catch (NumberFormatException e) { fail("Invalid floating point number format"); } sharedOfficeVisit.getOfficeVisit().setWeight(weight); } @When("^Enters (\\S+) for length$") public void enters_for_length(String lengthStr) throws Throwable { Float length = null; try { length = Float.parseFloat(lengthStr); sharedOfficeVisit.getOfficeVisit().setLength(length); } catch (NumberFormatException e) { sharedOfficeVisit.setHasError(true); } } @When("^Enters (\\S+) for Head Circumference$") public void enters_for_Head_Circumference(String headCircumferenceString) throws Throwable { Float headCircumference = null; try { headCircumference = Float.parseFloat(headCircumferenceString); } catch (NumberFormatException e) { fail("Invalid floating point number format"); } sharedOfficeVisit.getOfficeVisit().setHeadCircumference(headCircumference); } @When("^submits record$") public void submits_record() throws Throwable { sharedOfficeVisit.add(); } @Then("^The record is saved successfully$") public void a_success_message_is_displayed() throws Throwable { Assert.assertTrue(sharedOfficeVisit.wasAddSuccessful() && !sharedOfficeVisit.hasError()); } @When("^Enters (\\S+) for height$") public void enters_for_height(String heightStr) throws Throwable { Float height = Float.parseFloat(heightStr); sharedOfficeVisit.getOfficeVisit().setHeight(height); } @When("^selects (\\d+) for (?:.*) for household smoking status$") public void selects_for_indoors_smokers_for_household_smoking_status(int smokingStatus) throws Throwable { sharedOfficeVisit.getOfficeVisit().setHouseholdSmokingStatus(smokingStatus); } @When("^Enters (\\S+) for blood pressure$") public void enters_for_blood_pressure(String bloodPressure) throws Throwable { sharedOfficeVisit.getOfficeVisit().setBloodPressure(bloodPressure); } @When("^selects (\\d+) for (?:.*) for patient smoking status$") public void selects_for_former_smoker_for_patient_smoking_status(int smokingStatus) throws Throwable { sharedOfficeVisit.getOfficeVisit().setPatientSmokingStatus(smokingStatus); } @When("^enters (\\w+) for HDL$") public void enters_for_HDL(String hdlStr) throws Throwable { Integer hdl; try { hdl = Integer.parseInt(hdlStr); sharedOfficeVisit.getOfficeVisit().setHDL(hdl); } catch (NumberFormatException e) { sharedOfficeVisit.setHasError(true); } } @When("^enters (\\d+) for LDL$") public void enters_for_LDL(int ldl) throws Throwable { sharedOfficeVisit.getOfficeVisit().setLDL(ldl); } @When("^enters (\\d+) for Triglycerides$") public void enters_for_Triglycerides(int triglycerides) throws Throwable { sharedOfficeVisit.getOfficeVisit().setTriglyceride(triglycerides); } @Then("^the record is not successfully added$") public void an_error_message_is_displayed() throws Throwable { Assert.assertFalse(sharedOfficeVisit.wasAddSuccessful()); } @Then("^the record is saved successfully$") public void the_record_is_saved_successfully() throws Throwable { Assert.assertTrue(sharedOfficeVisit.wasAddSuccessful()); } }
6,722
35.340541
107
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/cucumber/EmergencyHealthRecordsStepDefs.java
package edu.ncsu.csc.itrust.cucumber; import cucumber.api.java.en.Given; import cucumber.api.java.en.Then; import cucumber.api.java.en.When; import edu.ncsu.csc.itrust.exception.DBException; import edu.ncsu.csc.itrust.model.ConverterDAO; import edu.ncsu.csc.itrust.model.diagnosis.Diagnosis; import edu.ncsu.csc.itrust.model.emergencyRecord.EmergencyRecordMySQL; import edu.ncsu.csc.itrust.model.immunization.Immunization; import edu.ncsu.csc.itrust.model.officeVisit.OfficeVisitMySQL; import edu.ncsu.csc.itrust.model.old.dao.mysql.AllergyDAO; import edu.ncsu.csc.itrust.model.old.dao.mysql.PatientDAO; import edu.ncsu.csc.itrust.model.prescription.Prescription; import edu.ncsu.csc.itrust.unit.datagenerators.TestDataGenerator; import edu.ncsu.csc.itrust.unit.testutils.TestDAOFactory; import static org.junit.Assert.fail; import java.io.FileNotFoundException; import java.io.IOException; import java.sql.SQLException; import java.util.List; import javax.sql.DataSource; import org.junit.Assert; public class EmergencyHealthRecordsStepDefs { private PatientDAO patientController; private DataSource ds; private TestDataGenerator gen; private OfficeVisitMySQL oVisSQL; private EmergencyRecordMySQL erSQL; private AllergyDAO allergyDAO; public EmergencyHealthRecordsStepDefs(){ this.ds = ConverterDAO.getDataSource(); this.patientController = new PatientDAO(TestDAOFactory.getTestInstance()); this.gen = new TestDataGenerator(); this.oVisSQL = new OfficeVisitMySQL(ds); } @Given("^I load uc21.sql$") public void loadTables(){ try { gen.clearAllTables(); gen.ndCodes(); gen.ndCodes1(); gen.ndCodes100(); gen.ndCodes2(); gen.ndCodes3(); gen.ndCodes4(); gen.uc21(); } catch (FileNotFoundException e) { fail(); e.printStackTrace(); } catch (SQLException e) { fail(); e.printStackTrace(); } catch (IOException e) { fail(); e.printStackTrace(); } } @Given("^No office visits exist for patient (.+)$") public void noVisits(int pid){ try { Assert.assertTrue(oVisSQL.getVisitsForPatient((long)pid).isEmpty()); } catch (DBException e) { fail(); e.printStackTrace(); } } @When("^Go to the Emergency Patient Report.$") public void goToEmerReport(){ this.allergyDAO = new AllergyDAO(TestDAOFactory.getTestInstance()); this.erSQL = new EmergencyRecordMySQL(ds, allergyDAO); } @Then("^mid: (.+) name: (.*), age: (.+), gender: (.*), emergency contact: (.*), phone: (.*), allergies: (.*), blood type: (.*), diagnoses: (.*), and (.*), prescriptions: (.*), and (.*), immunizaitons: (.*)$") public void checkResults(int mid, String name, int age, String gender, String contactName, String contactPhone, String allergies, String bloodType, String diagnoses1, String diagnoses2, String prescrip1, String prescrip2, String immunization ){ try { Assert.assertEquals(name, erSQL.getEmergencyRecordForPatient((long)mid).getName()); Assert.assertEquals(age, erSQL.getEmergencyRecordForPatient((long)mid).getAge()); Assert.assertEquals(gender, erSQL.getEmergencyRecordForPatient((long)mid).getGender()); Assert.assertEquals(contactName, erSQL.getEmergencyRecordForPatient((long)mid).getContactName()); Assert.assertEquals(contactPhone, erSQL.getEmergencyRecordForPatient((long)mid).getContactPhone()); Assert.assertEquals(allergies, erSQL.getEmergencyRecordForPatient((long)mid).getAllergies().toString()); Assert.assertEquals(bloodType, erSQL.getEmergencyRecordForPatient((long)mid).getBloodType()); List<Immunization> immuneList = erSQL.getEmergencyRecordForPatient((long)mid).getImmunizations(); Assert.assertEquals(immunization, immuneList.get(0).getCode()); List<Diagnosis> diagnosesList = erSQL.getEmergencyRecordForPatient((long)mid).getDiagnoses(); Assert.assertEquals(diagnoses1, diagnosesList.get(0).getCode()); Assert.assertEquals(diagnoses2, diagnosesList.get(1).getCode()); List<Prescription> prescriptionList = erSQL.getEmergencyRecordForPatient((long)mid).getPrescriptions(); Assert.assertEquals(prescrip1, prescriptionList.get(0).getCode()); Assert.assertEquals(prescrip2, prescriptionList.get(1).getCode()); } catch (DBException e) { fail(); e.printStackTrace(); } } @Then("^mid: (.+), name: (.*), age: (.+), gender: (.*), emergency contact: (.*), phone: (.*), no allergies, blood type: (.*), diagnosis: (.*), prescriptions: (.*), no immunizations$") public void checkResults2(int mid, String name, int age, String gender, String contactName, String contactPhone, String bloodType, String diagnoses1, String prescrip1){ try { Assert.assertEquals(name, erSQL.getEmergencyRecordForPatient((long)mid).getName()); Assert.assertEquals(age, erSQL.getEmergencyRecordForPatient((long)mid).getAge()); Assert.assertEquals(gender, erSQL.getEmergencyRecordForPatient((long)mid).getGender()); Assert.assertEquals(contactName, erSQL.getEmergencyRecordForPatient((long)mid).getContactName()); Assert.assertEquals(contactPhone, erSQL.getEmergencyRecordForPatient((long)mid).getContactPhone()); Assert.assertEquals(bloodType, erSQL.getEmergencyRecordForPatient((long)mid).getBloodType()); List<Diagnosis> diagnosesList = erSQL.getEmergencyRecordForPatient((long)mid).getDiagnoses(); Assert.assertEquals(diagnoses1, diagnosesList.get(0).getCode()); List<Prescription> prescriptionList = erSQL.getEmergencyRecordForPatient((long)mid).getPrescriptions(); Assert.assertEquals(prescrip1, prescriptionList.get(0).getCode()); Assert.assertTrue(erSQL.getEmergencyRecordForPatient((long)mid).getAllergies().size() == 0); Assert.assertTrue(erSQL.getEmergencyRecordForPatient((long)mid).getImmunizations().size() == 0); } catch (DBException e) { fail(); e.printStackTrace(); } } @Then("^Error: The patient (.*) does not exist$") public void noPatient(String mid){ try { Assert.assertFalse(patientController.checkPatientExists(Long.parseLong(mid))); } catch (NumberFormatException e) { fail(); e.printStackTrace(); } catch (DBException e) { fail(); e.printStackTrace(); } } @Then("^Office visit info missing for (.+) so no prescriptions, diagnoses, allergies, or immunizations$") public void noOfficeVisitForPatient(int mid){ try { Assert.assertTrue(erSQL.getEmergencyRecordForPatient((long)mid).getPrescriptions().size() == 0); Assert.assertTrue(erSQL.getEmergencyRecordForPatient((long)mid).getDiagnoses().size() == 0); Assert.assertTrue(erSQL.getEmergencyRecordForPatient((long)mid).getAllergies().size() == 0); Assert.assertTrue(erSQL.getEmergencyRecordForPatient((long)mid).getImmunizations().size() == 0); } catch (DBException e) { fail(); e.printStackTrace(); } } }
6,829
38.709302
245
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/cucumber/LabProcedureOfficeVisitStepDefs.java
package edu.ncsu.csc.itrust.cucumber; import cucumber.api.java.en.Given; import cucumber.api.java.en.Then; import cucumber.api.java.en.When; import edu.ncsu.csc.itrust.exception.DBException; import edu.ncsu.csc.itrust.exception.FormValidationException; import edu.ncsu.csc.itrust.model.ConverterDAO; import edu.ncsu.csc.itrust.model.cptcode.CPTCode; import edu.ncsu.csc.itrust.model.cptcode.CPTCodeMySQL; import edu.ncsu.csc.itrust.model.icdcode.ICDCode; import edu.ncsu.csc.itrust.model.icdcode.ICDCodeMySQL; import edu.ncsu.csc.itrust.model.labProcedure.LabProcedure; import edu.ncsu.csc.itrust.model.labProcedure.LabProcedureMySQL; import edu.ncsu.csc.itrust.model.ndcode.NDCCode; import edu.ncsu.csc.itrust.model.ndcode.NDCCodeMySQL; import edu.ncsu.csc.itrust.model.officeVisit.OfficeVisit; import edu.ncsu.csc.itrust.model.officeVisit.OfficeVisitMySQL; import edu.ncsu.csc.itrust.model.old.beans.HospitalBean; import edu.ncsu.csc.itrust.model.old.beans.MedicationBean; import edu.ncsu.csc.itrust.model.old.beans.PatientBean; import edu.ncsu.csc.itrust.model.old.dao.mysql.HospitalsDAO; import edu.ncsu.csc.itrust.model.old.dao.mysql.PatientDAO; import edu.ncsu.csc.itrust.model.old.dao.mysql.PersonnelDAO; import edu.ncsu.csc.itrust.model.prescription.Prescription; import edu.ncsu.csc.itrust.model.prescription.PrescriptionMySQL; import edu.ncsu.csc.itrust.unit.datagenerators.TestDataGenerator; import edu.ncsu.csc.itrust.unit.testutils.TestDAOFactory; import static org.junit.Assert.fail; import java.io.FileNotFoundException; import java.io.IOException; import java.sql.SQLException; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.List; import javax.sql.DataSource; import org.junit.Assert; public class LabProcedureOfficeVisitStepDefs { private PatientDAO patientController; private DataSource ds; private TestDataGenerator gen; private HospitalsDAO hospDAO; private PersonnelDAO persDAO; private OfficeVisitMySQL oVisSQL; private OfficeVisit oVis; private PrescriptionMySQL preSQL; private LabProcedureMySQL labSQL; private CPTCodeMySQL cptSQL; private ICDCodeMySQL icdSQL; private NDCCodeMySQL ndcSQL; public LabProcedureOfficeVisitStepDefs() { this.ds = ConverterDAO.getDataSource(); this.patientController = new PatientDAO(TestDAOFactory.getTestInstance()); this.gen = new TestDataGenerator(); this.hospDAO = new HospitalsDAO(TestDAOFactory.getTestInstance()); this.persDAO = new PersonnelDAO(TestDAOFactory.getTestInstance()); this.oVisSQL = new OfficeVisitMySQL(ds); this.oVis = new OfficeVisit(); this.preSQL = new PrescriptionMySQL(ds); this.labSQL = new LabProcedureMySQL(ds); this.cptSQL = new CPTCodeMySQL(ds); this.icdSQL = new ICDCodeMySQL(ds); this.ndcSQL = new NDCCodeMySQL(ds); } @Given("^I load uc11.sql$") public void loadData(){ try { gen.clearAllTables(); gen.patient1(); gen.hospitals(); gen.appointmentType(); gen.uc26(); gen.uc11(); } catch (SQLException | IOException e) { fail(); e.printStackTrace(); } } @When("^I add a new prescription with the following information: Medication: (.*) (.*), Dosage: (.*). Dates: (.*) to (.*), Instructions: (.*)") public void enterDiagnosisBlank(String medCode, String medName, String dosage, String date1, String date2, String instructions) { List<OfficeVisit> oList; try { oList = oVisSQL.getAll(); NDCCode nd = new NDCCode(); nd.setCode(medCode); nd.setDescription(medName); Prescription pre = new Prescription(); MedicationBean medBean = new MedicationBean(); medBean.setNDCode(medCode); pre.setOfficeVisitId(oList.get(oList.size() - 1).getVisitID()); pre.setPatientMID((long)1); pre.setDrugCode(medBean); pre.setInstructions(instructions); pre.setDosage(Long.parseLong(dosage)); pre.setStartDate(LocalDate.parse(date1)); pre.setEndDate(LocalDate.parse(date2)); preSQL.add(pre); ndcSQL.add(nd); } catch (DBException | SQLException | FormValidationException e1) { System.out.println(e1.toString()); fail(); e1.printStackTrace(); } } @When("^verify that it is there code: (.*), dosage (.*), start date (.*), end date (.*), and special instructions: (.*)$") public void newPrescrip(String code, String dosage, String start, String end, String instructions){ try { List<Prescription> pList = preSQL.getPrescriptionsByMID((long)1); Prescription prescrip = pList.get(pList.size() - 1); Assert.assertEquals(code, prescrip.getCode() + ""); Assert.assertEquals(dosage, prescrip.getDosage() + ""); Assert.assertEquals(instructions, prescrip.getInstructions()); Assert.assertTrue(prescrip.getStartDate().toString().contains(start)); Assert.assertTrue(prescrip.getEndDate().toString().contains(end)); } catch (SQLException e) { fail(); e.printStackTrace(); } } @When("^I add a prescription with backwards dates and the following information: Medication: (.*) (.*), Dosage: (.*). Dates: (.*) to (.*), Instructions: (.*)$") public void enterBackwardsDates(String medCode, String medName, String dosage, String date1, String date2, String instructions) { List<OfficeVisit> oList; try { oList = oVisSQL.getAll(); NDCCode nd = new NDCCode(); nd.setCode(medCode); nd.setDescription(medName); Prescription pre = new Prescription(); MedicationBean medBean = new MedicationBean(); medBean.setNDCode(medCode); pre.setOfficeVisitId(oList.get(oList.size() - 1).getVisitID()); pre.setPatientMID((long)1); pre.setDrugCode(medBean); pre.setInstructions(instructions); pre.setDosage(Long.parseLong(dosage)); pre.setStartDate(LocalDate.parse(date1)); pre.setEndDate(LocalDate.parse(date2)); preSQL.add(pre); ndcSQL.add(nd); } catch (DBException | SQLException e1) { Assert.assertTrue(true); e1.printStackTrace(); } catch (FormValidationException e) { Assert.assertTrue(true); } } @When("^delete the prescription you just made$") public void deletePrescrip(){ try { preSQL.remove(preSQL.getPrescriptionsForOfficeVisit((long)6).get(0).getId()); } catch (SQLException e) { fail(); e.printStackTrace(); } } @When("^I update notes to (.*), location to (.*), add CPT (.*) , (.*) to immunizations, delete (.*) from diagnosis$") public void updateHealthInfo(String newNotes, String newLocation, String newCPT, String newImmunization, String deleteThis ) { List<OfficeVisit> oList; try { oList = oVisSQL.getAll(); OfficeVisit updateOV = oList.get(oList.size() - 1); updateOV.setNotes(newNotes); updateOV.setLocationID(newLocation); CPTCode cCode = new CPTCode(newCPT, newImmunization); cptSQL.add(cCode); icdSQL.delete(icdSQL.getByCode(deleteThis)); oVisSQL.update(updateOV); } catch (DBException | SQLException | FormValidationException e) { System.out.println(e.toString()); fail(); //e.printStackTrace(); } } @When("^For the Lab Procedures associated with the office visit, select LOINC (.*), (.*)with priority 1 and Lab Technician (.*)$") public void makeLabProc(String code, String description, String midLab) { List<OfficeVisit> oList; try { oList = oVisSQL.getAll(); LabProcedure procedure = new LabProcedure(); procedure.setOfficeVisitID(oList.get(oList.size() - 1).getVisitID()); procedure.setStatus((long)1); procedure.setHcpMID(Long.parseLong("9000000000")); procedure.setLabProcedureCode(code); procedure.setPriority(1); procedure.setCommentary(description); procedure.setLabTechnicianID(Long.parseLong(midLab));//, status, hcpmid labSQL.add(procedure); } catch (DBException e) { e.printStackTrace(); fail(); } } @When("^Diagnosis: (.*), (.*), Medical Procedures: (.*), Immunizations: (.*), (.*)$") public void addDetails(String diagnosisCode, String diagnosisNotes, String medProcCode, String immunizationCode, String immunizationDescription) { ICDCode icd = new ICDCode(diagnosisCode, diagnosisNotes, false); CPTCode cpt = new CPTCode(medProcCode, "notNamed"); CPTCode cpt2 = new CPTCode(immunizationCode, immunizationDescription); try { icdSQL.add(icd); cptSQL.add(cpt); cptSQL.add(cpt2); } catch (SQLException | FormValidationException e) { System.out.println(e.toString()); fail(); } } @When("^User enters date: (.*), location: (.*), appointment type: (.*), notes: (.*), and select send a bill true, weight: (.*), height: (.*), blood pressure (.*), ldl: (.*), hdl: (.*), Triglycerides: (.*), house smoke: (.*), patient smoke: (.*)$") public void officeVisitBasics(String date, String location, String appType, String notes, String weight, String height, String blood, String ldl, String hdl, String trig, String house, String patient){ oVis.setDate(LocalDateTime.parse(date)); oVis.setLocationID(location); oVis.setApptTypeID(Long.parseLong(appType)); oVis.setNotes(notes); oVis.setSendBill(true); oVis.setWeight(Float.parseFloat(weight)); oVis.setHeight(Float.parseFloat(height)); oVis.setBloodPressure(blood); oVis.setLDL(Integer.parseInt(ldl)); oVis.setHDL(Integer.parseInt(hdl)); oVis.setTriglyceride(Integer.parseInt(trig)); oVis.setHouseholdSmokingStatus(Integer.parseInt(house)); oVis.setPatientSmokingStatus(Integer.parseInt(patient)); oVis.setPatientMID((long)1); try { oVisSQL.add(oVis); } catch (DBException e) { System.out.println(e.toString()); fail(); //e.printStackTrace(); } } @Then("^After the office visit has been (.*) it does include the following basic health metrics: height: (.*) in, weight: (.*) lbs, blood pressure: (.*), LDL: (.*), HDL: (.*), Triglycerides: (.*), Household Smoking Status: (.*), Patient Smoking Status: (.*)$") public void successfulUpdate(String createOrUpdate, String height, String weight, String blood, String ldl, String hdl, String trig, String house, String patient) { List<OfficeVisit> oList; try { oList = oVisSQL.getAll(); OfficeVisit visit = oList.get(oList.size() - 1); Assert.assertEquals(height, visit.getHeight() + ""); Assert.assertEquals(weight, visit.getWeight() + ""); Assert.assertEquals(blood, visit.getBloodPressure()); Assert.assertEquals(ldl, visit.getLDL() + ""); Assert.assertEquals(hdl, visit.getHDL() + ""); Assert.assertEquals(trig, visit.getTriglyceride() + ""); Assert.assertEquals(house, visit.getHouseholdSmokingStatus() + ""); Assert.assertEquals(patient, visit.getPatientSmokingStatus() + ""); } catch (DBException e) { e.printStackTrace(); fail(); } } @Then("^After the office visit has been created the Location: (.*), notes: (.*), sendbill: true$") public void locationNotesSendBill(String location, String notes) { List<OfficeVisit> oList; try { oList = oVisSQL.getAll(); OfficeVisit visit = oList.get(oList.size() - 1); Assert.assertEquals(location, visit.getLocationID()); Assert.assertEquals(notes, visit.getNotes()); Assert.assertEquals(true, visit.getSendBill()); } catch (DBException e) { e.printStackTrace(); fail(); } } @Then("^After the office visit has been updated the type saved for the office visit is 1$") public void appointmentType() { List<OfficeVisit> oList; try { oList = oVisSQL.getAll(); OfficeVisit visit = oList.get(oList.size() - 1); Assert.assertEquals("1", visit.getApptTypeID() + ""); } catch (DBException e) { e.printStackTrace(); fail(); } } @Then("^After the office visit has been updated, it does NOT include the following Diagnosis of (.*), (.*)$") public void successDeletion(String diagnosis, String diagnosisNotes) { List<OfficeVisit> oList; try { oList = oVisSQL.getAll(); OfficeVisit visit = oList.get(oList.size() - 1); List<ICDCode> icdList = icdSQL.getAll(); for(int i = 0; i < icdList.size(); i++){ if (icdList.get(i).getCode().equals(diagnosis)){ fail(); //otherwise it is not there and it passes } } } catch (DBException | SQLException e) { e.printStackTrace(); fail(); } } @Then("^After the office visit has been updated, it does include the following Immunization (.+), (.*)") public void successAddingImmunizaiont(String immuneCode, String immuneName) { try { Assert.assertEquals(immuneCode, cptSQL.getByCode(immuneCode).getCode()); Assert.assertEquals(immuneName, cptSQL.getByCode(immuneCode).getName()); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Then("^After the office visit has been created, its prescription info is: drugname: (.*), Code: (.*), Dosage: (.*), Start Date: (.*), End Date: (.*), Special instructions: (.*)$") public void prescripExistsInVisit(String name, String code, String dosage, String dateStart, String dateEnd, String spInstruct) { try { List<Prescription> pList = preSQL.getPrescriptionsByMID((long)1); Prescription prescrip = pList.get(pList.size() - 1); Assert.assertEquals(code, prescrip.getCode() + ""); Assert.assertEquals(dosage, prescrip.getDosage() + ""); Assert.assertEquals(spInstruct, prescrip.getInstructions()); Assert.assertTrue(prescrip.getStartDate().toString().contains(dateStart)); Assert.assertTrue(prescrip.getEndDate().toString().contains(dateEnd)); } catch (SQLException e) { fail(); e.printStackTrace(); } } @Then("^After the office visit has been created, Diagnosis: (.*), (.*), Medical Procedures: (.*), Immunizations: (.*), (.*)$") public void doubleChecking(String diagnosisCode, String diagnosisNotes, String medProcCode, String immunizationCode, String immunizationDescription) { try { Assert.assertEquals(medProcCode, cptSQL.getByCode(medProcCode).getCode()); Assert.assertEquals(diagnosisCode, icdSQL.getByCode(diagnosisCode).getCode()); Assert.assertEquals(diagnosisNotes, icdSQL.getByCode(diagnosisCode).getName()); Assert.assertEquals(immunizationCode, cptSQL.getByCode(immunizationCode).getCode()); Assert.assertEquals(immunizationDescription, cptSQL.getByCode(immunizationCode).getName()); } catch (SQLException e) { fail(); e.printStackTrace(); } } @Then("^After the office visit has been created, its Lab Procedures include (.*), (.*) with priority 1 and Lab Technician (.*)$") public void logEvent(String procCode, String procName, String labMid) { List<OfficeVisit> oList; try { oList = oVisSQL.getAll(); OfficeVisit oVis = oList.get(oList.size() - 1); List <LabProcedure> labProcs = labSQL.getAll(); LabProcedure labProc = labProcs.get(labProcs.size() - 1); Assert.assertEquals(procName, labProc.getCommentary()); Assert.assertEquals(procCode, labProc.getLabProcedureCode()); Assert.assertEquals(labMid, labProc.getLabTechnicianID() + ""); } catch (DBException e) { fail(); e.printStackTrace(); } } @Then("^None should be on record$") public void noPrescrips() { try { Assert.assertEquals(0, preSQL.getPrescriptionsForOfficeVisit((long)6).size()); } catch (SQLException e) { fail(); e.printStackTrace(); } } @Then("^No lab record are present when I check for baby Programmer id: (.*)$") public void noLabRecords(String id) { try { Assert.assertEquals(0, preSQL.getPrescriptionsByMID(Long.parseLong(id)).size()); } catch (NumberFormatException | SQLException e) { fail(); e.printStackTrace(); } } }
17,400
37.668889
268
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/cucumber/MaintainStandardsListStepDefs.java
package edu.ncsu.csc.itrust.cucumber; import cucumber.api.java.en.Given; import cucumber.api.java.en.When; import edu.ncsu.csc.itrust.exception.DBException; import edu.ncsu.csc.itrust.exception.FormValidationException; import edu.ncsu.csc.itrust.model.ConverterDAO; import edu.ncsu.csc.itrust.model.cptcode.CPTCode; import edu.ncsu.csc.itrust.model.cptcode.CPTCodeMySQL; import edu.ncsu.csc.itrust.model.icdcode.ICDCode; import edu.ncsu.csc.itrust.model.icdcode.ICDCodeMySQL; import edu.ncsu.csc.itrust.model.loinccode.LOINCCode; import edu.ncsu.csc.itrust.model.loinccode.LOINCCodeMySQL; import edu.ncsu.csc.itrust.model.ndcode.NDCCode; import edu.ncsu.csc.itrust.model.ndcode.NDCCodeMySQL; import edu.ncsu.csc.itrust.model.old.beans.PersonnelBean; import edu.ncsu.csc.itrust.model.old.dao.mysql.PersonnelDAO; import edu.ncsu.csc.itrust.model.old.enums.Role; import edu.ncsu.csc.itrust.unit.datagenerators.TestDataGenerator; import edu.ncsu.csc.itrust.unit.testutils.TestDAOFactory; import cucumber.api.java.en.Then; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import java.io.FileNotFoundException; import java.io.IOException; import java.sql.SQLException; import javax.sql.DataSource; import org.junit.Assert; public class MaintainStandardsListStepDefs { private DataSource ds; private TestDataGenerator gen; private PersonnelDAO persDAO; private CPTCodeMySQL cptSQL; private ICDCodeMySQL icdSQL; private NDCCodeMySQL ndcSQL; private LOINCCodeMySQL loincSQL; public MaintainStandardsListStepDefs(){ this.ds = ConverterDAO.getDataSource(); this.gen = new TestDataGenerator(); this.persDAO = new PersonnelDAO(TestDAOFactory.getTestInstance()); this.cptSQL = new CPTCodeMySQL(ds); this.icdSQL = new ICDCodeMySQL(ds); this.ndcSQL = new NDCCodeMySQL(ds); this.loincSQL = new LOINCCodeMySQL(ds); } @Given("^I load uc15.sql$") public void loadSql(){ try { gen.clearAllTables(); gen.uc15(); gen.admin1(); } catch (FileNotFoundException e) { fail(); e.printStackTrace(); } catch (SQLException e) { fail(); e.printStackTrace(); } catch (IOException e) { fail(); e.printStackTrace(); } } @Given("^Admin user MID: (.*) PW: (.*) exists$") public void userExists(String id, String pw){ PersonnelBean p; try { p = persDAO.getPersonnel(Long.parseLong(id)); assertEquals(Role.ADMIN, p.getRole()); } catch (NumberFormatException e) { fail(); e.printStackTrace(); } catch (DBException e) { fail(); System.out.println(e.toString()); } } @When("^Go to the Add CPT/Vaccine code functionality, enter (.*) as the Code, enter (.*) as the name then add the code$") public void addCPT(String code, String name){ CPTCode cpt = new CPTCode(code, name); try { cptSQL.add(cpt); } catch (SQLException e) { fail(); e.printStackTrace(); } catch (FormValidationException e) { fail(); e.printStackTrace(); } } @When("^Go to the Update CPT/Vaccine code functionality, update (.*), enter (.*) as the Name and update the code.$") public void updateCPT(String code, String name){ try { CPTCode cpt = cptSQL.getByCode(code); cpt.setName(name); cptSQL.update(cpt); } catch (SQLException e) { fail(); e.printStackTrace(); } catch (FormValidationException e) { fail(); e.printStackTrace(); } } @When("^Go to the Add ICD Code functionality, input (.*) as the code, input (.*) as the description field, select (.*), and add code.$") public void addICD(String code, String description, String chronic){ ICDCode icd = new ICDCode(code, description, Boolean.parseBoolean(chronic)); try { icdSQL.add(icd); } catch (SQLException e) { fail(); e.printStackTrace(); } catch (FormValidationException e) { System.out.println(e.toString()); System.out.println(code); fail(); } } @When("^Select Edit ICD Codes from the sidebar, select (.*) from the list, select (.*), and update Code$") public void updateICD(String code, String chronic){ try { ICDCode icd = icdSQL.getByCode(code); icd.setChronic(Boolean.parseBoolean(chronic)); icdSQL.update(icd); } catch (SQLException e) { fail(); e.printStackTrace(); } catch (FormValidationException e) { fail(); e.printStackTrace(); } } @When("^Go to the Add NDC functionality, enter (.*) as the code, enter (.*) as the Name, and Add Code$") public void addNDC(String code, String name){ NDCCode ndc = new NDCCode(); ndc.setCode(code); ndc.setDescription(name); try { ndcSQL.add(ndc); } catch (SQLException e) { fail(); e.printStackTrace(); } catch (FormValidationException e) { System.out.println(code); System.out.println(e.toString()); fail(); } } @When("^Go to the Update NDC functionality, Select NDC (.*), name to (.*), Update Code$") public void updateNDC(String code, String name){ try { NDCCode ndc = ndcSQL.getByCode(code); ndc.setDescription(name); ndcSQL.update(ndc); } catch (SQLException e) { fail(); e.printStackTrace(); } catch (FormValidationException e) { fail(); e.printStackTrace(); } } @When("^Enter (.*) as the code, (.*) as the Component, (.*) as the property, (.*) as the timing aspect, (.*) as the system, (.*) as the scale type, (.*) as the method type, and Add LOINC$") public void addLOINC(String code, String component, String property, String timing, String system, String scale, String method) throws FormValidationException{ LOINCCode loinc = new LOINCCode(code, component, property); loinc.setTimeAspect(timing); loinc.setSystem(system); loinc.setScaleType(scale); loinc.setMethodType(method); try { loincSQL.add(loinc); } catch (DBException e) { fail(); e.printStackTrace(); } } @When("^Go to the Update LOINC functionality, Select LOINC (.*), update the method type to (.*), and Update LOINC$") public void updateLOINC(String code, String method) throws FormValidationException{ try { LOINCCode loinc = loincSQL.getByCode(code); loinc.setMethodType(method); loincSQL.update(loinc); } catch (DBException e) { fail(); e.printStackTrace(); } } @When("^I enter (.*) as an icd code$") public void failureICDCode(String code){ ICDCode icd = new ICDCode(code, "bland description", true); try { icdSQL.add(icd); } catch (SQLException e) { fail(); e.printStackTrace(); } catch (FormValidationException e) { //allow it to pass since the code is invalid on purpose } } @When("^I add NDC code (.*) with name (.*)$") public void addNDCCode(String code, String name){ NDCCode ndc = new NDCCode(); ndc.setCode(code); ndc.setDescription(name); try { ndcSQL.add(ndc); } catch (SQLException e) { fail(); e.printStackTrace(); } catch (FormValidationException e) { fail(); } } @Then("^There are 0 cpt codes present when I attempt to search for (.*)$") public void noCPTCodes(String code){ try { CPTCode cpt = cptSQL.getByCode(code); Assert.assertEquals(null, cpt); } catch (SQLException e) { fail(); e.printStackTrace(); } } @Then("^After the user sees a message - Success: (.*) - (.*) and its in the system$") public void messageAndInSystem(String code, String name) throws SQLException{ //now way to assert message cause it is front end Assert.assertEquals(code, cptSQL.getByCode(code).getCode().toString()); } @Then("^After adding the information the user sees a message - Success: (.*) - (.*) added. it is also (.*)$") public void chronic(String code, String name, String chronicYesNo) throws SQLException{ ICDCode iCode = icdSQL.getByCode(code); Assert.assertEquals(name, iCode.getName()); Assert.assertEquals(Boolean.parseBoolean(chronicYesNo), iCode.isChronic()); } @Then("^After the update, message displays - Success 1 row updated and (.*) has (.*) selected$") public void rowsAndChronic(String code, String chronicYesNo) throws SQLException { ICDCode icd = null; System.out.println(code); icd = icdSQL.getByCode(code); Assert.assertEquals(Boolean.parseBoolean(chronicYesNo), icd.isChronic()); Assert.assertEquals(code, icd.getCode()); } @Then("^After adding the code the user sees a message - Success: (.*): (.*) added and is in the system$") public void addEggplantExtract(String code, String name) throws SQLException{ NDCCode nCode = ndcSQL.getByCode(code); Assert.assertEquals(name, nCode.getDescription()); Assert.assertEquals(code, nCode.getCode()); } @Then("^After the update, the user sees a message - Success! Code (.*): (.*) updated and is in the system$") public void updateAcid(String code, String name) throws SQLException{ NDCCode nCode = ndcSQL.getByCode(code); Assert.assertEquals(name, nCode.getDescription()); Assert.assertEquals(code, nCode.getCode()); } @Then("^After adding the code the user sees a message - Success: 66554-3 added and in the system, after adding the code LOINC (.*) has Component (.*), property (.*), timing aspect (.*), system (.*), scale (.*), type (.*)$") public void checkLOINCUpdate(String code, String component, String property, String timing, String system, String scale, String type) throws DBException{ LOINCCode loinc = loincSQL.getByCode(code); Assert.assertEquals(component, loinc.getComponent()); Assert.assertEquals(property, loinc.getKindOfProperty()); Assert.assertEquals(timing, loinc.getTimeAspect()); Assert.assertEquals(system, loinc.getSystem()); Assert.assertEquals(scale, loinc.getScaleType()); Assert.assertEquals(type, loinc.getMethodType()); } @Then("^After the update, the user sees a message - Success! Code 66554-4 updated and in the system, after adding the code LOINC (.*) has Component (.*), property (.*), timing aspect (.*), system (.*), scale (.*), type (.*)$") public void checkLOINCOtherUpdate(String code, String component, String property, String timing, String system, String scale, String type) throws DBException{ LOINCCode loinc = loincSQL.getByCode(code); System.out.println(code); Assert.assertEquals(component, loinc.getComponent()); Assert.assertEquals(property, loinc.getKindOfProperty()); Assert.assertEquals(timing, loinc.getTimeAspect()); Assert.assertEquals(system, loinc.getSystem()); Assert.assertEquals(scale, loinc.getScaleType()); Assert.assertEquals(type, loinc.getMethodType()); } @Then("^I get an error because the code (.*) is too long and the code is not added$") public void errorCodeTooLong(String code){ try { Assert.assertEquals(null, icdSQL.getByCode(code)); } catch (SQLException e) { fail(); e.printStackTrace(); } } @Then("^The code already exists and is not added$") public void alreadyExistsNotAdded() throws SQLException{ Assert.assertEquals(1, ndcSQL.getAll().size()); } @Then("^I clean up all of my data$") public void cleanTables(){ try { gen.clearAllTables(); } catch (FileNotFoundException e) { fail(); e.printStackTrace(); } catch (SQLException e) { fail(); e.printStackTrace(); } catch (IOException e) { fail(); e.printStackTrace(); } } }
11,165
30.811966
227
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/cucumber/ManageLabProcedureStepDefs.java
package edu.ncsu.csc.itrust.cucumber; import cucumber.api.java.en.Given; import cucumber.api.java.en.Then; import cucumber.api.java.en.When; import edu.ncsu.csc.itrust.exception.DBException; import edu.ncsu.csc.itrust.model.ConverterDAO; import edu.ncsu.csc.itrust.model.labProcedure.LabProcedure; import edu.ncsu.csc.itrust.model.labProcedure.LabProcedureMySQL; import edu.ncsu.csc.itrust.model.officeVisit.OfficeVisit; import edu.ncsu.csc.itrust.model.officeVisit.OfficeVisitMySQL; import edu.ncsu.csc.itrust.unit.datagenerators.TestDataGenerator; import static org.junit.Assert.fail; import java.io.FileNotFoundException; import java.io.IOException; import java.sql.SQLException; import java.util.List; import java.util.Stack; import javax.sql.DataSource; import org.junit.Assert; public class ManageLabProcedureStepDefs { private DataSource ds; private TestDataGenerator gen; private OfficeVisitMySQL oVisSQL; private LabProcedureMySQL labPSQL; public ManageLabProcedureStepDefs() { this.ds = ConverterDAO.getDataSource(); this.gen = new TestDataGenerator(); this.oVisSQL = new OfficeVisitMySQL(ds); this.labPSQL = new LabProcedureMySQL(ds); } @Given("^UC26sql has been loaded$") public void loadUC26SQL() throws FileNotFoundException, SQLException, IOException{ try { gen.clearAllTables(); gen.uc26(); } catch (FileNotFoundException e) { fail(); e.printStackTrace(); } catch (SQLException e) { System.out.println(e.toString()); fail(); //e.printStackTrace(); } catch (IOException e) { fail(); e.printStackTrace(); } } @Given("^the lab proc status' have been changed for this use case$") public void changeLabProcStatus() throws FileNotFoundException, SQLException, IOException{ List<LabProcedure> allLabProcedures; try { allLabProcedures = labPSQL.getAll(); for (int i = 0; i < allLabProcedures.size(); i++){ if(allLabProcedures.get(i).getLabProcedureCode().equals("5583-0")){ allLabProcedures.get(i).setStatus(2); labPSQL.update(allLabProcedures.get(i)); } else if (allLabProcedures.get(i).getLabProcedureCode().equals("5685-3")){ allLabProcedures.get(i).setStatus(4); labPSQL.update(allLabProcedures.get(i)); } else if (allLabProcedures.get(i).getLabProcedureCode().equals("12556-7")){ allLabProcedures.get(i).setStatus(2); labPSQL.update(allLabProcedures.get(i)); } else if (allLabProcedures.get(i).getLabProcedureCode().equals("14807-2")){ allLabProcedures.get(i).setStatus(3); labPSQL.update(allLabProcedures.get(i)); } } } catch (DBException e) { fail(); e.printStackTrace(); } } @Given("^the data for loinc (.*) is updated for this use case$") public void changeLabProcData(String loinc) throws FileNotFoundException, SQLException, IOException{ List<LabProcedure> allLabProcedures; try { allLabProcedures = labPSQL.getAll(); for (int i = 0; i < allLabProcedures.size(); i++){ if (allLabProcedures.get(i).getLabProcedureCode().equals("12556-7")){ allLabProcedures.get(i).setLabTechnicianID(allLabProcedures.get(i).getLabTechnicianID() - 1); allLabProcedures.get(i).setStatus(4); labPSQL.update(allLabProcedures.get(i)); } else if (allLabProcedures.get(i).getLabProcedureCode().equals("14807-2")){ allLabProcedures.get(i).setStatus(1); labPSQL.update(allLabProcedures.get(i)); } else if (allLabProcedures.get(i).getLabProcedureCode().equals("5685-3")){ allLabProcedures.get(i).setLabTechnicianID(allLabProcedures.get(i).getLabTechnicianID() - 1); labPSQL.update(allLabProcedures.get(i)); } else if (allLabProcedures.get(i).getLabProcedureCode().equals("71950-0")){ allLabProcedures.get(i).setLabTechnicianID(allLabProcedures.get(i).getLabTechnicianID() - 2); labPSQL.update(allLabProcedures.get(i)); } } } catch (DBException e) { System.out.println(e.toString()); fail(); e.printStackTrace(); } } @Given("^The office visit for (.+) from (.*) has only (.+) lab procedures$") public void visitsContainLabProcs(int mid, String date, int count) { List<LabProcedure> allLabProcedures; try { //make sure that the only lab procedures are 2 for 50000000002 and none for 5000000003 allLabProcedures = labPSQL.getAll(); int counter = 0; for (int i = 0; i < allLabProcedures.size(); i++) { //if the office visit associated with this lab proc has the same date, incerment the counter if (oVisSQL.getByID(allLabProcedures.get(i).getOfficeVisitID()).getDate().toString().contains(date)){ counter++; Assert.assertTrue(true); } } if (counter != count) { fail(); } } catch (DBException e) { fail(); e.printStackTrace(); } } @When("^Delete the Lab procedure with LOINC (.*) from (.+)'s office visit on (.*)$") public void deleteLabProc(String code, int mid, String date) { List<LabProcedure> allLabProcedures; try { allLabProcedures = labPSQL.getAll(); int success = 0; for (int i = 0; i < allLabProcedures.size(); i++) { if (allLabProcedures.get(i).getLabProcedureCode().equals(code)){ labPSQL.removeLabProcedure(allLabProcedures.get(i).getLabProcedureID()); success = 1; } } if (success == 0) { fail(); } } catch (DBException e) { fail(); e.printStackTrace(); } } @When("^Update the lab procedure with LOINC (.*) by setting the Lab Technician to (.*)$") public void UpdateLabProc(String code, String ltID) { List<LabProcedure> allLabProcedures; try { allLabProcedures = labPSQL.getAll(); int success = 0; for (int i = 0; i < allLabProcedures.size(); i++) { if (allLabProcedures.get(i).getLabProcedureCode().equals(code)){ allLabProcedures.get(i).setLabTechnicianID(Long.parseLong(ltID)); labPSQL.update(allLabProcedures.get(i)); success = 1; } } if (success == 0) { fail(); } } catch (DBException e) { fail(); e.printStackTrace(); } } @When("^Examine the lab procedures from the office visit (.*)$") public void examineLabProc(String date) { List<LabProcedure> allLabProcedures; try { allLabProcedures = labPSQL.getAll(); int found = 0; for (int i = 0; i < allLabProcedures.size(); i++) { if (oVisSQL.getByID(allLabProcedures.get(i).getOfficeVisitID()).getDate().toString().contains(date)){ Assert.assertTrue(true); found = 1; } } if (found == 0) { fail(); } } catch (DBException e) { fail(); e.printStackTrace(); } } @When("^Examine the lists of lab procedures assigned and Update the two (.+) lab procedures to (.+)$") public void examineAndUpdateList(int previous, int update) { List<LabProcedure> allLabProcedures; try { allLabProcedures = labPSQL.getAll(); for (int i = 0; i < allLabProcedures.size(); i++) { if (allLabProcedures.get(i).getStatus().getID() == previous){ allLabProcedures.get(i).setStatus(update); } } } catch (DBException e) { fail(); e.printStackTrace(); } } @When("^Examine the list of received procedures$") public void examineList2() { fail(); } @When("^I create a new lab procedure with LOINC (.+) Component: (.*), System: (.*), priority (.+), lab technicial (.+)$") public void createNewLabProcFailure(String code, String componenet, String system, int priority, int techID) { LabProcedure labP = new LabProcedure(); labP.setLabProcedureCode(code); labP.setPriority(priority); labP.setLabTechnicianID((long)techID); try { labPSQL.add(labP); fail(); } catch (DBException e) { //asserting true because the lab proc cant be created with some fields missing Assert.assertTrue(true); } } @When("^Add numerical result: (.*) and confidence interval: (.*)-(.*) to the procedure whose current status is (.*) loinc (.*)$") public void addNumericalResult(String result, String confInterval1, String interval2, String status, String code) { List<LabProcedure> allLabProcedures; try { allLabProcedures = labPSQL.getAll(); int found = 0; for (int i = 0; i < allLabProcedures.size(); i++) { if (allLabProcedures.get(i).getLabProcedureCode().equals(code)){ allLabProcedures.get(i).setResults(result); allLabProcedures.get(i).setConfidenceIntervalLower(Integer.parseInt(confInterval1)); allLabProcedures.get(i).setConfidenceIntervalUpper(Integer.parseInt(interval2)); allLabProcedures.get(i).setStatus(3); labPSQL.update(allLabProcedures.get(i)); found = 1; break; } } if (found == 0)fail(); } catch (DBException e) { System.out.println(e.toString()); fail(); e.printStackTrace(); } catch (NumberFormatException e){ //allow illegal number to get through for bbt 3 Assert.assertTrue(true); } } @When("^Add commentary to the lab procedure (.*) from date (.*)$") public void addCommentary(String comment, String date) { List<LabProcedure> allLabProcedures; try { allLabProcedures = labPSQL.getAll(); int found = 0; for (int i = 0; i < allLabProcedures.size(); i++) { if (oVisSQL.getByID(allLabProcedures.get(i).getOfficeVisitID()).getDate().toString().contains(date)){ allLabProcedures.get(i).setCommentary(comment); allLabProcedures.get(i).setStatus(5); labPSQL.update(allLabProcedures.get(i)); found = 1; } } if (found == 0)fail(); } catch (DBException e) { fail(); e.printStackTrace(); } } @Then("^When I conclude the update, there is a message displayed at the top of the page: Information Successfully Updated.$") public void successMessage() { //fail();//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// } @Then("^I view the (.*) and it is (.*) for office visit for patient (.*) on date (.*)$") public void checkFields(String category, String details, String patient, String date) { List<OfficeVisit> allOfficeVisits; try { int found = 0; allOfficeVisits = oVisSQL.getAll(); for (int i = 0; i < allOfficeVisits.size(); i++) { if (allOfficeVisits.get(i).getDate().toString().contains(date) && allOfficeVisits.get(i).getPatientMID().toString().equals(patient)){ if (category.equals("location")){ Assert.assertEquals(details, allOfficeVisits.get(i).getLocationID()); } else if (category.equals("notes")){ Assert.assertEquals(details, allOfficeVisits.get(i).getNotes()); } else if (category.equals("appointment type")){ Assert.assertEquals(details + "", allOfficeVisits.get(i).getApptTypeID().toString()); } else if (category.equals("date")){ Assert.assertTrue(allOfficeVisits.get(i).getDate().toString().contains(details)); } else if (category.equals("sendBill")){ Assert.assertEquals(details, allOfficeVisits.get(i).getSendBill().toString()); } found = 1; break; } } if (found == 0){ fail(); } } catch (DBException e) { fail(); e.printStackTrace(); } } @Then("^After the office visit from (.*) for (.*) has been (.*), it does include the following basic health metrics: height: (.+) in, weight: (.+) lbs, blood pressure: (.*), LDL: (.+), HDL: (.+), Triglycerides: (.+), Household Smoking Status: (.*), Patient Smoking Status: (.*)$") public void updateBmetrics(String date, String patient, String createOrUpdate, int height, int weight, String bloodPressure, int ldl, int hdl, int trigs, String hSmoke, String pSmoke ) { List<OfficeVisit> allOfficeVisits; try { int found = 0; allOfficeVisits = oVisSQL.getAll(); for (int i = 0; i < allOfficeVisits.size(); i++) { if (allOfficeVisits.get(i).getDate().toString().contains(date) && allOfficeVisits.get(i).getPatientMID().toString().equals(patient)){ Assert.assertEquals(Float.valueOf(height), allOfficeVisits.get(i).getHeight()); Assert.assertEquals(Float.valueOf(weight), allOfficeVisits.get(i).getWeight()); Assert.assertEquals(bloodPressure, allOfficeVisits.get(i).getBloodPressure()); Assert.assertEquals(Float.valueOf(ldl), Float.valueOf(allOfficeVisits.get(i).getLDL())); Assert.assertEquals(Float.valueOf(hdl), Float.valueOf(allOfficeVisits.get(i).getHDL())); Assert.assertEquals(Float.valueOf(trigs), Float.valueOf(allOfficeVisits.get(i).getTriglyceride())); Assert.assertEquals(hSmoke, allOfficeVisits.get(i).getHouseholdSmokingStatusDescription() ); Assert.assertEquals(pSmoke, allOfficeVisits.get(i).getPatientSmokingStatusDescription() ); found = 1; break; } } if (found == 0){ fail(); } } catch (DBException e) { fail(); e.printStackTrace(); } } @Then("^there is a procedure with LOINC (.*), priority (.*), Lab Technician (.*)$") public void thereIsAProcedure( String code, String priority, String labTech) { List<LabProcedure> allLabProcedures; try { allLabProcedures = labPSQL.getAll(); int success = 0; for (int i = 0; i < allLabProcedures.size(); i++) { System.out.println(allLabProcedures.get(i).getLabProcedureCode()); if (allLabProcedures.get(i).getLabProcedureCode().equals(code)){ Assert.assertEquals(allLabProcedures.get(i).getLabProcedureCode(), code); Assert.assertEquals(allLabProcedures.get(i).getPriority() + "", priority); Assert.assertTrue(allLabProcedures.get(i).getLabTechnicianID().equals(Long.parseLong(labTech))); success = 1; break; } } if (success == 0) { fail(); } } catch (DBException e) { fail(); e.printStackTrace(); } } @Then("^there is not a procedure with LOINC (.*), priority (.*), Lab Technician (.*)$") public void thereIsNoProcedure( String code, String priority, String labTech) { List<LabProcedure> allLabProcedures; try { allLabProcedures = labPSQL.getAll(); for (int i = 0; i < allLabProcedures.size(); i++) { if (allLabProcedures.get(i).getLabProcedureCode().equals(code)){ fail(); } } } catch (DBException e) { fail(); e.printStackTrace(); } } @Then("^When I view the office visits, they should include the visit from (.*)$") public void viewAndInclude(String Date) { List<OfficeVisit> allOfficeVisits; try { int found = 0; allOfficeVisits = oVisSQL.getAll(); for (int i = 0; i < allOfficeVisits.size(); i++) { if (allOfficeVisits.get(i).getDate().toString().contains(Date)){ found = 1; Assert.assertTrue(true); } } if (found == 0){ fail(); } } catch (DBException e) { fail(); e.printStackTrace(); } } @Then("^When I view the office visit from (.*), there should be (.+) lab procedure$") public void viewWithProcs(String date, int count) { List<LabProcedure> allLabProcedures; try { allLabProcedures = labPSQL.getAll(); int counter = 0; for (int i = 0; i < allLabProcedures.size(); i++) { if (oVisSQL.getByID(allLabProcedures.get(i).getOfficeVisitID()).getDate().toString().contains(date)){ counter++; Assert.assertTrue(true); } } if (counter != count) { fail(); } } catch (DBException e) { fail(); e.printStackTrace(); } } @Then("^When I examine the lab procedures from the office visit (.*) there is a procedure with LOINC (.*), priority (.*), Lab Technician (.*), status (.*), numerical result: (.+), confidence interval: (.*)-(.*), commentary (.*)$") public void examineLabProc(String date, String code, String priority, String labTech, String status, String result, String interval1, String interval2, String comments) { List<LabProcedure> allLabProcedures; try { allLabProcedures = labPSQL.getAll(); int found = 0; for (int i = 0; i < allLabProcedures.size(); i++) { if (oVisSQL.getByID(allLabProcedures.get(i).getOfficeVisitID()).getDate().toString().contains(date)){ found = 1; Assert.assertEquals(code, allLabProcedures.get(i).getLabProcedureCode()); Assert.assertEquals(priority, allLabProcedures.get(i).getPriority() + ""); Assert.assertEquals(labTech, allLabProcedures.get(i).getLabTechnicianID() + ""); Assert.assertEquals(status, allLabProcedures.get(i).getStatus().toString()); Assert.assertEquals(result, allLabProcedures.get(i).getResults()); Assert.assertEquals(interval1, allLabProcedures.get(i).getConfidenceIntervalLower() + ""); Assert.assertEquals(interval2, allLabProcedures.get(i).getConfidenceIntervalUpper() + ""); Assert.assertEquals(comments, allLabProcedures.get(i).getCommentary()); break; } } if (found == 0) { fail(); } } catch (DBException e) { fail(); e.printStackTrace(); } } @Then("^When I examine the lab procedures from the office visit (.*) there is a procedure with LOINC (.*), Lab Technician (.*), status (.*), and no other information$") public void examineProcNoOtherInfo(String date, String code, String labTech, String status) { List<LabProcedure> allLabProcedures; try { allLabProcedures = labPSQL.getAll(); int found = 0; for (int i = 0; i < allLabProcedures.size(); i++) if (oVisSQL.getByID(allLabProcedures.get(i).getOfficeVisitID()).getDate().toString().contains(date)){ if(allLabProcedures.get(i).getLabProcedureCode().equals(code)){ found = 1; Assert.assertEquals(code, allLabProcedures.get(i).getLabProcedureCode()); Assert.assertEquals(labTech, allLabProcedures.get(i).getLabTechnicianID() + ""); Assert.assertEquals(status, allLabProcedures.get(i).getStatus().toString()); } } if (found == 0) { fail(); } } catch (DBException e) { fail(); e.printStackTrace(); } } @Then("^When I first access and examine the lab procedures, the (.*) queue should contain the correct lab procedure ID, lab procedure code, status, priority, HCP name, and the date the lab was assigned for the procedures with LOINC (.*) and (.*)$") public void correctInfo(String qType, String code1, String code2) { List<LabProcedure> allLabProcedures; try { allLabProcedures = labPSQL.getAll(); int found = 0; for (int i = 0; i < allLabProcedures.size(); i++){ //iterates through list and makes sure all needed lab procs with corresponding codes are there if(allLabProcedures.get(i).getStatus().toString().equals(qType)){ found = 0; if (allLabProcedures.get(i).getLabProcedureCode().equals(code1) || allLabProcedures.get(i).getLabProcedureCode().equals(code2)){ found = 1; } } } if (found == 0) { fail(); } } catch (DBException e) { fail(); e.printStackTrace(); } } @Then("^After I update the two intransit lab procedures to received, when I examine the (.*) queue the order should be: the procedure with LOINC (.*) first, the procedure with LOINC (.*) second, the procedure with LOINC (.*) third, and the procedure with LOINC (.*) fourth$") public void afterUpdate(String qType, String code1, String code2, String code3, String code4) { List<LabProcedure> allLabProcedures; try { allLabProcedures = labPSQL.getAll(); for (int i = 0; i < allLabProcedures.size(); i++){ if(allLabProcedures.get(i).getLabProcedureCode().equals("12556-7") || allLabProcedures.get(i).getLabProcedureCode().equals("71950-0")){ allLabProcedures.get(i).setStatus(3); labPSQL.update(allLabProcedures.get(i)); } } Stack<LabProcedure> stackOfProcedures = new Stack<LabProcedure>(); for (int i = 0; i < allLabProcedures.size(); i++){ if(allLabProcedures.get(i).getStatus().toString().equals(qType)){ stackOfProcedures.push(allLabProcedures.get(i)); } } Assert.assertEquals(code4, stackOfProcedures.pop().getLabProcedureCode()); Assert.assertEquals(code3, stackOfProcedures.pop().getLabProcedureCode()); Assert.assertEquals(code2, stackOfProcedures.pop().getLabProcedureCode()); Assert.assertEquals(code1, stackOfProcedures.pop().getLabProcedureCode()); } catch (DBException e) { fail(); e.printStackTrace(); } } @Then("^The (.*) queue should contain the procedure with LOINC (.*) first and the procedure with LOINC (.*) second$") public void firstAccess(String qType, String code1, String code2) { List<LabProcedure> allLabProcedures; try { allLabProcedures = labPSQL.getAll(); Stack<LabProcedure> stackOfProcedures = new Stack<LabProcedure>(); for (int i = 0; i < allLabProcedures.size(); i++){ if(allLabProcedures.get(i).getStatus().toString().equals(qType)){ if(allLabProcedures.get(i).getLabProcedureCode().equals(code1) || allLabProcedures.get(i).getLabProcedureCode().equals(code2)){ stackOfProcedures.push(allLabProcedures.get(i)); } } } Assert.assertEquals(code2, stackOfProcedures.pop().getLabProcedureCode()); Assert.assertEquals(code1, stackOfProcedures.pop().getLabProcedureCode()); } catch (DBException e) { fail(); e.printStackTrace(); } } @Then("^After I add results to the lab procedure with LOINC (.*) and update the procedure, its status should change to pending and it should no longer appear in the lab technician's queue$") public void afterAddResults(String code) { //verify the status changed List<LabProcedure> allLabProcedures; try { allLabProcedures = labPSQL.getAll(); int found = 0; for (int i = 0; i < allLabProcedures.size(); i++){ if(allLabProcedures.get(i).getLabProcedureCode().equals(code)){ allLabProcedures.get(i).setStatus(1); allLabProcedures.get(i + 1).setStatus(4); labPSQL.update(allLabProcedures.get(i)); labPSQL.update(allLabProcedures.get(i + 1)); Assert.assertEquals("PENDING", allLabProcedures.get(i).getStatus().toString()); found = 1; } } if (found == 0) fail(); } catch (DBException e) { fail(); e.printStackTrace(); } } @Then("^After the lab procedure with LOINC (.*) has been updated, the procedure with LOINC (.*) should now have status testing and be first in the received queue$") public void afterMoreUpdate(String code1, String code2) { List<LabProcedure> allLabProcedures; try { allLabProcedures = labPSQL.getAll(); int found = 0; for (int i = 0; i < allLabProcedures.size(); i++){ if(allLabProcedures.get(i).getLabProcedureCode().equals(code2)){ Assert.assertEquals("TESTING", allLabProcedures.get(i).getStatus().toString()); found = 1; } } if (found == 0) fail(); } catch (DBException e) { fail(); e.printStackTrace(); } } @Then("^After the lab procedure with LOINC (.*) has been updated, the procedure with LOINC (.*) should be second in the received queue, and the procedure with LOINC (.*) should be third$") public void finalUpdate(String code1, String code2, String code3) { fail(); } @Then("^(.*) from (.*)'s status should change to completed$") public void statusCompleted(String code, String date) { List<LabProcedure> allLabProcedures; try { allLabProcedures = labPSQL.getAll(); for (int i = 0; i < allLabProcedures.size(); i++){ if (oVisSQL.getByID(allLabProcedures.get(i).getOfficeVisitID()).getDate().toString().contains(date)){ if(allLabProcedures.get(i).getLabProcedureCode().equals(code)){ Assert.assertEquals("COMPLETED", allLabProcedures.get(i).getStatus().toString()); } } } } catch (DBException e) { fail(); e.printStackTrace(); } } @Then("^After I add an invalid intervals to the lab procedure with LOINC (.*) and attempt to update the procedure, it should not successfully update.$") public void failedToAdd(String code) { List<LabProcedure> allLabProcedures; try { allLabProcedures = labPSQL.getAll(); int found = 0; for (int i = 0; i < allLabProcedures.size(); i++){ if(allLabProcedures.get(i).getLabProcedureCode().equals(code)){ found = 1; Assert.assertEquals("TESTING", allLabProcedures.get(i).getStatus().toString()); } } if (found == 0){ fail(); } } catch (DBException e) { fail(); e.printStackTrace(); } } @Then("^the lab procedure is not created$") public void failNotCreatedMessage() { //make sure there are still only the 9 lab procs from the sql file List<LabProcedure> allLabProcedures; try { allLabProcedures = labPSQL.getAll(); if (allLabProcedures.size() < 9){ fail(); } else{ Assert.assertTrue(true); } } catch (DBException e) { fail(); e.printStackTrace(); } } @Then("^I clean up the tables$") public void cleanUp(){ try { gen.clearAllTables(); } catch (FileNotFoundException e) { fail(); e.printStackTrace(); } catch (SQLException e) { System.out.println(e.toString()); fail(); //e.printStackTrace(); } catch (IOException e) { fail(); e.printStackTrace(); } } }
26,170
34.998624
281
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/cucumber/ManagePatientsStepDefs.java
package edu.ncsu.csc.itrust.cucumber; import cucumber.api.java.en.Given; import cucumber.api.java.en.When; import edu.ncsu.csc.itrust.action.AddPatientAction; import edu.ncsu.csc.itrust.exception.DBException; import edu.ncsu.csc.itrust.exception.FormValidationException; import edu.ncsu.csc.itrust.exception.ITrustException; import edu.ncsu.csc.itrust.model.old.beans.PatientBean; import edu.ncsu.csc.itrust.model.old.dao.mysql.PatientDAO; import edu.ncsu.csc.itrust.unit.testutils.TestDAOFactory; import cucumber.api.java.en.Then; import java.time.Instant; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.List; import org.apache.commons.lang.time.DateUtils; import org.junit.Assert; public class ManagePatientsStepDefs { // @Inject private long loggedInMID; private UserDataShared userData; private PatientDataShared patientData; public ManagePatientsStepDefs(UserDataShared currentUser, PatientDataShared currentPatient){ this.userData = currentUser; this.patientData = currentPatient; } @When("^I enter a (.+), (.+), and (.+) for a new patient and submit the information$") public void HCP_enters_new_patient_name_and_email(String firstName, String lastName, String email) { if(this.userData.loginID>0){ AddPatientAction testAction = new AddPatientAction(TestDAOFactory.getTestInstance(), this.userData.loginID); PatientBean newPatient = new PatientBean(); newPatient.setFirstName(firstName); newPatient.setLastName(lastName); newPatient.setEmail(email); try { long patientMID = 0; patientMID = testAction.addPatient(newPatient, this.userData.loginID); this.patientData.patientID = patientMID; } catch (FormValidationException e) { Assert.fail("Unable to create Patient - FormValidationException"); } catch (ITrustException e) { Assert.fail("Unable to create Patient ITrustException"); } }else{ Assert.fail("Not logged in"); } } @Given("^a Patient has been created$") public void create_patient(){ if(this.userData.loginID>0){ AddPatientAction testAction = new AddPatientAction(TestDAOFactory.getTestInstance(), this.userData.loginID); PatientBean newPatient = new PatientBean(); newPatient.setFirstName("Cucumber"); DateTimeFormatter dtFormatter = DateTimeFormatter.ofPattern("YYYYMMddhhmmss"); String curTime = LocalDateTime.now().format(dtFormatter); newPatient.setLastName("Test"); newPatient.setEmail("Cucumber_"+curTime+"@test.com"); try { long patientMID = 0; patientMID = testAction.addPatient(newPatient, this.userData.loginID); this.patientData.patientID = patientMID; } catch (FormValidationException e) { Assert.fail("Unable to create Patient - FormValidationException"); } catch (ITrustException e) { Assert.fail("Unable to create Patient ITrustException"); } }else{ Assert.fail("Not logged in"); } } //ToDo: Add check to verify that patient was created recently? @Then("^the new patient is assigned an MID$") public void patient_assigned_MID(){ Assert.assertTrue(this.patientData.patientID>0); } //ToDo: Add check to verify that patient was created recently? @Then("^all initial values except MID default to null$") public void new_patient_values_default_null(){ PatientDAO testPatientDAO = new PatientDAO(TestDAOFactory.getTestInstance()); try { PatientBean newPatient = testPatientDAO.getPatient(this.patientData.patientID); boolean b = true; //Check that age is 0 if((newPatient.getAge() !=0) || (newPatient.getAgeInDays() !=0) || (newPatient.getAgeInWeeks() !=0)){ Assert.fail("Age not equal to 0"); b = false; } if(!newPatient.getAlternateName().isEmpty() && (newPatient.getAlternateName() != null)){ Assert.fail("Alternate Name not null"); b = false; } if((!newPatient.getBloodType().getName().contains("N")) ||(!newPatient.getBloodType().getName().contains("S")) ){ Assert.fail("Blood Type not null"); b = false; } if(!newPatient.getCauseOfDeath().isEmpty() && (newPatient.getCauseOfDeath() != null)){ Assert.fail("Cause of Death not null"); b = false; } if(!newPatient.getCity().isEmpty() && (newPatient.getCity() != null)){ Assert.fail("City not null"); b = false; } if(!newPatient.getCreditCardNumber().isEmpty() && (newPatient.getCreditCardNumber() != null)){ Assert.fail("Credit Card Number not null"); b = false; } if(!newPatient.getCreditCardType().isEmpty() && (newPatient.getCreditCardType() != null)){ Assert.fail("Credit Card Type not null"); b = false; } if(!newPatient.getCreditCardType().isEmpty() && (newPatient.getCreditCardType() != null)){ Assert.fail("Credit Card Type not null"); b = false; } //date of birth if(!DateUtils.isSameDay(newPatient.getDateOfBirth(), java.util.Date.from(Instant.now()))){ Assert.fail("Date of Birth not correct"); b = false; } if(!newPatient.getDateOfDeactivationStr().isEmpty() && (newPatient.getDateOfDeactivationStr() != null)){ Assert.fail("Date of Deactivation not null"); b = false; } if(!(newPatient.getDateOfDeath() == null) ){ Assert.fail("Date of Death not null"); b = false; } if(!newPatient.getDirectionsToHome().isEmpty() && (newPatient.getDirectionsToHome() != null)){ Assert.fail("Directions to Home not null"); b = false; } if(!newPatient.getEmergencyName().isEmpty() && (newPatient.getEmergencyName() != null)){ Assert.fail("Emergency Name not null"); b = false; } if(!newPatient.getEmergencyPhone().isEmpty() && (newPatient.getEmergencyPhone() != null)){ Assert.fail("Emergency Phone not null"); b = false; } if(!(newPatient.getEthnicity().getName().contains("Not Specified"))){ Assert.fail("Ethnicity not null"); b = false; } if(!(newPatient.getFatherMID().contains("0")) && !(newPatient.getFatherMID() == null)){ Assert.fail("Father MID not null"); b = false; } if(!(newPatient.getGender().getName().contains("Not Specified"))){ Assert.fail("Gender not null"); b = false; } if(!newPatient.getIcAddress1().isEmpty() && (newPatient.getIcAddress1() != null)){ Assert.fail("IC Address 1 not null"); b = false; } if(!newPatient.getIcAddress2().isEmpty() && (newPatient.getIcAddress2() != null)){ Assert.fail("IC Address 2 not null"); b = false; } if(!newPatient.getIcCity().isEmpty() && (newPatient.getIcCity() != null)){ Assert.fail("IC City not null"); b = false; } if(!newPatient.getIcID().isEmpty() && (newPatient.getIcID() != null)){ Assert.fail("IC ID not null"); b = false; } if(!newPatient.getIcName().isEmpty() && (newPatient.getIcName() != null)){ Assert.fail("IC Name not null"); b = false; } if(!newPatient.getIcPhone().isEmpty() && (newPatient.getIcPhone() != null)){ Assert.fail("IC Phone not null"); b = false; } // States cannot be null - no verification for ICState if(!newPatient.getIcZip().isEmpty() && (newPatient.getIcZip() != null)){ Assert.fail("IC Zip not null"); b = false; } if(!newPatient.getLanguage().isEmpty() && (newPatient.getLanguage() != null)){ Assert.fail("Language not null"); b = false; } if(!(newPatient.getMotherMID().contains("0")) && (newPatient.getMotherMID() != null)){ Assert.fail("Mother MID not null"); b = false; } if(!newPatient.getPhone().isEmpty() && (newPatient.getPhone() != null)){ Assert.fail("Phone not null"); b = false; } if(!newPatient.getReligion().isEmpty() && (newPatient.getReligion() != null)){ Assert.fail("Religion not null"); b = false; } if(!newPatient.getSpiritualPractices().isEmpty() && (newPatient.getSpiritualPractices() != null)){ Assert.fail("Spiritual Practices not null"); b = false; } //States cannot be null, no verification for state if(!newPatient.getStreetAddress1().isEmpty() && (newPatient.getStreetAddress1() != null)){ Assert.fail("Street Address 1 not null"); b = false; } if(!newPatient.getStreetAddress2().isEmpty() && (newPatient.getStreetAddress2() != null)){ Assert.fail("Street Address 2 not null"); b = false; } if(!newPatient.getTopicalNotes().isEmpty() && (newPatient.getTopicalNotes() != null)){ Assert.fail("Topical Notes not null"); b = false; } if(!newPatient.getZip().isEmpty() && (newPatient.getZip() != null)){ Assert.fail("Zip Code not null"); b = false; } Assert.assertTrue(b); } catch (DBException e) { Assert.fail("Error in retrieving PatientName"); } } //ToDo: Add check to verify that patient was created recently? @Then("^(.+) (.+) is created$") public void patient_name_created(String fName, String lName){ PatientDAO testPatientDAO = new PatientDAO(TestDAOFactory.getTestInstance()); try { List<PatientBean> matchingPatientBeans = testPatientDAO.fuzzySearchForPatientsWithName(fName, lName); Assert.assertTrue(matchingPatientBeans.size()>0); boolean b = false; for(PatientBean pb : matchingPatientBeans){ String f = pb.getFirstName(); String l = pb.getLastName(); if((f.compareToIgnoreCase(fName) ==0) && (l.compareToIgnoreCase(lName) ==0)){ b = true; break; } } Assert.assertTrue(b); } catch (DBException e) { Assert.fail("Error in retrieving PatientName"); } } }
9,640
34.707407
117
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/cucumber/OfficeVisitStepDefs.java
package edu.ncsu.csc.itrust.cucumber; import cucumber.api.java.en.Given; import cucumber.api.java.en.When; import edu.ncsu.csc.itrust.controller.officeVisit.OfficeVisitController; import edu.ncsu.csc.itrust.exception.DBException; import edu.ncsu.csc.itrust.model.ConverterDAO; import edu.ncsu.csc.itrust.model.apptType.ApptTypeData; import edu.ncsu.csc.itrust.model.apptType.ApptTypeMySQLConverter; import edu.ncsu.csc.itrust.model.hospital.Hospital; import edu.ncsu.csc.itrust.model.hospital.HospitalData; import edu.ncsu.csc.itrust.model.hospital.HospitalMySQLConverter; import edu.ncsu.csc.itrust.model.officeVisit.OfficeVisit; import edu.ncsu.csc.itrust.model.officeVisit.OfficeVisitMySQL; import cucumber.api.java.en.Then; import java.security.InvalidParameterException; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.List; import javax.sql.DataSource; import org.junit.Assert; public class OfficeVisitStepDefs { private PatientDataShared patientData; private OfficeVisitMySQL ovData; private ApptTypeData atBean; private HospitalData hospBean; private DataSource ds; private OfficeVisit sharedVisit; private OfficeVisitController ovc; public OfficeVisitStepDefs(PatientDataShared currentPatient, OfficeVisit sharedOV){ this.ds =ConverterDAO.getDataSource(); this.patientData = currentPatient; this.ovData = new OfficeVisitMySQL(ds); this.atBean = new ApptTypeMySQLConverter(ds); this.hospBean = new HospitalMySQLConverter(ds); this.sharedVisit = sharedOV; this.ovc = new OfficeVisitController(ds); } @Given("^I have already selected (.+)") public void already_selected_patient(String patient){ Long id =Long.parseLong(patient); if((id <=0L) ||(id > 8999999999L) ){ throw new IllegalStateException("Not a valid patient MID"); } patientData.patientID = id; } @Given("^(.+) already has a visit with date: (.+), location: (.+), appointment type: (.+), notes: (.+), and select send a bill (.+)$") public void previous_valid_visit(String patient, String date, String location, String apptType, String notes, String bill){ OfficeVisit input = new OfficeVisit(); Long id =Long.parseLong(patient); if((id <=0L) ||(id > 8999999999L) ){ throw new IllegalStateException("Not a valid patient MID"); } input.setPatientMID(id); patientData.patientID = id; boolean sendBill; if(bill.toLowerCase().trim().startsWith("f") && ((bill.toLowerCase().trim().endsWith("alse")) || (bill.toLowerCase().trim().length() ==1))) sendBill = false; else{ if((bill.toLowerCase().trim().startsWith("t"))&& ((bill.toLowerCase().trim().endsWith("rue")) || (bill.toLowerCase().trim().length() ==1))) sendBill = true; else{ Assert.fail("Invalid value for sendBill boolean"); throw new InvalidParameterException("Invalid value for sendBill boolean"); } } try { input.setApptTypeID(atBean.getApptTypeIDs(apptType).keySet().iterator().next()); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"); LocalDateTime ldtVisitDate= LocalDateTime.parse(date, formatter); input.setDate(ldtVisitDate); input.setLocationID(getFirstIDforHospitalName(location)); input.setPatientMID(id); input.setNotes(notes); input.setSendBill(sendBill); ovData.add(input); sharedVisit.setApptTypeID(input.getApptTypeID()); sharedVisit.setDate(input.getDate()); sharedVisit.setLocationID(input.getLocationID()); sharedVisit.setNotes(input.getNotes()); sharedVisit.setPatientMID(input.getPatientMID()); sharedVisit.setSendBill(input.getSendBill()); } catch (DBException e) { Assert.fail("Office Visit Setup incorrect"); } } @When("^I enter date: (.+), location: (.+), appointment type: (.+), and no other information$") public void enter_basic_ov_values_for_selected_patient(String visitDate, String visitLocation, String appointmentType){ OfficeVisit ov = new OfficeVisit(); try { ov.setApptTypeID(atBean.getApptTypeIDs(appointmentType).keySet().iterator().next()); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"); LocalDateTime ldtVisitDate= LocalDateTime.parse(visitDate, formatter); ov.setDate(ldtVisitDate); ov.setLocationID(getFirstIDforHospitalName(visitLocation)); ov.setPatientMID(patientData.patientID); ovData.add(ov); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); Assert.fail(e.getMessage()); } } @When("^I update the office visit information to date: (.+), location: (.+), appointment type: (.+), notes: (.+), and send a bill: (.+)$") public void update_ov_values_for_selected_patient(String visitDate, String visitLocation, String appointmentType, String notes, String bill) throws DBException{ OfficeVisit ov = new OfficeVisit(); List<OfficeVisit> all = ovData.getVisitsForPatient(patientData.patientID); Long visitID = null; boolean sendBill; if(bill.toLowerCase().trim().startsWith("f") && ((bill.toLowerCase().trim().endsWith("alse")) || (bill.toLowerCase().trim().length() ==1))) sendBill = false; else{ if((bill.toLowerCase().trim().startsWith("t"))&& ((bill.toLowerCase().trim().endsWith("rue")) || (bill.toLowerCase().trim().length() ==1))) sendBill = true; else{ Assert.fail("Invalid value for sendBill boolean"); throw new InvalidParameterException("Invalid value for sendBill boolean"); } } ov.setApptTypeID(atBean.getApptTypeIDs(appointmentType).keySet().iterator().next()); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"); LocalDateTime ldtVisitDate= LocalDateTime.parse(visitDate, formatter); ov.setDate(ldtVisitDate); ov.setLocationID(getFirstIDforHospitalName(visitLocation)); ov.setPatientMID(patientData.patientID); ov.setNotes(notes); ov.setSendBill(sendBill); for(int o = 0; o<all.size(); o++){ OfficeVisit temp = all.get(o); boolean dateBool = (temp.getDate().equals(sharedVisit.getDate())); boolean locBool = (temp.getLocationID().equals(sharedVisit.getLocationID())); boolean midBool = (temp.getPatientMID().equals(sharedVisit.getPatientMID())); boolean notesBool = (temp.getNotes().equals(sharedVisit.getNotes())); if(!notesBool){ if((temp.getNotes() ==null) && (sharedVisit.getNotes() == null)){ notesBool = true; } } boolean billBool = (temp.getSendBill() == sharedVisit.getSendBill()); if(dateBool && locBool && midBool && notesBool && billBool){ visitID = all.get(o).getVisitID(); ov.setVisitID(visitID); } } if(visitID == null){ Assert.fail("Invalid Visit ID for update"); } else{ ovData.update(ov); } } @Then("^the patient's office visit for (.+), (.+), and (.+) is successfully documented$") public void required_info_office_visit_successfully_created(String date, String loc, String apptType){ boolean retval = false; try{ List<OfficeVisit> visits = ovData.getVisitsForPatient(patientData.patientID); for(int i=0; i<visits.size(); i++){ OfficeVisit o = visits.get(i); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"); String formatDate = o.getDate().format(formatter); boolean bDate = (formatDate.equals(date)); boolean bLoc = (hospBean.getHospitalName(o.getLocationID()).equals(loc)) ; boolean bApptType = (atBean.getApptTypeName(o.getApptTypeID()).equals(apptType)); boolean bPatient = (o.getPatientMID().equals(patientData.patientID)); if(bDate && bLoc && bApptType && bPatient){ retval = true; break; } } Assert.assertTrue("office visit does not exist",retval); } catch(DBException dbe){ Assert.fail(); } } @When("^I enter date: (.+), location: (.+), appointment type: (.+), notes: (.+), and select send a bill (.+)$") public void enter_all_ov_values_for_selected_patient(String visitDate, String visitLocation, String appointmentType, String notes, String bill){ OfficeVisit ov = new OfficeVisit(); boolean sendBill; if(bill.toLowerCase().trim().startsWith("f") && ((bill.toLowerCase().trim().endsWith("alse")) || (bill.toLowerCase().trim().length() ==1))) sendBill = false; else{ if((bill.toLowerCase().trim().startsWith("t"))&& ((bill.toLowerCase().trim().endsWith("rue")) || (bill.toLowerCase().trim().length() ==1))) sendBill = true; else{ Assert.fail("Invalid value for sendBill boolean"); throw new InvalidParameterException("Invalid value for sendBill boolean"); } } try { ov.setApptTypeID(atBean.getApptTypeIDs(appointmentType).keySet().iterator().next()); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"); LocalDateTime ldtVisitDate= LocalDateTime.parse(visitDate, formatter); ov.setDate(ldtVisitDate); ov.setLocationID(getFirstIDforHospitalName(visitLocation)); ov.setPatientMID(patientData.patientID); ov.setNotes(notes); ov.setSendBill(sendBill); ovData.add(ov); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } private String getFirstIDforHospitalName(String visitLocation) throws DBException { String LocID = ""; List<Hospital> hList = hospBean.getAll(); for(int i=0; i < hList.size(); i++){ if(hList.get(i).getHospitalName().contains(visitLocation)){ LocID = hList.get(i).getHospitalID(); break; } } return LocID; } @Then("^the patient's entire office visit for (.+), (.+), (.+), (.+), and send bill (.+) is successfully documented$") public void all_info_office_visit_successfully_created(String date, String loc, String apptType, String notes, String bill){ boolean retval = false; boolean sendBill; if(bill.toLowerCase().trim().startsWith("f") && ((bill.toLowerCase().trim().endsWith("alse")) || (bill.toLowerCase().trim().length() ==1))) sendBill = false; else{ if((bill.toLowerCase().trim().startsWith("t"))&& ((bill.toLowerCase().trim().endsWith("rue")) || (bill.toLowerCase().trim().length() ==1))) sendBill = true; else{ Assert.fail("Invalid value for sendBill boolean"); throw new InvalidParameterException("Invalid value for sendBill boolean"); } } try{ List<OfficeVisit> visits = ovc.getOfficeVisitsForPatient(Long.toString(patientData.patientID)); for(int i=0; i<visits.size(); i++){ OfficeVisit o = visits.get(i); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"); String formatDate = o.getDate().format(formatter); boolean bDate = (formatDate.equals(date)); boolean bLoc = (hospBean.getHospitalName(o.getLocationID()).equals(loc)) ; boolean bApptType = (atBean.getApptTypeName(o.getApptTypeID()).equals(apptType)); boolean bPatient = (o.getPatientMID().equals(patientData.patientID)); boolean bNotes = (o.getNotes().equals(notes)); boolean bSendBill = (o.getSendBill() == sendBill); if(bDate && bLoc && bApptType && bPatient && bNotes && bSendBill){ retval = true; break; } } Assert.assertTrue("office visit does not exist",retval); } catch(DBException dbe){ Assert.fail(); } } @Then("^the office visit information is - date: (.+), location: (.+), appointment type: (.+), notes: (.+), and send a bill: (.+)$") public void required_info_office_visit_successfully_created(String date, String loc, String apptType, String notes, String bill){ boolean retval = false; boolean sendBill; if(bill.toLowerCase().trim().startsWith("f") && ((bill.toLowerCase().trim().endsWith("alse")) || (bill.toLowerCase().trim().length() ==1))) sendBill = false; else{ if((bill.toLowerCase().trim().startsWith("t"))&& ((bill.toLowerCase().trim().endsWith("rue")) || (bill.toLowerCase().trim().length() ==1))) sendBill = true; else{ Assert.fail("Invalid value for sendBill boolean"); throw new InvalidParameterException("Invalid value for sendBill boolean"); } } try{ List<OfficeVisit> visits = ovData.getVisitsForPatient(patientData.patientID); for(int i=0; i<visits.size(); i++){ OfficeVisit o = visits.get(i); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"); String formatDate = o.getDate().format(formatter); boolean bDate = (formatDate.equals(date)); boolean bLoc = (hospBean.getHospitalName(o.getLocationID()).equals(loc)) ; boolean bApptType = (atBean.getApptTypeName(o.getApptTypeID()).equals(apptType)); boolean bPatient = (o.getPatientMID().equals(patientData.patientID)); boolean bNotes = (o.getNotes().equals(notes)); boolean bSendBill = (o.getSendBill() == sendBill); if(bDate && bLoc && bApptType && bPatient && bNotes && bSendBill){ retval = true; break; } } Assert.assertTrue("office visit does not exist",retval); } catch(DBException dbe){ Assert.fail(); } } }
12,887
38.292683
161
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/cucumber/PatientDataShared.java
package edu.ncsu.csc.itrust.cucumber; public class PatientDataShared { public Long patientID; public PatientDataShared(){ patientID = new Long(0); } }
164
12.75
37
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/cucumber/PrescriptionReportStepDefs.java
package edu.ncsu.csc.itrust.cucumber; import cucumber.api.java.en.Given; import cucumber.api.java.en.When; import edu.ncsu.csc.itrust.controller.officeVisit.OfficeVisitController; import edu.ncsu.csc.itrust.exception.DBException; import edu.ncsu.csc.itrust.exception.FormValidationException; import edu.ncsu.csc.itrust.model.ConverterDAO; import edu.ncsu.csc.itrust.model.cptcode.CPTCode; import edu.ncsu.csc.itrust.model.cptcode.CPTCodeMySQL; import edu.ncsu.csc.itrust.model.icdcode.ICDCode; import edu.ncsu.csc.itrust.model.icdcode.ICDCodeMySQL; import edu.ncsu.csc.itrust.model.labProcedure.LabProcedureMySQL; import edu.ncsu.csc.itrust.model.loinccode.LOINCCode; import edu.ncsu.csc.itrust.model.loinccode.LOINCCodeMySQL; import edu.ncsu.csc.itrust.model.ndcode.NDCCode; import edu.ncsu.csc.itrust.model.ndcode.NDCCodeMySQL; import edu.ncsu.csc.itrust.model.officeVisit.OfficeVisit; import edu.ncsu.csc.itrust.model.officeVisit.OfficeVisitMySQL; import edu.ncsu.csc.itrust.model.officeVisit.OfficeVisitValidator; import edu.ncsu.csc.itrust.model.old.beans.PersonnelBean; import edu.ncsu.csc.itrust.model.old.dao.mysql.AuthDAO; import edu.ncsu.csc.itrust.model.old.dao.mysql.HospitalsDAO; import edu.ncsu.csc.itrust.model.old.dao.mysql.PatientDAO; import edu.ncsu.csc.itrust.model.old.dao.mysql.PersonnelDAO; import edu.ncsu.csc.itrust.model.old.enums.Role; import edu.ncsu.csc.itrust.model.prescription.Prescription; import edu.ncsu.csc.itrust.model.prescription.PrescriptionMySQL; import edu.ncsu.csc.itrust.unit.datagenerators.TestDataGenerator; import edu.ncsu.csc.itrust.unit.testutils.TestDAOFactory; import cucumber.api.java.en.Then; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.fail; import java.io.FileNotFoundException; import java.io.IOException; import java.sql.SQLException; import java.time.LocalDate; import java.util.List; import javax.sql.DataSource; import org.junit.Assert; public class PrescriptionReportStepDefs { private AuthDAO authController; private PatientDAO patientController; private PatientDataShared sharedPatient; private OfficeVisitValidator ovValidator; private DataSource ds; private OfficeVisitController ovController; private OfficeVisit sharedVisit; private UserDataShared sharedUser; private TestDataGenerator gen; private HospitalsDAO hospDAO; private PersonnelDAO persDAO; private OfficeVisitMySQL oVisSQL; private LabProcedureMySQL labPSQL; private CPTCodeMySQL cptSQL; private ICDCodeMySQL icdSQL; private NDCCodeMySQL ndcSQL; private LOINCCodeMySQL loincSQL; private PrescriptionMySQL preSQL; public PrescriptionReportStepDefs(){ this.ds = ConverterDAO.getDataSource(); this.ovController = new OfficeVisitController(ds); this.ovValidator = new OfficeVisitValidator(ds); this.authController = new AuthDAO(TestDAOFactory.getTestInstance()); this.patientController = new PatientDAO(TestDAOFactory.getTestInstance()); this.gen = new TestDataGenerator(); this.hospDAO = new HospitalsDAO(TestDAOFactory.getTestInstance()); this.persDAO = new PersonnelDAO(TestDAOFactory.getTestInstance()); this.oVisSQL = new OfficeVisitMySQL(ds); this.labPSQL = new LabProcedureMySQL(ds); this.cptSQL = new CPTCodeMySQL(ds); this.icdSQL = new ICDCodeMySQL(ds); this.ndcSQL = new NDCCodeMySQL(ds); this.loincSQL = new LOINCCodeMySQL(ds); this.preSQL = new PrescriptionMySQL(ds); } @Given("^UC19.sql has not been loaded$") public void sqlNotLoaded(){ try { gen.clearAllTables(); } catch (FileNotFoundException e) { fail(); e.printStackTrace(); } catch (SQLException e) { fail(); e.printStackTrace(); } catch (IOException e) { fail(); e.printStackTrace(); } } @Given("^UC19.sql has been loaded$") public void sqlLoaded(){ try { gen.clearAllTables(); gen.uc19(); gen.admin1(); } catch (FileNotFoundException e) { fail(); e.printStackTrace(); } catch (SQLException e) { fail(); e.printStackTrace(); } catch (IOException e) { fail(); e.printStackTrace(); } } @Then("^When I view the prescrip report for (.*) it should have report title first: Andy Programmer, prescription (.*), (.*), (.*), (.*), (.*)$") public void viewReportFirst(String id, String prescripName, String ovDate, String startDate, String endDate, String hcp){ try { List <Prescription> preList = preSQL.getPrescriptionsForOfficeVisit(oVisSQL.getVisitsForPatient(Long.parseLong(id)).get(0).getVisitID()); List <NDCCode> ndcList = ndcSQL.getAll(); Assert.assertEquals(prescripName, ndcList.get(0).getDescription()); Assert.assertTrue(oVisSQL.getVisitsForPatient(Long.parseLong(id)).get(0).getDate().toString().contains(ovDate)); Assert.assertTrue(preList.get(0).getStartDate().toString().contains(startDate)); Assert.assertTrue(preList.get(0).getEndDate().toString().contains(endDate)); } catch (NumberFormatException | DBException | SQLException e) { System.out.println(e.toString()); fail(); } } @Then("^When I view the prescrip report for (.*) it should have report title second: Andy Programmer, prescription (.*), (.*), (.*), (.*), (.*)$") public void viewReportSecond(String id, String prescripName, String ovDate, String startDate, String endDate, String hcp){ try { List <Prescription> preList = preSQL.getPrescriptionsForOfficeVisit(oVisSQL.getVisitsForPatient(Long.parseLong(id)).get(1).getVisitID()); List <NDCCode> ndcList = ndcSQL.getAll(); Assert.assertEquals(prescripName, ndcList.get(1).getDescription()); Assert.assertTrue(oVisSQL.getVisitsForPatient(Long.parseLong(id)).get(1).getDate().toString().contains(ovDate)); Assert.assertTrue(preList.get(0).getStartDate().toString().contains(startDate)); Assert.assertTrue(preList.get(0).getEndDate().toString().contains(endDate)); } catch (NumberFormatException | DBException | SQLException e) { System.out.println(e.toString()); fail(); } } @Then("^When I view the prescrip report for (.*) it should have report title third: Andy Programmer, prescription (.*), (.*), (.*), (.*), (.*)$") public void viewReportThird(String id, String prescripName, String ovDate, String startDate, String endDate, String hcp){ try { List <Prescription> preList = preSQL.getPrescriptionsForOfficeVisit(oVisSQL.getVisitsForPatient(Long.parseLong(id)).get(1).getVisitID()); List <NDCCode> ndcList = ndcSQL.getAll(); Assert.assertEquals(prescripName, ndcList.get(2).getDescription()); Assert.assertTrue(oVisSQL.getVisitsForPatient(Long.parseLong(id)).get(1).getDate().toString().contains(ovDate)); Assert.assertTrue(preList.get(1).getStartDate().toString().contains(startDate)); Assert.assertTrue(preList.get(1).getEndDate().toString().contains(endDate)); } catch (NumberFormatException | DBException | SQLException e) { System.out.println(e.toString()); fail(); } } @Then("^When I view the prescrip report for (.*) it should have report title fourth: Andy Programmer, prescription (.*), (.*), (.*), (.*), (.*)$") public void viewReportFourth(String id, String prescripName, String ovDate, String startDate, String endDate, String hcp){ try { List <Prescription> preList = preSQL.getPrescriptionsForOfficeVisit(oVisSQL.getVisitsForPatient(Long.parseLong(id)).get(1).getVisitID()); List <NDCCode> ndcList = ndcSQL.getAll(); Assert.assertEquals(prescripName, ndcList.get(3).getDescription()); Assert.assertTrue(oVisSQL.getVisitsForPatient(Long.parseLong(id)).get(1).getDate().toString().contains(ovDate)); Assert.assertTrue(preList.get(2).getStartDate().toString().contains(startDate)); Assert.assertTrue(preList.get(2).getEndDate().toString().contains(endDate)); } catch (NumberFormatException | DBException | SQLException e) { System.out.println(e.toString()); fail(); } } @Then("^When I view the prescrip report for (.*), it should be empty$") public void emptyView(String id){ try { List <Prescription> preList = preSQL.getPrescriptionsForOfficeVisit(oVisSQL.getVisitsForPatient(Long.parseLong(id)).get(0).getVisitID()); Assert.assertEquals(0, preList.size()); List <Prescription> preList2 = preSQL.getPrescriptionsForOfficeVisit(oVisSQL.getVisitsForPatient(Long.parseLong(id)).get(1).getVisitID()); Assert.assertEquals(0, preList2.size()); } catch (NumberFormatException | DBException | SQLException e) { fail(); e.printStackTrace(); } catch (IndexOutOfBoundsException e){ //if index is out of bounds then the patient has no prescrips or office visits Assert.assertTrue(true); } } }
8,675
39.166667
147
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/cucumber/TestHooks.java
package edu.ncsu.csc.itrust.cucumber; import java.io.FileNotFoundException; import java.io.IOException; import java.sql.SQLException; import cucumber.api.java.Before; import edu.ncsu.csc.itrust.unit.datagenerators.TestDataGenerator; public class TestHooks { @Before public static void testPrep(){ TestDataGenerator gen = new TestDataGenerator(); try { gen.clearAllTables(); gen.standardData(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
704
21.03125
65
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/cucumber/TestRunner.java
package edu.ncsu.csc.itrust.cucumber; import org.junit.runner.RunWith; import cucumber.api.CucumberOptions; import cucumber.api.junit.Cucumber; @RunWith(Cucumber.class) @CucumberOptions(features="src/test/resources/edu/ncsu/csc/itrust/cucumber/") public class TestRunner { }
280
20.615385
77
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/cucumber/UserDataShared.java
package edu.ncsu.csc.itrust.cucumber; public class UserDataShared { public Long loginID; public UserDataShared(){ loginID = new Long(0); } }
154
11.916667
37
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/cucumber/ViewHealthInfoStepDefs.java
package edu.ncsu.csc.itrust.cucumber; import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import javax.sql.DataSource; import cucumber.api.java.en.Given; import cucumber.api.java.en.Then; import cucumber.api.java.en.When; import edu.ncsu.csc.itrust.controller.officeVisit.OfficeVisitController; import edu.ncsu.csc.itrust.exception.DBException; import edu.ncsu.csc.itrust.model.ConverterDAO; import edu.ncsu.csc.itrust.model.officeVisit.OfficeVisit; import edu.ncsu.csc.itrust.model.officeVisit.OfficeVisitValidator; import edu.ncsu.csc.itrust.model.old.dao.mysql.AuthDAO; import edu.ncsu.csc.itrust.model.old.dao.mysql.PatientDAO; import edu.ncsu.csc.itrust.unit.datagenerators.TestDataGenerator; import edu.ncsu.csc.itrust.unit.testutils.TestDAOFactory; public class ViewHealthInfoStepDefs { private AuthDAO authController; private PatientDAO patientController; private PatientDataShared sharedPatient; private OfficeVisitValidator ovValidator; private DataSource ds; private OfficeVisitController ovController; private OfficeVisit sharedVisit; private UserDataShared sharedUser; private TestDataGenerator gen; private List<OfficeVisit> healthMetricsTable; private int sharedVisitIndex; public static final Long DEFAULT_APPT_TYPE_ID = 1L; public ViewHealthInfoStepDefs(PatientDataShared sharedPatient, OfficeVisit sharedVisit, UserDataShared sharedUser){ this.ds = ConverterDAO.getDataSource(); this.ovController = new OfficeVisitController(ds); this.ovValidator = new OfficeVisitValidator(ds); this.authController = new AuthDAO(TestDAOFactory.getTestInstance()); this.patientController = new PatientDAO(TestDAOFactory.getTestInstance()); this.sharedPatient = sharedPatient; this.sharedVisit = sharedVisit; this.sharedUser = sharedUser; this.gen = new TestDataGenerator(); this.healthMetricsTable = Collections.emptyList(); } @Given("^standard data is loaded$") public void standard_data_is_loaded() throws Throwable { gen.clearAllTables(); gen.standardData(); } @Given("^UC51 data is loaded$") public void uc51_data_is_loaded() throws Throwable { gen.uc51(); } @Given("^UC52 data is loaded$") public void uc52_data_is_loaded() throws Throwable { gen.uc52(); } @Given("^user logs in as (?:.*) with MID: (\\d+) and Password: (\\S+)$") public void user_logs_in_with_MID_and_Password(long mid, String password) throws Throwable { try { if(authController.authenticatePassword(mid, password)){ sharedUser.loginID = mid; } } catch (DBException e) { fail("Unable to authenticate Password"); } } @When("^user enters \"(\\d+)\" in Search by name or MID field$") public void user_enters_in_Search_by_name_or_MID_field(Long mid) throws Throwable { assertTrue(patientController.checkPatientExists(mid)); } @When("^user selects patient with MID (\\d+)$") public void user_selects_patient_with_MID(Long mid) throws Throwable { sharedPatient.patientID = mid; } @When("^user clicks on Click Here to Create a New Office Visit Button$") public void user_clicks_on_Click_Here_to_Create_a_New_Office_Visit_Button() throws Throwable { sharedVisit = new OfficeVisit(); sharedVisit.setPatientMID(sharedPatient.patientID); } @When("^user enters \"([^\"]*)\" as the Office Visit Date$") public void user_enters_as_the_Office_Visit_Date(String dateStr) throws Throwable { LocalDateTime date = LocalDateTime.parse(dateStr, DateTimeFormatter.ofPattern("M/d/yyyy h:mm a")); sharedVisit.setDate(date); sharedVisit.setApptTypeID(DEFAULT_APPT_TYPE_ID); } @When("^user selects (?:.*) with id \"(\\d+)\" as the Location$") public void user_selects_with_id_as_the_Location(int locationId) throws Throwable { sharedVisit.setLocationID(Integer.toString(locationId)); } @When("^user enters \"([^\"]*)\" as Notes$") public void user_enters_as_Notes(String notes) throws Throwable { sharedVisit.setNotes(notes); } @When("^user clicks the \"([^\"]*)\" button$") public void user_clicks_the_button(String arg1) throws Throwable { ovValidator.validate(sharedVisit); } @When("^user enters \"([^\"]*)\" as the weight$") public void user_enters_as_the_weight(String weight) throws Throwable { sharedVisit.setWeight(Float.parseFloat(weight)); } @When("^user enters \"([^\"]*)\" as the length$") public void user_enters_as_the_length(String length) throws Throwable { sharedVisit.setLength(Float.parseFloat(length)); } @When("^user enters \"([^\"]*)\" as the head circumference$") public void user_enters_as_the_head_circumference(String headCircumference) throws Throwable { sharedVisit.setHeadCircumference(Float.parseFloat(headCircumference)); } @When("^user selects \"(\\d+)\" as the household smoking status$") public void user_selects_as_the_household_smoking_status(int hss) throws Throwable { sharedVisit.setHouseholdSmokingStatus(hss); } @When("^user clicks on the Add Record button$") public void user_clicks_on_the_Add_Record_button() throws Throwable { ovController.add(sharedVisit); } @When("^user navigates to view basic health info page for HCP$") public void user_navigates_to_view_basic_health_info_page_for_HCP() throws Throwable { healthMetricsTable = Collections.emptyList(); } @Then("^the baby records table is visible$") public void the_baby_records_table_is_visible() throws Throwable { healthMetricsTable = ovController.getBabyOfficeVisitsForPatient(Long.toString(sharedPatient.patientID)); assertTrue(healthMetricsTable.size() > 0); } @Then("^the above records table \\(if visible\\) contains (\\d+) entry\\(ies\\) \\(if visible\\)$") public void the_above_records_table_if_visible_contains_entry_ies_if_visible(int numEntries) throws Throwable { if (healthMetricsTable.size() == 0) { return; } assertEquals(numEntries, healthMetricsTable.size()); } @Then("^the office visit at (.*) exists in the above records table \\(if visible\\)$") public void the_office_visit_at_PM_exists_in_the_above_records_table_if_visible(String dateStr) throws Throwable { LocalDateTime date = LocalDateTime.parse(dateStr, DateTimeFormatter.ofPattern("M/d/yyyy h:mm a")); for (int i=0; i<healthMetricsTable.size(); i++) { if (healthMetricsTable.get(i).getDate().equals(date)) { sharedVisitIndex = i; break; } } assertTrue(sharedVisitIndex > -1); sharedVisit = (sharedVisitIndex > 0) ? healthMetricsTable.get(sharedVisitIndex) : null; } @Then("^the above office visit \\(if exists\\) is the (\\d+)-th entry of the above records table \\(if visible\\)$") public void the_above_office_visit_if_exists_is_the_th_entry_of_the_above_records_table_if_visible(int index) throws Throwable { if (sharedVisit == null) { return; } assertEquals(index-1, sharedVisitIndex); } @Then("^the above office visit \\(if exists\\) contains (\\S+) as the weight of the above records table \\(if visible\\)$") public void the_above_office_visit_if_exists_contains_as_the_weight_of_the_above_records_table_if_visible(String weightStr) throws Throwable { if (sharedVisit == null) { return; } assertTrue(Float.parseFloat(weightStr) == sharedVisit.getWeight()); } @Then("^the above office visit \\(if exists\\) contains (\\S+) as the length of the above records table \\(if visible\\)$") public void the_above_office_visit_if_exists_contains_as_the_length_of_the_above_records_table_if_visible(String lengthStr) throws Throwable { if (sharedVisit == null) { return; } assertTrue(Float.parseFloat(lengthStr) == sharedVisit.getLength()); } @Then("^the above office visit \\(if exists\\) contains (\\S+) as the head circumference of the above records table \\(if visible\\)$") public void the_above_office_visit_if_exists_contains_as_the_head_circumference_of_the_above_records_table_if_visible(String hsStr) throws Throwable { if (sharedVisit == null) { return; } assertTrue(Float.parseFloat(hsStr) == sharedVisit.getHeadCircumference()); } @Then("^the above office visit \\(if exists\\) contains (\\d+) as the household smoking the above records table \\(if visible\\)$") public void the_above_office_visit_if_exists_contains_as_the_household_smoking_the_above_records_table_if_visible( int id) throws Throwable { if (sharedVisit == null) { return; } assertEquals(id, sharedVisit.getHouseholdSmokingStatus().intValue()); } @Then("^the child records table is invisible$") public void the_child_records_table_is_invisible() throws Throwable { healthMetricsTable = ovController.getChildOfficeVisitsForPatient(Long.toString(sharedPatient.patientID)); assertEquals(0, healthMetricsTable.size()); } @Then("^the adult records table is invisible$") public void the_adult_records_table_is_invisible() throws Throwable { healthMetricsTable = ovController.getAdultOfficeVisitsForPatient(Long.toString(sharedPatient.patientID)); assertEquals(0, healthMetricsTable.size()); } @Then("^the above office visit \\(if exists\\) contains (\\S+) as the height of the above records table \\(if visible\\)$") public void the_above_office_visit_if_exists_contains_as_the_height_of_the_above_records_table_if_visible(String height) throws Throwable { if (sharedVisit == null) { return; } assertEquals(height, sharedVisit.getHeight().toString()); } @Then("^the above office visit \\(if exists\\) contains (\\S+) as the blood_pressure of the above records table \\(if visible\\)$") public void the_above_office_visit_if_exists_contains_as_the_blood_pressure_of_the_above_records_table_if_visible(String bloodPressure) throws Throwable { if (sharedVisit == null) { return; } assertEquals(bloodPressure, sharedVisit.getBloodPressure()); } @Then("^the above office visit \\(if exists\\) contains (\\d+) as the hdl of the above records table \\(if visible\\)$") public void the_above_office_visit_if_exists_contains_as_the_hdl_of_the_above_records_table_if_visible(int hdl) throws Throwable { if (sharedVisit == null) { return; } assertEquals(hdl, sharedVisit.getHDL().intValue()); } @Then("^the above office visit \\(if exists\\) contains (\\d+) as the ldl of the above records table \\(if visible\\)$") public void the_above_office_visit_if_exists_contains_as_the_ldl_of_the_above_records_table_if_visible(int ldl) throws Throwable { if (sharedVisit == null) { return; } assertEquals(ldl, sharedVisit.getLDL().intValue()); } @Then("^the above office visit \\(if exists\\) contains (\\d+) as the triglycerides of the above records table \\(if visible\\)$") public void the_above_office_visit_if_exists_contains_as_the_triglycerides_of_the_above_records_table_if_visible( int tryg) throws Throwable { if (sharedVisit == null) { return; } assertEquals(tryg, sharedVisit.getTriglyceride().intValue()); } @Then("^the child records table is visible$") public void the_child_records_table_is_visible() throws Throwable { healthMetricsTable = ovController.getChildOfficeVisitsForPatient(Long.toString(sharedPatient.patientID)); assertTrue(healthMetricsTable.size() > 0); } @Then("^the baby records table is invisible$") public void the_baby_records_table_is_invisible() throws Throwable { healthMetricsTable = ovController.getBabyOfficeVisitsForPatient(Long.toString(sharedPatient.patientID)); assertEquals(0, healthMetricsTable.size()); } @Then("^the adult records table is visible$") public void the_adult_records_table_is_visible() throws Throwable { healthMetricsTable = ovController.getAdultOfficeVisitsForPatient(Long.toString(sharedPatient.patientID)); assertTrue(healthMetricsTable.size() > 0); } @When("^user navigates to view basic health info page for Patient$") public void user_navigates_to_view_basic_health_info_page_for_Patient() throws Throwable { sharedPatient.patientID = sharedUser.loginID; } @Then("^the page displays message \"([^\"]*)\"$") public void the_page_displays_message(String arg1) throws Throwable { assertEquals(0, healthMetricsTable.size()); } @When("^user enters \"([^\"]*)\" as the height$") public void user_enters_as_the_height(String height) throws Throwable { sharedVisit.setHeight(Float.parseFloat(height)); } @When("^user enters \"([^\"]*)\" as the blood pressure$") public void user_enters_as_the_blood_pressure(String bloodPressure) throws Throwable { sharedVisit.setBloodPressure(bloodPressure); } @When("^user navigates to edit basic health info page$") public void user_navigates_to_edit_basic_health_info_page() throws Throwable { sharedVisit = null; sharedVisitIndex = -1; } @Then("^the above office visit \\(if exists\\) contains (\\S+) as the BMI of the above records table \\(if visible\\)$") public void the_above_office_visit_if_exists_contains_as_the_BMI_of_the_above_records_table_if_visible(String bmiStr) throws Throwable { if (sharedVisit == null) { return; } if ("N/A".equals(bmiStr)) { bmiStr = ""; } assertEquals(bmiStr, sharedVisit.getAdultBMI()); } }
13,220
38.583832
155
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/cucumber/util/SharedOfficeVisit.java
package edu.ncsu.csc.itrust.cucumber.util; import edu.ncsu.csc.itrust.controller.officeVisit.OfficeVisitController; import edu.ncsu.csc.itrust.model.officeVisit.OfficeVisit; import edu.ncsu.csc.itrust.unit.testutils.TestDAOFactory; public class SharedOfficeVisit { private OfficeVisit ov; private OfficeVisitController ovc; private boolean wasAddSuccessful; private boolean hasError; public SharedOfficeVisit() throws Exception { hasError = false; wasAddSuccessful = false; ovc = new OfficeVisitController(((TestDAOFactory)TestDAOFactory.getTestInstance()).getDataSource()); } public OfficeVisitController getOfficeVisitController() { return ovc; } public OfficeVisit getOfficeVisit() { return ov; } public void setOfficeVisit(OfficeVisit officeVisit) { this.ov = officeVisit; } public boolean wasAddSuccessful() { return wasAddSuccessful; } public void setHasError(boolean hasError) { this.hasError = hasError; } public boolean hasError() { return hasError; } public void add() { wasAddSuccessful = ovc.addReturnResult(this.ov); setHasError(!wasAddSuccessful); } }
1,110
26.775
102
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/cucumber/util/SharedPatient.java
package edu.ncsu.csc.itrust.cucumber.util; import edu.ncsu.csc.itrust.model.old.beans.PatientBean; import edu.ncsu.csc.itrust.model.old.dao.mysql.PatientDAO; import edu.ncsu.csc.itrust.unit.testutils.TestDAOFactory; public class SharedPatient { private PatientBean patient; private PatientDAO patientDAO; public SharedPatient() { patientDAO = TestDAOFactory.getTestInstance().getPatientDAO(); } public PatientDAO getPatientDAO() { return patientDAO; } public PatientBean getPatient() { return patient; } public void setPatient(PatientBean patient) { this.patient = patient; } }
598
25.043478
64
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/cucumber/util/SharedPersonnel.java
package edu.ncsu.csc.itrust.cucumber.util; import edu.ncsu.csc.itrust.model.old.beans.PersonnelBean; import edu.ncsu.csc.itrust.model.old.dao.mysql.PersonnelDAO; import edu.ncsu.csc.itrust.unit.testutils.TestDAOFactory; public class SharedPersonnel { private PersonnelBean personnel; private PersonnelDAO personnelDAO; public PersonnelDAO getPersonnelDAO() { return personnelDAO; } public PersonnelBean getPersonnel() { return personnel; } public void setPersonnel(PersonnelBean personnel) { this.personnel = personnel; } public SharedPersonnel() { this.personnelDAO = TestDAOFactory.getTestInstance().getPersonnelDAO(); } }
644
28.318182
73
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/logger/TransactionLoggerTest.java
package edu.ncsu.csc.itrust.logger; import static org.mockito.Matchers.any; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.when; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import edu.ncsu.csc.itrust.exception.DBException; import edu.ncsu.csc.itrust.model.old.dao.DAOFactory; import edu.ncsu.csc.itrust.model.old.dao.mysql.TransactionDAO; public class TransactionLoggerTest { @Before public void setUp() throws Exception { } @Test public void testGetInstance() { TransactionLogger first = TransactionLogger.getInstance(); TransactionLogger second = TransactionLogger.getInstance(); // Should be a singleton Assert.assertEquals(first, second); } @Test public void testLogTransaction() throws DBException { DAOFactory prod = spy(DAOFactory.getProductionInstance()); TransactionDAO mockDAO = mock(TransactionDAO.class); when(prod.getTransactionDAO()).thenReturn(mockDAO); doNothing().when(mockDAO).logTransaction(any(), any(), any(), any()); } }
1,115
27.615385
71
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/model/labtechnician/LabTechnicianControllerTest.java
package edu.ncsu.csc.itrust.model.labtechnician; import javax.sql.DataSource; import org.junit.Assert; import edu.ncsu.csc.itrust.controller.labtechnician.LabTechnicianController; import edu.ncsu.csc.itrust.exception.DBException; import edu.ncsu.csc.itrust.model.ConverterDAO; import edu.ncsu.csc.itrust.model.old.dao.mysql.PersonnelDAO; import edu.ncsu.csc.itrust.unit.datagenerators.TestDataGenerator; import edu.ncsu.csc.itrust.unit.testutils.TestDAOFactory; import junit.framework.TestCase; public class LabTechnicianControllerTest extends TestCase { LabTechnicianController controller; TestDataGenerator gen; @Override public void setUp() throws Exception { DataSource ds = ConverterDAO.getDataSource(); PersonnelDAO pdao = TestDAOFactory.getTestInstance().getPersonnelDAO(); controller = new LabTechnicianController(ds, pdao); gen = new TestDataGenerator(); gen.clearAllTables(); gen.standardData(); } public void testGetLabTechnicianStatusMID() throws DBException { Assert.assertFalse(controller.getLabTechnicianStatusMID().isEmpty()); } }
1,077
30.705882
76
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/selenium/ActivityFeedTest.java
package edu.ncsu.csc.itrust.selenium; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import org.openqa.selenium.*; public class ActivityFeedTest extends iTrustSeleniumTest { private WebDriver driver = null; @Override protected void setUp() throws Exception { super.setUp(); gen.clearAllTables(); gen.standardData(); } @Override protected void tearDown() throws Exception { gen.clearAllTables(); } /** * Tests the limit for activities on the home page and then for all the * activities. * * @throws Exception */ public void testOlderActivities() throws Exception { gen.transactionLog6(); // Login driver = login("2", "pw"); assertEquals("iTrust - Patient Home", driver.getTitle()); // Get the panels and select the activity panel List<WebElement> panels = driver.findElements(By.className("panel-group")); WebElement activityPanel = panels.get(panels.size() - 1); // Get the list items and count how many items there are, should be 20 List<WebElement> listItems = activityPanel.findElements(By.tagName("li")); assertEquals(20, listItems.size()); // Now we check the all the activities driver.findElement(By.linkText("Older Activities")).click(); // Get the panels and select the activity panel panels = driver.findElements(By.className("panel-group")); activityPanel = panels.get(panels.size() - 1); // Get the list items and count how many items there are, should be 40 listItems = activityPanel.findElements(By.tagName("li")); // Plus three because of the two refresh links and then the one padding // <li> assertEquals(40 + 3, listItems.size()); } /** * Tests the refresh functionality of the activity panel, which refreshes * and activity log on the homepage and limits it to 20. * * @throws Exception */ public void testUpdateActivityFeed() throws Exception { gen.transactionLog6(); // Login driver = login("2", "pw"); assertEquals("iTrust - Patient Home", driver.getTitle()); // Click on Older Activities to show all activity driver.findElement(By.linkText("Older Activities")).click(); // Then refresh to show only newest 20 driver.findElement(By.linkText("Refresh")).click(); // Get the panels and select toe activity panel List<WebElement> panels = driver.findElements(By.className("panel-group")); WebElement activityPanel = panels.get(panels.size() - 1); // Get the list items and count how many items there are, should be 20 List<WebElement> listItems = activityPanel.findElements(By.tagName("li")); assertEquals(20, listItems.size()); } /** * Tests for valid information in Activity Feed * * @throws Exception */ public void testViewActivityFeed() throws Exception { gen.transactionLog5(); // Login driver = login("1", "pw"); assertEquals("iTrust - Patient Home", driver.getTitle()); Date d = new Date(); d.setTime(d.getTime() - 3 * 24 * 60 * 60 * 1000); new SimpleDateFormat("MM/dd/yyyy"); // Get the panels and select toe activity panel List<WebElement> panels = driver.findElements(By.className("panel-group")); WebElement activityPanel = panels.get(panels.size() - 1); // Get the list items and count how many items there are, should be 20 List<WebElement> listItems = activityPanel.findElements(By.tagName("li")); assertEquals(8, listItems.size()); assertTrue(listItems.get(0).getText().contains("You successfully authenticated today at ")); assertEquals("Kelly Doctor viewed your risk factors yesterday at 1:15PM.", listItems.get(1).getText()); assertEquals("FirstUAP LastUAP viewed your risk factors yesterday at 1:02PM.", listItems.get(2).getText()); assertEquals("FirstUAP LastUAP viewed your lab procedure results yesterday at 12:02PM.", listItems.get(3).getText()); assertEquals("Justin Time created an emergency report for you yesterday at 10:04AM.", listItems.get(4).getText()); assertEquals("Andy Programmer viewed your prescription report yesterday at 9:43AM.", listItems.get(5).getText()); assertEquals("Kelly Doctor viewed your prescription report yesterday at 8:15AM.", listItems.get(6).getText()); assertTrue(listItems.get(7).getText().contains("Kelly Doctor edited your office visit on ")); } public void testDLHCPActivityHiddenInFeed2() throws Exception { driver = login("23", "pw"); assertEquals("iTrust - Patient Home", driver.getTitle()); WebElement element = driver.findElement(By.xpath("//div[@id='act-accord']//div[2]")); assertFalse(element.getText().contains("Beaker Beaker viewed your demographics")); assertFalse(element.getText().contains("Beaker Beaker edited your demographics")); assertFalse(element.getText().contains("Beaker Beaker added you to the telemedicine monitoring list")); } /** * Tests to see that certain activities from the patients DLHCP are showing * up in the activity field as well as verifying that other certain * activities from the patients DLHCP are hidden. * * This tests Black Box Test Case ViewActivityFeed_ShowRequiredDLHCPActivity * The scenario is that Patient Devil's Advocate logs into iTrust and then * checks his Activity Feed. The Activity Feed should not be displaying * certain actions that his DLHCP performed, such as looking at his * demographics etc. It should be displaying events from other LHCP's as * stated fully in the requirements doc. */ public void testShowRequiredDLHCPActivity() throws Exception { // Login driver = login("24", "pw"); assertEquals("iTrust - Patient Home", driver.getTitle()); // Get the activity log as an element // Verify that certain activities from the patient's DLHCP are present, // and that others are hidden WebElement element = driver.findElement(By.xpath("//div[@id='act-accord']//div[2]")); assertFalse("DLHCP activity that is supposed to be hidden is shown in Activity Feed.", element.getText().contains("Kelly Doctor viewed patient's immunization report")); assertFalse("DLHCP activity that is supposed to be hidden is shown in Activity Feed.", element.getText().contains("Kelly Doctor viewed your health records history today")); assertFalse("DLHCP activity that is supposed to be hidden is shown in Activity Feed.", element.getText().contains("Kelly Doctor edited your demographics")); assertTrue("DLHCP activity that is supposed to shown is not present in Activity Feed.", element.getText().contains("Kelly Doctor added you to the telemedicine monitoring list")); } }
6,516
38.49697
112
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/selenium/AddPatientTest.java
package edu.ncsu.csc.itrust.selenium; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import edu.ncsu.csc.itrust.model.old.enums.TransactionType; public class AddPatientTest extends iTrustSeleniumTest { protected WebDriver driver; @Override protected void setUp() throws Exception { super.setUp(); gen.clearAllTables(); gen.standardData(); } public void testBlankPatientName() throws Exception { // Login driver = login("9000000000", "pw"); assertEquals("iTrust - HCP Home", driver.getTitle()); assertLogged(TransactionType.HOME_VIEW, 9000000000L, 0L, ""); // Click the add patients link driver.findElement(By.linkText("Patient")).click(); assertEquals("iTrust - Add Patient", driver.getTitle()); // Enter in information but blank first name driver.findElement(By.xpath("//input[@name='firstName']")).sendKeys(""); driver.findElement(By.xpath("//input[@name='lastName']")).sendKeys("Doe"); driver.findElement(By.xpath("//input[@name='email']")).sendKeys("john.doe@example.com"); driver.findElement(By.xpath("//input[@type='submit']")).click(); assertTrue(driver.findElement(By.xpath("//body")).getText() .contains("This form has not been validated correctly.")); // Enter in information but blank last name driver.findElement(By.xpath("//input[@name='firstName']")).sendKeys("John"); driver.findElement(By.xpath("//input[@name='lastName']")).sendKeys(""); driver.findElement(By.xpath("//input[@name='email']")).sendKeys("john.doe@example.com"); driver.findElement(By.xpath("//input[@type='submit']")).click(); assertTrue(driver.findElement(By.xpath("//body")).getText() .contains("This form has not been validated correctly.")); } public void testInvalidPatientName() throws Exception { // Login driver = login("9000000000", "pw"); assertEquals("iTrust - HCP Home", driver.getTitle()); assertLogged(TransactionType.HOME_VIEW, 9000000000L, 0L, ""); // Click the add patients link driver.findElement(By.linkText("Patient")).click(); assertEquals("iTrust - Add Patient", driver.getTitle()); // Enter in information but invalid first name driver.findElement(By.xpath("//input[@name='firstName']")).sendKeys("----"); driver.findElement(By.xpath("//input[@name='lastName']")).sendKeys("Doe"); driver.findElement(By.xpath("//input[@name='email']")).sendKeys("john.doe@example.com"); driver.findElement(By.xpath("//input[@type='submit']")).click(); assertTrue(driver.findElement(By.xpath("//body")).getText() .contains("This form has not been validated correctly.")); // Enter in information but invalid last name driver.findElement(By.xpath("//input[@name='firstName']")).sendKeys("John"); driver.findElement(By.xpath("//input[@name='lastName']")).sendKeys("----"); driver.findElement(By.xpath("//input[@name='email']")).sendKeys("john.doe@example.com"); driver.findElement(By.xpath("//input[@type='submit']")).click(); assertTrue(driver.findElement(By.xpath("//body")).getText() .contains("This form has not been validated correctly.")); } // Should pass with email changes public void testInvalidPatientEmail() throws Exception { // Login driver = login("9000000000", "pw"); assertEquals("iTrust - HCP Home", driver.getTitle()); assertLogged(TransactionType.HOME_VIEW, 9000000000L, 0L, ""); // Click the add patients link driver.findElement(By.linkText("Patient")).click(); assertEquals("iTrust - Add Patient", driver.getTitle()); // Enter in information but invalid email driver.findElement(By.xpath("//input[@name='firstName']")).sendKeys("John"); driver.findElement(By.xpath("//input[@name='lastName']")).sendKeys("Doe"); driver.findElement(By.xpath("//input[@name='email']")).sendKeys("---@---.com"); driver.findElement(By.xpath("//input[@type='submit']")).click(); assertFalse(driver.findElement(By.xpath("//body")).getText() .contains("This form has not been validated correctly.")); } }
3,964
42.097826
90
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/selenium/AppointmentRequestTest.java
package edu.ncsu.csc.itrust.selenium; import java.text.SimpleDateFormat; import java.util.Calendar; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.ui.Select; import edu.ncsu.csc.itrust.model.old.enums.TransactionType; public class AppointmentRequestTest extends iTrustSeleniumTest { WebDriver driver; WebElement element; @Override protected void setUp() throws Exception { super.setUp(); gen.clearAllTables(); gen.standardData(); gen.hcp9(); } public void testAppointmnetRequestExpire() throws Exception { driver = login("9000000010", "pw"); // log in as Zoidberg assertEquals("iTrust - HCP Home", driver.getTitle()); // go to the page element = driver.findElement(By.linkText("Appointment Requests")); element.click(); assertEquals("iTrust - View My Appointment Requests", driver.getTitle()); assertLogged(TransactionType.APPOINTMENT_REQUEST_VIEW, 9000000010L, 0L, ""); assertFalse(driver.findElement(By.xpath("//*[@id='iTrustContent']")).getText() .contains("Request from: Philip Fry")); } public void testPatientAppointmentRequestNoConflict() throws Exception { driver = login("26", "pw"); // log in as Philip Fry assertEquals("iTrust - Patient Home", driver.getTitle()); // go to the page element = driver.findElement(By.linkText("Appointment Requests")); element.click(); assertEquals("iTrust - Appointment Requests", driver.getTitle()); // create date info Calendar cal = Calendar.getInstance(); SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy"); cal.add(Calendar.DAY_OF_YEAR, 1); // fill form Select select; select = new Select(driver.findElement(By.name("apptType"))); select.selectByValue("General Checkup"); select = new Select(driver.findElement(By.name("time1"))); select.selectByValue("09"); select = new Select(driver.findElement(By.name("time2"))); select.selectByValue("45"); select = new Select(driver.findElement(By.name("time3"))); element = driver.findElement(By.name("startDate")); element.clear(); element.sendKeys(format.format(cal.getTime())); ; element.submit(); // confirm that the request was accepted assertEquals("iTrust - Appointment Requests", driver.getTitle()); assertTrue(driver.findElement(By.xpath("//*[@id='iTrustContent']")).getText() .contains("Your appointment request has been saved and is pending.")); assertLogged(TransactionType.APPOINTMENT_REQUEST_SUBMITTED, 26L, 9000000000L, ""); } public void testBadDate() throws Exception { driver = login("26", "pw"); // log in as Philip Fry assertEquals("iTrust - Patient Home", driver.getTitle()); // go to the page element = driver.findElement(By.linkText("Appointment Requests")); element.click(); assertEquals("iTrust - Appointment Requests", driver.getTitle()); // fill form Select select; select = new Select(driver.findElement(By.name("apptType"))); select.selectByValue("General Checkup"); select = new Select(driver.findElement(By.name("time1"))); select.selectByValue("09"); select = new Select(driver.findElement(By.name("time2"))); select.selectByValue("45"); select = new Select(driver.findElement(By.name("time3"))); element = driver.findElement(By.name("startDate")); element.clear(); element.sendKeys("123/12/2014"); element.submit(); // Verify that the form was rejected assertTrue(driver.getPageSource().contains("ERROR: Date must by in the format: MM/dd/yyyy")); } }
3,536
33.676471
95
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/selenium/AppointmentTest.java
package edu.ncsu.csc.itrust.selenium; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.htmlunit.HtmlUnitDriver; import org.openqa.selenium.support.ui.Select; import edu.ncsu.csc.itrust.model.old.enums.TransactionType; public class AppointmentTest extends iTrustSeleniumTest { @Override protected void setUp() throws Exception { super.setUp(); gen.clearAllTables(); gen.standardData(); } public void testAddApptPatientDeceased() throws Exception { // Login as HCP Kelly Doctor WebDriver driver = login("9000000000", "pw"); assertLogged(TransactionType.HOME_VIEW, 9000000000L, 0L, ""); WebElement element; // go to the schedule appointment page element = driver.findElement(By.linkText("Schedule Appointment")); element.click(); // use the old search to go to the patients page element = driver.findElement(By.name("UID_PATIENTID")); element.sendKeys("2"); element = driver.findElement(By.id("mainForm")); element.submit(); // check to confirm cannot schedule appointment with dead patient element = driver.findElement(By.xpath("//*[@id='mainForm']/div/span")); assertTrue(element.getText().contains("Cannot schedule appointment")); } public void testEditApptConflictCancel() throws Exception { // Login as HCP Kelly Doctor gen.uc22(); HtmlUnitDriver driver = (HtmlUnitDriver) login("9000000000", "pw"); driver.setJavascriptEnabled(true); assertLogged(TransactionType.HOME_VIEW, 9000000000L, 0L, ""); WebElement element; element = driver.findElement(By.linkText("View My Appointments")); element.click(); new SimpleDateFormat("MM/dd/yyyy hh:mm a"); DateFormat format2 = new SimpleDateFormat("MM/dd/yyyy"); Calendar c = Calendar.getInstance(); c.add(Calendar.DATE, 12); c.set(Calendar.HOUR, 9); c.set(Calendar.AM_PM, Calendar.AM); c.set(Calendar.MINUTE, 45); // edit first entry to the desired time element = driver.findElements(By.linkText("Edit/Remove")).get(7); element.click(); assertTrue(driver.getCurrentUrl().contains("http://localhost:8080/iTrust/auth/hcp/editAppt.jsp")); c.add(Calendar.DATE, -5); c.set(Calendar.HOUR, 10); c.set(Calendar.AM_PM, Calendar.AM); c.set(Calendar.MINUTE, 00); // fill form Select select; select = new Select(driver.findElement(By.name("apptType"))); select.selectByIndex(0); select = new Select(driver.findElement(By.name("time1"))); select.selectByIndex(9); select = new Select(driver.findElement(By.name("time2"))); select.selectByIndex(0); select = new Select(driver.findElement(By.name("time3"))); select.selectByIndex(0); element = driver.findElement(By.name("schedDate")); element.clear(); element.sendKeys(format2.format(c.getTime())); driver.findElement(By.id("changeButton")).click(); assertTrue(driver.getPageSource().contains("Warning")); assertNotLogged(TransactionType.APPOINTMENT_ADD, 9000000000L, 1L, ""); // click 'cancel' driver.findElement(By.id("cancel")).click(); // fill form select = new Select(driver.findElement(By.name("apptType"))); select.selectByIndex(0); select = new Select(driver.findElement(By.name("time1"))); select.selectByIndex(1); select = new Select(driver.findElement(By.name("time2"))); select.selectByIndex(0); select = new Select(driver.findElement(By.name("time3"))); select.selectByIndex(1); element = driver.findElement(By.name("schedDate")); element.clear(); element.sendKeys(format2.format(c.getTime())); driver.findElement(By.id("changeButton")).click(); // confirm warning displayed and appointment not edited assertFalse(driver.getPageSource().contains("Warning")); } public void testAddApptConflictNoOverride() throws Exception { gen.uc22(); // Login WebDriver driver = login("9000000000", "pw"); assertLogged(TransactionType.HOME_VIEW, 9000000000L, 0L, ""); WebElement element; element = driver.findElement(By.linkText("Schedule Appointment")); element.click(); // use the old search to go to the patients page element = driver.findElement(By.name("UID_PATIENTID")); element.sendKeys("100"); element = driver.findElement(By.id("mainForm")); element.submit(); // set up date Calendar cal = Calendar.getInstance(); SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy"); cal.add(Calendar.DAY_OF_YEAR, 7); // fill out form Select select; select = new Select(driver.findElement(By.name("apptType"))); select.selectByValue("Physical"); select = new Select(driver.findElement(By.name("time1"))); select.selectByValue("09"); select = new Select(driver.findElement(By.name("time2"))); select.selectByValue("45"); select = new Select(driver.findElement(By.name("time3"))); select.selectByValue("AM"); element = driver.findElement(By.name("schedDate")); element.clear(); element.sendKeys(format.format(cal.getTime())); element.submit(); // check to make sure warning displayed and add is not logged element = driver.findElement(By.xpath("//*[@id='conflictTable']/span")); assertTrue(element.getText().contains("Warning")); assertNotLogged(TransactionType.APPOINTMENT_ADD, 9000000000L, 100L, ""); } public void testViewApptWithConflicts() throws Exception { gen.uc22(); // Login WebDriver driver = login("100", "pw"); assertLogged(TransactionType.HOME_VIEW, 100L, 0L, ""); WebElement element; // go to the View My Appointments link element = driver.findElement(By.linkText("View My Appointments")); element.click(); // confirm that appointments are showing assertFalse(driver.getPageSource().contains("You have no appointments")); assertLogged(TransactionType.APPOINTMENT_ALL_VIEW, 100L, 0L, ""); } public void testAddApptSameEndStartTimes() throws Exception { gen.uc22(); // Login WebDriver driver = login("9000000000", "pw"); assertLogged(TransactionType.HOME_VIEW, 9000000000L, 0L, ""); WebElement element; element = driver.findElement(By.linkText("Schedule Appointment")); element.click(); // use the old search to go to the patients page element = driver.findElement(By.name("UID_PATIENTID")); element.sendKeys("100"); element = driver.findElement(By.id("mainForm")); element.submit(); // set up date Calendar cal = Calendar.getInstance(); SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy"); cal.add(Calendar.DAY_OF_YEAR, 1); // fill out form Select select; select = new Select(driver.findElement(By.name("apptType"))); select.selectByValue("Physical"); select = new Select(driver.findElement(By.name("time1"))); select.selectByValue("10"); select = new Select(driver.findElement(By.name("time2"))); select.selectByValue("30"); select = new Select(driver.findElement(By.name("time3"))); select.selectByValue("AM"); element = driver.findElement(By.name("schedDate")); element.clear(); element.sendKeys(format.format(cal.getTime())); element.submit(); // check that the appointment was successfully added assertTrue(driver.findElement(By.xpath("//*[@id='apptDiv']/span[1]")).getText().contains("Success: Physical")); assertLogged(TransactionType.APPOINTMENT_ADD, 9000000000L, 100L, ""); } public void testAddApptInvalidDate() throws Exception { gen.uc22(); // Login WebDriver driver = login("9000000000", "pw"); assertLogged(TransactionType.HOME_VIEW, 9000000000L, 0L, ""); WebElement element; element = driver.findElement(By.linkText("Schedule Appointment")); element.click(); // use the old search to go to the patients page element = driver.findElement(By.name("UID_PATIENTID")); element.sendKeys("100"); element = driver.findElement(By.id("mainForm")); element.submit(); // fill out form Select select; select = new Select(driver.findElement(By.name("apptType"))); select.selectByValue("Physical"); select = new Select(driver.findElement(By.name("time1"))); select.selectByValue("09"); select = new Select(driver.findElement(By.name("time2"))); select.selectByValue("45"); select = new Select(driver.findElement(By.name("time3"))); select.selectByValue("AM"); element = driver.findElement(By.name("schedDate")); element.clear(); element.sendKeys("38/38/2025"); element.submit(); // check to make sure that appointment with invalid date was not added assertNotLogged(TransactionType.APPOINTMENT_ADD, 9000000000L, 100L, ""); } }
8,517
33.346774
113
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/selenium/AppointmentTypeTest.java
package edu.ncsu.csc.itrust.selenium; import java.sql.Timestamp; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Iterator; import java.util.List; import org.junit.Before; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.htmlunit.HtmlUnitDriver; import org.openqa.selenium.support.ui.Select; import edu.ncsu.csc.itrust.model.old.enums.TransactionType; public class AppointmentTypeTest extends iTrustSeleniumTest { private WebDriver driver = null; @Override @Before public void setUp() throws Exception { // Create a new instance of the driver driver = new HtmlUnitDriver(); super.setUp(); gen.clearAllTables(); gen.standardData(); } public void testAddAppointmentType() throws Exception { // HCP 9000000001 logs in. driver = login("9000000001", "pw"); assertTrue(driver.getTitle().contains("iTrust - Admin Home")); assertLogged(TransactionType.HOME_VIEW, 9000000001L, 0L, ""); // HCP 9000000001 moves to the edit appointment types page. driver.findElement(By.linkText("Edit Appointment Types")).click(); assertTrue(driver.getPageSource().contains("iTrust - Maintain Appointment Types")); assertLogged(TransactionType.APPOINTMENT_TYPE_VIEW, 9000000001L, 0L, ""); // HCP 9000000001 adds a new appointment type. driver.findElement(By.name("name")).sendKeys("Immunization"); driver.findElement(By.name("duration")).sendKeys("30"); driver.findElement(By.name("add")).click(); assertLogged(TransactionType.APPOINTMENT_TYPE_ADD, 9000000001L, 0L, ""); assertLogged(TransactionType.APPOINTMENT_TYPE_VIEW, 9000000001L, 0L, ""); } public void testEditAppointmentTypeDuration() throws Exception { // HCP 9000000001 logs in. driver = login("9000000001", "pw"); assertTrue(driver.getTitle().contains("iTrust - Admin Home")); assertLogged(TransactionType.HOME_VIEW, 9000000001L, 0L, ""); // HCP 9000000001 moves to the edit appointment types page. driver.findElement(By.linkText("Edit Appointment Types")).click(); assertTrue(driver.getPageSource().contains("iTrust - Maintain Appointment Types")); assertLogged(TransactionType.APPOINTMENT_TYPE_VIEW, 9000000001L, 0L, ""); // HCP 9000000001 edits an existing appointment type. driver.findElement(By.name("name")).sendKeys("Physical"); driver.findElement(By.name("duration")).sendKeys("45"); driver.findElement(By.name("update")).click(); assertLogged(TransactionType.APPOINTMENT_TYPE_EDIT, 9000000001L, 0L, ""); assertLogged(TransactionType.APPOINTMENT_TYPE_VIEW, 9000000001L, 0L, ""); } public void testEditAppointmentTypeDurationStringInput() throws Exception { // HCP 9000000001 logs in. driver = login("9000000001", "pw"); assertTrue(driver.getTitle().contains("iTrust - Admin Home")); assertLogged(TransactionType.HOME_VIEW, 9000000001L, 0L, ""); // HCP 9000000001 moves to the edit appointment types page. driver.findElement(By.linkText("Edit Appointment Types")).click(); assertTrue(driver.getPageSource().contains("iTrust - Maintain Appointment Types")); assertLogged(TransactionType.APPOINTMENT_TYPE_VIEW, 9000000001L, 0L, ""); // HCP 9000000001 edits an existing appointment type with a bad // duration. driver.findElement(By.name("name")).sendKeys("Physical"); driver.findElement(By.name("duration")).sendKeys("foo"); driver.findElement(By.name("update")).click(); assertNotLogged(TransactionType.APPOINTMENT_TYPE_EDIT, 9000000001L, 0L, ""); assertTrue(driver.getPageSource().contains("Error: Physical - Duration: must be an integer value.")); assertLogged(TransactionType.APPOINTMENT_TYPE_VIEW, 9000000001L, 0L, ""); } public void testScheduleAppointment() throws Exception { // HCP 9000000000 logs in. driver = login("9000000000", "pw"); assertTrue(driver.getTitle().contains("iTrust - HCP Home")); assertLogged(TransactionType.HOME_VIEW, 9000000000L, 0L, ""); // HCP 9000000000 moves to the schedule new appointment page. driver.findElement(By.linkText("Schedule Appointment")).click(); assertTrue(driver.getPageSource().contains("iTrust - Please Select a Patient")); // HCP 9000000000 selects patient 1 driver.findElement(By.name("UID_PATIENTID")).sendKeys("1"); driver.findElement(By.cssSelector("input[value='1']")).submit(); assertTrue(driver.getPageSource().contains("iTrust - Schedule an Appointment")); // HCP 9000000000 inputs the appointment information and submits int year = Calendar.getInstance().get(Calendar.YEAR) + 1; String scheduledDate = "07/06/" + year; Select dropdown = new Select(driver.findElement(By.name("apptType"))); dropdown.selectByValue("General Checkup"); driver.findElement(By.name("schedDate")).clear(); driver.findElement(By.name("schedDate")).sendKeys(scheduledDate); dropdown = new Select(driver.findElement(By.name("time1"))); dropdown.selectByValue("09"); dropdown = new Select(driver.findElement(By.name("time2"))); dropdown.selectByValue("00"); dropdown = new Select(driver.findElement(By.name("time3"))); dropdown.selectByValue("AM"); driver.findElement(By.name("comment")).sendKeys("This is the next checkup for your blood pressure medication."); driver.findElement(By.name("scheduleButton")).submit(); assertTrue(driver.getPageSource().contains("iTrust - Schedule an Appointment")); assertTrue(driver.getPageSource().contains("Success")); } public void testPatientViewUpcomingAppointments() throws Exception { gen.clearAppointments(); gen.appointmentCase1(); // Patient 2 logs in. driver = login("2", "pw"); assertTrue(driver.getTitle().contains("iTrust - Patient Home")); assertLogged(TransactionType.HOME_VIEW, 2L, 0L, ""); // Patient 2 moves to the view my appointments page. driver.findElement(By.linkText("View My Appointments")).click(); Thread.sleep(1000); assertTrue(driver.getPageSource().contains("iTrust - View My Messages")); // Create timestamp DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy"); Timestamp time = new Timestamp(new Date().getTime()); // Patient 2 checks for the right appointments WebElement tableElem = driver.findElements(By.tagName("table")).get(0); List<WebElement> tableData = tableElem.findElements(By.tagName("tr")); Iterator<WebElement> rowsOnTable = tableData.iterator(); int x = 0; while (rowsOnTable.hasNext()) { WebElement row = rowsOnTable.next(); if (x == 1) { Timestamp time1 = new Timestamp(time.getTime() + (14 * 24 * 60 * 60 * 1000)); String dt1 = dateFormat.format(new Date(time1.getTime())); assertTrue(row.getText().contains("Kelly Doctor")); assertTrue(row.getText().contains("General Checkup")); assertTrue(row.getText().contains(dt1 + " 10:30 AM")); assertTrue(row.getText().contains("45 minutes")); assertTrue(row.getText().contains("Read Comment")); } else if (x == 2) { assertTrue(row.getText().contains("Kelly Doctor")); assertTrue(row.getText().contains("Consultation")); assertTrue(row.getText() .contains("06/04/" + (Calendar.getInstance().get(Calendar.YEAR) + 1) + " 10:30 AM")); assertTrue(row.getText().contains("30 minutes")); assertTrue(row.getText().contains("Read Comment")); } else if (x == 3) { assertTrue(row.getText().contains("Kelly Doctor")); assertTrue(row.getText().contains("Colonoscopy")); assertTrue(row.getText() .contains("10/14/" + (Calendar.getInstance().get(Calendar.YEAR) + 1) + " 08:00 AM")); assertTrue(row.getText().contains("90 minutes")); assertTrue(row.getText().contains("No Comment")); } x++; } assertLogged(TransactionType.APPOINTMENT_ALL_VIEW, 2L, 0L, ""); } public void testHcpViewUpcomingAppointments() throws Exception { // Create DB for this test case gen.clearAppointments(); gen.appointmentCase2(); // HCP 9000000000 logs in. driver = login("9000000000", "pw"); assertTrue(driver.getTitle().contains("iTrust - HCP Home")); assertLogged(TransactionType.HOME_VIEW, 9000000000L, 0L, ""); // HCP 9000000000 moves to the view my appointments page. driver.findElement(By.linkText("View My Appointments")).click(); Thread.sleep(1000); assertTrue(driver.getPageSource().contains("iTrust - View My Messages")); // Create timestamp DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy"); Timestamp time = new Timestamp(new Date().getTime()); // HCP 9000000000 checks for the right appointments WebElement tableElem = driver.findElements(By.tagName("table")).get(0); List<WebElement> tableData = tableElem.findElements(By.tagName("tr")); Iterator<WebElement> rowsOnTable = tableData.iterator(); int x = 0; while (rowsOnTable.hasNext()) { WebElement row = rowsOnTable.next(); if (x == 1) { Timestamp time1 = new Timestamp(time.getTime() + (7 * 24 * 60 * 60 * 1000)); String dt1 = dateFormat.format(new Date(time1.getTime())); assertTrue(row.getText().contains("Random Person")); assertTrue(row.getText().contains("Consultation")); assertTrue(row.getText().contains(dt1 + " 09:10 AM")); assertTrue(row.getText().contains("30 minutes")); assertTrue(row.getText().contains("No Comment")); } else if (x == 2) { Timestamp time1 = new Timestamp(time.getTime() + (7 * 24 * 60 * 60 * 1000)); String dt1 = dateFormat.format(new Date(time1.getTime())); assertTrue(row.getText().contains("Baby Programmer")); assertTrue(row.getText().contains("General Checkup")); assertTrue(row.getText().contains(dt1 + " 09:30 AM")); assertTrue(row.getText().contains("45 minutes")); assertTrue(row.getText().contains("Read Comment")); } else if (x == 3) { Timestamp time2 = new Timestamp(time.getTime() + (10 * 24 * 60 * 60 * 1000)); String dt2 = dateFormat.format(new Date(time2.getTime())); assertTrue(row.getText().contains("Baby Programmer")); assertTrue(row.getText().contains("General Checkup")); assertTrue(row.getText().contains(dt2 + " 04:00 PM")); assertTrue(row.getText().contains("45 minutes")); assertTrue(row.getText().contains("Read Comment")); } else if (x == 4) { Timestamp time3 = new Timestamp(time.getTime() + (14 * 24 * 60 * 60 * 1000)); String dt3 = dateFormat.format(new Date(time3.getTime())); assertTrue(row.getText().contains("Random Person")); assertTrue(row.getText().contains("Ultrasound")); assertTrue(row.getText().contains(dt3 + " 01:30 PM")); assertTrue(row.getText().contains("30 minutes")); assertTrue(row.getText().contains("No Comment")); } else if (x == 5) { Timestamp time3 = new Timestamp(time.getTime() + (14 * 24 * 60 * 60 * 1000)); String dt3 = dateFormat.format(new Date(time3.getTime())); assertTrue(row.getText().contains("Andy Programmer")); assertTrue(row.getText().contains("General Checkup")); assertTrue(row.getText().contains(dt3 + " 01:45 PM")); assertTrue(row.getText().contains("45 minutes")); assertTrue(row.getText().contains("No Comment")); } x++; } assertLogged(TransactionType.APPOINTMENT_ALL_VIEW, 9000000000L, 0L, ""); } public void testAddAppointmentTypeLengthZero() throws Exception { // HCP 9000000001 logs in. driver = login("9000000001", "pw"); assertTrue(driver.getTitle().contains("iTrust - Admin Home")); assertLogged(TransactionType.HOME_VIEW, 9000000001L, 0L, ""); // HCP 9000000001 moves to the edit appointment types page. driver.findElement(By.linkText("Edit Appointment Types")).click(); assertTrue(driver.getPageSource().contains("iTrust - Maintain Appointment Types")); assertLogged(TransactionType.APPOINTMENT_TYPE_VIEW, 9000000001L, 0L, ""); // HCP 9000000001 edits an existing appointment type. driver.findElement(By.name("name")).sendKeys("Immunization"); driver.findElement(By.name("duration")).sendKeys("0"); driver.findElement(By.name("add")).click(); assertTrue(driver.getPageSource().contains("This form has not been validated correctly.")); } }
12,053
43.810409
114
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/selenium/AuditPatientTest.java
package edu.ncsu.csc.itrust.selenium; import org.junit.Before; import org.junit.Test; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; /** * This class contains unit tests for UC1, formerly part of UC62 **/ public class AuditPatientTest extends iTrustSeleniumTest { @Override @Before public void setUp() throws Exception { super.setUp(); gen.clearAllTables(); gen.standardData(); } @Test public void testHCPDeactivatePatient() throws Exception { WebDriver driver = login("9000000000", "pw"); driver.findElement(By.linkText("Audit Patients")).click(); assertEquals(driver.getTitle(), "iTrust - Please Select a Patient"); // searching for patient 2 driver.findElement(By.name("UID_PATIENTID")).sendKeys("2"); driver.findElement(By.name("UID_PATIENTID")).submit(); assertEquals(driver.getTitle(), "iTrust - Audit Page (UC62)"); // typing out I understand driver.findElement(By.name("understand")).sendKeys("I UNDERSTAND"); driver.findElement(By.name("understand")).submit(); // asserting deletion assertEquals("Patient Successfully Deactivated", driver.findElement(By.className("iTrustMessage")).getText()); } public void testHCPDeactivatePatientWrongConfirmation() throws Exception { WebDriver driver = login("9000000000", "pw"); driver.findElement(By.linkText("Audit Patients")).click(); assertEquals(driver.getTitle(), "iTrust - Please Select a Patient"); // searching for patient 2 driver.findElement(By.name("UID_PATIENTID")).sendKeys("2"); driver.findElement(By.name("UID_PATIENTID")).submit(); assertEquals(driver.getTitle(), "iTrust - Audit Page (UC62)"); // typing out I understand driver.findElement(By.name("understand")).sendKeys("iunderstand"); driver.findElement(By.name("understand")).submit(); // asserting deletion assertEquals("You must type \"I UNDERSTAND\" in the textbox.", driver.findElement(By.className("iTrustError")).getText()); } public void testHCPActivatePatient() throws Exception { WebDriver driver = login("9000000000", "pw"); driver.findElement(By.linkText("Audit Patients")).click(); assertEquals(driver.getTitle(), "iTrust - Please Select a Patient"); // searching for patient 314159 driver.findElement(By.id("allowDeactivated")).click(); driver.findElement(By.name("UID_PATIENTID")).sendKeys("314159"); driver.findElement(By.name("UID_PATIENTID")).submit(); assertEquals(driver.getTitle(), "iTrust - Audit Page (UC62)"); // typing out I understand driver.findElement(By.name("understand")).sendKeys("I UNDERSTAND"); driver.findElement(By.name("understand")).submit(); // asserting activation assertEquals("Patient Successfully Activated", driver.findElement(By.className("iTrustMessage")).getText()); } public void testHCPActivatePatientWrongConfirmation() throws Exception { WebDriver driver = login("9000000000", "pw"); driver.findElement(By.linkText("Audit Patients")).click(); assertEquals(driver.getTitle(), "iTrust - Please Select a Patient"); // searching for patient 314159 driver.findElement(By.id("allowDeactivated")).click(); driver.findElement(By.name("UID_PATIENTID")).sendKeys("314159"); driver.findElement(By.name("UID_PATIENTID")).submit(); assertEquals(driver.getTitle(), "iTrust - Audit Page (UC62)"); // typing out I understand driver.findElement(By.name("understand")).sendKeys("iunderstand"); driver.findElement(By.name("understand")).submit(); // asserting activation assertEquals("You must type \"I UNDERSTAND\" in the textbox.", driver.findElement(By.className("iTrustError")).getText()); } }
3,621
34.861386
112
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/selenium/CalendarTest.java
package edu.ncsu.csc.itrust.selenium; import java.util.Calendar; import java.util.Iterator; import java.util.List; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import org.openqa.selenium.htmlunit.HtmlUnitDriver; import edu.ncsu.csc.itrust.model.old.enums.TransactionType; import edu.ncsu.csc.itrust.selenium.iTrustSeleniumTest; public class CalendarTest extends iTrustSeleniumTest { private HtmlUnitDriver driver = null; @Override protected void setUp() throws Exception { // Create a new instance of the driver driver = new HtmlUnitDriver(); super.setUp(); // clear tables is called in super gen.clearAllTables(); gen.standardData(); // gen.officeVisit5(); } @Override protected void tearDown() throws Exception { gen.clearAllTables(); // gen.standardData(); } public void testHCPViewAppointmentCalendar() throws Exception { // Login driver = (HtmlUnitDriver) login("9000000000", "pw"); assertTrue(driver.getTitle().contains("iTrust - HCP Home")); // Click Calendar driver.findElement(By.linkText("Appointment Calendar")).click(); // check title assertTrue(driver.getTitle().contains("Appointment Calendar")); assertLogged(TransactionType.CALENDAR_VIEW, 9000000000L, 0L, ""); // check for the right appointments WebElement tableElem = driver.findElement(By.id("calendarTable")); List<WebElement> tableData = tableElem.findElements(By.tagName("tr")); Iterator<WebElement> rowsOnTable = tableData.iterator(); while (rowsOnTable.hasNext()) { WebElement row = rowsOnTable.next(); List<WebElement> j = row.findElements(By.tagName("td")); Iterator<WebElement> columnsOnTable = j.iterator(); while (columnsOnTable.hasNext()) { WebElement column = columnsOnTable.next(); if (column.getText().startsWith("5")) { // On the 5th: 1:30PM - General Checkup assertTrue(column.getText().contains("General Checkup")); } else if (column.getText().startsWith("18")) { // On the 18th: 8:00AM - Colonoscopy assertTrue(column.getText().contains("Colonoscopy")); } else if (column.getText().startsWith("28")) { // On the 28th: 9:00AM - Physical assertTrue(column.getText().contains("Physical")); } } } } public void testHCPViewAppointmentCalendarDetails() throws Exception { // Login driver = (HtmlUnitDriver) login("9000000000", "pw"); assertTrue(driver.getTitle().contains("iTrust - HCP Home")); // Click Calendar driver.findElement(By.linkText("Appointment Calendar")).click(); // check title assertTrue(driver.getTitle().contains("Appointment Calendar")); assertLogged(TransactionType.CALENDAR_VIEW, 9000000000L, 0L, ""); List<WebElement> links = driver.findElements(By.tagName("a")); int count = 0; // get the second link with General Checkup-5 for (int i = 0; i < links.size(); i++) { String name = links.get(i).getAttribute("name"); if (name != null && name.contains("General Checkup-5")) { count++; if (count == 2) { links.get(i).click(); break; } } } // ensure proper data is showing up assertTrue(driver.getPageSource().contains("Andy Programmer")); assertTrue(driver.getPageSource().contains("General Checkup")); assertTrue(driver.getPageSource().contains("45 minutes")); assertTrue(driver.getPageSource().contains("No Comment")); // get the current month and year Calendar cal = Calendar.getInstance(); int month1 = cal.get(Calendar.MONTH) + 1; int day1 = 5; int year1 = cal.get(Calendar.YEAR); assertTrue(driver.getPageSource().contains(month1 + "/0" + day1 + "/" + year1 + " 09:10 AM")); } }
3,634
29.546218
96
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/selenium/ChangePasswordTest.java
package edu.ncsu.csc.itrust.selenium; import java.util.List; import org.junit.Before; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.htmlunit.HtmlUnitDriver; import edu.ncsu.csc.itrust.model.old.enums.TransactionType; public class ChangePasswordTest extends iTrustSeleniumTest { private WebDriver driver = null; @Override @Before public void setUp() throws Exception { // Create a new instance of the driver driver = new HtmlUnitDriver(); super.setUp(); gen.clearAllTables(); gen.standardData(); } public void testChangePassword_Invalid_Length() throws Exception { // Patient1 logs into iTrust driver = login("1", "pw"); assertTrue(driver.getTitle().contains("iTrust - Patient Home")); // User goes to change password List<WebElement> links = driver.findElements(By.tagName("a")); int count = 0; for (int i = 0; i < links.size(); i++) { if (links.get(i).getAttribute("href").contains("changePassword")) { count = i; break; } } links.get(count).click(); // User types in their current, new, and confirm passwords driver.findElement(By.name("oldPass")).sendKeys("pw"); driver.findElement(By.name("newPass")).sendKeys("pas1"); driver.findElement(By.name("confirmPass")).sendKeys("pas1"); driver.findElement(By.name("oldPass")).submit(); // User submits password change. Change logged assertTrue(driver.getPageSource().contains("Invalid password")); assertLogged(TransactionType.PASSWORD_CHANGE_FAILED, 1L, 0, ""); // User logs out links = driver.findElements(By.tagName("a")); links.get(count - 1).click(); // User can log in with old password, but can't with new one try { driver = login("1", "pas1"); fail("Should have thrown an exception"); } catch (IllegalArgumentException d) { assertTrue(driver.getTitle().contains("iTrust - Login")); driver = login("1", "pw"); assertTrue(driver.getTitle().contains("iTrust - Patient Home")); } } public void testChangePassword_Invalid_Characters() throws Exception { // Patient1 logs into iTrust driver = login("1", "pw"); assertTrue(driver.getTitle().contains("iTrust - Patient Home")); // User goes to change password List<WebElement> links = driver.findElements(By.tagName("a")); int count = 0; for (int i = 0; i < links.size(); i++) { if (links.get(i).getAttribute("href").contains("changePassword")) { count = i; break; } } links.get(count).click(); // User types in their current, new, and confirm passwords driver.findElement(By.name("oldPass")).sendKeys("pw"); driver.findElement(By.name("newPass")).sendKeys("password"); driver.findElement(By.name("confirmPass")).sendKeys("password"); driver.findElement(By.name("oldPass")).submit(); // User submits password change. Change logged assertTrue(driver.getPageSource().contains("Invalid password")); assertLogged(TransactionType.PASSWORD_CHANGE_FAILED, 1L, 0, ""); // User logs out links = driver.findElements(By.tagName("a")); links.get(count - 1).click(); // User can log in with old password, but can't with new one try { driver = login("1", "password"); fail("Should have thrown an exception"); } catch (IllegalArgumentException d) { assertTrue(driver.getTitle().contains("iTrust - Login")); driver = login("1", "pw"); assertTrue(driver.getTitle().contains("iTrust - Patient Home")); } } public void testChangePassword_Failed_Confirmation() throws Exception { // Patient1 logs into iTrust driver = login("1", "pw"); assertTrue(driver.getTitle().contains("iTrust - Patient Home")); // User goes to change password List<WebElement> links = driver.findElements(By.tagName("a")); int count = 0; for (int i = 0; i < links.size(); i++) { if (links.get(i).getAttribute("href").contains("changePassword")) { count = i; break; } } links.get(count).click(); // User types in their current, new, and confirm passwords driver.findElement(By.name("oldPass")).sendKeys("pw"); driver.findElement(By.name("newPass")).sendKeys("pass1"); driver.findElement(By.name("confirmPass")).sendKeys("pass2"); driver.findElement(By.name("oldPass")).submit(); // User submits password change. Change logged assertTrue(driver.getPageSource().contains("Invalid password")); assertLogged(TransactionType.PASSWORD_CHANGE_FAILED, 1L, 0, ""); // User logs out links = driver.findElements(By.tagName("a")); links.get(count - 1).click(); // User can log in with old password, but can't with new one try { driver = login("1", "pas1"); fail("Should have thrown an exception"); } catch (IllegalArgumentException d) { assertTrue(driver.getTitle().contains("iTrust - Login")); driver = login("1", "pw"); assertTrue(driver.getTitle().contains("iTrust - Patient Home")); } } public void testChangePassword_Invalid_Password() throws Exception { // Patient1 logs into iTrust driver = login("1", "pw"); assertTrue(driver.getTitle().contains("iTrust - Patient Home")); // User goes to change password List<WebElement> links = driver.findElements(By.tagName("a")); int count = 0; for (int i = 0; i < links.size(); i++) { if (links.get(i).getAttribute("href").contains("changePassword")) { count = i; break; } } links.get(count).click(); // User types in their current, new, and confirm passwords driver.findElement(By.name("oldPass")).sendKeys("password"); driver.findElement(By.name("newPass")).sendKeys("pass1"); driver.findElement(By.name("confirmPass")).sendKeys("pass1"); driver.findElement(By.name("oldPass")).submit(); // User submits password change. Change logged assertTrue(driver.getPageSource().contains("Invalid password")); assertLogged(TransactionType.PASSWORD_CHANGE_FAILED, 1L, 0, ""); // User logs out links = driver.findElements(By.tagName("a")); links.get(count - 1).click(); // User can log in with old password, but can't with new one try { driver = login("1", "pass1"); fail("Should have thrown an exception"); } catch (IllegalArgumentException d) { assertTrue(driver.getTitle().contains("iTrust - Login")); driver = login("1", "pw"); assertTrue(driver.getTitle().contains("iTrust - Patient Home")); } } }
6,339
30.231527
72
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/selenium/ComprehensiveReportingTest.java
package edu.ncsu.csc.itrust.selenium; import org.junit.Before; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import edu.ncsu.csc.itrust.model.old.enums.TransactionType; public class ComprehensiveReportingTest extends iTrustSeleniumTest { // private static WebDriver driver = null; @Override @Before public void setUp() throws Exception { // Create a new instance of the driver // driver = new HtmlUnitDriver(); super.setUp(); gen.clearAllTables(); gen.standardData(); } public void testComprehensiveAcceptanceSuccess() throws Exception { // HCP 9000000000 logs in WebDriver driver = login("9000000000", "pw"); assertTrue(driver.getTitle().contains("iTrust - HCP Home")); assertLogged(TransactionType.HOME_VIEW, 9000000000L, 0L, ""); // HCP 9000000000 moves to the add new report request page driver.findElement(By.linkText("My Report Requests")).click(); driver.findElement(By.linkText("Add a new Report Request")).click(); assertTrue(driver.getPageSource().contains("Please Select a Patient")); // HCP 9000000000 requests a report on patient 2 driver.findElement(By.name("UID_PATIENTID")).sendKeys("2"); driver.findElement(By.cssSelector("input[value='2']")).submit(); assertTrue(driver.getPageSource().contains("Report Request Accepted")); assertLogged(TransactionType.COMPREHENSIVE_REPORT_ADD, 9000000000L, 2L, "Report ID:"); } public void testHCPChoosesInvalidPatient() throws Exception { // HCP 9000000000 logs in WebDriver driver = login("9000000000", "pw"); assertTrue(driver.getTitle().contains("iTrust - HCP Home")); assertLogged(TransactionType.HOME_VIEW, 9000000000L, 0L, ""); // HCP 9000000000 moves to the add new report request page driver.findElement(By.linkText("My Report Requests")).click(); driver.findElement(By.linkText("Add a new Report Request")).click(); assertTrue(driver.getPageSource().contains("Please Select a Patient")); // HCP 9000000000 requests a report on patient 260 driver.findElement(By.name("UID_PATIENTID")).sendKeys("260"); driver.findElement(By.cssSelector("input[value='260']")).submit(); assertNotLogged(TransactionType.COMPREHENSIVE_REPORT_ADD, 9000000000L, 23L, "Report ID:"); } public void testHCPChoosesIncorrectPatient() throws Exception { // HCP 9000000000 logs in WebDriver driver = login("9000000000", "pw"); assertTrue(driver.getTitle().contains("iTrust - HCP Home")); assertLogged(TransactionType.HOME_VIEW, 9000000000L, 0L, ""); // HCP 9000000000 moves to the add new report request page driver.findElement(By.linkText("My Report Requests")).click(); driver.findElement(By.linkText("Add a new Report Request")).click(); assertTrue(driver.getPageSource().contains("Please Select a Patient")); // HCP 9000000000 requests a report on patient 260 driver.findElement(By.name("UID_PATIENTID")).sendKeys("2"); assertNotLogged(TransactionType.COMPREHENSIVE_REPORT_ADD, 9000000000L, 2L, "Report ID:"); } }
2,979
40.388889
92
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/selenium/ConsultationTest.java
package edu.ncsu.csc.itrust.selenium; import org.junit.Before; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.htmlunit.HtmlUnitDriver; import org.junit.*; public class ConsultationTest extends iTrustSeleniumTest { private WebDriver driver; @Override @Before public void setUp() throws Exception { super.setUp(); gen.standardData(); // Create a new instance of the html unit driver driver = new HtmlUnitDriver(); // Navigate to desired web page driver.get("http://localhost:8080/iTrust/"); } @Test public void testSubmitAndReceiveConsultation() throws Exception { String expectedTitle = "iTrust - HCP Home"; driver.findElement(By.id("j_username")).sendKeys("9000000000"); driver.findElement(By.id("j_password")).sendKeys("pw"); driver.findElement(By.cssSelector("input[type=\"submit\"]")).click(); // get the title of the page String actualTitle = driver.getTitle(); // verify title assertEquals(actualTitle, expectedTitle); } @Test public void testSubmitAndEditConsultation() throws Exception { String expectedTitle = "iTrust - HCP Home"; driver.findElement(By.id("j_username")).sendKeys("9000000000"); driver.findElement(By.id("j_password")).sendKeys("pw"); driver.findElement(By.cssSelector("input[type=\"submit\"]")).click(); // get the title of the page String actualTitle = driver.getTitle(); // verify title assertEquals(actualTitle, expectedTitle); } @Test public void testReceiveAndEditConsultation() throws Exception { String expectedTitle = "iTrust - HCP Home"; driver.findElement(By.id("j_username")).sendKeys("9000000000"); driver.findElement(By.id("j_password")).sendKeys("pw"); driver.findElement(By.cssSelector("input[type=\"submit\"]")).click(); // get the title of the page String actualTitle = driver.getTitle(); // verify title assertEquals(actualTitle, expectedTitle); } }
1,926
29.587302
71
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/selenium/CreateHCPSpecTest.java
package edu.ncsu.csc.itrust.selenium; import org.openqa.selenium.*; import org.openqa.selenium.support.ui.Select; import edu.ncsu.csc.itrust.model.old.enums.TransactionType; public class CreateHCPSpecTest extends iTrustSeleniumTest { @Override protected void setUp() throws Exception { super.setUp(); gen.clearAllTables(); gen.standardData(); } public void testSpecialtyOnForm() throws Exception { WebDriver driver = login("9000000001", "pw"); assertLogged(TransactionType.HOME_VIEW, 9000000001L, 0L, ""); assertEquals("iTrust - Admin Home", driver.getTitle()); driver.findElement(By.linkText("Add HCP")).click(); assertEquals("iTrust - Add HCP", driver.getTitle()); driver.findElement(By.name("firstName")).sendKeys("Firstname"); driver.findElement(By.name("lastName")).sendKeys("Lastname"); driver.findElement(By.name("email")).sendKeys("abcdef@ncsu.edu"); Select select = new Select(driver.findElement(By.name("specialty"))); select.selectByValue("pediatrician"); driver.findElement(By.name("email")).submit(); } }
1,060
29.314286
71
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/selenium/CreateLTSpecTest.java
package edu.ncsu.csc.itrust.selenium; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.htmlunit.HtmlUnitDriver; import org.openqa.selenium.support.ui.Select; import edu.ncsu.csc.itrust.model.old.enums.TransactionType; /** * Makes sure the "specialty" field is available when adding an HCP, creates an * HCP with the specialty "Medicine", and makes sure that HCP was successfully * created. * */ public class CreateLTSpecTest extends iTrustSeleniumTest { /** * Gives us the standard testing data */ @Override protected void setUp() throws Exception { super.setUp(); gen.clearAllTables(); gen.standardData(); } /** * Test we can create HCP's as an admin */ public void testSpecialtyOnForm() throws Exception { // login admin WebDriver driver = new HtmlUnitDriver(); driver = login("9000000001", "pw"); assertEquals("iTrust - Admin Home", driver.getTitle()); assertLogged(TransactionType.HOME_VIEW, 9000000001L, 0L, ""); // click on add hcp driver.findElement(By.linkText("Add LT")).click(); // add the hcp assertEquals("iTrust - Add LT", driver.getTitle()); WebElement form = driver.findElement(By.tagName("form")); // fill in the information WebElement firstName = form.findElement(By.name("firstName")); firstName.sendKeys("New"); WebElement lastName = form.findElement(By.name("lastName")); lastName.sendKeys("Person"); WebElement email = form.findElement(By.name("email")); email.sendKeys("nperson@gmail.com"); // get the dropdown options for the apptType Select specialty = new Select(form.findElement(By.name("specialty"))); // make sure there is such a field assertFalse(specialty == null); String currentVal = specialty.getAllSelectedOptions().get(0).toString(); specialty.deselectByValue(currentVal); specialty.selectByValue("general"); /* * I know this seems crazy, selecting an option, and then creating a new * select option to make sure that the right option is selected before * we even submit the form, but this is as close to the previous test * this is based off of as I could think of making it. */ Select dropbox = new Select(form.findElement(By.name("specialty"))); assertEquals(1, dropbox.getAllSelectedOptions().size()); assertEquals("general", dropbox.getFirstSelectedOption().getAttribute(VALUE)); form.submit(); } }
2,433
32.342466
80
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/selenium/CreatePHATest.java
package edu.ncsu.csc.itrust.selenium; import java.util.List; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.htmlunit.HtmlUnitDriver; import edu.ncsu.csc.itrust.model.old.enums.TransactionType; public class CreatePHATest extends iTrustSeleniumTest { @Override protected void setUp() throws Exception { super.setUp(); gen.clearAllTables(); gen.admin1(); } public void testCreateNullPHA() throws Exception { // Log in as an Admin. WebDriver driver = new HtmlUnitDriver(); driver = login("9000000001", "pw"); assertLogged(TransactionType.HOME_VIEW, 9000000001L, 0L, ""); // Click on Add PHA. driver.findElement(By.linkText("Add PHA")).click(); assertEquals("iTrust - Add PHA", driver.getTitle()); // Add the PHA. WebElement elem = driver.findElement(By.name("firstName")); elem.submit(); // Make sure the text displays. List<WebElement> list = driver.findElements( By.xpath("//*[contains(text(),'" + "This form has not been validated correctly." + "')]")); assertTrue("Text not found!", list.size() > 0); // Make sure nothing happened. assertNotLogged(TransactionType.PHA_DISABLE, 9000000001L, 0L, ""); } }
1,248
26.152174
95
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/selenium/CreateUAPTest.java
package edu.ncsu.csc.itrust.selenium; import org.openqa.selenium.By; import org.openqa.selenium.NoSuchElementException; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.htmlunit.HtmlUnitDriver; /** * Test class for iTrust creation of UAP's. */ public class CreateUAPTest extends iTrustSeleniumTest { /** * Set up for testing by creating necessary data. */ @Override public void setUp() throws Exception { super.setUp(); gen.clearAllTables(); gen.admin1(); gen.hcp0(); } /** * Test creating a standard UAP. The form should submit without any issues. */ public void testCreateUAP1() throws Exception { WebDriver driver = new HtmlUnitDriver(); driver = login("9000000000", "pw"); driver.findElement(By.linkText("UAP")).click(); assertEquals("iTrust - Add UAP", driver.getTitle()); WebElement firstName = driver.findElement(By.name("firstName")); firstName.sendKeys("Drake"); WebElement lastName = driver.findElement(By.name("lastName")); lastName.sendKeys("Ramoray"); WebElement email = driver.findElement(By.name("email")); email.sendKeys("drake@drake.com"); WebElement form = driver.findElement(By.name("formIsFilled")); form.submit(); } /** * When creating a UAP, the entered email needs to be validated against the * RFC3696 specification. This specification allows for quoted strings, * escaped characters, and underscores. * * In this test, Joe Bob with the email _"joe@email"\\email@gmail.com should * validate. */ public void testCreateUAPRFC3696() throws Exception { try { // Log in HtmlUnitDriver driver = (HtmlUnitDriver) login("9000000000", "pw"); // Click on the add UAP link driver.findElement(By.linkText("UAP")).click(); // Fill in the fields driver.findElement(By.name("firstName")).sendKeys("Joe"); driver.findElement(By.name("lastName")).sendKeys("Bob"); String email = "_\"joe@email\"\\\\email@gmail.com"; driver.findElement(By.name("email")).sendKeys(email); // Submit driver.findElement(By.cssSelector("input[type='submit']")).click(); // Verify that the success text appears assertTrue("Success Message", driver.findElement(By.className("iTrustMessage")).getText().contains("succesfully added!")); } catch (NoSuchElementException e) { fail(e.getMessage()); } } }
2,369
29.384615
97
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/selenium/CreditCardValidatorTest.java
package edu.ncsu.csc.itrust.selenium; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.ui.Select; import edu.ncsu.csc.itrust.model.old.enums.TransactionType; public class CreditCardValidatorTest extends iTrustSeleniumTest { @Override protected void setUp() throws Exception { super.setUp(); gen.clearAllTables(); gen.patient1(); gen.clearLoginFailures(); } public void testGoodMasterCards() throws Exception { // login patient 2 WebDriver wd = login("1", "pw"); assertEquals("iTrust - Patient Home", wd.getTitle()); assertLogged(TransactionType.HOME_VIEW, 1L, 0L, ""); // click on My Demographics wd.findElement(By.linkText("My Demographics")).click(); assertLogged(TransactionType.DEMOGRAPHICS_VIEW, 1L, 1L, ""); Select creditCardType = new Select(wd.findElement(By.name("creditCardType"))); creditCardType.selectByVisibleText("Mastercard"); WebElement creditCardNumber = wd.findElement(By.name("creditCardNumber")); creditCardNumber.sendKeys("5593090746812380"); creditCardNumber.submit(); assertTrue(wd.findElement(By.tagName("body")).getText().contains("Information Successfully Updated")); assertLogged(TransactionType.DEMOGRAPHICS_EDIT, 1L, 1L, ""); creditCardNumber = wd.findElement(By.name("creditCardNumber")); creditCardNumber.clear(); creditCardNumber.sendKeys("5437693863890467"); creditCardNumber.submit(); assertTrue(wd.findElement(By.tagName("body")).getText().contains("Information Successfully Updated")); assertLogged(TransactionType.DEMOGRAPHICS_EDIT, 1L, 1L, ""); creditCardNumber = wd.findElement(By.name("creditCardNumber")); creditCardNumber.clear(); creditCardNumber.sendKeys("5343017708937494"); creditCardNumber.submit(); assertTrue(wd.findElement(By.tagName("body")).getText().contains("Information Successfully Updated")); assertLogged(TransactionType.DEMOGRAPHICS_EDIT, 1L, 1L, ""); } public void testBadMasterCards() throws Exception { // login patient 2 WebDriver wd = login("1", "pw"); assertEquals("iTrust - Patient Home", wd.getTitle()); assertLogged(TransactionType.HOME_VIEW, 1L, 0L, ""); // click on My Demographics wd.findElement(By.linkText("My Demographics")).click(); assertLogged(TransactionType.DEMOGRAPHICS_VIEW, 1L, 1L, ""); Select creditCardType = new Select(wd.findElement(By.name("creditCardType"))); creditCardType.selectByVisibleText("Mastercard"); WebElement creditCardNumber = wd.findElement(By.name("creditCardNumber")); creditCardNumber.sendKeys("1593090746812380"); creditCardNumber.submit(); assertTrue( wd.findElement(By.tagName("body")).getText().contains("not properly filled in: [Credit Card Number]")); assertNotLogged(TransactionType.DEMOGRAPHICS_EDIT, 1L, 1L, ""); creditCardType = new Select(wd.findElement(By.name("creditCardType"))); creditCardType.selectByVisibleText("Mastercard"); creditCardNumber = wd.findElement(By.name("creditCardNumber")); creditCardNumber.clear(); creditCardNumber.sendKeys("4539592576502361"); // Legit Visa creditCardNumber.submit(); assertTrue( wd.findElement(By.tagName("body")).getText().contains("not properly filled in: [Credit Card Number]")); assertNotLogged(TransactionType.DEMOGRAPHICS_EDIT, 1L, 1L, ""); } public void testGoodVisas() throws Exception { // login patient 2 WebDriver wd = login("1", "pw"); assertEquals("iTrust - Patient Home", wd.getTitle()); assertLogged(TransactionType.HOME_VIEW, 1L, 0L, ""); // click on My Demographics wd.findElement(By.linkText("My Demographics")).click(); assertLogged(TransactionType.DEMOGRAPHICS_VIEW, 1L, 1L, ""); Select creditCardType = new Select(wd.findElement(By.name("creditCardType"))); creditCardType.selectByVisibleText("Visa"); WebElement creditCardNumber = wd.findElement(By.name("creditCardNumber")); creditCardNumber.sendKeys("4539592576502361"); creditCardNumber.submit(); assertTrue(wd.findElement(By.tagName("body")).getText().contains("Information Successfully Updated")); assertLogged(TransactionType.DEMOGRAPHICS_EDIT, 1L, 1L, ""); creditCardNumber = wd.findElement(By.name("creditCardNumber")); creditCardNumber.clear(); creditCardNumber.sendKeys("4716912133362668"); creditCardNumber.submit(); assertTrue(wd.findElement(By.tagName("body")).getText().contains("Information Successfully Updated")); assertLogged(TransactionType.DEMOGRAPHICS_EDIT, 1L, 1L, ""); creditCardNumber = wd.findElement(By.name("creditCardNumber")); creditCardNumber.clear(); creditCardNumber.sendKeys("4485333709241203"); creditCardNumber.submit(); assertTrue(wd.findElement(By.tagName("body")).getText().contains("Information Successfully Updated")); assertLogged(TransactionType.DEMOGRAPHICS_EDIT, 1L, 1L, ""); } public void testBadVisas() throws Exception { // login patient 2 WebDriver wd = login("1", "pw"); assertEquals("iTrust - Patient Home", wd.getTitle()); assertLogged(TransactionType.HOME_VIEW, 1L, 0L, ""); // click on My Demographics wd.findElement(By.linkText("My Demographics")).click(); assertLogged(TransactionType.DEMOGRAPHICS_VIEW, 1L, 1L, ""); Select creditCardType = new Select(wd.findElement(By.name("creditCardType"))); creditCardType.selectByVisibleText("Visa"); WebElement creditCardNumber = wd.findElement(By.name("creditCardNumber")); creditCardNumber.sendKeys("5593090746812380"); creditCardNumber.submit(); assertTrue( wd.findElement(By.tagName("body")).getText().contains("not properly filled in: [Credit Card Number]")); assertNotLogged(TransactionType.DEMOGRAPHICS_EDIT, 1L, 1L, ""); creditCardType = new Select(wd.findElement(By.name("creditCardType"))); creditCardType.selectByVisibleText("Visa"); creditCardNumber = wd.findElement(By.name("creditCardNumber")); creditCardNumber.clear(); creditCardNumber.sendKeys("6437693863890467"); creditCardNumber.submit(); assertTrue( wd.findElement(By.tagName("body")).getText().contains("not properly filled in: [Credit Card Number]")); assertNotLogged(TransactionType.DEMOGRAPHICS_EDIT, 1L, 1L, ""); } public void testGoodDiscovers() throws Exception { // login patient 2 WebDriver wd = login("1", "pw"); assertEquals("iTrust - Patient Home", wd.getTitle()); assertLogged(TransactionType.HOME_VIEW, 1L, 0L, ""); // click on My Demographics wd.findElement(By.linkText("My Demographics")).click(); assertLogged(TransactionType.DEMOGRAPHICS_VIEW, 1L, 1L, ""); Select creditCardType = new Select(wd.findElement(By.name("creditCardType"))); creditCardType.selectByVisibleText("Discover"); WebElement creditCardNumber = wd.findElement(By.name("creditCardNumber")); creditCardNumber.sendKeys("6011263089803439"); creditCardNumber.submit(); assertTrue(wd.findElement(By.tagName("body")).getText().contains("Information Successfully Updated")); assertLogged(TransactionType.DEMOGRAPHICS_EDIT, 1L, 1L, ""); creditCardNumber = wd.findElement(By.name("creditCardNumber")); creditCardNumber.clear(); creditCardNumber.sendKeys("6011953266156193"); creditCardNumber.submit(); assertTrue(wd.findElement(By.tagName("body")).getText().contains("Information Successfully Updated")); assertLogged(TransactionType.DEMOGRAPHICS_EDIT, 1L, 1L, ""); creditCardNumber = wd.findElement(By.name("creditCardNumber")); creditCardNumber.clear(); creditCardNumber.sendKeys("6011726402628022"); creditCardNumber.submit(); assertTrue(wd.findElement(By.tagName("body")).getText().contains("Information Successfully Updated")); assertLogged(TransactionType.DEMOGRAPHICS_EDIT, 1L, 1L, ""); } public void testBadDiscovers() throws Exception { // login patient 2 WebDriver wd = login("1", "pw"); assertEquals("iTrust - Patient Home", wd.getTitle()); assertLogged(TransactionType.HOME_VIEW, 1L, 0L, ""); // click on My Demographics wd.findElement(By.linkText("My Demographics")).click(); assertLogged(TransactionType.DEMOGRAPHICS_VIEW, 1L, 1L, ""); Select creditCardType = new Select(wd.findElement(By.name("creditCardType"))); creditCardType.selectByVisibleText("Discover"); WebElement creditCardNumber = wd.findElement(By.name("creditCardNumber")); creditCardNumber.sendKeys("5593090746812380"); creditCardNumber.submit(); assertTrue( wd.findElement(By.tagName("body")).getText().contains("not properly filled in: [Credit Card Number]")); assertNotLogged(TransactionType.DEMOGRAPHICS_EDIT, 1L, 1L, ""); creditCardType = new Select(wd.findElement(By.name("creditCardType"))); creditCardType.selectByVisibleText("Discover"); creditCardNumber = wd.findElement(By.name("creditCardNumber")); creditCardNumber.clear(); creditCardNumber.sendKeys("6437693863890467"); creditCardNumber.submit(); assertTrue( wd.findElement(By.tagName("body")).getText().contains("not properly filled in: [Credit Card Number]")); assertNotLogged(TransactionType.DEMOGRAPHICS_EDIT, 1L, 1L, ""); } /* * AMEX stands for American Express. */ public void testGoodAmex() throws Exception { // login patient 2 WebDriver wd = login("1", "pw"); assertEquals("iTrust - Patient Home", wd.getTitle()); assertLogged(TransactionType.HOME_VIEW, 1L, 0L, ""); // click on My Demographics wd.findElement(By.linkText("My Demographics")).click(); assertLogged(TransactionType.DEMOGRAPHICS_VIEW, 1L, 1L, ""); Select creditCardType = new Select(wd.findElement(By.name("creditCardType"))); creditCardType.selectByVisibleText("American Express"); WebElement creditCardNumber = wd.findElement(By.name("creditCardNumber")); creditCardNumber.sendKeys("343570480641495"); creditCardNumber.submit(); assertTrue(wd.findElement(By.tagName("body")).getText().contains("Information Successfully Updated")); assertLogged(TransactionType.DEMOGRAPHICS_EDIT, 1L, 1L, ""); creditCardNumber = wd.findElement(By.name("creditCardNumber")); creditCardNumber.clear(); creditCardNumber.sendKeys("377199947956764"); creditCardNumber.submit(); assertTrue(wd.findElement(By.tagName("body")).getText().contains("Information Successfully Updated")); assertLogged(TransactionType.DEMOGRAPHICS_EDIT, 1L, 1L, ""); creditCardNumber = wd.findElement(By.name("creditCardNumber")); creditCardNumber.clear(); creditCardNumber.sendKeys("344558915054011"); creditCardNumber.submit(); assertTrue(wd.findElement(By.tagName("body")).getText().contains("Information Successfully Updated")); assertLogged(TransactionType.DEMOGRAPHICS_EDIT, 1L, 1L, ""); } public void testBadAmex() throws Exception { // login patient 2 WebDriver wd = login("1", "pw"); assertEquals("iTrust - Patient Home", wd.getTitle()); assertLogged(TransactionType.HOME_VIEW, 1L, 0L, ""); // click on My Demographics wd.findElement(By.linkText("My Demographics")).click(); assertLogged(TransactionType.DEMOGRAPHICS_VIEW, 1L, 1L, ""); Select creditCardType = new Select(wd.findElement(By.name("creditCardType"))); creditCardType.selectByVisibleText("American Express"); WebElement creditCardNumber = wd.findElement(By.name("creditCardNumber")); creditCardNumber.sendKeys("5593090746812380"); creditCardNumber.submit(); assertTrue( wd.findElement(By.tagName("body")).getText().contains("not properly filled in: [Credit Card Number]")); assertNotLogged(TransactionType.DEMOGRAPHICS_EDIT, 1L, 1L, ""); creditCardType = new Select(wd.findElement(By.name("creditCardType"))); creditCardType.selectByVisibleText("American Express"); creditCardNumber = wd.findElement(By.name("creditCardNumber")); creditCardNumber.clear(); creditCardNumber.sendKeys("6437693863890467"); creditCardNumber.submit(); assertTrue( wd.findElement(By.tagName("body")).getText().contains("not properly filled in: [Credit Card Number]")); assertNotLogged(TransactionType.DEMOGRAPHICS_EDIT, 1L, 1L, ""); } public void testEmptyTypeEmptyNumber() throws Exception { // login patient 2 WebDriver wd = login("1", "pw"); assertEquals("iTrust - Patient Home", wd.getTitle()); assertLogged(TransactionType.HOME_VIEW, 1L, 0L, ""); // click on My Demographics wd.findElement(By.linkText("My Demographics")).click(); assertLogged(TransactionType.DEMOGRAPHICS_VIEW, 1L, 1L, ""); Select creditCardType = new Select(wd.findElement(By.name("creditCardType"))); creditCardType.selectByValue(""); WebElement creditCardNumber = wd.findElement(By.name("creditCardNumber")); creditCardNumber.sendKeys(""); creditCardNumber.submit(); assertTrue(wd.findElement(By.tagName("body")).getText().contains("Information Successfully Updated")); assertLogged(TransactionType.DEMOGRAPHICS_EDIT, 1L, 1L, ""); } public void testEmptyTypeFilledNumber() throws Exception { // login patient 2 WebDriver wd = login("1", "pw"); assertEquals("iTrust - Patient Home", wd.getTitle()); assertLogged(TransactionType.HOME_VIEW, 1L, 0L, ""); // click on My Demographics wd.findElement(By.linkText("My Demographics")).click(); assertLogged(TransactionType.DEMOGRAPHICS_VIEW, 1L, 1L, ""); Select creditCardType = new Select(wd.findElement(By.name("creditCardType"))); creditCardType.selectByValue(""); WebElement creditCardNumber = wd.findElement(By.name("creditCardNumber")); creditCardNumber.sendKeys("5593090746812380"); creditCardNumber.submit(); assertTrue(wd.findElement(By.tagName("body")).getText().contains("not properly filled in: [Credit Card Type]")); assertNotLogged(TransactionType.DEMOGRAPHICS_EDIT, 1L, 1L, ""); creditCardType = new Select(wd.findElement(By.name("creditCardType"))); creditCardType.selectByValue(""); creditCardNumber = wd.findElement(By.name("creditCardNumber")); creditCardNumber.clear(); creditCardNumber.sendKeys("6437693863890467"); creditCardNumber.submit(); assertTrue(wd.findElement(By.tagName("body")).getText().contains("not properly filled in: [Credit Card Type]")); assertNotLogged(TransactionType.DEMOGRAPHICS_EDIT, 1L, 1L, ""); } }
14,034
41.020958
114
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/selenium/DependencyExtensionSeleniumTest.java
package edu.ncsu.csc.itrust.selenium; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.htmlunit.HtmlUnitDriver; import edu.ncsu.csc.itrust.unit.datagenerators.TestDataGenerator; /** * Tests viewing/editing dependent's demographic information as the "dependee" */ public class DependencyExtensionSeleniumTest extends iTrustSeleniumTest { /** * set up standard test data */ @Override public void setUp() throws Exception { super.setUp(); gen.standardData(); } /** * Make sure the parent of a dependent can see the dependent's information. * * @throws Exception */ public void testViewableDependentsInMyDemographics() throws Exception { // add in the baby TestDataGenerator gen = new TestDataGenerator(); gen.doBaby(); // login WebDriver driver = new HtmlUnitDriver(); driver = login("2", "pw"); // make sure you can see baby driver.findElement(By.linkText("My Demographics")).click(); assertTrue(driver.getPageSource().contains("Baby Programmer")); } /** * Tests that you can edit one of your dependent's demographic data */ public void testEditableDependentsInMyDemographics() throws Exception { // add in baby again TestDataGenerator gen = new TestDataGenerator(); gen.doBaby(); WebDriver driver = new HtmlUnitDriver(); driver = login("2", "pw"); // make sure you can see baby driver.findElement(By.linkText("My Demographics")).click(); assertTrue(driver.getPageSource().contains("Baby Programmer")); // get the form to update baby's info WebElement babyForm = driver.findElement(By.id("edit_2")); WebElement babyName = babyForm.findElement(By.name("firstName")); babyName.clear(); babyName.sendKeys("BabyO"); // submit the form babyForm.submit(); assertTrue(driver.getPageSource().contains("Information Successfully Updated")); } /** * Test that without adding in baby, there are no dependents */ public void testNoDependentsInMyDemographics() throws Exception { WebDriver driver = new HtmlUnitDriver(); driver = login("2", "pw"); // go to my demographics driver.findElement(By.linkText("My Demographics")).click(); assertFalse(driver.getPageSource().contains("Baby Programmer")); } }
2,284
27.924051
82
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/selenium/DependentsTest.java
package edu.ncsu.csc.itrust.selenium; import java.util.List; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.htmlunit.HtmlUnitDriver; import org.openqa.selenium.support.ui.Select; import edu.ncsu.csc.itrust.model.old.enums.TransactionType; public class DependentsTest extends iTrustSeleniumTest { public static final String ADDRESS = "http://localhost:8080/iTrust/auth/hcp-uap/addPatient.jsp"; @Override protected void setUp() throws Exception { super.setUp(); gen.clearAllTables(); gen.standardData(); } /** * Tests adding a dependent / representative relationship to existing * patients * * @throws Exception */ public void testEditDependentRepresentative() throws Exception { // Log in. WebDriver driver = new HtmlUnitDriver(); driver = login("9000000000", "pw"); assertLogged(TransactionType.HOME_VIEW, 9000000000L, 0L, ""); // Click on Representatives. driver.findElement(By.linkText("Representatives")).click(); // search for patient 103 by MID. driver.findElement(By.name("UID_PATIENTID")).sendKeys("103"); // the button to click should have the text of the MID driver.findElement(By.cssSelector("input[value='103']")).submit(); assertTrue(driver.getTitle().equals("iTrust - Manage Representatives")); // Add Caldwell Hudson as a representative WebElement elem = driver.findElement(By.name("UID_repID")); elem.sendKeys("102"); elem.submit(); // Make sure the text displays. List<WebElement> list = driver.findElements(By.xpath("//*[contains(text(),'" + "Caldwell Hudson" + "')]")); assertTrue("Text not found!", list.size() > 0); } /** * Tests that a dependent cannot login * * @throws Exception */ public void testDependentLogin() throws Exception { // Load UC58 data gen.uc58(); // Try to log in (dependents can't). WebDriver driver = new HtmlUnitDriver(); driver.get("http://localhost:8080/iTrust/"); WebElement elem = driver.findElement(By.name("j_username")); elem.sendKeys("580"); driver.findElement(By.name("j_password")); elem.sendKeys("pw"); elem.submit(); // Make sure we didn't go anywhere. List<WebElement> list = driver.findElements(By.xpath("//*[contains(text(),'" + "iTrust - Login" + "')]")); assertTrue("Text not found!", list.size() > 0); } /** * Tests that a list of a depedent's representatives is displayed to them * * @throws Exception */ public void testListRepresentatives() throws Exception { // Load UC58 data gen.uc58(); // Log in. WebDriver driver = new HtmlUnitDriver(); driver = login("9000000000", "pw"); assertLogged(TransactionType.HOME_VIEW, 9000000000L, 0L, ""); // Click on Representatives. driver.findElement(By.linkText("Representatives")).click(); // search for patient 103 by MID. driver.findElement(By.name("UID_PATIENTID")).sendKeys("581"); // the button to click should have the text of the MID driver.findElement(By.cssSelector("input[value='581']")).submit(); assertTrue(driver.getTitle().equals("iTrust - Manage Representatives")); // Add Caldwell Hudson as a representative WebElement elem = driver.findElement(By.name("UID_repID")); elem.sendKeys("102"); elem.submit(); // Make sure the text displays. List<WebElement> list = driver.findElements(By.xpath("//*[contains(text(),'" + "Bob Marley" + "')]")); assertTrue("Text not found!", list.size() > 0); } /** * Tests to make sure representatives can't be dependents themselves * * @throws Exception */ public void testRepresentativeNotDependent() throws Exception { // Load UC58 data gen.uc58(); // Log in. WebDriver driver = new HtmlUnitDriver(); driver = login("9000000000", "pw"); assertLogged(TransactionType.HOME_VIEW, 9000000000L, 0L, ""); // Click on Representatives. driver.findElement(By.linkText("Representatives")).click(); // search for patient 103 by MID. driver.findElement(By.name("UID_PATIENTID")).sendKeys("580"); // the button to click should have the text of the MID driver.findElement(By.cssSelector("input[value='580']")).submit(); assertTrue(driver.getTitle().equals("iTrust - Manage Representatives")); // Make sure the text displays. List<WebElement> list = driver .findElements(By.xpath("//*[contains(text(),'" + "Bob Marley is a dependent." + "')]")); assertTrue("Text not found!", list.size() > 0); list = driver .findElements(By.xpath("//*[contains(text(),'" + "Dependent users cannot represent others." + "')]")); assertTrue("Text not found!", list.size() > 0); } public void testRequestRecordsForDependent() throws Exception { // Load UC59 data gen.uc59(); // Log in. WebDriver driver = new HtmlUnitDriver(); driver = login("750", "pw"); assertLogged(TransactionType.HOME_VIEW, 750L, 0L, ""); // Click on Representatives. driver.findElement(By.linkText("Request Records Release")).click(); WebElement elem = driver.findElement(By.name("selectedPatient")); Select s = new Select(elem); s.selectByIndex(1); elem.submit(); // Make sure the text displays. List<WebElement> list = driver.findElements(By.xpath("//*[contains(text(),'" + "Billy Ross" + "')]")); assertTrue("Text not found!", list.size() > 0); driver.findElement(By.id("submitReq")).click(); assertTrue(driver.getTitle().equals("iTrust - Records Release Request")); // Fill in medical records release form s = new Select(driver.findElement(By.name("releaseHospital"))); s.selectByIndex(1); elem = driver.findElement(By.name("recFirstName")); elem.sendKeys("Benedict"); elem = driver.findElement(By.name("recLastName")); elem.sendKeys("Cucumberpatch"); elem = driver.findElement(By.name("recPhone")); elem.sendKeys("555-666-7777"); elem = driver.findElement(By.name("recEmail")); elem.sendKeys("a@b.com"); elem = driver.findElement(By.name("recHospitalName")); elem.sendKeys("Rex Hospital"); elem = driver.findElement(By.name("recHospitalAddress1")); elem.sendKeys("123 Broad St."); elem = driver.findElement(By.name("recHospitalAddress2")); elem.sendKeys(" "); elem = driver.findElement(By.name("recHospitalCity")); elem.sendKeys("Cary"); elem = driver.findElement(By.name("recHospitalState")); elem.sendKeys("NC"); elem = driver.findElement(By.name("recHospitalZip")); elem.sendKeys("27164"); elem = driver.findElement(By.name("releaseJustification")); elem.sendKeys("Moving"); elem = driver.findElement(By.name("verifyForm")); elem.click(); elem = driver.findElement(By.name("digitalSig")); elem.sendKeys("Bob Ross"); driver.findElement(By.id("submit")).click(); list = driver.findElements(By.xpath("//*[contains(text(),'" + "Request successfully sent" + "')]")); assertTrue("Text not found!", list.size() > 0); } public void testRequestRecordsWithDependentSignature() throws Exception { // Load UC59 data gen.uc59(); // Log in. WebDriver driver = new HtmlUnitDriver(); driver = login("750", "pw"); assertLogged(TransactionType.HOME_VIEW, 750L, 0L, ""); // Click on Representatives. driver.findElement(By.linkText("Request Records Release")).click(); WebElement elem = driver.findElement(By.name("selectedPatient")); Select s = new Select(elem); s.selectByIndex(1); elem.submit(); // Make sure the text displays. List<WebElement> list = driver.findElements(By.xpath("//*[contains(text(),'" + "Billy Ross" + "')]")); assertTrue("Text not found!", list.size() > 0); driver.findElement(By.id("submitReq")).click(); assertTrue(driver.getTitle().equals("iTrust - Records Release Request")); // Fill in medical records release form s = new Select(driver.findElement(By.name("releaseHospital"))); s.selectByIndex(1); elem = driver.findElement(By.name("recFirstName")); elem.sendKeys("Benedict"); elem = driver.findElement(By.name("recLastName")); elem.sendKeys("Cucumberpatch"); elem = driver.findElement(By.name("recPhone")); elem.sendKeys("555-666-7777"); elem = driver.findElement(By.name("recEmail")); elem.sendKeys("a@b.com"); elem = driver.findElement(By.name("recHospitalName")); elem.sendKeys("Rex Hospital"); elem = driver.findElement(By.name("recHospitalAddress1")); elem.sendKeys("123 Broad St."); elem = driver.findElement(By.name("recHospitalAddress2")); elem.sendKeys(" "); elem = driver.findElement(By.name("recHospitalCity")); elem.sendKeys("Cary"); elem = driver.findElement(By.name("recHospitalState")); elem.sendKeys("NC"); elem = driver.findElement(By.name("recHospitalZip")); elem.sendKeys("27164"); elem = driver.findElement(By.name("releaseJustification")); elem.sendKeys("Moving"); elem = driver.findElement(By.name("verifyForm")); elem.click(); elem = driver.findElement(By.name("digitalSig")); elem.sendKeys("Billy Ross"); driver.findElement(By.id("submit")).click(); list = driver.findElements(By.xpath("//*[contains(text(),'" + "Error" + "')]")); assertTrue("Text not found!", list.size() > 0); } public void testRequestRecordsForNotRepresentedDependent() throws Exception { // Load UC59 data gen.uc59(); // Log in. WebDriver driver = new HtmlUnitDriver(); driver = login("9000000000", "pw"); assertLogged(TransactionType.HOME_VIEW, 9000000000L, 0L, ""); // Click on Representatives. driver.findElement(By.linkText("Representatives")).click(); // search for patient 103 by MID. driver.findElement(By.name("UID_PATIENTID")).sendKeys("750"); // the button to click should have the text of the MID driver.findElement(By.cssSelector("input[value='750']")).submit(); assertTrue(driver.getTitle().equals("iTrust - Manage Representatives")); // Remove the representative. driver.findElement(By.partialLinkText("Remove")).click(); driver.findElement(By.xpath("//a[text()='Logout']")).click(); // Log in as Bob Ross. driver = login("750", "pw"); assertLogged(TransactionType.HOME_VIEW, 750L, 0L, ""); // Click on Add Patient. driver.findElement(By.linkText("Request Records Release")).click(); // Try to select Billy. try { // Should fail. WebElement elem = driver.findElement(By.name("selectedPatient")); Select s = new Select(elem); s.selectByIndex(2); // Billy. elem.submit(); fail(); } catch (Exception e) { assertEquals("iTrust - Records Release Request History", driver.getTitle()); } } public void testViewRequestedRecordsForDependent() throws Exception { // Load UC59 data gen.uc59(); // Log in. WebDriver driver = new HtmlUnitDriver(); driver = login("750", "pw"); assertLogged(TransactionType.HOME_VIEW, 750L, 0L, ""); // Click on Add Patient. driver.findElement(By.linkText("Request Records Release")).click(); WebElement elem = driver.findElement(By.name("selectedPatient")); Select s = new Select(elem); s.selectByIndex(0); elem.submit(); driver.findElement(By.partialLinkText("View")).click(); assertEquals("iTrust - View My Records", driver.getTitle()); } }
11,035
32.646341
109
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/selenium/DetermineOperationalProfileTest.java
package edu.ncsu.csc.itrust.selenium; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import edu.ncsu.csc.itrust.model.old.enums.TransactionType; public class DetermineOperationalProfileTest extends iTrustSeleniumTest { @Override protected void setUp() throws Exception { super.setUp(); gen.clearAllTables(); gen.uap1(); gen.tester(); } /** * Precondition: Sample data is in the database. CreatePatient2 has passed. * Login with user 9999999999 and password pw. */ public void testDetermineOperationalProfile() throws Exception { // login as uap and add a patient WebDriver wd = login("8000000009", "uappass1"); wd.get(ADDRESS + "auth/uap/home.jsp"); assertEquals("iTrust - UAP Home", wd.getTitle()); assertLogged(TransactionType.HOME_VIEW, 8000000009L, 0L, ""); wd.findElement(By.linkText("Add Patient")).click(); WebElement firstName = wd.findElement(By.name("firstName")); WebElement lastName = wd.findElement(By.name("lastName")); WebElement email = wd.findElement(By.name("email")); firstName.sendKeys("bob"); lastName.sendKeys("bob"); email.sendKeys("bob@bob.com"); firstName.submit(); } public int getRowNumber(String description) { TransactionType[] values = TransactionType.values(); int rownumber = 0; for (int i = 0; i < values.length; i++) { if (description.equals(values[i].getDescription())) rownumber = i + 1; } return rownumber; } }
1,485
26.518519
76
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/selenium/Driver.java
package edu.ncsu.csc.itrust.selenium; import org.openqa.selenium.htmlunit.HtmlUnitDriver; import com.gargoylesoftware.htmlunit.SilentCssErrorHandler; /** * Custom implementation of an HtmlUnitDriver that does not report js and css errors. */ public class Driver extends HtmlUnitDriver { /** * Construct a new driver and disable script error reporting. */ public Driver() { super(); this.getWebClient().getOptions().setThrowExceptionOnScriptError(false); this.getWebClient().setCssErrorHandler(new SilentCssErrorHandler()); } }
549
22.913043
85
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/selenium/EditApptTest.java
package edu.ncsu.csc.itrust.selenium; import java.util.List; import java.util.concurrent.TimeUnit; import org.junit.*; import org.openqa.selenium.*; import org.openqa.selenium.htmlunit.HtmlUnitDriver; import edu.ncsu.csc.itrust.model.old.enums.TransactionType; public class EditApptTest extends iTrustSeleniumTest { private HtmlUnitDriver driver; private StringBuffer verificationErrors = new StringBuffer(); @Override @Before public void setUp() throws Exception { super.setUp(); gen.clearAllTables(); gen.standardData(); driver = new HtmlUnitDriver(); driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); } @Test public void testSetPassedDate() throws Exception { gen.uc22(); driver = (HtmlUnitDriver) login("9000000000", "pw"); driver.setJavascriptEnabled(true); assertEquals("iTrust - HCP Home", driver.getTitle()); driver.findElement(By.linkText("View My Appointments")).click(); assertLogged(TransactionType.APPOINTMENT_ALL_VIEW, 9000000000L, 0L, ""); driver.findElements(By.tagName("td")).get(35).findElement(By.tagName("a")).click(); driver.findElement(By.name("schedDate")).clear(); driver.findElement(By.name("schedDate")).sendKeys("10/10/2009"); driver.findElement(By.id("changeButton")).click(); assertTrue(driver.getPageSource().contains("The scheduled date of this appointment")); assertTrue(driver.getPageSource().contains("has already passed")); assertNotLogged(TransactionType.APPOINTMENT_EDIT, 9000000000L, 100L, ""); } @Test public void testRemoveAppt() throws Exception { gen.uc22(); driver = (HtmlUnitDriver) login("9000000000", "pw"); driver.setJavascriptEnabled(true); assertEquals("iTrust - HCP Home", driver.getTitle()); driver.findElement(By.linkText("View My Appointments")).click(); assertLogged(TransactionType.APPOINTMENT_ALL_VIEW, 9000000000L, 0L, ""); driver.findElements(By.tagName("td")).get(23).findElement(By.tagName("a")).click(); driver.findElement(By.id("removeButton")).click(); assertTrue(driver.getPageSource().contains("Success: Appointment removed")); assertLoggedNoSecondary(TransactionType.APPOINTMENT_REMOVE, 9000000000L, 0L, ""); } @Test public void testEditAppt() throws Exception { driver = (HtmlUnitDriver) login("9000000000", "pw"); driver.setJavascriptEnabled(true); assertEquals("iTrust - HCP Home", driver.getTitle()); driver.findElement(By.linkText("View My Appointments")).click(); assertLogged(TransactionType.APPOINTMENT_ALL_VIEW, 9000000000L, 0L, ""); List<WebElement> rows = driver.findElements(By.tagName("td")); // should be the last one WebElement mine = rows.get(rows.size() - 1); mine.findElement(By.tagName("a")).click(); assertTrue(driver.getPageSource().contains("Andy Programmer")); driver.findElement(By.name("comment")).clear(); driver.findElement(By.name("comment")).sendKeys("New comment!"); driver.findElement(By.id("changeButton")).click(); assertTrue(driver.getPageSource().contains("Success: Appointment changed")); assertLogged(TransactionType.APPOINTMENT_EDIT, 9000000000L, 2L, ""); } @Override @After public void tearDown() throws Exception { driver.quit(); String verificationErrorString = verificationErrors.toString(); if (!"".equals(verificationErrorString)) { fail(verificationErrorString); } } }
3,318
38.047059
88
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/selenium/EditPatientTest.java
package edu.ncsu.csc.itrust.selenium; import java.util.concurrent.TimeUnit; import static org.junit.Assert.*; import static org.hamcrest.CoreMatchers.*; import org.openqa.selenium.*; import org.openqa.selenium.htmlunit.HtmlUnitDriver; import edu.ncsu.csc.itrust.model.old.enums.TransactionType; import org.junit.Test; public class EditPatientTest extends iTrustSeleniumTest { private String baseUrl; private StringBuffer verificationErrors = new StringBuffer(); @Override public void setUp() throws Exception { super.setUp(); gen.clearAllTables(); gen.standardData(); } @Test public void testViewDemographicsTest() throws Exception { // set up for the start location and driver WebDriver driver = new HtmlUnitDriver(); baseUrl = "http://localhost:8080/iTrust/"; driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); driver.get(baseUrl + "auth/forwardUser.jsp"); driver.findElement(By.id("j_username")).clear(); driver.findElement(By.id("j_username")).sendKeys("9000000000"); driver.findElement(By.id("j_password")).clear(); driver.findElement(By.id("j_password")).sendKeys("pw"); driver.findElement(By.cssSelector("input[type=\"submit\"]")).click(); try { assertEquals("iTrust - HCP Home", driver.getTitle()); } catch (Error e) { verificationErrors.append(e.toString()); fail(); } assertLogged(TransactionType.HOME_VIEW, 9000000000L, 0L, ""); driver.findElement(By.cssSelector("h2.panel-title")).click(); driver.findElement(By.linkText("Patient Information")).click(); driver.findElement(By.name("UID_PATIENTID")).sendKeys("2"); driver.findElement(By.xpath("//input[@value='2']")).submit(); // check if its on the correct page try { assertEquals("http://localhost:8080/iTrust/auth/hcp-uap/editPatient.jsp", driver.getCurrentUrl()); } catch (Error e) { verificationErrors.append(e.toString()); fail(); } // clears and enters a email driver.findElement(By.name("email")).clear(); driver.findElement(By.name("email")).sendKeys("history@gmail.com"); driver.findElement(By.name("action")).click(); try { // get the massage that the info has been updated assertEquals("Information Successfully Updated", driver.findElement(By.cssSelector("span.iTrustMessage")).getText()); } catch (Error e) { verificationErrors.append(e.toString()); fail(); } // submits } @Test public void testMFWithPersonnelMID() throws Exception { // set up for the start location and driver WebDriver driver = new HtmlUnitDriver(); baseUrl = "http://localhost:8080/iTrust/"; driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); driver.get(baseUrl + "auth/forwardUser.jsp"); driver.findElement(By.id("j_username")).clear(); driver.findElement(By.id("j_username")).sendKeys("9000000000"); driver.findElement(By.id("j_password")).clear(); driver.findElement(By.id("j_password")).sendKeys("pw"); driver.findElement(By.cssSelector("input[type=\"submit\"]")).click(); try { assertEquals("iTrust - HCP Home", driver.getTitle()); } catch (Error e) { verificationErrors.append(e.toString()); fail(); } driver.findElement(By.cssSelector("h2.panel-title")).click(); driver.findElement(By.linkText("Patient Information")).click(); driver.findElement(By.name("UID_PATIENTID")).sendKeys("2"); driver.findElement(By.xpath("//input[@value='2']")).submit(); try { assertEquals("http://localhost:8080/iTrust/auth/hcp-uap/editPatient.jsp", driver.getCurrentUrl()); } catch (Error e) { verificationErrors.append(e.toString()); fail(); } // enters bad info for mothers and fathers MID driver.findElement(By.name("motherMID")).clear(); driver.findElement(By.name("motherMID")).sendKeys("9"); driver.findElement(By.name("fatherMID")).clear(); driver.findElement(By.name("fatherMID")).sendKeys("98"); driver.findElement(By.name("action")).click(); try { // gets error message assertEquals( "This form has not been validated correctly. The following field are not properly filled in: [Mother MID: 1-10 digit number not beginning with 9, Father MID: 1-10 digit number not beginning with 9]", driver.findElement(By.cssSelector("#iTrustContent > div")).getText()); } catch (Error e) { verificationErrors.append(e.toString()); fail(); } } @Test public void testMisspellings() throws Exception { // set up for the start location and driver WebDriver driver = new HtmlUnitDriver(); baseUrl = "http://localhost:8080/iTrust/"; driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); driver.get(baseUrl + "auth/forwardUser.jsp"); driver.findElement(By.id("j_username")).clear(); driver.findElement(By.id("j_username")).sendKeys("9000000000"); driver.findElement(By.id("j_password")).clear(); driver.findElement(By.id("j_password")).sendKeys("pw"); driver.findElement(By.cssSelector("input[type=\"submit\"]")).click(); try { assertEquals("iTrust - HCP Home", driver.getTitle()); } catch (Error e) { verificationErrors.append(e.toString()); fail(); } assertLogged(TransactionType.HOME_VIEW, 9000000000L, 0L, ""); driver.findElement(By.cssSelector("h2.panel-title")).click(); driver.findElement(By.linkText("Patient Information")).click(); driver.findElement(By.name("UID_PATIENTID")).sendKeys("2"); driver.findElement(By.xpath("//input[@value='2']")).submit(); try { assertEquals("http://localhost:8080/iTrust/auth/hcp-uap/editPatient.jsp", driver.getCurrentUrl()); } catch (Error e) { verificationErrors.append(e.toString()); fail(); } // check that its not there assertThat("Mother MIDs", is(not(driver.findElement(By.id("editForm")).getText()))); } }
5,704
37.033333
204
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/selenium/ExpertReviewsTest.java
package edu.ncsu.csc.itrust.selenium; import java.util.concurrent.TimeUnit; import org.junit.*; import org.openqa.selenium.*; import org.openqa.selenium.htmlunit.HtmlUnitDriver; import org.openqa.selenium.support.ui.Select; public class ExpertReviewsTest extends iTrustSeleniumTest { private WebDriver driver; private StringBuffer verificationErrors = new StringBuffer(); @Override @Before public void setUp() throws Exception { super.setUp(); gen.standardData(); gen.reviews(); driver = new HtmlUnitDriver(); driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); } @Test public void testValidHCP() throws Exception { driver = login("2", "pw"); driver.findElement(By.linkText("Find an Expert")).click(); new Select(driver.findElement(By.name("specialty"))).selectByVisibleText("Surgeon"); new Select(driver.findElement(By.name("range"))).selectByVisibleText("250 Miles"); driver.findElement(By.xpath("//form[@id='mainForm']/div[4]/button")).click(); driver.findElement(By.linkText("View")).click(); driver.findElement(By.xpath("//div[@id='iTrustContent']/a")).click(); driver.findElement(By.name("title")).clear(); driver.findElement(By.name("title")).sendKeys("Too bored?"); new Select(driver.findElement(By.name("rating"))).selectByVisibleText("2"); driver.findElement(By.name("description")).clear(); driver.findElement(By.name("description")) .sendKeys("They seemed nice, but they asked how I was then started snoring."); driver.findElement(By.name("addReview")).click(); assertTrue(driver.getPageSource().contains("Too bored?")); } @Test public void testInvalidHCP() throws Exception { driver = login("109", "pw"); driver.findElement(By.linkText("Find an Expert")).click(); new Select(driver.findElement(By.name("specialty"))).selectByVisibleText("Pediatrician"); new Select(driver.findElement(By.name("range"))).selectByVisibleText("All"); driver.findElement(By.xpath("//form[@id='mainForm']/div[4]/button")).click(); assertTrue(driver.getPageSource().contains("Beaker Beaker")); assertTrue(driver.findElement(By.cssSelector("BODY")).getText().contains("Beaker Beaker")); driver.findElement(By.linkText("View")).click(); assertFalse(driver.findElement(By.cssSelector("BODY")).getText().contains("Add a Review")); } @Test public void testDirectRating() throws Exception { driver = login("109", "pw"); driver.get(ADDRESS + "auth/patient/reviewsPage.jsp?expertID=9000000000"); assertEquals(ADDRESS + "auth/patient/reviewsPage.jsp", driver.getCurrentUrl()); assertTrue(driver.getPageSource().contains("Kelly Doctor is horrible!")); assertTrue(driver.getPageSource().contains("Best doctor at this hospital!")); assertTrue(driver.getPageSource().contains("So Bad.")); assertTrue(driver.getPageSource().contains("I am pretty happy")); } @Test public void testOverallRating() throws Exception { driver = login("22", "pw"); driver.get(ADDRESS + "auth/patient/reviewsPage.jsp?expertID=9000000003"); assertEquals(ADDRESS + "auth/patient/reviewsPage.jsp", driver.getCurrentUrl()); assertTrue(driver.findElement(By.cssSelector("BODY")).getText().contains("Gandalf Stormcrow")); assertTrue(driver.findElement(By.cssSelector("BODY")).getText().contains("Pretty happy")); assertTrue(driver.findElement(By.cssSelector("BODY")).getText().contains("Good service.")); } @Override @After public void tearDown() throws Exception { driver.quit(); String verificationErrorString = verificationErrors.toString(); if (!"".equals(verificationErrorString)) { fail(verificationErrorString); } } }
3,610
41.482353
97
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/selenium/FindExpertTest.java
package edu.ncsu.csc.itrust.selenium; import java.util.List; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import org.openqa.selenium.htmlunit.HtmlUnitDriver; import org.openqa.selenium.support.ui.Select; /* * This is the Selenium equivalent of FindExpertTest.java */ public class FindExpertTest extends iTrustSeleniumTest { /** * Selenium html unit driver. */ private HtmlUnitDriver driver; /** * MID of the test user "Random Person" */ private static final String RANDOM_PERSON_MID = "1"; /** * Default user password. */ private static final String PASSWORD = "pw"; /** * Build the absolute URL for Find Expert off of the base URL and relative * url. */ private static final String FIND_EXPERT = ADDRESS + "/auth/patient/findExpert.jsp"; /** * Set up for testing by clearing and recreating all standard data, then * performing UC47 specific data generation. */ @Override protected void setUp() throws Exception { super.setUp(); // clear tables is called in super gen.clearAllTables(); gen.standardData(); gen.uc47SetUp(); } /** * Remove the UC47 specific data and clear all tables. */ @Override protected void tearDown() throws Exception { gen.uc47TearDown(); gen.clearAllTables(); } /** * Test the displayed distances when searching for an expert. According to * the iTrust Wiki experts should be displayed by hospital location, not by * their personal listed address. * * EX: A doctor that lives in New York but is a provider for a hospital in * Raleigh, NC should be displayed as from Raleigh, NC. When a user from * Raleigh, NC searches for an expert, that doctor should be displayed with * a distance of zero miles. */ public void testFindExpertDisplayedDistances() throws Exception { // Login as Random User driver = (HtmlUnitDriver) login(RANDOM_PERSON_MID, PASSWORD); // Navigate to the Find Expert page driver.get(FIND_EXPERT); // Verify Specialty: All Doctors, ZIP Code: 27606, Distance: All, Sort // By: Distance Select select; select = new Select(driver.findElement(By.name("specialty"))); select.selectByVisibleText("All Doctors"); WebElement zipcode = driver.findElement(By.name("zipCode")); zipcode.clear(); zipcode.sendKeys("27606"); select = new Select(driver.findElement(By.name("range"))); select.selectByVisibleText("All"); select = new Select(driver.findElement(By.name("sortby"))); select.selectByVisibleText("Distance"); // Submit the form driver.findElement(By.name("findExpert")).click(); ; // Verify display distances for two of the doctors. // Kelly Doctor: Lives in New York, NY and practices in Raleigh, NC. // Shelly Vang: Lives in Greensboro, NC and practecesin Greensboro, NC. // Get container elements that group doctor information List<WebElement> elements = driver.findElements(By.className("grey-border-container")); // Number of doctors found int doctors = 0; // Search through the list of doctors for (WebElement doc : elements) { // Get the doctor name WebElement docID = doc.findElements(By.tagName("p")).get(0); String name = docID.findElement(By.tagName("a")).getText(); // Get the doctor's displayed distance String distance = doc.findElements(By.tagName("p")).get(1).getText(); // If doctor is Shelly Vang, verify display distance is 62 miles if (name.equals("Shelly Vang")) { doctors++; assertTrue("Distance is 62 miles", distance.contains("62 miles")); } // If doctor is Kelly Doctor, verify display distance is 0 miles. else if (name.equals("Kelly Doctor")) { doctors++; assertTrue("Distance is 3 miles", distance.contains("3 miles")); } // If doctor is John Zoidberg, verify distance is unknown (invalid // zip) else if (name.equals("John Zoidberg")) { doctors++; assertTrue("Distance is unknown", distance.contains("Unknown miles")); } } // Sanity check and verify that both doctors were found in the list. // If neither was found there may be an underlying issue with the // feature // or the structure of the html page may have changed. assertTrue("All doctors found", doctors == 3); } }
4,207
29.057143
89
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/selenium/GetPatientIDTest.java
package edu.ncsu.csc.itrust.selenium; import org.junit.After; import org.junit.Before; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import org.openqa.selenium.htmlunit.HtmlUnitDriver; /** * Selenium test conversion for HttpUnit GetPatientIDTest */ @SuppressWarnings("unused") public class GetPatientIDTest extends iTrustSeleniumTest { private HtmlUnitDriver driver; @Override @Before public void setUp() throws Exception { super.setUp(); gen.clearAllTables(); gen.standardData(); driver = new HtmlUnitDriver(); driver.get("http://localhost:8080/iTrust/"); } /* * Tests if back-end "Select Patient" function is connected to front-end JSP */ public void testSelectPatientButton() throws Exception { gen.hcp4(); gen.hcp5(); WebElement element; driver.findElement(By.id("j_username")).sendKeys("9000000003"); driver.findElement(By.id("j_password")).sendKeys("pw"); driver.findElement(By.cssSelector("input[type='submit']")).click(); assertEquals("iTrust - HCP Home", driver.getTitle()); driver.findElement(By.cssSelector("a[href= '/iTrust/auth/hcp-uap/editPatient.jsp']")).click(); assertEquals("iTrust - Please Select a Patient", driver.getTitle()); // click on the "Select Patient" button driver.findElement(By.id("selectPatientButton")).click(); assertEquals("iTrust - Please Select a Patient", driver.getTitle()); assertFalse(driver.getPageSource().contains("HTTP Status 500")); assertFalse(driver.getPageSource().contains("java.lang.NumberFormatException")); // click on the "Select Patient" button driver.findElement(By.id("selectPatientButton")).click(); assertEquals("iTrust - Please Select a Patient", driver.getTitle()); assertFalse(driver.getPageSource().contains("HTTP Status 500")); assertFalse(driver.getPageSource().contains("java.lang.NumberFormatException")); assertFalse(driver.getPageSource().contains("Viewing information for <b>null</b>")); } @Override @After public void tearDown() throws Exception { driver.quit(); } }
2,048
29.132353
96
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/selenium/GroupReportTest.java
package edu.ncsu.csc.itrust.selenium; import java.util.List; import org.junit.After; import org.junit.Before; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.ui.*; import edu.ncsu.csc.itrust.model.old.enums.TransactionType; import org.openqa.selenium.htmlunit.HtmlUnitDriver; @SuppressWarnings("unused") /** * Selenium test conversion for HttpUnit GroupReportTest */ public class GroupReportTest extends iTrustSeleniumTest { private WebDriver driver; @Override @Before protected void setUp() throws Exception { super.setUp(); gen.clearAllTables(); gen.standardData(); gen.uc47SetUp(); driver = new HtmlUnitDriver(); driver.get("http://localhost:8080/iTrust/"); } /* * Matches acceptance test scenario */ public void testViewGroupReportAcceptScenario() throws Exception { WebElement element; driver.findElement(By.id("j_username")).sendKeys("9000000000"); driver.findElement(By.id("j_password")).sendKeys("pw"); driver.findElement(By.cssSelector("input[type='submit']")).click(); assertEquals("iTrust - HCP Home", driver.getTitle()); assertLogged(TransactionType.HOME_VIEW, 9000000000L, 0L, ""); driver.findElement(By.cssSelector("a[href='/iTrust/auth/hcp/groupReport.jsp']")).click(); assertEquals("iTrust - Generate Group Report", driver.getTitle()); driver.findElement(By.cssSelector("input[value='GENDER']")).click(); driver.findElement(By.cssSelector("input[value='LOWER_AGE_LIMIT']")).click(); driver.findElement(By.cssSelector("input[type='submit']")).click(); assertEquals("iTrust - Generate Group Report", driver.getTitle()); Select genderDropDown = new Select(driver.findElement(By.name("GENDER"))); genderDropDown.selectByVisibleText("Female"); driver.findElement(By.name("LOWER_AGE_LIMIT")).clear(); driver.findElement(By.name("LOWER_AGE_LIMIT")).sendKeys("60"); driver.findElement(By.name("generate")).submit(); assertEquals("iTrust - View Group Report", driver.getTitle()); } /* * Filters by demographic filters */ public void testViewGroupReportDemographic() throws Exception { WebElement element; driver.findElement(By.id("j_username")).sendKeys("9000000000"); driver.findElement(By.id("j_password")).sendKeys("pw"); driver.findElement(By.cssSelector("input[type='submit']")).click(); assertEquals("iTrust - HCP Home", driver.getTitle()); assertLogged(TransactionType.HOME_VIEW, 9000000000L, 0L, ""); driver.findElement(By.cssSelector("a[href='/iTrust/auth/hcp/groupReport.jsp']")).click(); assertEquals("iTrust - Generate Group Report", driver.getTitle()); driver.findElement(By.cssSelector("input[value='GENDER']")).click(); driver.findElement(By.cssSelector("input[value='FIRST_NAME']")).click(); driver.findElement(By.cssSelector("input[value='CONTACT_EMAIL']")).click(); driver.findElement(By.cssSelector("input[value='CITY']")).click(); driver.findElement(By.cssSelector("input[value='STATE']")).click(); driver.findElement(By.cssSelector("input[value='ZIP']")).click(); driver.findElement(By.cssSelector("input[value='INSURE_NAME']")).click(); driver.findElement(By.cssSelector("input[value='INSURE_ID']")).click(); driver.findElement(By.cssSelector("input[value='LOWER_AGE_LIMIT']")).click(); driver.findElement(By.cssSelector("input[value='UPPER_AGE_LIMIT']")).click(); driver.findElement(By.cssSelector("input[type='submit']")).click(); assertEquals("iTrust - Generate Group Report", driver.getTitle()); Select genderDropDown = new Select(driver.findElement(By.name("GENDER"))); genderDropDown.selectByVisibleText("Male"); driver.findElement(By.name("FIRST_NAME")).clear(); driver.findElement(By.name("FIRST_NAME")).sendKeys("Baby"); driver.findElement(By.name("CONTACT_EMAIL")).clear(); driver.findElement(By.name("CONTACT_EMAIL")).sendKeys("fake@email.com"); driver.findElement(By.name("CITY")).clear(); driver.findElement(By.name("CITY")).sendKeys("Raleigh"); driver.findElement(By.name("STATE")).clear(); driver.findElement(By.name("STATE")).sendKeys("NC"); driver.findElement(By.name("ZIP")).clear(); driver.findElement(By.name("ZIP")).sendKeys("27606"); driver.findElement(By.name("INSURE_NAME")).clear(); driver.findElement(By.name("INSURE_NAME")).sendKeys("Aetna"); driver.findElement(By.name("INSURE_ID")).clear(); driver.findElement(By.name("INSURE_ID")).sendKeys("ChetumNHowe"); driver.findElement(By.name("LOWER_AGE_LIMIT")).clear(); driver.findElement(By.name("LOWER_AGE_LIMIT")).sendKeys("10"); driver.findElement(By.name("UPPER_AGE_LIMIT")).clear(); driver.findElement(By.name("UPPER_AGE_LIMIT")).sendKeys("30"); driver.findElement(By.name("generate")).submit(); assertEquals("iTrust - View Group Report", driver.getTitle()); } /* * Filters by personnel filters */ public void testViewGroupReportPersonnel() throws Exception { driver.findElement(By.id("j_username")).sendKeys("9000000000"); driver.findElement(By.id("j_password")).sendKeys("pw"); driver.findElement(By.cssSelector("input[type='submit']")).click(); assertEquals("iTrust - HCP Home", driver.getTitle()); assertLogged(TransactionType.HOME_VIEW, 9000000000L, 0L, ""); driver.findElement(By.cssSelector("a[href='/iTrust/auth/hcp/groupReport.jsp']")).click(); assertEquals("iTrust - Generate Group Report", driver.getTitle()); driver.findElement(By.cssSelector("input[name='personnel']")).click(); driver.findElement(By.cssSelector("input[type='submit']")).click(); assertEquals("iTrust - Generate Group Report", driver.getTitle()); Select listSelect = new Select(driver.findElement(By.cssSelector("[name='DLHCP']"))); listSelect.selectByVisibleText("Gandalf Stormcrow"); driver.findElement(By.name("generate")).submit(); } /* * Test viewing unselected MID */ public void testMID() throws Exception { driver.findElement(By.id("j_username")).sendKeys("9000000000"); driver.findElement(By.id("j_password")).sendKeys("pw"); driver.findElement(By.cssSelector("input[type='submit']")).click(); assertEquals("iTrust - HCP Home", driver.getTitle()); assertLogged(TransactionType.HOME_VIEW, 9000000000L, 0L, ""); driver.findElement(By.cssSelector("a[href='/iTrust/auth/hcp/groupReport.jsp']")).click(); assertEquals("iTrust - Generate Group Report", driver.getTitle()); driver.findElement(By.name("fillValues")).submit(); assertEquals("iTrust - Generate Group Report", driver.getTitle()); driver.findElement(By.name("generate")).submit(); assertFalse(driver.getPageSource().contains("<th>MID</th>")); } /* * Tests invalid entries for age, solely for code coverage purposes */ public void testGroupReportInvalidAge() throws Exception { driver.findElement(By.id("j_username")).sendKeys("9000000000"); driver.findElement(By.id("j_password")).sendKeys("pw"); driver.findElement(By.cssSelector("input[type='submit']")).click(); assertEquals("iTrust - HCP Home", driver.getTitle()); assertLogged(TransactionType.HOME_VIEW, 9000000000L, 0L, ""); driver.findElement(By.cssSelector("a[href='/iTrust/auth/hcp/groupReport.jsp']")).click(); assertEquals("iTrust - Generate Group Report", driver.getTitle()); driver.findElement(By.cssSelector("input[value='LOWER_AGE_LIMIT']")).click(); driver.findElement(By.cssSelector("input[value='UPPER_AGE_LIMIT']")).click(); driver.findElement(By.cssSelector("input[type='submit']")).click(); assertEquals("iTrust - Generate Group Report", driver.getTitle()); driver.findElement(By.name("LOWER_AGE_LIMIT")).clear(); driver.findElement(By.name("LOWER_AGE_LIMIT")).sendKeys("-1"); driver.findElement(By.name("UPPER_AGE_LIMIT")).clear(); driver.findElement(By.name("UPPER_AGE_LIMIT")).sendKeys("asdf"); driver.findElement(By.name("generate")).submit(); } /* * Test function of pressing the "download" button */ public void testDownloadButton() throws Exception { driver.findElement(By.id("j_username")).sendKeys("9000000000"); driver.findElement(By.id("j_password")).sendKeys("pw"); driver.findElement(By.cssSelector("input[type='submit']")).click(); assertEquals("iTrust - HCP Home", driver.getTitle()); assertLogged(TransactionType.HOME_VIEW, 9000000000L, 0L, ""); driver.findElement(By.cssSelector("a[href='/iTrust/auth/hcp/groupReport.jsp']")).click(); assertEquals("iTrust - Generate Group Report", driver.getTitle()); driver.findElement(By.name("fillValues")).submit(); assertEquals("iTrust - Generate Group Report", driver.getTitle()); List<WebElement> submitButtons = driver.findElements(By.className("clear_button")); assertEquals(2, submitButtons.size()); // NOTE: After clicking "Download" button, iTrust is redirecting to home // page (unexpected) // Existing error in XML download functionality // driver.findElement(By.name("download")).submit(); submitButtons.get(1).submit(); } /* * Tests downloading XML file */ public void testXMLCheckboxFalse() throws Exception { driver.findElement(By.id("j_username")).sendKeys("9000000000"); driver.findElement(By.id("j_password")).sendKeys("pw"); driver.findElement(By.cssSelector("input[type='submit']")).click(); assertEquals("iTrust - HCP Home", driver.getTitle()); assertLogged(TransactionType.HOME_VIEW, 9000000000L, 0L, ""); driver.findElement(By.cssSelector("a[href='/iTrust/auth/hcp/groupReport.jsp']")).click(); assertEquals("iTrust - Generate Group Report", driver.getTitle()); driver.findElement(By.name("fillValues")).submit(); assertEquals("iTrust - Generate Group Report", driver.getTitle()); // This is testing an element that currently does not exist on the JSP // in the first place /* * try { driver.findElement(By.name("Download XML Report")); } * catch(NoSuchElementException e) { //Exception is good return; } * fail("Should have thrown NoSuchElementException."); */ } @Override @After public void tearDown() throws Exception { driver.quit(); } }
10,045
36.625468
91
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/selenium/LoginTest.java
package edu.ncsu.csc.itrust.selenium; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.htmlunit.HtmlUnitDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import com.meterware.httpunit.HttpUnitOptions; import edu.ncsu.csc.itrust.model.old.enums.TransactionType; /** * Test class for logging into iTrust. */ public class LoginTest extends iTrustSeleniumTest { /* * The URL for iTrust, change as needed */ /** ADDRESS */ public static final String ADDRESS = "http://localhost:8080/iTrust/"; /** * Set up for testing. */ @Override protected void setUp() throws Exception { super.setUp(); gen.clearAllTables(); gen.standardData(); // turn off htmlunit warnings java.util.logging.Logger.getLogger("com.gargoylesoftware.htmlunit").setLevel(java.util.logging.Level.OFF); java.util.logging.Logger.getLogger("org.apache.http").setLevel(java.util.logging.Level.OFF); HttpUnitOptions.setExceptionsThrownOnScriptError(false); } /** * Tear down from testing. */ @Override protected void tearDown() throws Exception { super.tearDown(); } /** * Test the behavior expected when a user enters a non numeric string into * the username box. iTrust currently excpects to see a * NumberFormatException. */ public void testNonNumericLogin() { HtmlUnitDriver driver = new HtmlUnitDriver(); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); driver.get(ADDRESS); // log in using the given username and password driver.findElement(By.id("j_username")).clear(); driver.findElement(By.id("j_username")).sendKeys("foo"); driver.findElement(By.id("j_password")).clear(); driver.findElement(By.id("j_password")).sendKeys("1234"); driver.findElement(By.cssSelector("input[type=\"submit\"]")).click(); assertFalse(driver.getPageSource().contains("NumberFormatException")); } /** * Test the standard login feature. After logging in, a user should end up * at the itrust home page, and the login should be logged. */ public void testLogin() throws Exception { // Log in as a patient WebDriver driver = login("2", "pw"); // Wait until redirected to page WebDriverWait wait = new WebDriverWait(driver, DEFAULT_TIMEOUT); wait.until(ExpectedConditions.titleIs("iTrust - Patient Home")); // Verify Logging assertLogged(TransactionType.LOGIN_SUCCESS, 2L, 2L, ""); } }
2,501
29.888889
108
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/selenium/ManageHospitalListingTest.java
package edu.ncsu.csc.itrust.selenium; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import edu.ncsu.csc.itrust.model.old.enums.TransactionType; public class ManageHospitalListingTest extends iTrustSeleniumTest { /* * The URL for iTrust, change as needed */ /** ADDRESS */ public static final String ADDRESS = "http://localhost:8080/iTrust/"; private WebDriver driver; @Override protected void setUp() throws Exception { super.setUp(); gen.clearAllTables(); gen.standardData(); // turn off htmlunit warnings java.util.logging.Logger.getLogger("com.gargoylesoftware.htmlunit").setLevel(java.util.logging.Level.OFF); java.util.logging.Logger.getLogger("org.apache.http").setLevel(java.util.logging.Level.OFF); } public void testCreateHospital() throws Exception { driver = login("9000000001", "pw"); assertLogged(TransactionType.HOME_VIEW, 9000000001L, 0L, ""); driver.findElement(By.linkText("Manage Hospital Listing")).click(); assertEquals(driver.getTitle(), "iTrust - Maintain Hospital Listing and Assignments"); driver.findElement(By.name("hospitalID")).clear(); driver.findElement(By.name("hospitalID")).sendKeys("777"); driver.findElement(By.name("hospitalName")).clear(); driver.findElement(By.name("hospitalName")).sendKeys("Pokemon Center"); driver.findElement(By.name("hospitalAddress")).clear(); driver.findElement(By.name("hospitalAddress")).sendKeys("123 Centenial Parkway"); driver.findElement(By.name("hospitalCity")).clear(); driver.findElement(By.name("hospitalCity")).sendKeys("Raleigh"); driver.findElement(By.name("hospitalState")).clear(); driver.findElement(By.name("hospitalState")).sendKeys("NC"); driver.findElement(By.name("hospitalZip")).clear(); driver.findElement(By.name("hospitalZip")).sendKeys("27607"); driver.findElement(By.name("add")).click(); assertTrue(driver.getPageSource().contains("Success")); assertTrue(driver.getPageSource().contains("777")); assertTrue(driver.getPageSource().contains("Pokemon Center")); assertTrue(driver.getPageSource().contains("123 Centenial Parkway")); assertTrue(driver.getPageSource().contains("Raleigh")); assertTrue(driver.getPageSource().contains("NC")); assertTrue(driver.getPageSource().contains("27607")); } public void testUpdateHospital() throws Exception { driver = login("9000000001", "pw"); assertLogged(TransactionType.HOME_VIEW, 9000000001L, 0L, ""); driver.findElement(By.linkText("Manage Hospital Listing")).click(); assertEquals(driver.getTitle(), "iTrust - Maintain Hospital Listing and Assignments"); driver.findElement(By.name("hospitalID")).clear(); driver.findElement(By.name("hospitalID")).sendKeys("5"); driver.findElement(By.name("hospitalName")).clear(); driver.findElement(By.name("hospitalName")).sendKeys("Facebook Insane Asylum"); driver.findElement(By.name("hospitalAddress")).clear(); driver.findElement(By.name("hospitalAddress")).sendKeys("2 Yarborough Drive"); driver.findElement(By.name("hospitalCity")).clear(); driver.findElement(By.name("hospitalCity")).sendKeys("Raleigh"); driver.findElement(By.name("hospitalState")).clear(); driver.findElement(By.name("hospitalState")).sendKeys("NC"); driver.findElement(By.name("hospitalZip")).clear(); driver.findElement(By.name("hospitalZip")).sendKeys("27607"); driver.findElement(By.name("update")).click(); assertTrue(driver.getPageSource().contains("Success")); assertTrue(driver.getPageSource().contains("5")); assertTrue(driver.getPageSource().contains("Facebook Insane Asylum")); assertTrue(driver.getPageSource().contains("2 Yarborough Drive")); assertTrue(driver.getPageSource().contains("Raleigh")); assertTrue(driver.getPageSource().contains("NC")); assertTrue(driver.getPageSource().contains("27607")); } public void testUpdateWithoutID() throws Exception { driver = login("9000000001", "pw"); assertLogged(TransactionType.HOME_VIEW, 9000000001L, 0L, ""); driver.findElement(By.linkText("Manage Hospital Listing")).click(); assertEquals(driver.getTitle(), "iTrust - Maintain Hospital Listing and Assignments"); driver.findElement(By.name("hospitalName")).clear(); driver.findElement(By.name("hospitalName")).sendKeys("Facebook Insane Asylum"); driver.findElement(By.name("hospitalAddress")).clear(); driver.findElement(By.name("hospitalAddress")).sendKeys("2 Yarborough Drive"); driver.findElement(By.name("hospitalCity")).clear(); driver.findElement(By.name("hospitalCity")).sendKeys("Raleigh"); driver.findElement(By.name("hospitalState")).clear(); driver.findElement(By.name("hospitalState")).sendKeys("NC"); driver.findElement(By.name("hospitalZip")).clear(); driver.findElement(By.name("hospitalZip")).sendKeys("27607"); driver.findElement(By.name("update")).click(); assertTrue(driver.getPageSource().contains("This form has not been validated correctly")); } public void testNameTooLong() throws Exception { driver = login("9000000001", "pw"); assertLogged(TransactionType.HOME_VIEW, 9000000001L, 0L, ""); driver.findElement(By.linkText("Manage Hospital Listing")).click(); assertEquals(driver.getTitle(), "iTrust - Maintain Hospital Listing and Assignments"); driver.findElement(By.name("hospitalID")).clear(); driver.findElement(By.name("hospitalID")).sendKeys("777"); driver.findElement(By.name("hospitalName")).clear(); driver.findElement(By.name("hospitalName")).sendKeys("ABCABCABCABCABCABCABCABCABCABCABC"); driver.findElement(By.name("hospitalAddress")).clear(); driver.findElement(By.name("hospitalAddress")).sendKeys("2 Yarborough Drive"); driver.findElement(By.name("hospitalCity")).clear(); driver.findElement(By.name("hospitalCity")).sendKeys("Raleigh"); driver.findElement(By.name("hospitalState")).clear(); driver.findElement(By.name("hospitalState")).sendKeys("NC"); driver.findElement(By.name("hospitalZip")).clear(); driver.findElement(By.name("hospitalZip")).sendKeys("27607"); driver.findElement(By.name("add")).click(); assertTrue(driver.getPageSource().contains("This form has not been validated correctly")); } }
6,129
49.661157
108
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/selenium/MessagingUseCaseTest.java
package edu.ncsu.csc.itrust.selenium; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import com.meterware.httpunit.HttpUnitOptions; import edu.ncsu.csc.itrust.model.old.enums.TransactionType; public class MessagingUseCaseTest extends iTrustSeleniumTest { /* * The URL for iTrust, change as needed */ /** ADDRESS */ public static final String ADDRESS = "http://localhost:8080/iTrust/"; private WebDriver driver; @Override protected void setUp() throws Exception { super.setUp(); gen.clearAllTables(); gen.standardData(); HttpUnitOptions.setScriptingEnabled(false); // turn off htmlunit warnings java.util.logging.Logger.getLogger("com.gargoylesoftware.htmlunit").setLevel(java.util.logging.Level.OFF); java.util.logging.Logger.getLogger("org.apache.http").setLevel(java.util.logging.Level.OFF); } public void testHCPSendMessage() throws Exception { driver = login("9000000000", "pw"); assertLogged(TransactionType.HOME_VIEW, 9000000000L, 0L, ""); driver.findElement(By.linkText("Message Outbox")).click(); assertLogged(TransactionType.OUTBOX_VIEW, 9000000000L, 0L, ""); driver.findElement(By.linkText("Compose a Message")).click(); driver.findElement(By.name("UID_PATIENTID")).sendKeys("2"); driver.findElement(By.xpath("//input[@value='2']")).submit(); driver.findElement(By.name("subject")).clear(); driver.findElement(By.name("subject")).sendKeys("Visit Request"); driver.findElement(By.name("messageBody")).clear(); driver.findElement(By.name("messageBody")).sendKeys("We really need to have a visit."); driver.findElement(By.cssSelector("input[type=\"submit\"]")).click(); assertLogged(TransactionType.MESSAGE_SEND, 9000000000L, 2L, ""); DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm"); Date date = new Date(); String stamp = dateFormat.format(date); assertTrue(driver.getPageSource().contains("My Sent Messages")); driver.findElement(By.linkText("Message Outbox")).click(); assertTrue(driver.getPageSource().contains("Visit Request")); assertTrue(driver.getPageSource().contains("Andy Programmer")); assertTrue(driver.getPageSource().contains(stamp)); assertLogged(TransactionType.OUTBOX_VIEW, 9000000000L, 0L, ""); driver = login("2", "pw"); assertLogged(TransactionType.HOME_VIEW, 2L, 0L, ""); driver.findElement(By.linkText("Message Inbox")).click(); assertLogged(TransactionType.INBOX_VIEW, 2L, 0L, ""); assertTrue(driver.getPageSource().contains("Kelly Doctor")); assertTrue(driver.getPageSource().contains("Visit Request")); assertTrue(driver.getPageSource().contains(stamp)); } public void testPatientSendReply() throws Exception { driver = login("2", "pw"); assertLogged(TransactionType.HOME_VIEW, 2L, 0L, ""); driver.findElement(By.linkText("Message Inbox")).click(); assertLogged(TransactionType.INBOX_VIEW, 2L, 0L, ""); driver.findElement(By.linkText("Read")).click(); // assertLogged(TransactionType.MESSAGE_VIEW, 2L, 9000000000L, ""); driver.findElement(By.linkText("Reply")).click(); driver.findElement(By.name("messageBody")).clear(); driver.findElement(By.name("messageBody")).sendKeys("Which office visit did you update?"); driver.findElement(By.cssSelector("input[type=\"submit\"]")).click(); assertLogged(TransactionType.MESSAGE_SEND, 2L, 9000000000L, ""); DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm"); Date date = new Date(); String stamp = dateFormat.format(date); driver.findElement(By.linkText("Message Outbox")).click(); assertTrue(driver.getPageSource().contains("RE: Office Visit Updated")); assertTrue(driver.getPageSource().contains("Kelly Doctor")); assertTrue(driver.getPageSource().contains(stamp)); assertLogged(TransactionType.OUTBOX_VIEW, 2L, 0L, ""); driver = login("9000000000", "pw"); assertLogged(TransactionType.HOME_VIEW, 9000000000L, 0L, ""); driver.findElement(By.linkText("Message Inbox")).click(); assertLogged(TransactionType.INBOX_VIEW, 9000000000L, 0L, ""); assertTrue(driver.getPageSource().contains("Andy Programmer")); assertTrue(driver.getPageSource().contains("RE: Office Visit Updated")); assertTrue(driver.getPageSource().contains(stamp)); } }
4,296
44.231579
108
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/selenium/NotificationAreaTest.java
package edu.ncsu.csc.itrust.selenium; import java.text.SimpleDateFormat; import java.util.Date; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; public class NotificationAreaTest extends iTrustSeleniumTest { /* * The URL for iTrust, change as needed */ /** ADDRESS */ public static final String ADDRESS = "http://localhost:8080/iTrust/"; private WebDriver driver; @Override protected void setUp() throws Exception { super.setUp(); gen.clearAllTables(); gen.standardData(); gen.uc60(); // turn off htmlunit warnings java.util.logging.Logger.getLogger("com.gargoylesoftware.htmlunit").setLevel(java.util.logging.Level.OFF); java.util.logging.Logger.getLogger("org.apache.http").setLevel(java.util.logging.Level.OFF); } public void testPatientViewDeclaredProviderFromNotificationCenter() throws Exception { driver = login("2", "pw"); assertEquals(driver.getTitle(), "iTrust - Patient Home"); assertTrue(driver.getPageSource().contains("Gandalf Stormcrow")); assertTrue(driver.getPageSource().contains("999-888-7777")); assertTrue(driver.getPageSource().contains("gstormcrow@iTrust.org")); } public void testHCPTelemedicineDetailsFromNotificationCenter() throws Exception { SimpleDateFormat formatter = new SimpleDateFormat(); formatter.applyPattern("MM/dd/yyyy"); // String tomorrow = formatter.format(new Date((new Date()).getTime() + // 86400000)); gen.appointmentCase3(); gen.remoteMonitoring3(); driver = login("9000000000", "pw"); assertEquals(driver.getTitle(), "iTrust - HCP Home"); assertTrue(driver.getPageSource().contains("3 physiological status reports")); assertTrue(driver.getPageSource().contains("0 weight/pedometer status reports")); } public void testRepresenteeAppointmentDetailsFromNotificationCenter() throws Exception { SimpleDateFormat formatter = new SimpleDateFormat(); formatter.applyPattern("MM/dd/yyyy"); String tomorrow = formatter.format(new Date((new Date()).getTime() + 86400000)); gen.appointmentCase3(); driver = login("1", "pw"); assertEquals(driver.getTitle(), "iTrust - Patient Home"); driver.findElement(By.linkText(tomorrow)).click(); assertTrue(driver.getPageSource().contains("Random Person")); assertTrue(driver.getPageSource().contains("10:30")); assertTrue(driver.getPageSource().contains("Kelly Doctor")); assertTrue(driver.getPageSource().contains("45 minutes")); assertTrue(driver.getPageSource().contains("General Checkup after your knee surgery.")); } public void testUnreadMessagesCount() throws Exception { driver = login("9000000000", "pw"); assertEquals(driver.getTitle(), "iTrust - HCP Home"); assertTrue(driver.getPageSource().contains("12")); } public void testUnpaidBillsCount() throws Exception { driver = login("311", "pw"); assertEquals(driver.getTitle(), "iTrust - Patient Home"); assertTrue(driver.getPageSource().contains("1")); assertTrue(driver.getPageSource().contains("new bill.")); } }
2,983
37.753247
108
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/selenium/PendingApptTest.java
package edu.ncsu.csc.itrust.selenium; import java.util.List; import java.util.concurrent.TimeUnit; import org.junit.After; import org.junit.Before; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.htmlunit.HtmlUnitDriver; /** * Use Case 42 */ public class PendingApptTest extends iTrustSeleniumTest { private WebDriver driver; private String baseUrl; private StringBuffer verificationErrors = new StringBuffer(); @Override @Before public void setUp() throws Exception { super.setUp(); gen.clearAllTables(); gen.standardData(); gen.pendingAppointmentAlert(); driver = new HtmlUnitDriver(); baseUrl = "http://localhost:8080"; driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); } public void testPendingAppointmentAlert() throws Exception { driver.get(baseUrl + "/iTrust/auth/forwardUser.jsp"); driver.findElement(By.id("j_username")).clear(); driver.findElement(By.id("j_username")).sendKeys("9000000000"); driver.findElement(By.id("j_password")).clear(); driver.findElement(By.id("j_password")).sendKeys("pw"); driver.findElement(By.cssSelector("input[type=\"submit\"]")).click(); assertTextPresent("Welcome, Kelly Doctor", driver); assertTextPresent("Appointment requests.", driver); } public void testAcceptAnAppointment() throws Exception { gen.clearAllTables(); gen.standardData(); gen.pendingAppointmentAlert(); driver.get(baseUrl + "/iTrust/auth/forwardUser.jsp"); driver.findElement(By.id("j_username")).clear(); driver.findElement(By.id("j_username")).sendKeys("9000000000"); driver.findElement(By.id("j_password")).clear(); driver.findElement(By.id("j_password")).sendKeys("pw"); driver.findElement(By.cssSelector("input[type=\"submit\"]")).click(); assertTextPresent("Appointment requests.", driver); driver.findElement(By.linkText("Appointment Requests")).click(); driver.findElement(By.linkText("Approve")).click(); driver.get(baseUrl + "/iTrust/auth/hcp/home.jsp"); assertTextPresent("No appointment requests.", driver); } public void testConflictingAppt() throws Exception { gen.clearAllTables(); gen.standardData(); gen.pendingAppointmentConflict(); driver.get(baseUrl + "/iTrust/auth/forwardUser.jsp"); driver.findElement(By.id("j_username")).clear(); driver.findElement(By.id("j_username")).sendKeys("9000000000"); driver.findElement(By.id("j_password")).clear(); driver.findElement(By.id("j_password")).sendKeys("pw"); driver.findElement(By.cssSelector("input[type=\"submit\"]")).click(); assertTrue(driver.findElements(By.linkText("2")).size() > 0); driver.findElement(By.linkText("Appointment Requests")).click(); driver.findElement(By.linkText("Approve")).click(); driver.get(baseUrl + "/iTrust/auth/hcp/home.jsp"); assertTrue(driver.findElements(By.linkText("2")).size() == 0); assertTrue(driver.findElements(By.linkText("1")).size() > 0); } public void testDeclineAnAppointment() throws Exception { gen.clearAllTables(); gen.standardData(); gen.pendingAppointmentAlert(); driver.get(baseUrl + "/iTrust/auth/forwardUser.jsp"); driver.findElement(By.id("j_username")).clear(); driver.findElement(By.id("j_username")).sendKeys("9000000000"); driver.findElement(By.id("j_password")).clear(); driver.findElement(By.id("j_password")).sendKeys("pw"); driver.findElement(By.cssSelector("input[type=\"submit\"]")).click(); assertTextPresent("Appointment requests.", driver); driver.findElement(By.linkText("Appointment Requests")).click(); driver.findElement(By.linkText("Reject")).click(); driver.get(baseUrl + "/iTrust/auth/hcp/home.jsp"); assertTextPresent("No appointment requests.", driver); } @Override @After public void tearDown() throws Exception { driver.quit(); String verificationErrorString = verificationErrors.toString(); if (!"".equals(verificationErrorString)) { fail(verificationErrorString); } } /** * Asserts that the text is on the page * * @param text * @param driver */ public void assertTextPresent(String text, WebDriver driver2) { List<WebElement> list = driver2.findElements(By.xpath("//*[contains(body, \"" + text + "\")]")); assertTrue("Text not found!", list.size() > 0); } /** * Asserts that the text is not on the page. Does not pause for text to * appear. * * @param text * @param driver */ public void assertTextNotPresent(String text, WebDriver driver2) { assertFalse("Text should not be found!", driver2.findElement(By.cssSelector("BODY")).getText().contains(text)); } }
4,620
33.744361
113
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/selenium/PersonnelUseCaseTest.java
package edu.ncsu.csc.itrust.selenium; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.htmlunit.HtmlUnitDriver; import edu.ncsu.csc.itrust.model.old.enums.TransactionType; public class PersonnelUseCaseTest extends iTrustSeleniumTest { @Override protected void setUp() throws Exception { super.setUp(); gen.clearAllTables(); gen.standardData(); } /** ADDRESS */ public static final String ADDRESS = "http://localhost:8080/iTrust/"; /** * testAddER * * @throws Exception */ public void testAddER() throws Exception { // Create a new instance of the html unit driver // Notice that the remainder of the code relies on the interface, // not the implementation. WebDriver driver = new HtmlUnitDriver(); // And now use this to visit iTrust driver.get(ADDRESS); // driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); assertEquals("iTrust - Login", driver.getTitle()); // Find the text input element by its name driver.findElement(By.name("j_username")).sendKeys("9000000001"); driver.findElement(By.name("j_password")).sendKeys("pw"); driver.findElement(By.cssSelector("input[type=\"submit\"]")).click(); assertLogged(TransactionType.HOME_VIEW, 9000000001L, 0L, ""); // Check to make sure this is the correct page assertEquals("iTrust - Admin Home", driver.getTitle()); driver.findElement(By.cssSelector("h2.panel-title")).click(); driver.findElement(By.linkText("Add ER")).click(); assertEquals("iTrust - Add ER", driver.getTitle()); // quit driver driver.quit(); } }
1,598
27.553571
71
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/selenium/SecureMIDNFRTest.java
package edu.ncsu.csc.itrust.selenium; import java.util.concurrent.TimeUnit; import org.junit.Before; import org.junit.Test; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.htmlunit.HtmlUnitDriver; import com.gargoylesoftware.htmlunit.BrowserVersion; import edu.ncsu.csc.itrust.model.old.enums.TransactionType; public class SecureMIDNFRTest extends iTrustSeleniumTest { private HtmlUnitDriver driver; private String baseUrl; @Override @Before public void setUp() throws Exception { super.setUp(); gen.clearAllTables(); gen.standardData(); driver = new HtmlUnitDriver(BrowserVersion.FIREFOX_24); baseUrl = "http://localhost:8080/iTrust/"; driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); driver.setJavascriptEnabled(true); } @Test public void testMIDShown1() throws Exception { driver.get(baseUrl); driver.findElement(By.id("j_username")).clear(); driver.findElement(By.id("j_username")).sendKeys("8000000009"); driver.findElement(By.id("j_password")).clear(); driver.findElement(By.id("j_password")).sendKeys("uappass1"); driver.findElement(By.cssSelector("input[type=\"submit\"]")).click(); assertLogged(TransactionType.HOME_VIEW, 8000000009L, 0L, ""); assertEquals("iTrust - UAP Home", driver.getTitle()); driver.findElement(By.xpath("//div[@id='iTrustMenu']/div/div[2]/div/h2")).click(); driver.findElement(By.linkText("Edit Patient")).click(); driver.findElement(By.id("searchBox")).sendKeys("2"); for (int second = 0;; second++) { if (second >= 60) fail("timeout"); try { if ("".equals(driver.findElement(By.xpath("//input[@value='2']")).getText())) break; } catch (Exception e) { } Thread.sleep(1000); } JavascriptExecutor js = driver; js.executeScript("parent.location.href='getPatientID.jsp?UID_PATIENTID=2&forward=hcp-uap/editPatient.jsp';"); Thread.sleep(1000); assertEquals("iTrust - Edit Patient", driver.getTitle()); assertLogged(TransactionType.DEMOGRAPHICS_VIEW, 8000000009L, 2L, ""); } @Test public void testMIDShown2() throws Exception { driver.get(baseUrl); driver.findElement(By.id("j_username")).clear(); driver.findElement(By.id("j_username")).sendKeys("9000000000"); driver.findElement(By.id("j_password")).clear(); driver.findElement(By.id("j_password")).sendKeys("pw"); driver.findElement(By.cssSelector("input[type=\"submit\"]")).click(); assertLogged(TransactionType.HOME_VIEW, 9000000000L, 0L, ""); assertEquals("iTrust - HCP Home", driver.getTitle()); driver.findElement(By.cssSelector("h2.panel-title")).click(); driver.findElement(By.linkText("Patient Information")).click(); driver.findElement(By.id("searchBox")).sendKeys("2"); for (int second = 0;; second++) { if (second >= 60) fail("timeout"); try { if ("".equals(driver.findElement(By.xpath("//input[@value='2']")).getText())) break; } catch (Exception e) { } Thread.sleep(1000); } JavascriptExecutor js = driver; js.executeScript("parent.location.href='getPatientID.jsp?UID_PATIENTID=2&forward=hcp-uap/editPatient.jsp';"); Thread.sleep(1000); assertEquals("iTrust - Edit Patient", driver.getTitle()); assertLogged(TransactionType.DEMOGRAPHICS_VIEW, 9000000000L, 2L, ""); } }
3,298
34.473118
111
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/selenium/SecurePasswordTest.java
package edu.ncsu.csc.itrust.selenium; import java.util.concurrent.TimeUnit; import org.junit.*; import org.openqa.selenium.By; import org.openqa.selenium.htmlunit.HtmlUnitDriver; import com.gargoylesoftware.htmlunit.BrowserVersion; import edu.ncsu.csc.itrust.model.old.enums.TransactionType; public class SecurePasswordTest extends iTrustSeleniumTest { private HtmlUnitDriver driver; private String baseUrl; @Override @Before public void setUp() throws Exception { super.setUp(); gen.clearAllTables(); gen.standardData(); driver = new HtmlUnitDriver(BrowserVersion.INTERNET_EXPLORER_11); baseUrl = "http://localhost:8080/iTrust/"; driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); } @Test public void testLoginHash() throws Exception { driver.get(baseUrl); driver.findElement(By.id("j_username")).clear(); driver.findElement(By.id("j_username")).sendKeys("9000000000"); driver.findElement(By.id("j_password")).clear(); driver.findElement(By.id("j_password")).sendKeys("pw"); driver.findElement(By.cssSelector("input[type=\"submit\"]")).click(); assertEquals("iTrust - HCP Home", driver.getTitle()); assertLogged(TransactionType.HOME_VIEW, 9000000000L, 0L, ""); } }
1,225
28.902439
71
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/selenium/TelemonitoringUseCaseTest.java
package edu.ncsu.csc.itrust.selenium; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.htmlunit.HtmlUnitDriver; import edu.ncsu.csc.itrust.model.old.enums.TransactionType; /** * Use Case 34 */ public class TelemonitoringUseCaseTest extends iTrustSeleniumTest { /** * setUp */ @Override protected void setUp() throws Exception { super.setUp(); gen.clearAllTables(); gen.standardData(); } /** * testAddPatientsToMonitor * * @throws Exception */ public void testAddPatientsToMonitor() throws Exception { // login HCP WebDriver driver = login("9000000000", "pw"); assertEquals("iTrust - HCP Home", driver.getTitle()); assertLogged(TransactionType.HOME_VIEW, 9000000000L, 0L, ""); // Click Edit Patient List driver.findElement(By.xpath("//a[text()='Edit Patient List']")).click(); driver.findElement(By.name("UID_PATIENTID")).sendKeys("2"); driver.findElement(By.xpath("//input[@value='2']")).submit(); // Allow Blood Pressure, Weight, and Pedometer driver.findElement(By.name("bloodPressure")).click(); driver.findElement(By.name("weight")).click(); driver.findElement(By.name("pedometer")).click(); assertEquals("Add Andy Programmer", driver.findElement(By.name("fSubmit")).getAttribute(VALUE)); driver.findElement(By.name("fSubmit")).click(); assertTrue(driver.findElement(By.cssSelector("BODY")).getText().contains("Patient Andy Programmer Added")); assertLogged(TransactionType.PATIENT_LIST_ADD, 9000000000L, 2L, ""); } /** * testRemovePatientsToMonitor * * @throws Exception */ public void testRemovePatientsToMonitor() throws Exception { // Add patient 1 to HCP 9000000000's monitoring list gen.remoteMonitoring2(); // login HCP HtmlUnitDriver driver = (HtmlUnitDriver) login("9000000000", "pw"); assertEquals("iTrust - HCP Home", driver.getTitle()); assertLogged(TransactionType.HOME_VIEW, 9000000000L, 0L, ""); // Click Edit Patient List driver.findElement(By.xpath("//a[text()='Edit Patient List']")).click(); driver.findElement(By.name("UID_PATIENTID")).sendKeys("1"); driver.findElement(By.xpath("//input[@value='1']")).submit(); assertEquals("Remove Random Person", driver.findElement(By.name("fSubmit")).getAttribute(VALUE)); driver.findElement(By.name("fSubmit")).click(); assertTrue(driver.findElement(By.cssSelector("BODY")).getText().contains("Patient Random Person Removed")); assertLogged(TransactionType.PATIENT_LIST_REMOVE, 9000000000L, 1L, ""); } /** * testReportPatientStatus * * @throws Exception */ public void testReportPatientStatus() throws Exception { // Add patient 1 to HCP 9000000000's monitoring list gen.remoteMonitoring2(); // login Patient WebDriver driver = login("1", "pw"); assertEquals("iTrust - Patient Home", driver.getTitle()); assertLogged(TransactionType.HOME_VIEW, 1L, 0L, ""); // Click Report Status driver.findElement(By.xpath("//a[text()='Report Telemedicine Status']")).click(); driver.findElement(By.name("systolicBloodPressure")).sendKeys("100"); driver.findElement(By.name("diastolicBloodPressure")).sendKeys("75"); driver.findElement(By.name("glucoseLevel")).sendKeys("120"); driver.findElement(By.name("action")).submit(); assertTrue(driver.findElement(By.cssSelector("BODY")).getText().contains("Information Successfully Added")); assertLogged(TransactionType.TELEMEDICINE_DATA_REPORT, 1L, 1L, ""); } /** * testReportPatientWeightAndPedometer * * @throws Exception */ public void testReportPatientWeightAndPedometer() throws Exception { // Add patient 1 to HCP 9000000000's monitoring list gen.remoteMonitoring2(); // login Patient WebDriver driver = login("1", "pw"); assertEquals("iTrust - Patient Home", driver.getTitle()); assertLogged(TransactionType.HOME_VIEW, 1L, 0L, ""); // Click Report Status driver.findElement(By.xpath("//a[text()='Report Telemedicine Status']")).click(); driver.findElement(By.name("weight")).sendKeys("174"); driver.findElement(By.name("pedometerReading")).sendKeys("8238"); driver.findElement(By.name("action")).submit(); assertTrue(driver.findElement(By.cssSelector("BODY")).getText().contains("Information Successfully Added")); assertLogged(TransactionType.TELEMEDICINE_DATA_REPORT, 1L, 1L, ""); } /** * testViewMonitoringList * * @throws Exception */ public void testViewMonitoringList() throws Exception { // Sets up all preconditions listed in acceptance test gen.remoteMonitoring3(); // login HCP WebDriver driver = login("9000000000", "pw"); assertEquals("iTrust - HCP Home", driver.getTitle()); assertLogged(TransactionType.HOME_VIEW, 9000000000L, 0L, ""); driver.findElement(By.xpath("//a[text()='Monitor Patients']")).click(); // Verify all data assertTrue(driver.findElement(By.cssSelector("BODY")).getText().contains("Patient Physiologic Statistics")); DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); java.util.Date date = new java.util.Date(); assertEquals("Random Person (MID 1)", driver.findElement(By.xpath("//table/tbody/tr[3]/td[1]")).getText()); assertTrue( driver.findElement(By.xpath("//table/tbody/tr[3]/td[2]")).getText().contains(dateFormat.format(date))); assertTrue(driver.findElement(By.xpath("//table/tbody/tr[3]/td[2]")).getText().contains("08:00:00")); assertEquals("160", driver.findElement(By.xpath("//table/tbody/tr[3]/td[3]")).getText()); assertEquals("110", driver.findElement(By.xpath("//table/tbody/tr[3]/td[4]")).getText()); assertEquals("60", driver.findElement(By.xpath("//table/tbody/tr[3]/td[5]")).getText()); assertEquals("Andy Programmer", driver.findElement(By.xpath("//table/tbody/tr[3]/td[6]")).getText()); // Highlighting for abnormal data assertEquals("#ffff00", driver.findElement(By.xpath("//table/tbody/tr[3]")).getAttribute("bgcolor")); assertEquals("Random Person (MID 1)", driver.findElement(By.xpath("//table/tbody/tr[4]/td[1]")).getText()); assertTrue( driver.findElement(By.xpath("//table/tbody/tr[4]/td[2]")).getText().contains(dateFormat.format(date))); assertTrue(driver.findElement(By.xpath("//table/tbody/tr[4]/td[2]")).getText().contains("07:15:00")); assertEquals("100", driver.findElement(By.xpath("//table/tbody/tr[4]/td[3]")).getText()); assertEquals("70", driver.findElement(By.xpath("//table/tbody/tr[4]/td[4]")).getText()); assertEquals("90", driver.findElement(By.xpath("//table/tbody/tr[4]/td[5]")).getText()); assertEquals("FirstUAP LastUAP", driver.findElement(By.xpath("//table/tbody/tr[4]/td[6]")).getText()); assertEquals("Random Person (MID 1)", driver.findElement(By.xpath("//table/tbody/tr[5]/td[1]")).getText()); assertTrue( driver.findElement(By.xpath("//table/tbody/tr[5]/td[2]")).getText().contains(dateFormat.format(date))); assertTrue(driver.findElement(By.xpath("//table/tbody/tr[5]/td[2]")).getText().contains("05:30:00")); assertEquals("90", driver.findElement(By.xpath("//table/tbody/tr[5]/td[3]")).getText()); assertEquals("60", driver.findElement(By.xpath("//table/tbody/tr[5]/td[4]")).getText()); assertEquals("80", driver.findElement(By.xpath("//table/tbody/tr[5]/td[5]")).getText()); assertEquals("Random Person", driver.findElement(By.xpath("//table/tbody/tr[5]/td[6]")).getText()); assertEquals("Baby Programmer (MID 5)", driver.findElement(By.xpath("//table/tbody/tr[6]/td[1]")).getText()); assertEquals("No Information Provided", driver.findElement(By.xpath("//table/tbody/tr[6]/td[2]")).getText()); assertEquals("", driver.findElement(By.xpath("//table/tbody/tr[6]/td[3]")).getText()); assertEquals("", driver.findElement(By.xpath("//table/tbody/tr[6]/td[4]")).getText()); assertEquals("", driver.findElement(By.xpath("//table/tbody/tr[6]/td[5]")).getText()); // Highlighting for abnormal data assertEquals("#ff6666", driver.findElement(By.xpath("//table/tbody/tr[6]")).getAttribute("bgcolor")); assertLogged(TransactionType.TELEMEDICINE_DATA_VIEW, 9000000000L, 0L, ""); } /** * testViewWeightAndPedometerReports * * @throws Exception */ public void testViewWeightAndPedometerReports() throws Exception { // Sets up all preconditions listed in acceptance test gen.remoteMonitoring5(); // login HCP WebDriver driver = login("9000000000", "pw"); assertEquals("iTrust - HCP Home", driver.getTitle()); assertLogged(TransactionType.HOME_VIEW, 9000000000L, 0L, ""); driver.findElement(By.xpath("//a[text()='Monitor Patients']")).click(); // Verify all data assertTrue(driver.findElement(By.cssSelector("BODY")).getText().contains("Patient External Statistics")); DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); java.util.Date date = new java.util.Date(); assertEquals("Random Person (MID 1)", driver.findElement(By.xpath("//table[2]/tbody/tr[3]/td[1]")).getText()); assertTrue(driver.findElement(By.xpath("//table[2]/tbody/tr[3]/td[2]")).getText() .contains(dateFormat.format(date))); assertTrue(driver.findElement(By.xpath("//table[2]/tbody/tr[3]/td[2]")).getText().contains("07:17:00")); assertEquals("186.5", driver.findElement(By.xpath("//table/tbody/tr[3]/td[4]")).getText()); assertEquals("", driver.findElement(By.xpath("//table/tbody/tr[3]/td[5]")).getText()); assertEquals("Random Person", driver.findElement(By.xpath("//table/tbody/tr[3]/td[6]")).getText()); // Highlighting for abnormal data assertEquals("#ffff00", driver.findElement(By.xpath("//table[2]/tbody/tr[3]")).getAttribute("bgcolor")); assertLogged(TransactionType.TELEMEDICINE_DATA_VIEW, 9000000000L, 0L, ""); } /** * testUAPReportPatientStatus * * @throws Exception */ public void testUAPReportPatientStatus() throws Exception { gen.remoteMonitoringUAP(); WebDriver driver = login("8000000009", "uappass1"); assertEquals("iTrust - UAP Home", driver.getTitle()); assertLogged(TransactionType.HOME_VIEW, 8000000009L, 0L, ""); driver.findElement(By.xpath("//a[text()='Report Telemedicine Status']")).click(); assertEquals("iTrust - View Monitored Patients", driver.getTitle()); driver.findElement(By.linkText("Andy Programmer")).click(); assertEquals("iTrust - Report Status", driver.getTitle()); driver.findElement(By.name("systolicBloodPressure")).sendKeys("100"); driver.findElement(By.name("diastolicBloodPressure")).sendKeys("75"); driver.findElement(By.name("glucoseLevel")).sendKeys("120"); driver.findElement(By.name("action")).submit(); assertTrue(driver.findElement(By.cssSelector("BODY")).getText().contains("Information Successfully Added")); assertLogged(TransactionType.TELEMEDICINE_DATA_REPORT, 8000000009L, 2L, ""); } /** * testRepresentativeReportPatientStatus * * @throws Exception */ public void testRepresentativeReportPatientStatus() throws Exception { gen.remoteMonitoring4(); HtmlUnitDriver driver = (HtmlUnitDriver) login("2", "pw"); assertEquals("iTrust - Patient Home", driver.getTitle()); assertLogged(TransactionType.HOME_VIEW, 2L, 0L, ""); driver.findElement(By.xpath("//a[text()='Report Telemedicine Status']")).click(); assertEquals("iTrust - Report Status", driver.getTitle()); // have to use JS driver.setJavascriptEnabled(true); driver.findElement(By.linkText("Random Person")).click(); driver.findElement(By.name("glucoseLevel")).sendKeys("120"); driver.findElement(By.name("action")).click(); assertTrue(driver.findElement(By.cssSelector("BODY")).getText().contains("Information Successfully Added")); assertLogged(TransactionType.TELEMEDICINE_DATA_REPORT, 2L, 1L, ""); } /** * testRepresentativeReportWeight * * @throws Exception */ public void testRepresentativeReportWeight() throws Exception { // Add patient 1 to HCP 9000000000's monitoring list // Also add three reports gen.remoteMonitoring2(); // login Patient HtmlUnitDriver driver = (HtmlUnitDriver) login("2", "pw"); assertEquals("iTrust - Patient Home", driver.getTitle()); assertLogged(TransactionType.HOME_VIEW, 2L, 0L, ""); // Click Report Status driver.findElement(By.xpath("//a[text()='Report Telemedicine Status']")).click(); assertEquals("iTrust - Report Status", driver.getTitle()); // have to use JS driver.setJavascriptEnabled(true); driver.findElement(By.linkText("Random Person")).click(); driver.findElement(By.name("weight")).sendKeys("174"); driver.findElement(By.name("action")).click(); assertTrue(driver.findElement(By.cssSelector("BODY")).getText().contains("Information Successfully Added")); assertLogged(TransactionType.TELEMEDICINE_DATA_REPORT, 2L, 1L, ""); } /** * testUAPReportPatientPedometerReading * * @throws Exception */ public void testUAPReportPatientPedometerReading() throws Exception { // Add patient 1 to HCP 9000000000's monitoring list // Also add three reports gen.remoteMonitoring2(); gen.remoteMonitoringUAP(); // login Patient HtmlUnitDriver driver = (HtmlUnitDriver) login("8000000009", "uappass1"); assertEquals("iTrust - UAP Home", driver.getTitle()); assertLogged(TransactionType.HOME_VIEW, 8000000009L, 0L, ""); // Click Report Status driver.findElement(By.xpath("//a[text()='Report Telemedicine Status']")).click(); // have to use JS driver.setJavascriptEnabled(true); driver.findElement(By.linkText("Andy Programmer")).click(); driver.findElement(By.name("pedometerReading")).sendKeys("9163"); driver.findElement(By.name("action")).click(); assertTrue(driver.findElement(By.cssSelector("BODY")).getText().contains("Information Successfully Added")); assertLogged(TransactionType.TELEMEDICINE_DATA_REPORT, 8000000009L, 2L, ""); } /** * testUAPAddPatientToMonitorTest * * @throws Exception */ public void testUAPAddPatientToMonitorTest() throws Exception { HtmlUnitDriver driver = (HtmlUnitDriver) login("8000000009", "uappass1"); assertEquals("iTrust - UAP Home", driver.getTitle()); assertLogged(TransactionType.HOME_VIEW, 8000000009L, 0L, ""); driver.findElement(By.xpath("//a[text()='Edit Patient List']")).click(); // search patient with mid 2 driver.findElement(By.name("UID_PATIENTID")).sendKeys("2"); driver.findElement(By.xpath("//input[@value='2']")).submit(); assertEquals("Add Andy Programmer", driver.findElement(By.cssSelector("input[type=\"submit\"]")).getAttribute(VALUE)); driver.findElement(By.cssSelector("input[type=\"submit\"]")).click(); assertTrue(driver.findElement(By.cssSelector("BODY")).getText().contains("Patient Andy Programmer Added")); assertLogged(TransactionType.PATIENT_LIST_ADD, 8000000009L, 2L, ""); } /** * testUAPAddHCPMonitor * * @throws Exception */ public void testUAPAddHCPMonitor() throws Exception { gen.remoteMonitoring8(); HtmlUnitDriver driver = (HtmlUnitDriver) login("8000000009", "uappass1"); assertEquals("iTrust - UAP Home", driver.getTitle()); assertLogged(TransactionType.HOME_VIEW, 8000000009L, 0L, ""); driver.findElement(By.xpath("//a[text()='Edit Patient List']")).click(); // search patient with mid 2 driver.findElement(By.name("UID_PATIENTID")).sendKeys("2"); driver.findElement(By.xpath("//input[@value='2']")).submit(); assertEquals("Add Andy Programmer", driver.findElement(By.cssSelector("input[type=\"submit\"]")).getAttribute(VALUE)); driver.findElement(By.cssSelector("input[type=\"submit\"]")).click(); assertTrue(driver.findElement(By.cssSelector("BODY")).getText().contains("Patient Andy Programmer Added")); assertLogged(TransactionType.PATIENT_LIST_ADD, 8000000009L, 2L, ""); // go to reporting page driver.findElement(By.xpath("//a[text()='Report Telemedicine Status']")).click(); assertTrue(driver.findElement(By.cssSelector("BODY")).getText().contains("Andy Programmer")); assertEquals("iTrust - Report Status", driver.getTitle()); driver.findElement(By.name("systolicBloodPressure")).sendKeys("110"); driver.findElement(By.name("diastolicBloodPressure")).sendKeys("85"); driver.findElement(By.name("action")).click(); assertTrue(driver.findElement(By.cssSelector("BODY")).getText().contains("Information Successfully Added")); assertLogged(TransactionType.TELEMEDICINE_DATA_REPORT, 8000000009L, 2L, ""); // logout driver.findElement(By.xpath("//a[text()='Logout']")).click(); // log back in HtmlUnitDriver HCPdriver = (HtmlUnitDriver) login("9000000000", "pw"); assertEquals("iTrust - HCP Home", HCPdriver.getTitle()); assertLogged(TransactionType.HOME_VIEW, 9000000000L, 0L, ""); HCPdriver.findElement(By.xpath("//a[text()='Monitor Patients']")).click(); assertEquals("Andy Programmer (MID 2)", HCPdriver.findElement(By.xpath("//table/tbody/tr[3]/td[1]")).getText()); assertEquals("110", HCPdriver.findElement(By.xpath("//table/tbody/tr[3]/td[3]")).getText()); assertEquals("85", HCPdriver.findElement(By.xpath("//table/tbody/tr[3]/td[4]")).getText()); assertEquals("", HCPdriver.findElement(By.xpath("//table/tbody/tr[3]/td[5]")).getText()); assertLogged(TransactionType.TELEMEDICINE_DATA_VIEW, 9000000000L, 0L, ""); } /** * testUAPAddReportDeleteCannotReport * * @throws Exception */ public void testUAPAddReportDeleteCannotReport() throws Exception { gen.remoteMonitoring8(); // log in to iTrust HtmlUnitDriver driver = (HtmlUnitDriver) login("8000000009", "uappass1"); assertEquals("iTrust - UAP Home", driver.getTitle()); assertLogged(TransactionType.HOME_VIEW, 8000000009L, 0L, ""); // add Patient 2 to reporting list driver.findElement(By.xpath("//a[text()='Edit Patient List']")).click(); // search patient with mid 2 driver.findElement(By.name("UID_PATIENTID")).sendKeys("2"); driver.findElement(By.xpath("//input[@value='2']")).submit(); assertEquals("Add Andy Programmer", driver.findElement(By.cssSelector("input[type=\"submit\"]")).getAttribute(VALUE)); driver.findElement(By.cssSelector("input[type=\"submit\"]")).click(); assertTrue(driver.findElement(By.cssSelector("BODY")).getText().contains("Patient Andy Programmer Added")); assertLogged(TransactionType.PATIENT_LIST_ADD, 8000000009L, 2L, ""); // go to reporting page driver.findElement(By.xpath("//a[text()='Report Telemedicine Status']")).click(); assertTrue(driver.findElement(By.cssSelector("BODY")).getText().contains("Andy Programmer")); assertEquals("iTrust - Report Status", driver.getTitle()); driver.findElement(By.name("systolicBloodPressure")).sendKeys("100"); driver.findElement(By.name("diastolicBloodPressure")).sendKeys("75"); driver.findElement(By.name("action")).click(); assertTrue(driver.findElement(By.cssSelector("BODY")).getText().contains("Information Successfully Added")); assertLogged(TransactionType.TELEMEDICINE_DATA_REPORT, 8000000009L, 2L, ""); // remove Patient 2 from reporting list driver.findElement(By.xpath("//a[text()='Edit Patient List']")).click(); assertEquals("Remove Andy Programmer", driver.findElement(By.cssSelector("input[type=\"submit\"]")).getAttribute(VALUE)); driver.findElement(By.cssSelector("input[type=\"submit\"]")).click(); assertTrue(driver.findElement(By.cssSelector("BODY")).getText().contains("Patient Andy Programmer Removed")); assertLogged(TransactionType.PATIENT_LIST_REMOVE, 8000000009L, 2L, ""); } // Test for UC34 /** * testWeightHighlighting * * @throws Exception */ public void testWeightHighlighting() throws Exception { gen.remoteMonitoring6(); HtmlUnitDriver driver = (HtmlUnitDriver) login("9000000000", "pw"); assertEquals("iTrust - HCP Home", driver.getTitle()); assertLogged(TransactionType.HOME_VIEW, 9000000000L, 0L, ""); driver.findElement(By.xpath("//a[text()='Monitor Patients']")).click(); DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); java.util.Date date = new java.util.Date(); assertEquals("Random Person (MID 1)", driver.findElement(By.xpath("//table[2]/tbody/tr[3]/td[1]")).getText()); assertTrue(driver.findElement(By.xpath("//table[2]/tbody/tr[3]/td[2]")).getText() .contains(dateFormat.format(date))); assertTrue(driver.findElement(By.xpath("//table[2]/tbody/tr[3]/td[2]")).getText().contains("07:17:00")); assertEquals("70.0", driver.findElement(By.xpath("//table/tbody/tr[3]/td[3]")).getText()); assertEquals("192.5", driver.findElement(By.xpath("//table/tbody/tr[3]/td[4]")).getText()); assertEquals("", driver.findElement(By.xpath("//table/tbody/tr[3]/td[5]")).getText()); assertEquals("Random Person", driver.findElement(By.xpath("//table/tbody/tr[3]/td[6]")).getText()); // Highlighting for abnormal data assertEquals("#ffff00", driver.findElement(By.xpath("//table[2]/tbody/tr[3]")).getAttribute("bgcolor")); assertLogged(TransactionType.TELEMEDICINE_DATA_VIEW, 9000000000L, 0L, ""); } // Test for UC34 /** * testDetailedExternalData * * @throws Exception */ public void testDetailedExternalData() throws Exception { gen.remoteMonitoring6(); HtmlUnitDriver driver = (HtmlUnitDriver) login("9000000000", "pw"); assertEquals("iTrust - HCP Home", driver.getTitle()); assertLogged(TransactionType.HOME_VIEW, 9000000000L, 0L, ""); driver.findElement(By.xpath("//a[text()='Monitor Patients']")).click(); driver.findElement(By.xpath("//a[text()='Random Person (MID 1)']")).click(); int ONE_DAY = 24 * 60 * 60 * 1000; SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy"); SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd"); java.util.Date date = new java.util.Date(); date.setTime(date.getTime() - 3 * (long) ONE_DAY); Date yesterday = new Date(); yesterday.setTime(yesterday.getTime() - ONE_DAY); Date twoDaysAgo = new Date(yesterday.getTime() - ONE_DAY); driver.findElement(By.name("startDate")).clear(); driver.findElement(By.name("startDate")).sendKeys(sdf.format(date)); assertEquals(sdf.format(date), driver.findElement(By.name("startDate")).getAttribute(VALUE)); driver.findElement(By.name("submit")).submit(); // First entry: assertEquals(sdf2.format(new Date()) + " 07:17:00.0", driver.findElement(By.xpath("//table[4]/tbody/tr[3]/td[1]")).getText()); assertEquals("70.0", driver.findElement(By.xpath("//table[4]/tbody/tr[3]/td[2]")).getText()); assertEquals("192.5", driver.findElement(By.xpath("//table[4]/tbody/tr[3]/td[3]")).getText()); assertEquals("", driver.findElement(By.xpath("//table[4]/tbody/tr[3]/td[4]")).getText()); // Second entry: assertEquals(sdf2.format(yesterday) + " 07:48:00.0", driver.findElement(By.xpath("//table[4]/tbody/tr[4]/td[1]")).getText()); assertEquals("70.0", driver.findElement(By.xpath("//table[4]/tbody/tr[4]/td[2]")).getText()); assertEquals("", driver.findElement(By.xpath("//table[4]/tbody/tr[4]/td[3]")).getText()); assertEquals("8153", driver.findElement(By.xpath("//table[4]/tbody/tr[4]/td[4]")).getText()); // Third entry: assertEquals(sdf2.format(twoDaysAgo) + " 08:19:00.0", driver.findElement(By.xpath("//table[4]/tbody/tr[5]/td[1]")).getText()); assertEquals("70.0", driver.findElement(By.xpath("//table[4]/tbody/tr[5]/td[2]")).getText()); assertEquals("180.0", driver.findElement(By.xpath("//table[4]/tbody/tr[5]/td[3]")).getText()); assertEquals("", driver.findElement(By.xpath("//table[4]/tbody/tr[5]/td[4]")).getText()); assertLogged(TransactionType.TELEMEDICINE_DATA_VIEW, 9000000000L, 0L, ""); } // Test for UC34 /** * testReportPatientHeight * * @throws Exception */ public void testReportPatientHeight() throws Exception { gen.remoteMonitoring7(); HtmlUnitDriver driver = (HtmlUnitDriver) login("1", "pw"); assertEquals("iTrust - Patient Home", driver.getTitle()); assertLogged(TransactionType.HOME_VIEW, 1L, 0L, ""); driver.findElement(By.xpath("//a[text()='Report Telemedicine Status']")).click(); driver.findElement(By.name("height")).sendKeys("73.2"); driver.findElement(By.name("action")).click(); assertTrue(driver.findElement(By.cssSelector("BODY")).getText().contains("Information Successfully Added")); assertLogged(TransactionType.TELEMEDICINE_DATA_REPORT, 1L, 1L, ""); driver.findElement(By.xpath("//a[text()='Report Telemedicine Status']")).click(); driver.findElement(By.name("height")).sendKeys("73.2"); driver.findElement(By.name("action")).click(); assertTrue(driver.findElement(By.cssSelector("BODY")).getText() .contains("Invalid entry: Patient height entries for today cannot exceed 1.")); } }
24,493
42.352212
114
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/selenium/UploadPatientFileTest.java
package edu.ncsu.csc.itrust.selenium; import org.junit.Test; import org.openqa.selenium.By; import org.openqa.selenium.htmlunit.HtmlUnitDriver; /** * Tests the functionality of the Upload Patient File page in iTrust */ public class UploadPatientFileTest extends iTrustSeleniumTest { // Not sure what this is for, the Sel IDE just made it, might delete private StringBuffer verificationErrors = new StringBuffer(); @Override protected void setUp() throws Exception { super.setUp(); gen.clearAllTables(); gen.standardData(); } @Test /** * Tests the patient file upload with a valid file that should be successful * * @throws Exception */ public void testHCPPatientUploadValidData() throws Exception { // This logs us into iTrust and returns the HtmlUnitDriver for use in // this case HtmlUnitDriver driver = (HtmlUnitDriver) login("9000000000", "pw"); // Make sure we were able to log in assertEquals("iTrust - HCP Home", driver.getTitle()); driver.findElement(By.cssSelector("h2.panel-title")).click(); driver.findElement(By.xpath("//div[@id='iTrustMenu']/div/div[6]/div/h2")).click(); driver.findElement(By.linkText("Upload Patient File")).click(); assertEquals("iTrust - Upload Patient File", driver.getTitle()); driver.findElement(By.name("patientFile")).clear(); // These testing files already exist in iTrust, so we just need to // specify the path to them driver.findElement(By.name("patientFile")) .sendKeys("/iTrust/testing-files/sample_patientupload/HCPPatientUploadValidData.csv"); driver.findElement(By.id("sendFile")).click(); try { assertEquals("Upload Successful", driver.findElement(By.cssSelector("span.iTrustMessage")).getText()); } catch (Error e) { verificationErrors.append(e.toString()); } } /** * Tests the patient file upload with a file that has a missing email field * * @throws Exception */ public void testHCPPatientUploadRequiredFieldMissing() throws Exception { HtmlUnitDriver driver = (HtmlUnitDriver) login("9000000000", "pw"); assertEquals("iTrust - HCP Home", driver.getTitle()); driver.findElement(By.cssSelector("h2.panel-title")).click(); driver.findElement(By.xpath("//div[@id='iTrustMenu']/div/div[6]/div/h2")).click(); driver.findElement(By.linkText("Upload Patient File")).click(); assertEquals("iTrust - Upload Patient File", driver.getTitle()); driver.findElement(By.name("patientFile")).clear(); // These testing files already exist in iTrust, so we just need to // specify the path to them driver.findElement(By.name("patientFile")) .sendKeys("/iTrust/testing-files/sample_patientupload/HCPPatientUploadRequiredFieldMissing.csv"); driver.findElement(By.id("sendFile")).click(); try { assertEquals("File upload was unsuccessful", driver.findElement(By.cssSelector("span.iTrustMessage")).getText()); } catch (Error e) { verificationErrors.append(e.toString()); } } /** * Tests the file upload with a file that has an invalid field. * * @throws Exception */ public void testHCPPatientUploadInvalidField() throws Exception { HtmlUnitDriver driver = (HtmlUnitDriver) login("9000000000", "pw"); assertEquals("iTrust - HCP Home", driver.getTitle()); driver.findElement(By.cssSelector("h2.panel-title")).click(); driver.findElement(By.xpath("//div[@id='iTrustMenu']/div/div[6]/div/h2")).click(); driver.findElement(By.linkText("Upload Patient File")).click(); assertEquals("iTrust - Upload Patient File", driver.getTitle()); driver.findElement(By.name("patientFile")).clear(); // These testing files already exist in iTrust, so we just need to // specify the path to them driver.findElement(By.name("patientFile")) .sendKeys("/iTrust/testing-files/sample_patientupload/HCPPatientUploadInvalidField.csv"); driver.findElement(By.id("sendFile")).click(); try { assertEquals("File upload was unsuccessful", driver.findElement(By.cssSelector("span.iTrustMessage")).getText()); assertEquals("Field \"invalidfield\" is invalid", driver.findElement(By.cssSelector("span.iTrustMessage")).getText()); } catch (Error e) { verificationErrors.append(e.toString()); } } /** * Tests the file upload with a file that has mismatched fields. * * @throws Exception */ public void testHCPPatientUploadInvalidData() throws Exception { HtmlUnitDriver driver = (HtmlUnitDriver) login("9000000000", "pw"); assertEquals("iTrust - HCP Home", driver.getTitle()); driver.findElement(By.cssSelector("h2.panel-title")).click(); driver.findElement(By.xpath("//div[@id='iTrustMenu']/div/div[6]/div/h2")).click(); driver.findElement(By.linkText("Upload Patient File")).click(); assertEquals("iTrust - Upload Patient File", driver.getTitle()); driver.findElement(By.name("patientFile")).clear(); // These testing files already exist in iTrust, so we just need to // specify the path to them driver.findElement(By.name("patientFile")) .sendKeys("/iTrust/testing-files/sample_patientupload/HCPPatientUploadInvalidData.csv"); driver.findElement(By.id("sendFile")).click(); try { assertEquals("File upload was successful, but some patients could not be added", driver.findElement(By.cssSelector("span.iTrustMessage")).getText()); assertEquals("Field number mismatch on line 3", driver.findElement(By.cssSelector("span.iTrustMessage")).getText()); assertEquals("Field number mismatch on line 4", driver.findElement(By.cssSelector("span.iTrustMessage")).getText()); } catch (Error e) { verificationErrors.append(e.toString()); } } /** * Tests the file upload with a file is empty * * @throws Exception */ public void testHCPPatientUploadEmptyFile() throws Exception { HtmlUnitDriver driver = (HtmlUnitDriver) login("9000000000", "pw"); assertEquals("iTrust - HCP Home", driver.getTitle()); driver.findElement(By.cssSelector("h2.panel-title")).click(); driver.findElement(By.xpath("//div[@id='iTrustMenu']/div/div[6]/div/h2")).click(); driver.findElement(By.linkText("Upload Patient File")).click(); assertEquals("iTrust - Upload Patient File", driver.getTitle()); driver.findElement(By.name("patientFile")).clear(); // These testing files already exist in iTrust, so we just need to // specify the path to them driver.findElement(By.name("patientFile")) .sendKeys("/iTrust/testing-files/sample_patientupload/HCPPatientUploadEmptyFile.csv"); driver.findElement(By.id("sendFile")).click(); try { assertEquals("File upload was unsuccessful", driver.findElement(By.cssSelector("span.iTrustMessage")).getText()); assertEquals("File is not valid CSV file", driver.findElement(By.cssSelector("span.iTrustMessage")).getText()); } catch (Error e) { verificationErrors.append(e.toString()); } } /** * Tests the file upload with a file that has duplicate fields * * @throws Exception */ public void testHCPPatientUploadDuplicateField() throws Exception { HtmlUnitDriver driver = (HtmlUnitDriver) login("9000000000", "pw"); assertEquals("iTrust - HCP Home", driver.getTitle()); driver.findElement(By.cssSelector("h2.panel-title")).click(); driver.findElement(By.xpath("//div[@id='iTrustMenu']/div/div[6]/div/h2")).click(); driver.findElement(By.linkText("Upload Patient File")).click(); assertEquals("iTrust - Upload Patient File", driver.getTitle()); driver.findElement(By.name("patientFile")).clear(); // These testing files already exist in iTrust, so we just need to // specify the path to them driver.findElement(By.name("patientFile")) .sendKeys("/iTrust/testing-files/sample_patientupload/HCPPatientUploadDuplicateField.csv"); driver.findElement(By.id("sendFile")).click(); try { assertEquals("File upload was unsuccessful", driver.findElement(By.cssSelector("span.iTrustMessage")).getText()); assertEquals("Duplicate field \"firstName\"", driver.findElement(By.cssSelector("span.iTrustMessage")).getText()); } catch (Error e) { verificationErrors.append(e.toString()); } } /** * Tests the file upload with a file that is a different type and has binary * data * * @throws Exception */ public void testHCPPatientUploadBinaryData() throws Exception { HtmlUnitDriver driver = (HtmlUnitDriver) login("9000000000", "pw"); assertEquals("iTrust - HCP Home", driver.getTitle()); driver.findElement(By.cssSelector("h2.panel-title")).click(); driver.findElement(By.xpath("//div[@id='iTrustMenu']/div/div[6]/div/h2")).click(); driver.findElement(By.linkText("Upload Patient File")).click(); assertEquals("iTrust - Upload Patient File", driver.getTitle()); driver.findElement(By.name("patientFile")).clear(); // These testing files already exist in iTrust, so we just need to // specify the path to them driver.findElement(By.name("patientFile")) .sendKeys("/iTrust/testing-files/sample_patientupload/HCPPatientUploadBinaryData.doc"); driver.findElement(By.id("sendFile")).click(); try { assertEquals("File upload was unsuccessful", driver.findElement(By.cssSelector("span.iTrustMessage")).getText()); } catch (Error e) { verificationErrors.append(e.toString()); } } }
9,206
40.286996
105
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/selenium/ViewAccessLogTest.java
package edu.ncsu.csc.itrust.selenium; import java.util.concurrent.TimeUnit; import org.junit.After; import org.junit.Test; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.htmlunit.HtmlUnitDriver; import edu.ncsu.csc.itrust.model.old.enums.TransactionType; import edu.ncsu.csc.itrust.selenium.iTrustSeleniumTest; public class ViewAccessLogTest extends iTrustSeleniumTest { private WebDriver driver; private StringBuffer verificationErrors = new StringBuffer(); @Override protected void setUp() throws Exception { driver = new HtmlUnitDriver(); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); super.setUp(); gen.clearAllTables(); gen.uap1(); gen.patient2(); gen.patient1(); gen.patient4(); gen.hcp0(); gen.hcp3(); gen.er4(); } @Test public void testViewaccesslog2() throws Exception { // clear operational profile gen.transactionLog(); // This logs us into iTrust and returns the HtmlUnitDriver for use in // this case HtmlUnitDriver driver = (HtmlUnitDriver) login("2", "pw"); assertEquals("iTrust - Patient Home", driver.getTitle()); assertLogged(TransactionType.HOME_VIEW, 2L, 0L, ""); driver.findElement(By.id("toggleMenu")).click(); driver.findElement(By.xpath("//div[@id='iTrustMenu']/div/div[2]/div/h2")).click(); driver.findElement(By.linkText("Access Log")).click(); assertEquals("iTrust - View My Access Log", driver.getTitle()); driver.findElement(By.name("startDate")).clear(); driver.findElement(By.name("startDate")).sendKeys("06/22/2000"); driver.findElement(By.name("endDate")).clear(); driver.findElement(By.name("endDate")).sendKeys("06/23/2000"); driver.findElement(By.name("submit")).click(); assertEquals("iTrust - View My Access Log", driver.getTitle()); assertLogged(TransactionType.ACCESS_LOG_VIEW, 2L, 0L, ""); } @Test public void testViewAccessLog3() throws Exception { // clear operational profile gen.transactionLog(); // This logs us into iTrust and returns the HtmlUnitDriver for use in // this case HtmlUnitDriver driver = (HtmlUnitDriver) login("1", "pw"); assertEquals("iTrust - Patient Home", driver.getTitle()); assertLogged(TransactionType.HOME_VIEW, 1L, 0L, ""); driver.findElement(By.id("toggleMenu")).click(); driver.findElement(By.xpath("//div[@id='iTrustMenu']/div/div[2]/div/h2")).click(); driver.findElement(By.linkText("Access Log")).click(); assertEquals("iTrust - View My Access Log", driver.getTitle()); assertLogged(TransactionType.ACCESS_LOG_VIEW, 1L, 0L, ""); } @Test public void testViewAccessLogByDate() throws Exception { gen.transactionLog2(); // This logs us into iTrust and returns the HtmlUnitDriver for use in // this case HtmlUnitDriver driver = (HtmlUnitDriver) login("2", "pw"); assertEquals("iTrust - Patient Home", driver.getTitle()); assertLogged(TransactionType.HOME_VIEW, 2L, 0L, ""); driver.findElement(By.id("toggleMenu")).click(); driver.findElement(By.xpath("//div[@id='iTrustMenu']/div/div[2]/div/h2")).click(); driver.findElement(By.linkText("Access Log")).click(); assertEquals("iTrust - View My Access Log", driver.getTitle()); driver.findElement(By.name("startDate")).clear(); driver.findElement(By.name("startDate")).sendKeys("03/01/2008"); driver.findElement(By.name("endDate")).clear(); driver.findElement(By.name("endDate")).sendKeys("12/01/2008"); driver.findElement(By.name("submit")).click(); // The rest of the original test was commented out } @Test public void testViewAccessLogByRole() throws Exception { gen.transactionLog3(); // This logs us into iTrust and returns the HtmlUnitDriver for use in // this case HtmlUnitDriver driver = (HtmlUnitDriver) login("1", "pw"); driver.setJavascriptEnabled(true); assertEquals("iTrust - Patient Home", driver.getTitle()); assertLogged(TransactionType.HOME_VIEW, 1L, 0L, ""); driver.findElement(By.id("toggleMenu")).click(); driver.findElement(By.xpath("//div[@id='iTrustMenu']/div/div[2]/div/h2")).click(); driver.findElement(By.linkText("Access Log")).click(); assertEquals("iTrust - View My Access Log", driver.getTitle()); driver.findElement(By.name("startDate")).clear(); driver.findElement(By.name("startDate")).sendKeys("02/01/2008"); driver.findElement(By.name("endDate")).clear(); driver.findElement(By.name("endDate")).sendKeys("09/22/2009"); driver.findElement(By.name("submit")).click(); driver.findElement(By.linkText("Role")).click(); driver.findElement(By.name("submit")).click(); assertEquals("LHCP", driver.findElement(By.xpath("//div[@id='iTrustContent']/table/tbody/tr[2]/td[3]")).getText()); assertEquals("Emergency Responder", driver.findElement(By.xpath("//div[@id='iTrustContent']/table/tbody/tr[3]/td[3]")).getText()); assertEquals("Personal Health Representative", driver.findElement(By.xpath("//div[@id='iTrustContent']/table/tbody/tr[4]/td[3]")).getText()); assertEquals("UAP", driver.findElement(By.xpath("//div[@id='iTrustContent']/table/tbody/tr[5]/td[3]")).getText()); assertEquals("LHCP", driver.findElement(By.xpath("//div[@id='iTrustContent']/table/tbody/tr[6]/td[3]")).getText()); assertEquals("LHCP", driver.findElement(By.xpath("//div[@id='iTrustContent']/table/tbody/tr[7]/td[3]")).getText()); assertLogged(TransactionType.ACCESS_LOG_VIEW, 1L, 0L, ""); } @Test public void testViewAccessLogRepresentativeView() throws Exception { gen.clearAllTables(); gen.standardData(); // This logs us into iTrust and returns the HtmlUnitDriver for use in // this case HtmlUnitDriver driver = (HtmlUnitDriver) login("1", "pw"); assertEquals("iTrust - Patient Home", driver.getTitle()); driver.findElement(By.id("toggleMenu")).click(); driver.findElement(By.xpath("//div[@id='iTrustMenu']/div/div[2]/div/h2")).click(); driver.findElement(By.linkText("Access Log")).click(); // new // Select(driver.findElement(By.id("logMIDSelectMenu"))).selectByVisibleText("Dare // Devil"); driver.findElement(By.name("submit")).click(); // There is no way to read all text on the page through Selenium assertEquals("iTrust - View My Access Log", driver.getTitle()); assertEquals("Kelly Doctor", driver.findElement(By.xpath("//div[@id='iTrustContent']/table/tbody/tr[2]/td[2]")).getText()); assertEquals("Justin Time", driver.findElement(By.xpath("//div[@id='iTrustContent']/table/tbody/tr[3]/td[2]")).getText()); assertEquals("Andy Programmer", driver.findElement(By.xpath("//div[@id='iTrustContent']/table/tbody/tr[4]/td[2]")).getText()); driver.findElement(By.linkText("Role")).click(); driver.findElement(By.name("submit")).click(); assertEquals("iTrust - View My Access Log", driver.getTitle()); assertEquals("Kelly Doctor", driver.findElement(By.xpath("//div[@id='iTrustContent']/table/tbody/tr[2]/td[2]")).getText()); assertEquals("Justin Time", driver.findElement(By.xpath("//div[@id='iTrustContent']/table/tbody/tr[3]/td[2]")).getText()); assertEquals("Andy Programmer", driver.findElement(By.xpath("//div[@id='iTrustContent']/table/tbody/tr[4]/td[2]")).getText()); } @Test public void testViewAccessLogNonRepresentativeView1() throws Exception { gen.clearAllTables(); gen.standardData(); // This logs us into iTrust and returns the HtmlUnitDriver for use in // this case HtmlUnitDriver driver = (HtmlUnitDriver) login("1", "pw"); assertEquals("iTrust - Patient Home", driver.getTitle()); // Check the text currently in the drop down box to ensure it is not // "Devil's Advocate" driver.findElement(By.id("toggleMenu")).click(); driver.findElement(By.xpath("//div[@id='iTrustMenu']/div/div[2]/div/h2")).click(); driver.findElement(By.linkText("Access Log")).click(); assertEquals("iTrust - View My Access Log", driver.getTitle()); assertEquals("Random Person", driver.findElement(By.id("logMIDSelectMenu")).getText()); } public void testViewAccessLogBadDateHandling() throws Exception { gen.clearAllTables(); gen.standardData(); // This logs us into iTrust and returns the HtmlUnitDriver for use in // this case HtmlUnitDriver driver = (HtmlUnitDriver) login("23", "pw"); assertEquals("iTrust - Patient Home", driver.getTitle()); driver.findElement(By.id("toggleMenu")).click(); driver.findElement(By.xpath("//div[@id='iTrustMenu']/div/div[2]/div/h2")).click(); driver.findElement(By.linkText("Access Log")).click(); assertEquals("iTrust - View My Access Log", driver.getTitle()); driver.findElement(By.name("startDate")).clear(); driver.findElement(By.name("startDate")).sendKeys("06/22/2007"); driver.findElement(By.name("endDate")).clear(); driver.findElement(By.name("endDate")).sendKeys("06/21/2007"); driver.findElement(By.name("submit")).click(); assertEquals("iTrust - View My Access Log", driver.getTitle()); assertEquals("Information not valid", driver.findElement(By.cssSelector("#iTrustContent > h2")).getText()); assertEquals("Start date must be before end date!", driver.findElement(By.cssSelector("div.errorList")).getText()); driver.findElement(By.name("startDate")).clear(); driver.findElement(By.name("startDate")).sendKeys("June 22nd, 2007"); driver.findElement(By.name("endDate")).clear(); driver.findElement(By.name("endDate")).sendKeys("6/23/2007"); driver.findElement(By.name("submit")).click(); assertEquals("iTrust - View My Access Log", driver.getTitle()); assertEquals("Information not valid", driver.findElement(By.cssSelector("#iTrustContent > h2")).getText()); assertEquals("Enter dates in MM/dd/yyyy", driver.findElement(By.cssSelector("div.errorList")).getText()); } @Override @After public void tearDown() throws Exception { driver.quit(); String verificationErrorString = verificationErrors.toString(); if (!"".equals(verificationErrorString)) { fail(verificationErrorString); } } }
9,938
40.936709
109
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/selenium/ViewMyReportRequestsTest.java
package edu.ncsu.csc.itrust.selenium; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import org.openqa.selenium.htmlunit.HtmlUnitDriver; import edu.ncsu.csc.itrust.model.old.enums.TransactionType; import java.util.ArrayList; import java.util.List; public class ViewMyReportRequestsTest extends iTrustSeleniumTest { private HtmlUnitDriver driver; @Override protected void setUp() throws Exception { super.setUp(); gen.hcp0(); gen.patient2(); } public void testViewMyReportRequests() throws Exception { driver = (HtmlUnitDriver) login("9000000000", "pw"); assertEquals("iTrust - HCP Home", driver.getTitle()); assertLogged(TransactionType.HOME_VIEW, 9000000000L, 0L, ""); driver.findElement(By.cssSelector("div.panel-heading")).click(); driver.findElement(By.linkText("My Report Requests")).click(); driver.findElement(By.linkText("Add a new Report Request")).click(); // search for patient 2 driver.findElement(By.name("UID_PATIENTID")).sendKeys("2"); // the button to click should have the text of the MID driver.findElement(By.cssSelector("input[value='2']")).submit(); TableElement table = new TableElement(driver.findElement(By.tagName("table"))); assertLogged(TransactionType.COMPREHENSIVE_REPORT_ADD, 9000000000L, 2L, ""); assertTrue(table.getTableCell(2, 4).getText().contains("Requested")); driver.findElement(By.linkText("View")).click(); assertEquals("iTrust - Comprehensive Patient Report", driver.getTitle()); driver.findElement(By.cssSelector("div.panel-heading")).click(); driver.findElement(By.linkText("My Report Requests")).click(); table = new TableElement(driver.findElement(By.tagName("table"))); assertTrue(table.getTableCell(2, 4).getText().contains("Viewed")); driver.findElement(By.linkText("View")).click(); assertEquals("iTrust - Comprehensive Patient Report", driver.getTitle()); assertLogged(TransactionType.COMPREHENSIVE_REPORT_VIEW, 9000000000L, 2L, ""); } /** * TableElement a helper class for Selenium test htmlunitdriver retrieving * data from tables. */ private class TableElement { List<List<WebElement>> table; /** * Constructor. This object will help user to get data from each cell of * the table. * * @param tableElement * The table WebElement. */ public TableElement(WebElement tableElement) { // TODO Auto-generated constructor stub table = new ArrayList<List<WebElement>>(); List<WebElement> trCollection = tableElement.findElements(By.xpath("tbody/tr")); for (WebElement trElement : trCollection) { List<WebElement> tdCollection = trElement.findElements(By.xpath("td")); table.add(tdCollection); } } /** * Get data from given row and column cell. * * @param row * (start from 0) * @param column(start * from 0) * @return The WebElement in that given cell. */ public WebElement getTableCell(int row, int column) { return table.get(row).get(column); } } }
3,016
32.153846
83
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/selenium/WardTest.java
package edu.ncsu.csc.itrust.selenium; import org.openqa.selenium.By; import org.openqa.selenium.htmlunit.HtmlUnitDriver; import org.openqa.selenium.support.ui.Select; /** * WardTest */ public class WardTest extends iTrustSeleniumTest { private HtmlUnitDriver driver; @Override protected void setUp() throws Exception { super.setUp(); gen.clearAllTables(); gen.standardData(); // gen.insertwards(); // gen.hcp0(); } // 6. Heart Doctor will assign 3 patients to the cardiac ward. If Heart // Doctor tries to assign yet another, an error will be displayed static the // ward is full. /** * testhcpaddremovepatient * * @throws Exception */ public void testhcpaddremovepatient() throws Exception { driver = (HtmlUnitDriver) login("9000000000", "pw"); driver.findElement(By.linkText("Manage Wards")).click(); new Select(driver.findElement(By.name("searchbyroomWard"))).selectByVisibleText("Pediatrics"); driver.findElement(By.name("searchWards")).click(); driver.findElement(By.name("removePatient")).click(); new Select(driver.findElement(By.name("searchbyroomWard"))).selectByVisibleText("Pediatrics"); driver.findElement(By.name("searchWards")).click(); driver.findElement(By.name("assignPatient")).click(); // select patient 1 driver.findElement(By.name("UID_PATIENTID")).sendKeys("1"); // the button to click should have the text of the MID driver.findElement(By.cssSelector("input[value='1']")).submit(); assertTrue(driver.getPageSource().contains("Random Person")); } /** * testadminaddremoveward * * @throws Exception */ public void testadminaddremoveward() throws Exception { driver = (HtmlUnitDriver) login("9000000001", "pw"); driver.findElement(By.xpath("//div[@id='iTrustMenu']/div/div[3]/div/h2")).click(); driver.findElement(By.linkText("Manage Wards")).click(); new Select(driver.findElement(By.name("hospitals"))).selectByVisibleText("Facebook Rehab Center"); driver.findElement(By.name("selectHospital")).click(); driver.findElement(By.name("ward")).clear(); driver.findElement(By.name("ward")).sendKeys("ChatAddictionClinic"); driver.findElement(By.name("addWard")).click(); assertTrue(driver.getPageSource().contains("ChatAddictionClinic")); driver.findElement(By.name("removeWardButton")).click(); // check make sure table is gone assertFalse(driver.getPageSource().contains("ChatAddictionClinic")); } // 5. Admin will assigned "Heart Doctor (Heart Surgeon)" to the cardiac ward // and "Baby Doctor (Pediatrician)" to the two pediatric wards. // If the admin assigns the wrong doctor to the wrong ward, an error will be // displayed. // changed baby doctor to kelly doctor because testdata is already present /** * testadminassignhcp * * @throws Exception */ public void testadminassignhcp() throws Exception { driver = (HtmlUnitDriver) login("9000000001", "pw"); driver.findElement(By.xpath("//div[@id='iTrustMenu']/div/div[3]/div/h2")).click(); driver.findElement(By.linkText("Manage Wards")).click(); new Select(driver.findElement(By.name("hospitals"))).selectByVisibleText("Health Institute Dr. E"); driver.findElement(By.name("selectHospital")).click(); Select hcpToAdd = new Select(driver.findElement(By.name("HCPtoAdd"))); hcpToAdd.selectByVisibleText("Kelly Doctor"); // ERROR: Caught exception [ERROR: Unsupported command [addSelection | // name=HCPtoAdd | label=Kelly Doctor]] driver.findElement(By.name("addHCP")).click(); Select hcpToRemove = new Select(driver.findElement(By.name("HCPtoRemove"))); hcpToRemove.selectByVisibleText("Kelly Doctor"); driver.findElement(By.name("removeHCP")).click(); // ERROR: Caught exception [ERROR: Unsupported command [addSelection | // name=HCPtoRemove | label=Kelly Doctor]] } // 4. Admin will create a three test wards to Central Hospital, and proceed // some related operations on it, such as creating testing rooms. /** * testaddwardtohospital * * @throws Exception */ public void testaddwardtohospital() throws Exception { driver = (HtmlUnitDriver) login("9000000001", "pw"); driver.findElement(By.xpath("//div[@id='iTrustMenu']/div/div[3]/div/h2")).click(); driver.findElement(By.linkText("Manage Wards")).click(); new Select(driver.findElement(By.name("hospitals"))).selectByVisibleText("Central Hospital"); driver.findElement(By.name("selectHospital")).click(); driver.findElement(By.name("ward")).clear(); driver.findElement(By.name("ward")).sendKeys("TestOneWard"); driver.findElement(By.name("addWard")).click(); driver.findElement(By.name("ward")).clear(); driver.findElement(By.name("ward")).sendKeys("TestTwoWard"); driver.findElement(By.name("addWard")).click(); driver.findElement(By.name("ward")).clear(); driver.findElement(By.name("ward")).sendKeys("TestThreeWard"); driver.findElement(By.name("addWard")).click(); driver.findElement(By.name("room")).clear(); driver.findElement(By.name("room")).sendKeys("TestOneRoom"); driver.findElement(By.name("addRoomButton")).click(); driver.findElement(By.name("room")).clear(); driver.findElement(By.name("room")).sendKeys("TestTwoRoom"); driver.findElement(By.name("addRoomButton")).click(); driver.findElement(By.xpath("(//input[@name='room'])[2]")).clear(); driver.findElement(By.xpath("(//input[@name='room'])[2]")).sendKeys("TestOneRoom"); driver.findElement(By.xpath("(//input[@name='addRoomButton'])[2]")).click(); driver.findElement(By.xpath("(//input[@name='room'])[3]")).clear(); driver.findElement(By.xpath("(//input[@name='room'])[3]")).sendKeys("TestOneRoom"); driver.findElement(By.xpath("(//input[@name='addRoomButton'])[3]")).click(); Select hcpToAdd = new Select(driver.findElement(By.name("HCPtoAdd"))); hcpToAdd.selectByVisibleText("Shelly Vang"); // ERROR: Caught exception [ERROR: Unsupported command [addSelection | // name=HCPtoAdd | label=Shelly Vang]] driver.findElement(By.name("ward")).clear(); driver.findElement(By.name("ward")).sendKeys("Pediatric"); driver.findElement(By.name("addWard")).click(); driver.findElement(By.name("ward")).clear(); driver.findElement(By.name("ward")).sendKeys("Cardiac"); driver.findElement(By.name("addWard")).click(); hcpToAdd = new Select(driver.findElement(By.name("HCPtoAdd"))); hcpToAdd.selectByVisibleText("Shelly Vang"); // ERROR: Caught exception [ERROR: Unsupported command [addSelection | // name=HCPtoAdd | label=Shelly Vang]] driver.findElement(By.name("addHCP")).click(); driver.findElement(By.name("room")).clear(); driver.findElement(By.name("room")).sendKeys("TestOneRoomCardiac"); driver.findElement(By.name("addRoomButton")).click(); // Check if all wards have been created and rooms. assertTrue(driver.getPageSource().contains("TestOneWard")); assertTrue(driver.getPageSource().contains("TestTwoWard")); assertTrue(driver.getPageSource().contains("TestThreeWard")); assertTrue(driver.getPageSource().contains("TestOneRoom")); assertTrue(driver.getPageSource().contains("TestTwoRoom")); assertTrue(driver.getPageSource().contains("Pediatric")); } }
7,119
43.5
101
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/selenium/iTrustSeleniumTest.java
package edu.ncsu.csc.itrust.selenium; import java.util.List; import java.util.concurrent.TimeUnit; import junit.framework.TestCase; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import edu.ncsu.csc.itrust.exception.DBException; import edu.ncsu.csc.itrust.model.old.beans.TransactionBean; import edu.ncsu.csc.itrust.model.old.enums.TransactionType; import edu.ncsu.csc.itrust.unit.datagenerators.TestDataGenerator; import edu.ncsu.csc.itrust.unit.testutils.TestDAOFactory; /** * There's nothing special about this class other than adding a few handy test * utility methods and variables. When extending this class, be sure to invoke * super.setUp() first. */ abstract public class iTrustSeleniumTest extends TestCase { /* * The URL for iTrust, change as needed */ /** ADDRESS */ public static final String ADDRESS = "http://localhost:8080/iTrust/"; /** gen */ protected TestDataGenerator gen = new TestDataGenerator(); /** Default timeout for Selenium webdriver */ public static final int DEFAULT_TIMEOUT = 2; /** * Name of the value attribute of html tags. Used for getting the value from * a form input with .getAttribute("value"). Was previously * .getAttribute(VALUE) before being removed by s selenium. */ public static final String VALUE = "value"; @Override protected void setUp() throws Exception { gen.clearAllTables(); } /** * Helper method for logging in to iTrust * * Also creates an explicit WebDriverWait for optional use. * * @param username * username * @param password * password * @return {@link WebConversation} * @throws Exception */ public WebDriver login(String username, String password) throws Exception { // begin at the iTrust home page WebDriver wd = new Driver(); // Implicitly wait at most 2 seconds for each element to load wd.manage().timeouts().implicitlyWait(DEFAULT_TIMEOUT, TimeUnit.SECONDS); wd.get(ADDRESS); // log in using the given username and password WebElement user = wd.findElement(By.name("j_username")); WebElement pass = wd.findElement(By.name("j_password")); user.sendKeys(username); pass.sendKeys(password); pass.submit(); if (wd.getTitle().equals("iTrust - Login")) { throw new IllegalArgumentException("Error logging in, user not in database?"); } return wd; } /** * assertLogged * * @param code * code * @param loggedInMID * loggedInMID * @param secondaryMID * secondaryMID * @param addedInfo * addedInfo * @throws DBException */ public static void assertLogged(TransactionType code, long loggedInMID, long secondaryMID, String addedInfo) throws DBException, InterruptedException { // Selenium on jenkins sometimes has issues finding a log the first // time. // The proper solution would be to add explicit waits, but it is easier // to wait a second and try again. int i = 0; while (i < 3) { List<TransactionBean> transList = TestDAOFactory.getTestInstance().getTransactionDAO().getAllTransactions(); for (TransactionBean t : transList) { if ((t.getTransactionType() == code) && (t.getLoggedInMID() == loggedInMID) && (t.getSecondaryMID() == secondaryMID)) { assertTrue(t.getTransactionType() == code); if (!t.getAddedInfo().trim().contains(addedInfo.trim())) { fail("Additional Information is not logged correctly."); } return; } } i++; Thread.sleep(1000); } fail("Event not logged as specified."); } /** * assertLogged * * @param code * code * @param loggedInMID * loggedInMID * @param secondaryMID * secondaryMID not used * @param addedInfo * addedInfo * @throws DBException */ public static void assertLoggedNoSecondary(TransactionType code, long loggedInMID, long secondaryMID, String addedInfo) throws DBException { List<TransactionBean> transList = TestDAOFactory.getTestInstance().getTransactionDAO().getAllTransactions(); for (TransactionBean t : transList) { if ((t.getTransactionType() == code) && (t.getLoggedInMID() == loggedInMID)) { assertTrue(t.getTransactionType() == code); if (!t.getAddedInfo().trim().contains(addedInfo.trim())) { fail("Additional Information is not logged correctly."); } return; } } fail("Event not logged as specified."); } /** * assertNotLogged * * @param code * code * @param loggedInMID * loggedInMID * @param secondaryMID * secondaryMID * @param addedInfo * addedInfo * @throws DBException */ public static void assertNotLogged(TransactionType code, long loggedInMID, long secondaryMID, String addedInfo) throws DBException { List<TransactionBean> transList = TestDAOFactory.getTestInstance().getTransactionDAO().getAllTransactions(); for (TransactionBean t : transList) { if ((t.getTransactionType() == code) && (t.getLoggedInMID() == loggedInMID) && (t.getSecondaryMID() == secondaryMID) && (t.getAddedInfo().trim().contains(addedInfo))) { fail("Event was logged, but should NOT have been logged"); return; } } } }
5,261
28.897727
112
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/unit/BeanBuilderTest.java
package edu.ncsu.csc.itrust.unit; import java.util.HashMap; import java.util.Map; import junit.framework.TestCase; import edu.ncsu.csc.itrust.BeanBuilder; import edu.ncsu.csc.itrust.model.old.beans.HospitalBean; import edu.ncsu.csc.itrust.model.old.beans.PatientBean; import edu.ncsu.csc.itrust.unit.testutils.BadBean; import edu.ncsu.csc.itrust.unit.testutils.OkayBean; public class BeanBuilderTest extends TestCase { public void testEmptyPatientDateOfBirth() throws Exception { assertEquals("empty patient bean", new PatientBean().getDateOfBirthStr(), new BeanBuilder<PatientBean>() .build(new HashMap<String, String>(), new PatientBean()).getDateOfBirthStr()); } // just testing the building process - test the bean validation elsewhere! public void testPartialPatient() throws Exception { PatientBean p = new PatientBean(); p.setFirstName("Bob"); p.setDateOfBirthStr("10/10/1950"); p.setPhone("85"); Map<String, Object> m = new HashMap<String, Object>(); m.put("firstName", new String[] { "Bob" }); m.put("dateOfBirthStr", new String[] { "10/10/1950" }); m.put("phone", new String[] { "85" }); PatientBean builtBean = new BeanBuilder<PatientBean>().build(m, new PatientBean()); assertEquals("correctly built patient bean from hashmap", p.getFirstName(), builtBean.getFirstName()); assertEquals("correctly built patient bean from hashmap", p.getDateOfBirthStr(), builtBean.getDateOfBirthStr()); assertEquals("correctly built patient bean from hashmap", p.getPhone(), builtBean.getPhone()); assertEquals("correctly built patient bean from hashmap", p.getLastName(), builtBean.getLastName()); } public void testNotOverloaded() throws Exception { try { HashMap<String, Object> map = new HashMap<String, Object>(); map.put("thing", new String[] { "5" }); new BeanBuilder<BadBean>().build(map, new BadBean()); fail("exception should have been thrown"); } catch (IllegalArgumentException e) { assertEquals( "edu.ncsu.csc.itrust.unit.testutils.BadBean should not have any overloaded methods, like setThing", e.getMessage()); } } public void testOverloadedConstructor() throws Exception { HashMap<String, Object> map = new HashMap<String, Object>(); map.put("hospitalName", new String[] { "test text" }); HospitalBean hosp = new BeanBuilder<HospitalBean>().build(map, new HospitalBean()); assertEquals("test text", hosp.getHospitalName()); } public void testEqualsOkayToBeOverloaded() throws Exception { HashMap<String, Object> map = new HashMap<String, Object>(); map.put("thing", new String[] { "test text" }); OkayBean ok = new BeanBuilder<OkayBean>().build(map, new OkayBean()); assertEquals("test text", ok.getThing()); } public void testOkayBean1() throws Exception { OkayBean ok = new OkayBean(); assertFalse(ok.equals("")); OkayBean ok2 = new OkayBean(); assertTrue(ok.equals(ok2)); assertEquals(42, ok.hashCode()); } }
2,932
40.9
114
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/unit/CSVParserTest.java
package edu.ncsu.csc.itrust.unit; import java.util.ArrayList; import java.util.Scanner; import edu.ncsu.csc.itrust.CSVParser; import edu.ncsu.csc.itrust.exception.CSVFormatException; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import junit.framework.TestCase; public class CSVParserTest extends TestCase { public void testCSVParseHeader() { Scanner CSVHeader = new Scanner("test1,test2,test3"); CSVParser test = null; try { test = new CSVParser(CSVHeader); } catch (Exception e) { assertTrue(false); } ArrayList<String> header = test.getHeader(); assertEquals(3, header.size()); assertEquals("test1", header.get(0)); assertEquals("test2", header.get(1)); assertEquals("test3", header.get(2)); assertFalse(test.getErrors().hasErrors()); } public void testCSVParseData() { Scanner CSVHeader = new Scanner("test1,test2,test3\ntesting,testing,123"); CSVParser test = null; try { test = new CSVParser(CSVHeader); } catch (Exception e) { assertTrue(false); } ArrayList<ArrayList<String>> data = test.getData(); assertEquals(1, data.size()); assertEquals(3, data.get(0).size()); assertEquals("testing", data.get(0).get(0)); assertEquals("testing", data.get(0).get(1)); assertEquals("123", data.get(0).get(2)); assertFalse(test.getErrors().hasErrors()); } @SuppressFBWarnings(value = "DLS_DEAD_LOCAL_STORE") public void testEmptyCSV() { Scanner CSVHeader = new Scanner(""); @SuppressWarnings("unused") CSVParser test = null; try { test = new CSVParser(CSVHeader); } catch (CSVFormatException e) { // CSVFormatException is good here return; } catch (Exception e) { // Other exceptions are bad assertTrue(false); } } public void testWrongNumberFields() { Scanner CSVHeader = new Scanner("test1,test2,test3\ntesting,123"); CSVParser test = null; try { test = new CSVParser(CSVHeader); } catch (Exception e) { assertTrue(false); } ArrayList<ArrayList<String>> data = test.getData(); assertEquals(0, data.size()); assertTrue(test.getErrors().hasErrors()); assertEquals("[Field number mismatch on line 2]", test.getErrors().toString()); } public void testCSVCommaInField() { Scanner CSVHeader = new Scanner("\"test,1\",\"test,2\",\"test,3\""); CSVParser test = null; try { test = new CSVParser(CSVHeader); } catch (Exception e) { assertTrue(false); } ArrayList<String> header = test.getHeader(); assertEquals(3, header.size()); assertEquals("test,1", header.get(0)); assertEquals("test,2", header.get(1)); assertEquals("test,3", header.get(2)); assertFalse(test.getErrors().hasErrors()); } public void testCSVEndsWhileInQuote() { Scanner CSVHeader = new Scanner("test1,test2,test3\ntesting,testing,\"123"); CSVParser test = null; try { test = new CSVParser(CSVHeader); } catch (Exception e) { assertTrue(false); } ArrayList<ArrayList<String>> data = test.getData(); assertEquals(0, data.size()); assertEquals("[Line ended while inside quotes on line 2]", test.getErrors().toString()); } }
3,073
28.27619
90
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/unit/DBBuilder.java
package edu.ncsu.csc.itrust.unit; import java.io.FileNotFoundException; import java.io.IOException; import java.sql.Connection; import java.sql.SQLException; import java.sql.Statement; import java.util.List; import edu.ncsu.csc.itrust.model.old.dao.DAOFactory; import edu.ncsu.csc.itrust.unit.testutils.SQLFileCache; import edu.ncsu.csc.itrust.unit.testutils.TestDAOFactory; /** * Drops and rebuilds the entire database. Also provides some utility methods. * DO NOT PUT TEST DATA HERE!!! */ public class DBBuilder { public static int numExecuted = 0; public static long queryTimeTaken = 0; private DAOFactory factory; public DBBuilder() { factory = TestDAOFactory.getTestInstance(); } public DBBuilder(DAOFactory factory) { this.factory = factory; } public static void main(String[] args) throws Exception { rebuildAll(); } public static void rebuildAll() throws FileNotFoundException, IOException, SQLException { DBBuilder dbBuilder = new DBBuilder(TestDAOFactory.getTestInstance()); dbBuilder.dropTables(); dbBuilder.createTables(); } public void dropTables() throws FileNotFoundException, IOException, SQLException { List<String> queries = SQLFileCache.getInstance().getQueries("sql/dropTables.sql"); executeSQL(queries); } public void createTables() throws FileNotFoundException, IOException, SQLException { List<String> queries = SQLFileCache.getInstance().getQueries("sql/createTables.sql"); executeSQL(queries); } public void createProcedures() throws FileNotFoundException, IOException, SQLException { List<String> queries = SQLFileCache.getInstance().getQueries("sql/createProcedures.sql"); executeSQL(queries); } public void executeSQL(List<String> queries) throws SQLException { Connection conn = factory.getConnection(); long start = System.currentTimeMillis(); for (String sql : queries) { numExecuted++; Statement stmt = conn.createStatement(); try { stmt.execute(sql); } catch (SQLException e) { throw new SQLException(e.getMessage() + " from executing: " + sql, e.getSQLState(), e.getErrorCode()); } finally { stmt.close(); } } queryTimeTaken += (System.currentTimeMillis() - start); conn.close(); } public void executeSQLFile(String filepath) throws FileNotFoundException, SQLException, IOException { executeSQL(SQLFileCache.getInstance().getQueries((filepath))); } }
2,390
29.265823
106
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/unit/DateUtilTest.java
package edu.ncsu.csc.itrust.unit; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import edu.ncsu.csc.itrust.DateUtil; import junit.framework.TestCase; public class DateUtilTest extends TestCase { public void testYearsAgo() throws Exception { int yearsAgo = 50; SimpleDateFormat formatter = new SimpleDateFormat("yyyy"); String year = "" + (Integer.valueOf(formatter.format(new Date())) - yearsAgo); assertEquals(year, DateUtil.yearsAgo(yearsAgo).split("/")[2]); } public void testYearsFromNow() throws Exception { // This test is intended to test the logic of the conversion // java.util.Date to the java.sql.Date // Along with the intent of "years ago". // This test no longer tests the arithmetic of adding/subtracting years, // we assume Java got that right Calendar cal = new GregorianCalendar(); cal.add(Calendar.YEAR, -2); Long twoYearsAgo = cal.getTimeInMillis(); assertEquals("Date should be within 5s: ", twoYearsAgo, DateUtil.getSQLdateXyearsAgoFromNow(2).getTime(), 5000); } public void testSetSQLMonthRange0() { java.sql.Date month1 = new java.sql.Date(0l); java.sql.Date month2 = new java.sql.Date(0l); int year1 = new GregorianCalendar().get(Calendar.YEAR); DateUtil.setSQLMonthRange(month1, 8, 0, month2, 11, 0); int year2 = new GregorianCalendar().get(Calendar.YEAR); if (year1 != year2) DateUtil.setSQLMonthRange(month1, 8, 0, month2, 11, 0); GregorianCalendar cal = new GregorianCalendar(); cal.setTime(month1); assertEquals(cal.get(Calendar.YEAR), year2); assertEquals(cal.get(Calendar.MONTH), 8); assertEquals(cal.get(Calendar.DAY_OF_MONTH), 1); cal.setTime(month2); assertEquals(cal.get(Calendar.YEAR), year2); assertEquals(cal.get(Calendar.MONTH), 11); assertEquals(cal.get(Calendar.DAY_OF_MONTH), 31); } public void testSetSQLMonthRange1() { java.sql.Date month1 = new java.sql.Date(0l); java.sql.Date month2 = new java.sql.Date(0l); int year1 = new GregorianCalendar().get(Calendar.YEAR); DateUtil.setSQLMonthRange(month1, 8, 1, month2, 11, 1); int year2 = new GregorianCalendar().get(Calendar.YEAR); if (year1 != year2) DateUtil.setSQLMonthRange(month1, 8, 1, month2, 11, 1); GregorianCalendar cal = new GregorianCalendar(); cal.setTime(month1); assertEquals(cal.get(Calendar.YEAR), year2 - 1); assertEquals(cal.get(Calendar.MONTH), 8); assertEquals(cal.get(Calendar.DAY_OF_MONTH), 1); cal.setTime(month2); assertEquals(cal.get(Calendar.YEAR), year2 - 1); assertEquals(cal.get(Calendar.MONTH), 11); assertEquals(cal.get(Calendar.DAY_OF_MONTH), 31); } }
2,660
36.478873
114
java