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/beans/DrugInteractionBean.java
package edu.ncsu.csc.itrust.model.old.beans; /** * A bean for storing data about a message from one user to another. * * A bean's purpose is to store data. Period. Little or no functionality is to be added to a bean * (with the exception of minor formatting such as concatenating phone numbers together). * A bean must only have Getters and Setters (Eclipse Hint: Use Source > Generate Getters and Setters. * to create these easily) */ public class DrugInteractionBean { String firstDrug; String secondDrug; String description; /** * @return the firstDrug */ public String getFirstDrug() { return firstDrug; } /** * @param firstDrug the firstDrug to set */ public void setFirstDrug(String firstDrug) { this.firstDrug = firstDrug; } /** * @return the secondDrug */ public String getSecondDrug() { return secondDrug; } /** * @param secondDrug the secondDrug to set */ public void setSecondDrug(String secondDrug) { this.secondDrug = secondDrug; } /** * @return the description */ public String getDescription() { return description; } /** * @param description the description to set */ public void setDescription(String description) { this.description = description; } }
1,246
20.877193
102
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/beans/Email.java
package edu.ncsu.csc.itrust.model.old.beans; import java.sql.Timestamp; import java.util.ArrayList; import java.util.List; /** * A bean for storing data about Fake Emails. * * A bean's purpose is to store data. Period. Little or no functionality is to be added to a bean * (with the exception of minor formatting such as concatenating phone numbers together). * A bean must only have Getters and Setters (Eclipse Hint: Use Source > Generate Getters and Setters * to create these easily) */ public class Email { private List<String> toList = new ArrayList<String>(); private String from = ""; private String subject = ""; private String body = ""; private Timestamp timeAdded; public List<String> getToList() { return toList; } public void setToList(List<String> toList) { this.toList = toList; } public String getToListStr() { String str = ""; StringBuffer buf = new StringBuffer(); for (String addr : toList) { buf.append(addr + ","); } str = buf.toString(); if(str.length() < 1) return str; else return str.substring(0, str.length() - 1); } public String getFrom() { return from; } public void setFrom(String from) { this.from = from; } public String getSubject() { return subject; } public void setSubject(String subject) { this.subject = subject; } public String getBody() { return body; } public void setBody(String body) { this.body = body; } public Timestamp getTimeAdded() { return (Timestamp) timeAdded.clone(); } public void setTimeAdded(Timestamp timeAdded) { this.timeAdded = (Timestamp) timeAdded.clone(); } @Override public boolean equals(Object obj) { return obj != null && obj.getClass().equals(this.getClass()) && this.equals((Email) obj); } @Override public int hashCode() { return 42; // any arbitrary constant will do } private boolean equals(Email other) { return from.equals(other.from) && subject.equals(other.subject) && body.equals(other.body) && listEquals(toList, other.toList); } private boolean listEquals(List<String> toList, List<String> otherToList) { if (toList.size() != otherToList.size()) return false; for (int i = 0; i < toList.size(); i++) { if (!toList.get(i).equals(otherToList.get(i))) return false; } return true; } @Override public String toString() { return "FROM: " + from + " TO: " + toList.toString() + " SUBJECT: " + subject + " BODY: " + body; } }
2,443
21.841121
101
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/beans/EntryBean.java
package edu.ncsu.csc.itrust.model.old.beans; /** * An abstract parent for Wellness Diary beans. */ public abstract class EntryBean { }
139
14.555556
47
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/beans/FamilyMemberBean.java
package edu.ncsu.csc.itrust.model.old.beans; /** * A bean for storing data about Family Members. * * A bean's purpose is to store data. Period. Little or no functionality is to be added to a bean * (with the exception of minor formatting such as concatenating phone numbers together). * A bean must only have Getters and Setters (Eclipse Hint: Use Source > Generate Getters and Setters. * to create these easily) */ public class FamilyMemberBean { private long mid = 0; private String relation = ""; private String firstName = ""; private String lastName = ""; public FamilyMemberBean() { } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getFullName() { return getFirstName() + " " + getLastName(); } public long getMid() { return mid; } public void setMid(long mid) { this.mid = mid; } public String getRelation() { return relation; } public void setRelation(String relation) { this.relation = relation; } }
1,185
20.178571
102
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/beans/GroupReportBean.java
package edu.ncsu.csc.itrust.model.old.beans; import java.util.ArrayList; import java.util.List; import edu.ncsu.csc.itrust.report.ReportFilter; /** * * */ public class GroupReportBean { private List<PatientBean> patients; private List<ReportFilter> filters; /** * * @param patients * @param filters */ public GroupReportBean(List<PatientBean> patients, List<ReportFilter> filters) { this.patients = patients; this.filters = filters; } /** * * @return */ public List<PatientBean> getPatients() { return patients; } /** * * @return */ public List<ReportFilter> getFilters() { return filters; } /** * * @return */ public List<String> getFilterStrings() { List<String> out = new ArrayList<String>(); for(ReportFilter filter : filters) { out.add(filter.toString()); } return out; } /** * * @return */ public List<String> getPatientNames() { List<String> out = new ArrayList<String>(); for(PatientBean patient : patients) { out.add(patient.getFullName()); } return out; } }
1,068
15.446154
81
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/beans/HCPLinkBean.java
package edu.ncsu.csc.itrust.model.old.beans; /** * A mini-bean to pass data between viewPrescriptionRecords.jsp and reportAdverseEvent.jsp * * A bean's purpose is to store data. Period. Little or no functionality is to be added to a bean * (with the exception of minor formatting such as concatenating phone numbers together). * A bean must only have Getters and Setters (Eclipse Hint: Use Source > Generate Getters and Setters. * to create these easily) */ public class HCPLinkBean { long prescriberMID; String drug; boolean checked; String code; public boolean isChecked() { return checked; } public void setChecked(boolean checked) { this.checked = checked; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } /** * @return the patient MID */ public long getPrescriberMID() { return prescriberMID; } /** * * @param mID the patients MID */ public void setPrescriberMID(long mID) { prescriberMID = mID; } /** * * @return the drug the event is being reported for */ public String getDrug() { return drug; } /** * * @param drug sets the drug the event is being reported for */ public void setDrug(String drug) { this.drug = drug; } }
1,267
18.8125
102
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/beans/HospitalBean.java
package edu.ncsu.csc.itrust.model.old.beans; /** * A bean for storing data about a hospital. * * A bean's purpose is to store data. Period. Little or no functionality is to be added to a bean * (with the exception of minor formatting such as concatenating phone numbers together). * A bean must only have Getters and Setters (Eclipse Hint: Use Source > Generate Getters and Setters. * to create these easily) */ public class HospitalBean { String hospitalID = ""; String hospitalName = ""; String hospitalAddress = ""; String hospitalCity = ""; String hospitalState = ""; String hospitalZip = ""; public HospitalBean() { } public HospitalBean(String hospitalID) { this.hospitalID = hospitalID; } public HospitalBean(String hospitalID, String hospitalName) { this.hospitalID = hospitalID; this.hospitalName = hospitalName; } public HospitalBean(String hospitalID, String hospitalName, String hospitalAddress, String hospitalCity, String hospitalState, String hospitalZip) { this.hospitalID = hospitalID; this.hospitalName = hospitalName; this.hospitalAddress = hospitalAddress; this.hospitalCity = hospitalCity; this.hospitalState = hospitalState; this.hospitalZip = hospitalZip; } public String getHospitalID() { return hospitalID; } public void setHospitalID(String hospitalID) { this.hospitalID = hospitalID; } public String getHospitalName() { return hospitalName; } public void setHospitalName(String hospitalName) { this.hospitalName = hospitalName; } public String getHospitalAddress() { return hospitalAddress; } public void setHospitalAddress(String hospitalAddress) { this.hospitalAddress = hospitalAddress; } public String getHospitalCity() { return hospitalCity; } public void setHospitalCity(String hospitalCity) { this.hospitalCity = hospitalCity; } public String getHospitalState() { return hospitalState; } public void setHospitalState(String hospitalState) { this.hospitalState = hospitalState; } public String getHospitalZip() { return hospitalZip; } public void setHospitalZip(String hospitalZip) { this.hospitalZip = hospitalZip; } @Override public boolean equals(Object obj) { return obj != null && obj.getClass().equals(this.getClass()) && this.equals((HospitalBean) obj); } @Override public int hashCode() { return 42; // any arbitrary constant will do } private boolean equals(HospitalBean other) { return hospitalID.equals(other.hospitalID) && hospitalName.equals(other.hospitalName); } }
2,543
23.699029
149
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/beans/MedicationBean.java
package edu.ncsu.csc.itrust.model.old.beans; /** * A medication is the same thing as an ND code - it's like "Aspirin". A medication is not associated with an * office visit; that's a "prescription". See {@link PrescriptionBean} * * */ public class MedicationBean { private String NDCode = ""; private String description = ""; public MedicationBean() { } public MedicationBean(String code) { NDCode = code; } public MedicationBean(String code, String description) { NDCode = code; this.description = description; } /** * Gets the ND Code for this procedure * * @return The ND Code for this procedure */ public String getNDCode() { return NDCode; } public void setNDCode(String code) { NDCode = code; } /** * Gets the ND Description for this procedure * * @return The ND Description for this procedure */ public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getNDCodeFormatted() { String code = getNDCode(); if (code.length() > 5) return code.substring(0, 5) + "-" + code.substring(5); else return code; } @Override public int hashCode() { return 42; // any arbitrary constant will do } @Override public boolean equals(Object other) { return (other != null) && this.getClass().equals(other.getClass()) && this.equals((MedicationBean) other); } private boolean equals(MedicationBean other) { return description.equals(other.description) && NDCode.equals(other.NDCode); } }
1,572
19.973333
109
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/beans/MessageBean.java
package edu.ncsu.csc.itrust.model.old.beans; import java.sql.Timestamp; /** * A bean for storing data about a message from one user to another. * * A bean's purpose is to store data. Period. Little or no functionality is to be added to a bean * (with the exception of minor formatting such as concatenating phone numbers together). * A bean must only have Getters and Setters (Eclipse Hint: Use Source > Generate Getters and Setters * to create these easily) */ public class MessageBean { private long to; private long from; private long id; private long parentMsgId; private String subject; private String body; private Timestamp timestamp; private int read; private long originalMsgId; //NEW /** * Gets the MIDs of the recipients for this Message * @return */ public long getTo() { return to; } /** * Sets the MIDs of the recipients for this Message * @param to */ public void setTo(long to) { this.to = to; } public long getMessageId() { return id; } public void setMessageId(long id) { this.id = id; } public long getParentMessageId() { return this.parentMsgId; } public void setParentMessageId(long parentMsgId) { this.parentMsgId = parentMsgId; } /** * Gets the MID of the sender for this message * @return */ public long getFrom() { return from; } /** * Sets the MID of the sender for this message * @param from */ public void setFrom(long from) { this.from = from; } /** * Gets the subject of this message * @return */ public String getSubject() { return subject; } /** * Sets the subject of this message * @param subject */ public void setSubject(String subject) { this.subject = subject; } /** * Gets the body of this message * @return */ public String getBody() { return body; } /** * Sets the body of this message * @param body */ public void setBody(String body) { this.body = body; } /** * Gets the time for this message * @return */ public Timestamp getSentDate() { return (Timestamp) this.timestamp.clone(); } /** * Sets the time for this message * @param timestamp */ public void setSentDate(Timestamp timestamp) { this.timestamp = (Timestamp) timestamp.clone(); } /** * Gets read for this message * @return */ public int getRead() { return this.read; } /** * Sets read for this message * @param read */ public void setRead(int read) { this.read = read; } public long getOriginalMessageId() { //NEW return this.originalMsgId; } public void setOriginalMessageId(long originalMsgId) { //NEW this.originalMsgId = originalMsgId; } }
2,654
17.061224
101
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/beans/OperationalProfile.java
package edu.ncsu.csc.itrust.model.old.beans; import java.util.HashMap; import edu.ncsu.csc.itrust.model.old.enums.TransactionType; /** * A bean for storing operational profile data. * * A bean's purpose is to store data. Period. Little or no functionality is to be added to a bean * (with the exception of minor formatting such as concatenating phone numbers together). * A bean must only have Getters and Setters (Eclipse Hint: Use Source > Generate Getters and Setters. * to create these easily) */ public class OperationalProfile { private int numTotalTransactions = 0; private int numPatientTransactions = 0; private int numPersonnelTransactions = 0; private HashMap<TransactionType, Integer> totalCount; private HashMap<TransactionType, Integer> personnelCount; private HashMap<TransactionType, Integer> patientCount; public OperationalProfile() { totalCount = createEmptyMap(); personnelCount = createEmptyMap(); patientCount = createEmptyMap(); } private HashMap<TransactionType, Integer> createEmptyMap() { HashMap<TransactionType, Integer> map = new HashMap<TransactionType, Integer>(TransactionType .values().length); for (TransactionType type : TransactionType.values()) { map.put(type, 0); } return map; } public HashMap<TransactionType, Integer> getTotalCount() { return totalCount; } public void setTotalCount(HashMap<TransactionType, Integer> totalCount) { this.totalCount = totalCount; } public HashMap<TransactionType, Integer> getPersonnelCount() { return personnelCount; } public void setPersonnelCount(HashMap<TransactionType, Integer> personnelCount) { this.personnelCount = personnelCount; } public HashMap<TransactionType, Integer> getPatientCount() { return patientCount; } public void setPatientCount(HashMap<TransactionType, Integer> patientCount) { this.patientCount = patientCount; } public void setNumTotalTransactions(int numTransactions) { this.numTotalTransactions = numTransactions; } public int getNumTotalTransactions() { return numTotalTransactions; } public int getNumPatientTransactions() { return numPatientTransactions; } public void setNumPatientTransactions(int numPatientTransactions) { this.numPatientTransactions = numPatientTransactions; } public int getNumPersonnelTransactions() { return numPersonnelTransactions; } public void setNumPersonnelTransactions(int numPersonnelTransactions) { this.numPersonnelTransactions = numPersonnelTransactions; } }
2,504
28.127907
102
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/beans/OverrideReasonBean.java
package edu.ncsu.csc.itrust.model.old.beans; /** * A reason code is like "Aspirin". A reason code is not associated with an * office visit; that's a reason associated with a "prescription". See {@link PrescriptionBean} * */ public class OverrideReasonBean { private long id; private long presID; private String reasonCode; private String description; public OverrideReasonBean() { description = null; reasonCode = ""; } public OverrideReasonBean(String code) { reasonCode = code; } public OverrideReasonBean(String code, String description) { reasonCode = code; this.description = description; } public long getPresID() { return presID; } public void setPresID(long id) { this.presID = id; } public long getID() { return id; } public void setID(long id) { this.id = id; } /** * Gets the reason Code for this procedure * * @return The reason Code for this procedure */ public String getORCode() { return reasonCode; } public void setORCode(String code) { reasonCode = code; } /** * Gets the reason Description for this procedure * * @return The reason Description for this procedure */ public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } @Override public int hashCode() { return 42; // any arbitrary constant will do } @Override public boolean equals(Object other) { if ((other == null) || !this.getClass().equals(other.getClass())) return false; OverrideReasonBean orb = (OverrideReasonBean)other; return (orb.description.equals(description) && orb.reasonCode.equals(reasonCode) && orb.presID == presID && orb.id == id); } }
1,738
18.761364
95
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/beans/PatientBean.java
package edu.ncsu.csc.itrust.model.old.beans; import java.io.Serializable; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import edu.ncsu.csc.itrust.model.old.enums.BloodType; import edu.ncsu.csc.itrust.model.old.enums.Ethnicity; import edu.ncsu.csc.itrust.model.old.enums.Gender; /** * A bean for storing data about a patient. * * A bean's purpose is to store data. Period. Little or no functionality is to be added to a bean * (with the exception of minor formatting such as concatenating phone numbers together). * A bean must only have Getters and Setters (Eclipse Hint: Use Source > Generate Getters and Setters * to create these easily) */ public class PatientBean implements Serializable, Comparable<PatientBean> { private static final long serialVersionUID = -6474182977342257877L; private long MID = 0; private String firstName = ""; private String lastName = ""; private String email = ""; private String securityQuestion = ""; private String securityAnswer = ""; private String password = ""; private String confirmPassword = ""; private String streetAddress1 = ""; private String streetAddress2 = ""; private String city = ""; private String state = "AK"; private String zip = ""; private String phone = ""; private String emergencyName = ""; private String emergencyPhone = ""; private String icName = ""; private String icAddress1 = ""; private String icAddress2 = ""; private String icCity = ""; private String icState = "AK"; private String icZip = ""; private String icPhone = ""; private String icID = ""; private String creditCardType = ""; private String creditCardNumber = ""; // Topical Health Information private String dateOfBirthStr = new SimpleDateFormat("MM/dd/yyyy").format(new Date()); private String dateOfDeathStr = ""; private String causeOfDeath = ""; private String motherMID = "0"; private String fatherMID = "0"; private BloodType bloodType = BloodType.NS; private Ethnicity ethnicity = Ethnicity.NotSpecified; private Gender gender = Gender.NotSpecified; private String topicalNotes = ""; private String directionsToHome = ""; private String religion = ""; private String language = ""; private String spiritualPractices = ""; private String alternateName = ""; private String dateOfDeactivationStr = ""; public BloodType getBloodType() { return bloodType; } public void setBloodTypeStr(String bloodType) { this.bloodType = BloodType.parse(bloodType); } public void setBloodType(BloodType bloodType) { this.bloodType = bloodType; } public String getCauseOfDeath() { return causeOfDeath; } public void setCauseOfDeath(String causeOfDeath) { this.causeOfDeath = causeOfDeath; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getDateOfBirthStr() { return dateOfBirthStr; } public Date getDateOfBirth() { try { return new SimpleDateFormat("MM/dd/yyyy").parse(dateOfBirthStr); } catch (ParseException e) { return null; } } public Date getDateOfDeath() { try { return new SimpleDateFormat("MM/dd/yyyy").parse(dateOfDeathStr); } catch (ParseException e) { return null; } } public void setDateOfBirthStr(String dateOfBirthStr) { this.dateOfBirthStr = dateOfBirthStr; } public int getAge() { try { long ageInMs = System.currentTimeMillis() - new SimpleDateFormat("MM/dd/yyyy").parse(dateOfBirthStr).getTime(); long age = ageInMs / (1000L * 60L * 60L * 24L * 365L); return (int) age; } catch (ParseException e) { return -1; } } public long getAgeInDays() { long age; long ageInMs; try { ageInMs = System.currentTimeMillis() - new SimpleDateFormat("MM/dd/yyyy").parse(dateOfBirthStr).getTime(); age = ageInMs / (1000L * 60L * 60L * 24L); } catch (ParseException e) { return -1; } return age; } public long getAgeInWeeks() { long age; long ageInMs; try { ageInMs = System.currentTimeMillis() - new SimpleDateFormat("MM/dd/yyyy").parse(dateOfBirthStr).getTime(); age = ageInMs / (1000L * 60L * 60L * 24L * 7L); } catch (ParseException e) { return -1; } return age; } public String getDateOfDeathStr() { return dateOfDeathStr; } public void setDateOfDeathStr(String dateOfDeathStr) { this.dateOfDeathStr = dateOfDeathStr; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getEmergencyName() { return emergencyName; } public void setEmergencyName(String emergencyName) { this.emergencyName = emergencyName; } public Ethnicity getEthnicity() { return ethnicity; } public void setEthnicityStr(String ethnicity) { this.ethnicity = Ethnicity.parse(ethnicity); } public void setEthnicity(Ethnicity ethnicity) { this.ethnicity = ethnicity; } public String getFatherMID() { return fatherMID; } public void setFatherMID(String fatherMID) { this.fatherMID = fatherMID; } public String getFullName() { return getFirstName() + " " + getLastName(); } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public Gender getGender() { return gender; } public void setGenderStr(String gender) { this.gender = Gender.parse(gender); } public void setGender(Gender gender) { this.gender = gender; } public String getIcAddress1() { return icAddress1; } public void setIcAddress1(String icAddress1) { this.icAddress1 = icAddress1; } public String getIcAddress2() { return icAddress2; } public void setIcAddress2(String icAddress2) { this.icAddress2 = icAddress2; } // Composition of city, state, and zip public String getIcAddress3() { return getIcCity() + ", " + getIcState() + " " + getIcZip(); } public String getIcCity() { return icCity; } public void setIcCity(String icCity) { this.icCity = icCity; } public String getIcID() { return icID; } public void setIcID(String icID) { this.icID = icID; } public String getCreditCardType() { return creditCardType; } public void setCreditCardType(String creditCardType) { this.creditCardType = creditCardType; } public String getCreditCardNumber() { return creditCardNumber; } public void setCreditCardNumber(String creditCardNumber) { this.creditCardNumber = creditCardNumber; } public String getIcName() { return icName; } public void setIcName(String icName) { this.icName = icName; } public String getIcZip() { return icZip; } public void setIcZip(String icZip) { this.icZip = icZip; } public String getIcState() { return icState; } public void setIcState(String icState) { this.icState = icState; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public long getMID() { return MID; } public void setMID(long mid) { MID = mid; } public String getMotherMID() { return motherMID; } public void setMotherMID(String motherMID) { this.motherMID = motherMID; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getSecurityAnswer() { return securityAnswer; } public void setSecurityAnswer(String securityAnswer) { this.securityAnswer = securityAnswer; } public String getSecurityQuestion() { return securityQuestion; } public void setSecurityQuestion(String securityQuestion) { this.securityQuestion = securityQuestion; } public String getState() { return state; } public void setState(String state) { this.state = state; } public String getStreetAddress1() { return streetAddress1; } public void setStreetAddress1(String streetAddress1) { this.streetAddress1 = streetAddress1; } public String getStreetAddress2() { return streetAddress2; } public void setStreetAddress2(String streetAddress2) { this.streetAddress2 = streetAddress2; } // Composition of the city, state, zip public String getStreetAddress3() { return getCity() + ", " + getState() + " " + getZip(); } public String getTopicalNotes() { return topicalNotes; } public void setTopicalNotes(String topicalNotes) { this.topicalNotes = topicalNotes; } public String getZip() { return zip; } public void setZip(String zip) { this.zip = zip; } public String getEmergencyPhone() { return emergencyPhone; } public void setEmergencyPhone(String emergencyPhone) { this.emergencyPhone = emergencyPhone; } public String getIcPhone() { return icPhone; } public void setIcPhone(String icPhone) { this.icPhone = icPhone; } public String getConfirmPassword() { return confirmPassword; } public void setConfirmPassword(String confirmPassword) { this.confirmPassword = confirmPassword; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getDirectionsToHome() { return directionsToHome; } public void setDirectionsToHome(String directionsToHome) { this.directionsToHome = directionsToHome; } public String getReligion() { return religion; } public void setReligion(String religion) { this.religion = religion; } public String getLanguage() { return language; } public void setLanguage(String language) { this.language = language; } public String getSpiritualPractices() { return spiritualPractices; } public void setSpiritualPractices(String spiritualPractices) { this.spiritualPractices = spiritualPractices; } public String getAlternateName() { return alternateName; } public void setAlternateName(String alternateName) { this.alternateName = alternateName; } public String getDateOfDeactivationStr() { return dateOfDeactivationStr; } public void setDateOfDeactivationStr(String dateOfDeactivationStr) { this.dateOfDeactivationStr = dateOfDeactivationStr; } @Override public int compareTo(PatientBean o) { return (int)(o.MID-this.MID); } public int equals(PatientBean o) { return (int)(o.MID-this.MID); } @Override public int hashCode() { assert false : "hashCode not designed"; return 42; // any arbitrary constant will do } }
10,380
19.51581
102
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/beans/PersonnelBean.java
package edu.ncsu.csc.itrust.model.old.beans; import java.io.Serializable; import java.util.List; import edu.ncsu.csc.itrust.model.old.enums.Role; /** * A bean for storing data about a hospital employee. * * A bean's purpose is to store data. Period. Little or no functionality is to be added to a bean * (with the exception of minor formatting such as concatenating phone numbers together). * A bean must only have Getters and Setters (Eclipse Hint: Use Source > Generate Getters and Setters * to create these easily) */ public class PersonnelBean implements Serializable { private static final long serialVersionUID = 6575544592646001050L; private long MID = 0; private long AMID = 0; private String roleString; private String firstName = ""; private String lastName = ""; private String password = ""; private String confirmPassword = ""; private String securityQuestion = ""; private String securityAnswer = ""; private String streetAddress1 = ""; private String streetAddress2 = ""; private String city = ""; private String state = ""; private String zip = ""; private String phone = ""; private String email = ""; private String specialty = ""; public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public long getAMID() { return AMID; } public void setAMID(long amid) { AMID = amid; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getConfirmPassword() { return confirmPassword; } public void setConfirmPassword(String confirmPassword) { this.confirmPassword = confirmPassword; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getFullName() { return getFirstName() + " " + getLastName(); } public long getMID() { return MID; } public void setMID(long mid) { MID = mid; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getRoleString() { return roleString; } public String getSecurityAnswer() { return securityAnswer; } public void setSecurityAnswer(String securityAnswer) { this.securityAnswer = securityAnswer; } public String getSecurityQuestion() { return securityQuestion; } public void setSecurityQuestion(String securityQuestion) { this.securityQuestion = securityQuestion; } public String getState() { return state; } public void setState(String state) { this.state = state; } public String getStreetAddress1() { return streetAddress1; } public void setStreetAddress1(String streetAddress1) { this.streetAddress1 = streetAddress1; } public String getStreetAddress2() { return streetAddress2; } public void setStreetAddress2(String streetAddress2) { this.streetAddress2 = streetAddress2; } public String getZip() { return zip; } public void setZip(String zip) { this.zip = zip; } public String getSpecialty() { return specialty; } public void setSpecialty(String specialty) { this.specialty = specialty; } public int getIndexIn(List<PersonnelBean> list) { for (int i = 0; i < list.size(); i++) { if (list.get(i).MID == this.MID) return i; } return -1; } public void setRoleString(String role) { this.roleString = role; } public Role getRole() { return Role.parse(roleString); } public void setRole(Role role) { } @Override public boolean equals(Object o){ if(o == null || getClass() != o.getClass()) return false; return this.MID == ((PersonnelBean) o).MID; } @Override public int hashCode() { assert false : "hashCode not designed"; return 0; } }
4,028
18.653659
102
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/beans/RatingComparator.java
package edu.ncsu.csc.itrust.model.old.beans; import java.util.Comparator; import edu.ncsu.csc.itrust.action.ReviewsAction; import edu.ncsu.csc.itrust.exception.DBException; public class RatingComparator implements Comparator<PersonnelBean> { ReviewsAction action; @Override public int compare(PersonnelBean bean1, PersonnelBean bean2) { double avg1 = 0; double avg2 = 0; try { avg1 = action.getAverageRating(bean1.getMID()); avg2 = action.getAverageRating(bean2.getMID()); } catch (DBException e) { // TODO Auto-generated catch block e.printStackTrace(); } return Double.compare(avg1, avg2); } public RatingComparator(ReviewsAction action) { this.action = action; } }
722
21.59375
68
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/beans/RecordsReleaseBean.java
package edu.ncsu.csc.itrust.model.old.beans; import java.sql.Timestamp; import java.text.DateFormat; import java.text.SimpleDateFormat; /** * A bean for storing information about releasing medical records. * * A bean's purpose is to store data. Period. Little or no functionality is to be added to a bean * (with the exception of minor formatting such as concatenating phone numbers together). * A bean must only have Getters and Setters (Eclipse Hint: Use Source > Generate Getters and Setters * to create these easily) */ public class RecordsReleaseBean { private long releaseID = 0; private long pid; private String releaseHospitalID; private String recHospitalName; private String recHospitalAddress; private String docFirstName; private String docLastName; private String docPhone; private String docEmail; private String justification; private int status; private Timestamp dateRequested; /** * Constructor for RecordsRelease bean. Creates a RecordsReleaseBean with null fields */ public RecordsReleaseBean() { } /** * Sets the releaseID of the release request * @param releaseID the id of the release request as a long */ public void setReleaseID(long releaseID) { this.releaseID = releaseID; } /** * Gets the release request id as a long * @return the release request id */ public long getReleaseID() { return releaseID; } /** * Sets the patient mid * @param pid the patient's mid as a long */ public void setPid(long pid) { this.pid = pid; } /** * Gets the patient's mid * @return the patient's mid */ public long getPid() { return pid; } /** * Sets the name of the release hospital for the records release * @param hospital the hospital's name as a string */ public void setReleaseHospitalID(String hospitalID) { releaseHospitalID = hospitalID; } /** * Gets the id of the hospital for which to release the patient's medical records * @return the name of the hospital */ public String getReleaseHospitalID() { return releaseHospitalID; } /** * Set the receiving hospital's name * @param name the receiving hospital's name as a string */ public void setRecHospitalName(String name) { recHospitalName = name; } /** * Get the receiving hospital's name * @return the receiving hospital's name */ public String getRecHospitalName() { return recHospitalName; } /** * Set the receiving hospital's address. * @param address the receiving hospital's address */ public void setRecHospitalAddress(String address) { recHospitalAddress = address; } /** * Get the receiving hospital's address * @return the receiving hospital's address */ public String getRecHospitalAddress() { return recHospitalAddress; } /** * Set the first name of the receiving doctor * @param firstName the first name of the receiving doctor as a string */ public void setDocFirstName(String firstName) { docFirstName = firstName; } /** * Gets the first name of the receiving doctor * @return the receiving doctor's first name */ public String getDocFirstName() { return docFirstName; } /** * Set the last name of the receiving doctor * @param lastName the first name of the receiving doctor as a string */ public void setDocLastName(String lastName) { docLastName = lastName; } /** * Get the receiving doctor's last name * @return the doctor's last name */ public String getDocLastName() { return docLastName; } /** * Set the receiving doctor's phone number * @param phoneNumber the doctor's phone number as a string */ public void setDocPhone(String phoneNumber) { docPhone = phoneNumber; } /** * Get the receiving doctor's phone number * @return the receiving doctor's phone number */ public String getDocPhone() { return docPhone; } /** * Set the receiving doctor's email address * @param email the receiving doctor's email address as a string */ public void setDocEmail(String email) { docEmail = email; } /** * Get the receiving doctor's email address * @return the receiving doctor's email address */ public String getDocEmail() { return docEmail; } /** * Set the justification for the medical records release * @param justification the justification as a string */ public void setJustification(String justification) { this.justification = justification; } /** * Get the justification for the medical records release * @return the justification for the medical records release */ public String getJustification() { return justification; } /** * Sets the status of the medical records release request. * 0 for pending. 1 for approved. 2 for denied. * @param status the status as an integer. 0 for pending. 1 for approved. 2 for denied. */ public void setStatus(int status) { this.status = status; } /** * Gets the status of the medical records release request. * 0 for pending. 1 for approved. 2 for denied. * @return the status of the release request. 0 for pending. 1 for approved. 2 for denied. */ public int getStatus() { return status; } /** * Gets the status description of the release request. * @return the status description of the release request */ public String getStatusStr() { switch (status) { case 0: return "Pending"; case 1: return "Approved"; case 2: return "Denied"; default: return ""; } } /** * Sets the date that the medical records release is requested * @param requestDate the date of the medical records release as a Date object */ public void setDateRequested(Timestamp requestDate) { this.dateRequested = (Timestamp) requestDate.clone(); } /** * Gets the date that the medical records release was requested * @return the date that the medical records release was requested */ public Timestamp getDateRequested() { return (Timestamp) dateRequested.clone(); } /** * Gets the date of the request as a string in mm/dd/yyyy format * @return the date of the request as a string */ public String getDateRequestedStr() { DateFormat df = new SimpleDateFormat("MM/dd/yyyy"); String dateString = df.format(dateRequested); return dateString; } }
6,245
23.303502
102
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/beans/RemoteMonitoringDataBean.java
package edu.ncsu.csc.itrust.model.old.beans; import java.sql.Timestamp; /** * A bean for storing remote monitoring data for patients. * * A bean's purpose is to store data. Period. Little or no functionality is to be added to a bean * (with the exception of minor formatting such as concatenating phone numbers together). * A bean must only have Getters and Setters (Eclipse Hint: Use Source > Generate Getters and Setters * to create these easily) */ public class RemoteMonitoringDataBean { private long patientMID; private Timestamp time; private int systolicBloodPressure; private int diastolicBloodPressure; private int glucoseLevel; private float height; private float weight; private int pedometerReading; private String reporterRole; private long reporterMID; /** * Constructor with no parameters */ public RemoteMonitoringDataBean() { } /** * Constructor with loggedInMID parameter */ public RemoteMonitoringDataBean(long patientMID) { this.patientMID = patientMID; } public long getReporterMID() { return reporterMID; } public void setReporterMID(long reporterMID) { this.reporterMID = reporterMID; } public long getPatientMID() { return patientMID; } public void setLoggedInMID(long patientMID) { this.patientMID = patientMID; } public Timestamp getTime() { Timestamp currTime = time; if(time == null){ return currTime; } return currTime; } public void setTime(Timestamp time) { this.time = (Timestamp) time.clone(); } public int getSystolicBloodPressure() { return systolicBloodPressure; } public void setSystolicBloodPressure(int systolicBloodPressure) { this.systolicBloodPressure = systolicBloodPressure; } public int getDiastolicBloodPressure() { return diastolicBloodPressure; } public void setDiastolicBloodPressure(int diastolicBloodPressure) { this.diastolicBloodPressure = diastolicBloodPressure; } public int getGlucoseLevel() { return glucoseLevel; } public void setGlucoseLevel(int glucoseLevel) { this.glucoseLevel = glucoseLevel; } public float getHeight() { return height; } public void setHeight(float height) { this.height = height; } public float getWeight() { return weight; } public void setWeight(float weight) { this.weight = weight; } public int getPedometerReading() { return pedometerReading; } public void setPedometerReading(int pedometerReading) { this.pedometerReading = pedometerReading; } public String getReporterRole() { return reporterRole; } public void setReporterRole(String reporterRole) { this.reporterRole = reporterRole; } }
2,653
20.232
101
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/beans/ReportRequestBean.java
package edu.ncsu.csc.itrust.model.old.beans; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import edu.ncsu.csc.itrust.Messages; /** * A bean for storing data about a report request. * * A bean's purpose is to store data. Period. Little or no functionality is to be added to a bean * (with the exception of minor formatting such as concatenating phone numbers together). * A bean must only have Getters and Setters (Eclipse Hint: Use Source > Generate Getters and Setters. * to create these easily) */ public class ReportRequestBean { private long ID = 0L; private long requesterMID = 0L; private long patientMID = 0L; private Date requestedDate; private Date viewedDate; private String status = ""; //$NON-NLS-1$ public final static String dateFormat = "MM/dd/yyyy HH:mm"; //$NON-NLS-1$ public final static String Requested = Messages.getString("ReportRequestBean.requested"); //$NON-NLS-1$ public final static String Viewed = Messages.getString("ReportRequestBean.viewed"); //$NON-NLS-1$ public ReportRequestBean() { } public void setID(long iD) { ID = iD; } public long getID() { return ID; } public void setRequesterMID(long requesterMID) { this.requesterMID = requesterMID; } public long getRequesterMID() { return requesterMID; } public void setPatientMID(long patientMID) { this.patientMID = patientMID; } public long getPatientMID() { return patientMID; } public void setRequestedDate(Date requestedDate) { this.requestedDate = (requestedDate == null ? null : (Date) requestedDate.clone()); } public void setRequestedDateString(String s) { try { setRequestedDate(new SimpleDateFormat(dateFormat).parse(s)); } catch (ParseException ex) { System.out.println(ex.getMessage()); } } public Date getRequestedDate() { return (requestedDate == null ? null : (Date) requestedDate.clone()); } public String getRequestedDateString() { if (requestedDate == null) return ""; //$NON-NLS-1$ return new SimpleDateFormat(dateFormat).format(requestedDate); } public void setViewedDate(Date viewedDate) { this.viewedDate = (viewedDate == null ? null : (Date) viewedDate.clone()); } public void setViewedDateString(String s) { try { setViewedDate(new SimpleDateFormat(dateFormat).parse(s)); } catch (ParseException ex) { System.out.println(ex.getMessage()); } } public Date getViewedDate() { return (viewedDate == null ? null : (Date) viewedDate.clone()); } public String getViewedDateString() { if (viewedDate == null) return ""; //$NON-NLS-1$ return new SimpleDateFormat(dateFormat).format(viewedDate); } public void setStatus(String status) { this.status = status; } public String getStatus() { return status; } }
2,785
24.796296
104
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/beans/ReviewsBean.java
package edu.ncsu.csc.itrust.model.old.beans; import java.util.Date; /** * A bean for storing data about a review of a physician. * * A bean's purpose is to store data. Period. Little or no functionality is to be added to a bean * (with the exception of minor formatting such as concatenating phone numbers together). * A bean must only have Getters and Setters (Eclipse Hint: Use Source > Generate Getters and Setters * to create these easily) */ public class ReviewsBean { private long MID; private Date dateOfReview; private long PID; private int rating; private String descriptiveReview; private String title; /** * Gets the MID of the reviewer. * @return MID */ public long getMID() { return MID; } /** * Gets the title of the review. * @return title */ public String getTitle() { return title; } /** * Sets the title of the review. * @param title */ public void setTitle(String title) { this.title = title; } /** * Set the MID of the reviewer * @param MID The MID of the reviwer. */ public void setMID(long mID) { MID = mID; } /** * Gets the date that the review was made. * @return Date */ public Date getDateOfReview() { return new Date(dateOfReview.getTime()); } /** * Sets the date that the review was made. * @param dateOfReview The date of the review. */ public void setDateOfReview(Date dateOfReview) { this.dateOfReview = new Date(dateOfReview.getTime()); } /** * Gets the ID of the physician who is being reviewed. * @return */ public long getPID() { return PID; } /** * Sets the ID of the physician who is being reviewed. * @param PID */ public void setPID(long pID) { PID = pID; } /** * Gets the number of stars that were given to the phyician. * @return Rating */ public int getRating() { return rating; } /** * Sets the rating associated with a review. * @param rating String value 1-5. */ public void setRating(int rating) { this.rating = rating; } /** * Gets the descriptive review of the Physician. * @return Descriptive Review */ public String getDescriptiveReview() { return descriptiveReview; } /** * Sets the descriptive review attribute. * @param descriptiveReview */ public void setDescriptiveReview(String descriptiveReview) { this.descriptiveReview = descriptiveReview; } }
2,406
17.234848
101
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/beans/SecurityQA.java
package edu.ncsu.csc.itrust.model.old.beans; /** * A bean for storing data about a security question and answer. * * A bean's purpose is to store data. Period. Little or no functionality is to be added to a bean * (with the exception of minor formatting such as concatenating phone numbers together). * A bean must only have Getters and Setters (Eclipse Hint: Use Source > Generate Getters and Setters. * to create these easily) */ public class SecurityQA { String question, answer, confirmAnswer; public String getQuestion() { return question; } public void setQuestion(String question) { this.question = question; } public String getAnswer() { return answer; } public void setAnswer(String answer) { this.answer = answer; } public String getConfirmAnswer() { return confirmAnswer; } public void setConfirmAnswer(String confirmAnswer) { this.confirmAnswer = confirmAnswer; } }
922
22.075
102
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/beans/SurveyBean.java
package edu.ncsu.csc.itrust.model.old.beans; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; /** * A bean for storing survey data associated with an office visit. * * A bean's purpose is to store data. Period. Little or no functionality is to be added to a bean * (with the exception of minor formatting such as concatenating phone numbers together). * A bean must only have Getters and Setters (Eclipse Hint: Use Source > Generate Getters and Setters. * to create these easily) */ public class SurveyBean { private long visitID; private Date surveyDate; private int waitingRoomMinutes; private int examRoomMinutes; private int visitSatisfaction; private int treatmentSatisfaction; public final static String dateFormat = "MM/dd/yyyy HH:mm"; public void setVisitID(long iD) { visitID = iD; } public long getVisitID() { return visitID; } public void setSurveyDate(Date surveyDate) { this.surveyDate = (surveyDate == null ? null : (Date)surveyDate.clone()); } public void setSurveyDateString(String s) { try { setSurveyDate(new SimpleDateFormat(dateFormat).parse(s)); } catch (ParseException ex) { System.out.println(ex.getMessage()); } } public Date getSurveyDate() { return (surveyDate == null ? null : (Date)surveyDate.clone()); } public String getSurveyDateString() { if (surveyDate == null) return ""; return new SimpleDateFormat(dateFormat).format(getSurveyDate()); } public void setWaitingRoomMinutes(int waitingRoomMinutes) { this.waitingRoomMinutes = waitingRoomMinutes; } public int getWaitingRoomMinutes() { return waitingRoomMinutes; } public void setExamRoomMinutes(int examRoomMinutes) { this.examRoomMinutes = examRoomMinutes; } public int getExamRoomMinutes() { return examRoomMinutes; } public void setVisitSatisfaction(int visitSatisfaction) { this.visitSatisfaction = visitSatisfaction; } public int getVisitSatisfaction() { return visitSatisfaction; } public void setTreatmentSatisfaction(int treatmentSatisfaction) { this.treatmentSatisfaction = treatmentSatisfaction; } public int getTreatmentSatisfaction() { return treatmentSatisfaction; } }
2,211
26.308642
102
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/beans/SurveyResultBean.java
package edu.ncsu.csc.itrust.model.old.beans; /** * Bean to be used for survey results (search). Stores address information about a HCP * in addition to their specialty, hospital, and averages from survey (results range from 1-5). This * beans also contains a variable that stores the percent of office visits that satisfaction results are * available. */ public class SurveyResultBean { private long hcpMID; private String hcpFirstName; private String hcpLastName; private String hcpAddress1; private String hcpAddress2; private String hcpCity; private String hcpState; private String hcpZip; private String hcpSpecialty; private String hcpHospitalID; private float avgWaitingRmMinutes; private float avgExamRmMinutues; private float avgVisitSatisfaction; private float avgTreatmentSatisfaction; private float percentSatResultsAvailable; //list of specialties public final static String GENERAL_SPECIALTY = "General"; public final static String SURGEON_SPECIALTY = "Surgeon"; public final static String HEART_SPECIALTY = "Heart Specialist"; public final static String PEDIATRICIAN_SPECIALTY = "Pediatrician"; public final static String OBGYN_SPECIALTY = "OB/GYN"; public final static String ANY_SPECIALTY = "None"; public void setHCPMID(long mid) { hcpMID = mid; } public long getHCPMID() { return hcpMID; } public void setHCPFirstName(String firstName) { this.hcpFirstName = firstName; } public String getHCPFirstName() { return hcpFirstName; } public void setHCPLastName(String lastName) { this.hcpLastName = lastName; } public String getHCPLastName() { return hcpLastName; } public void setHCPaddress1(String address1) { this.hcpAddress1 = address1; } public String getHCPaddress1() { return hcpAddress1; } public void setHCPaddress2(String address2) { this.hcpAddress2 = address2; } public String getHCPaddress2() { return hcpAddress2; } public void setHCPcity(String city) { this.hcpCity = city; } public String getHCPcity() { return hcpCity; } public void setHCPstate(String state) { this.hcpState = state; } public String getHCPstate() { return hcpState; } public void setHCPzip(String zip) { this.hcpZip = zip; } public String getHCPzip() { return hcpZip; } public void setHCPspecialty(String specialty) { this.hcpSpecialty = specialty; } public String getHCPspecialty() { return hcpSpecialty; } public void setHCPhospital(String hospital) { this.hcpHospitalID = hospital; } public String getHCPhospital() { return hcpHospitalID; } public void setAvgWaitingRoomMinutes(float waitingRoomMinutes) { this.avgWaitingRmMinutes = waitingRoomMinutes; } public float getAvgWaitingRoomMinutes() { return avgWaitingRmMinutes; } public void setAvgExamRoomMinutes(float examRoomMinutes) { this.avgExamRmMinutues = examRoomMinutes; } public float getAvgExamRoomMinutes() { return avgExamRmMinutues; } public void setAvgVisitSatisfaction(float visitSatisfaction) { this.avgVisitSatisfaction = visitSatisfaction; } public float getAvgVisitSatisfaction() { return avgVisitSatisfaction; } public void setAvgTreatmentSatisfaction(float treatmentSatisfaction) { this.avgTreatmentSatisfaction = treatmentSatisfaction; } public float getAvgTreatmentSatisfaction() { return avgTreatmentSatisfaction; } public void setPercentSatisfactionResults (float percent) { this.percentSatResultsAvailable= percent; } public float getPercentSatisfactionResults() { return percentSatResultsAvailable; } }
3,562
24.45
105
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/beans/TelemedicineBean.java
package edu.ncsu.csc.itrust.model.old.beans; public class TelemedicineBean { private boolean systolicBloodPressureAllowed = true; private boolean diastolicBloodPressureAllowed = true; private boolean glucoseLevelAllowed = true; private boolean heightAllowed = true; private boolean weightAllowed = true; private boolean pedometerReadingAllowed = true; public boolean isHeightAllowed() { return heightAllowed; } public void setHeightAllowed(boolean heightAllowed) { this.heightAllowed = heightAllowed; } public boolean isSystolicBloodPressureAllowed() { return systolicBloodPressureAllowed; } public void setSystolicBloodPressureAllowed(boolean systolicBloodPressureAllowed) { this.systolicBloodPressureAllowed = systolicBloodPressureAllowed; } public boolean isDiastolicBloodPressureAllowed() { return diastolicBloodPressureAllowed; } public void setDiastolicBloodPressureAllowed(boolean diastolicBloodPressureAllowed) { this.diastolicBloodPressureAllowed = diastolicBloodPressureAllowed; } public boolean isGlucoseLevelAllowed() { return glucoseLevelAllowed; } public void setGlucoseLevelAllowed(boolean glucoseLevelAllowed) { this.glucoseLevelAllowed = glucoseLevelAllowed; } public boolean isWeightAllowed() { return weightAllowed; } public void setWeightAllowed(boolean weightAllowed) { this.weightAllowed = weightAllowed; } public boolean isPedometerReadingAllowed() { return pedometerReadingAllowed; } public void setPedometerReadingAllowed(boolean pedometerReadingAllowed) { this.pedometerReadingAllowed = pedometerReadingAllowed; } }
1,619
26.457627
86
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/beans/TransactionBean.java
package edu.ncsu.csc.itrust.model.old.beans; import java.sql.Timestamp; import edu.ncsu.csc.itrust.model.old.enums.TransactionType; /** * A bean for storing data about a transaction that occurred within iTrust. * * A bean's purpose is to store data. Period. Little or no functionality is to be added to a bean * (with the exception of minor formatting such as concatenating phone numbers together). * A bean must only have Getters and Setters (Eclipse Hint: Use Source > Generate Getters and Setters * to create these easily) */ public class TransactionBean { private long transactionID; private long loggedInMID; private long secondaryMID; private TransactionType transactionType; private Timestamp timeLogged; private String addedInfo; private String role; public TransactionBean() { } public String getRole() { return role; } public void setRole(String role) { this.role = role; } public String getAddedInfo() { return addedInfo; } public void setAddedInfo(String addedInfo) { this.addedInfo = addedInfo; } public long getLoggedInMID() { return loggedInMID; } public void setLoggedInMID(long loggedInMID) { this.loggedInMID = loggedInMID; } public long getSecondaryMID() { return secondaryMID; } public void setSecondaryMID(long secondaryMID) { this.secondaryMID = secondaryMID; } public Timestamp getTimeLogged() { return (Timestamp) timeLogged.clone(); } public void setTimeLogged(Timestamp timeLogged) { this.timeLogged = (Timestamp) timeLogged.clone(); } public TransactionType getTransactionType() { return transactionType; } public void setTransactionType(TransactionType tranactionType) { this.transactionType = tranactionType; } public long getTransactionID() { return transactionID; } public void setTransactionID(long transactionID) { this.transactionID = transactionID; } }
1,881
21.674699
101
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/beans/VisitFlag.java
package edu.ncsu.csc.itrust.model.old.beans; /** * A bean for storing data to flag an office visit. * * A bean's purpose is to store data. Period. Little or no functionality is to be added to a bean * (with the exception of minor formatting such as concatenating phone numbers together). * A bean must only have Getters and Setters (Eclipse Hint: Use Source > Generate Getters and Setters. * to create these easily) */ public class VisitFlag { public static final String DIAGNOSED = "Diagnosed"; public static final String MISSED_MEDICATION = "Missed Medication"; public static final String MISSING_MEDICATION = "Currently Missing Medication"; public static final String LAST_VISIT = "Last Visit"; public static final String IMMUNIZATION = "Needs Immunization"; private String type; private String value; public VisitFlag(String type) { this.type = type; } public VisitFlag(String type, String value) { this.type = type; this.value = value; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } }
1,196
23.9375
102
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/beans/WardBean.java
package edu.ncsu.csc.itrust.model.old.beans; /** * A bean for storing data about a Ward. * * A bean's purpose is to store data. Period. Little or no functionality is to be added to a bean * (with the exception of minor formatting such as concatenating phone numbers together). * A bean must only have Getters and Setters (Eclipse Hint: Use Source > Generate Getters and Setters. * to create these easily) */ public class WardBean { long wardID = 0; String requiredSpecialty = ""; long inHospital = 0; public WardBean(long wardID, String requiredSpecialty, long inHospital){ this.wardID = wardID; this.requiredSpecialty= requiredSpecialty; this.inHospital = inHospital; } public long getWardID() { return wardID; } public void setWardID(long wardID) { this.wardID = wardID; } public String getRequiredSpecialty() { return requiredSpecialty; } public void setRequiredSpecialty(String requiredSpecialty) { this.requiredSpecialty = requiredSpecialty; } public long getInHospital() { return inHospital; } public void setInHospital(long inHospital) { this.inHospital = inHospital; } @Override public boolean equals(Object obj) { return obj != null && obj.getClass().equals(this.getClass()) && this.equals((WardBean) obj); } @Override public int hashCode() { return 42; // any arbitrary constant will do } private boolean equals(WardBean other) { return wardID == other.wardID && requiredSpecialty.equals(other.requiredSpecialty); } }
1,505
23.290323
102
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/beans/WardRoomBean.java
package edu.ncsu.csc.itrust.model.old.beans; /** * A bean for storing data about a WardRoom. * * A bean's purpose is to store data. Period. Little or no functionality is to be added to a bean * (with the exception of minor formatting such as concatenating phone numbers together). * A bean must only have Getters and Setters (Eclipse Hint: Use Source > Generate Getters and Setters. * to create these easily) */ public class WardRoomBean { long roomID = 0; Long occupiedBy = null; long inWard = 0; String roomName = ""; String status = "Clean"; public WardRoomBean(long roomID, long occupiedBy, long inWard, String roomName, String status){ this.roomID = roomID; this.occupiedBy = occupiedBy; this.inWard = inWard; this.roomName = roomName; this.status = status; } public long getRoomID() { return roomID; } public void setRoomID(long roomID) { this.roomID = roomID; } public Long getOccupiedBy() { return occupiedBy; } public void setOccupiedBy(Long occupiedBy) { this.occupiedBy = occupiedBy; } public long getInWard() { return inWard; } public void setInWard(long inWard) { this.inWard = inWard; } public String getRoomName() { return roomName; } public void setRoomName(String roomName) { this.roomName = roomName; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } @Override public boolean equals(Object obj) { return obj != null && obj.getClass().equals(this.getClass()) && this.equals((WardRoomBean) obj); } @Override public int hashCode() { return 42; // any arbitrary constant will do } private boolean equals(WardRoomBean other) { return roomID == other.roomID && roomName.equals(other.roomName); } }
1,769
20.851852
103
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/beans/ZipCodeBean.java
package edu.ncsu.csc.itrust.model.old.beans; import edu.ncsu.csc.itrust.model.old.enums.State; /** * A bean for storing zip code information. * * A bean's purpose is to store data. Period. Little or no functionality is to be added to a bean * (with the exception of minor formatting such as concatenating phone numbers together). * A bean must only have Getters and Setters (Eclipse Hint: Use Source > Generate Getters and Setters. * to create these easily) */ public class ZipCodeBean { private String zip; private State state; private String latitude; private String longitude; private String city; private String fullState; /** * Returns the zip code. * @return zip code */ public String getZip() { return zip; } /** * Sets the zip code * @param zip code */ public void setZip(String zip) { this.zip = zip; } /** * Gets the state * @return State */ public State getState() { return state; } /** * Sets the state * @param state */ public void setState(State state) { this.state = state; } /** * Gets the latitude * @return returns the latitude */ public String getLatitude() { return latitude; } /** * Sets the latitude * @param latitude */ public void setLatitude(String latitude) { this.latitude = latitude; } /** * Gets the longitude * @return longitude */ public String getLongitude() { return longitude; } /** * Sets the longitude * @param longitude */ public void setLongitude(String longitude) { this.longitude = longitude; } /** * Returns the city * @return city */ public String getCity() { return city; } /** * Sets the city * @param city */ public void setCity(String city) { this.city = city; } /** * Gets the full state name. * @return State name */ public String getFullState() { return fullState; } /** * Sets the full string value of state * @param fullState State string */ public void setFullState(String fullState) { this.fullState = fullState; } }
2,076
14.734848
103
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/beans/forms/RecordsReleaseForm.java
package edu.ncsu.csc.itrust.model.old.beans.forms; public class RecordsReleaseForm{ private String releaseHospitalID = ""; private String recipientFirstName = ""; private String recipientLastName = ""; private String recipientPhone = ""; private String recipientEmail = ""; private String recipientHospitalName = ""; private String recipientHospitalAddress = ""; private String requestJustification = " "; private Boolean digitalSignature = false; public RecordsReleaseForm(){}; public String getReleaseHospitalID(){ return releaseHospitalID; } public void setReleaseHospitalID(String hospitalID){ this.releaseHospitalID = hospitalID; } public String getRecipientFirstName(){ return recipientFirstName; } public void setRecipientFirstName(String firstName){ this.recipientFirstName = firstName; } public String getRecipientLastName(){ return recipientLastName; } public void setRecipientLastName(String lastName){ this.recipientLastName = lastName; } public String getRecipientPhone(){ return recipientPhone; } public void setRecipientPhone(String phone){ this.recipientPhone = phone; } public String getRecipientEmail(){ return recipientEmail; } public void setRecipientEmail(String email){ this.recipientEmail = email; } public String getRecipientHospitalName(){ return recipientHospitalName; } public void setRecipientHospitalName(String hospitalName){ this.recipientHospitalName = hospitalName; } public String getRecipientHospitalAddress(){ return recipientHospitalAddress; } public void setRecipientHospitalAddress(String hospitalAddress){ this.recipientHospitalAddress = hospitalAddress; } public String getRequestJustification(){ return requestJustification; } public void setRequestJustification(String justification){ this.requestJustification = justification; } public Boolean getDigitalSignature(){ return digitalSignature; } public void setDigitalSignature(Boolean signed){ this.digitalSignature = signed; } }
2,047
22.011236
65
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/beans/loaders/AllergyBeanLoader.java
package edu.ncsu.csc.itrust.model.old.beans.loaders; 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.model.old.beans.AllergyBean; /** * A loader for AllergyBeans. * * Loads in information to/from beans using ResultSets and PreparedStatements. Use the superclass to enforce consistency. * For details on the paradigm for a loader (and what its methods do), see {@link BeanLoader} */ public class AllergyBeanLoader implements BeanLoader<AllergyBean> { @Override public List<AllergyBean> loadList(ResultSet rs) throws SQLException { ArrayList<AllergyBean> list = new ArrayList<AllergyBean>(); while (rs.next()) { list.add(loadSingle(rs)); } return list; } @Override public AllergyBean loadSingle(ResultSet rs) throws SQLException { AllergyBean allergy = new AllergyBean(); allergy.setId(rs.getLong("ID")); allergy.setPatientID(rs.getLong("PatientID")); allergy.setDescription(rs.getString("Description")); allergy.setNDCode(rs.getString("Code")); allergy.setFirstFound(rs.getTimestamp("FirstFound")); return allergy; } @Override public PreparedStatement loadParameters(PreparedStatement ps, AllergyBean bean) throws SQLException { throw new IllegalStateException("unimplemented!"); } }
1,355
29.133333
122
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/beans/loaders/ApptBeanLoader.java
package edu.ncsu.csc.itrust.model.old.beans.loaders; 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.model.old.beans.ApptBean; public class ApptBeanLoader implements BeanLoader<ApptBean> { @Override public List<ApptBean> loadList(ResultSet rs) throws SQLException { List<ApptBean> list = new ArrayList<ApptBean>(); while (rs.next()) list.add(loadSingle(rs)); return list; } @Override public PreparedStatement loadParameters(PreparedStatement ps, ApptBean bean) throws SQLException { ps.setString(1, bean.getApptType()); ps.setLong(2, bean.getPatient()); ps.setLong(3, bean.getHcp()); ps.setTimestamp(4, bean.getDate()); ps.setString(5, bean.getComment()); return ps; } @Override public ApptBean loadSingle(ResultSet rs) throws SQLException { ApptBean bean = new ApptBean(); bean.setApptID(rs.getInt("appt_id")); bean.setApptType(rs.getString("appt_type")); bean.setPatient(rs.getLong("patient_id")); bean.setHcp(rs.getLong("doctor_id")); bean.setDate(rs.getTimestamp("sched_date")); bean.setComment(rs.getString("comment")); return bean; } }
1,217
26.681818
99
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/beans/loaders/ApptRequestBeanLoader.java
package edu.ncsu.csc.itrust.model.old.beans.loaders; 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.model.old.beans.ApptBean; import edu.ncsu.csc.itrust.model.old.beans.ApptRequestBean; /** * * */ public class ApptRequestBeanLoader implements BeanLoader<ApptRequestBean> { private ApptBeanLoader loader = new ApptBeanLoader(); /** * */ @Override public List<ApptRequestBean> loadList(ResultSet rs) throws SQLException { List<ApptRequestBean> list = new ArrayList<ApptRequestBean>(); while (rs.next()) { list.add(loadSingle(rs)); } return list; } /** * */ @Override public ApptRequestBean loadSingle(ResultSet rs) throws SQLException { ApptRequestBean bean = new ApptRequestBean(); ApptBean appt = loader.loadSingle(rs); bean.setRequestedAppt(appt); bean.setPending(rs.getBoolean("pending")); bean.setAccepted(rs.getBoolean("accepted")); return bean; } /** * */ @Override public PreparedStatement loadParameters(PreparedStatement ps, ApptRequestBean bean) throws SQLException { PreparedStatement ps2 = loader.loadParameters(ps, bean.getRequestedAppt()); ps2.setBoolean(6, bean.isPending()); ps2.setBoolean(7, bean.isAccepted()); return ps2; } }
1,338
22.491228
106
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/beans/loaders/ApptTypeBeanLoader.java
package edu.ncsu.csc.itrust.model.old.beans.loaders; 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.model.old.beans.ApptTypeBean; public class ApptTypeBeanLoader implements BeanLoader<ApptTypeBean> { @Override public List<ApptTypeBean> loadList(ResultSet rs) throws SQLException { List<ApptTypeBean> list = new ArrayList<ApptTypeBean>(); while (rs.next()) list.add(loadSingle(rs)); return list; } @Override public PreparedStatement loadParameters(PreparedStatement ps, ApptTypeBean apptType) throws SQLException { ps.setString(1, apptType.getName()); ps.setInt(2, apptType.getDuration()); return ps; } @Override public ApptTypeBean loadSingle(ResultSet rs) throws SQLException { ApptTypeBean apptType = new ApptTypeBean(); apptType.setName(rs.getString("appt_type")); apptType.setDuration(rs.getInt("duration")); return apptType; } }
996
25.945946
107
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/beans/loaders/BeanLoader.java
package edu.ncsu.csc.itrust.model.old.beans.loaders; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; /** * This interface helps enforce the paradigm of what should be contained in a loader. * * The generic type <T> specifies the type of bean that the loader is responsible for extacting from * a result set. * * @param <T> A type for the bean that will be loaded with this class. */ public interface BeanLoader<T> { /** * Loads a list of the bean of type T from a result set. Typically makes iterated calls * to loadSingle. * @param rs The java.sql.ResultSet we are extracting. * @return A java.util.List<T> where T is the type for this loader. * @throws SQLException */ public List<T> loadList(ResultSet rs) throws SQLException; /** * Contains the instructions for mapping the rows in this java.sql.ResultSet into * beans of type <T>. * @param rs The java.sql.ResultSet to be loaded. * @return A Bean of type T containing the loaded information, typically of the first (or next) item in the result set. * @throws SQLException */ public T loadSingle(ResultSet rs) throws SQLException; /** * Used for an insert or update, this method contains the instructions for mapping the fields within * a bean of type T into a prepared statement which modifies the appropriate table. * @param ps The prepared statement to be loaded. * @param bean The bean containing the data to be placed. * @return A prepared statement with the appropriately loaded parameters. * @throws SQLException */ public PreparedStatement loadParameters(PreparedStatement ps, T bean) throws SQLException; }
1,695
36.688889
120
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/beans/loaders/BillingBeanLoader.java
package edu.ncsu.csc.itrust.model.old.beans.loaders; 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.model.old.beans.BillingBean; public class BillingBeanLoader implements BeanLoader<BillingBean> { @Override /** * loadList simply takes a ResultSet from a query to the Billing table, and * then it creates a list of BillingBeans from it. * @param rs The ResultSet that is being converted into a list. * @return The list that contains all the BillingBeans in the ResultSet. */ public List<BillingBean> loadList(ResultSet rs) throws SQLException { ArrayList<BillingBean> result = new ArrayList<BillingBean>(); while(rs.next()){ BillingBean b = loadSingle(rs); result.add(b); } return result; } @Override /** * loadSingle does the heavy lifting for the loadList method. I am not really sure * why this method is public. * Preconditions: The ResultSet must already be on an actual entry in the set. * @param rs The result set that the BillingBean is being loaded from. * @return The BillingBean that represents the entry that is currently in the set. */ public BillingBean loadSingle(ResultSet rs) throws SQLException { if(rs == null) return null; BillingBean result = new BillingBean(); //Just go through all the billing bean stuff and initialize the //bean that was just created. result.setBillID(rs.getInt("billID")); result.setApptID(rs.getInt("appt_id")); result.setPatient(rs.getLong("PatientID")); result.setHcp(rs.getLong("HCPID")); result.setAmt(rs.getInt("amt")); result.setStatus(rs.getString("status")); result.setCcHolderName(rs.getString("ccHolderName")); result.setBillingAddress(rs.getString("billingAddress")); result.setCcType(rs.getString("ccType")); result.setCcNumber(rs.getString("ccNumber")); result.setCvv(rs.getString("cvv")); result.setInsHolderName(rs.getString("insHolderName")); result.setInsID(rs.getString("insID")); result.setInsProviderName(rs.getString("insProviderName")); result.setInsAddress1(rs.getString("insAddress1")); result.setInsAddress2(rs.getString("insAddress2")); result.setInsCity(rs.getString("insCity")); result.setInsState(rs.getString("insState")); result.setInsZip(rs.getString("insZip")); result.setInsPhone(rs.getString("insPhone")); result.setSubmissions(rs.getInt("submissions")); result.setBillTime(rs.getDate("billTimeS")); result.setSubTime(rs.getTimestamp("subTime")); result.setInsurance(rs.getBoolean("isInsurance")); return result; } @Override /** * loadParameters is used to insert the values of a bean into a pepared statement. * This version of loadParameters assumes that the values in the prepared statement are in * the same order as in the createTables.sql file for billing. * @param ps The prepared statement that the bean will be loaded into. * @param bean The BillingBean that will be loaded into the prepared statement. * @return The PreparedStatement that was passed in. */ public PreparedStatement loadParameters(PreparedStatement ps, BillingBean bean) throws SQLException { int i = 1; //Just run through everything in the bean, and set it to the //pepared statement ps.setInt(i++, bean.getApptID()); ps.setLong(i++, bean.getPatient()); ps.setLong(i++, bean.getHcp()); ps.setInt(i++, bean.getAmt()); ps.setString(i++, bean.getStatus()); ps.setString(i++, bean.getCcHolderName()); ps.setString(i++, bean.getBillingAddress()); ps.setString(i++, bean.getCcType()); ps.setString(i++, bean.getCcNumber()); ps.setString(i++, bean.getCvv()); ps.setString(i++, bean.getInsHolderName()); ps.setString(i++, bean.getInsID()); ps.setString(i++, bean.getInsProviderName()); ps.setString(i++, bean.getInsAddress1()); ps.setString(i++, bean.getInsAddress2()); ps.setString(i++, bean.getInsCity()); ps.setString(i++, bean.getInsState()); ps.setString(i++, bean.getInsZip()); ps.setString(i++, bean.getInsPhone()); ps.setInt(i++, bean.getSubmissions()); ps.setBoolean(i++, bean.isInsurance()); return ps; } }
4,170
37.266055
91
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/beans/loaders/DrugInteractionBeanLoader.java
package edu.ncsu.csc.itrust.model.old.beans.loaders; 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.model.old.beans.DrugInteractionBean; /** * A loader for MedicationBeans. * * Loads in information to/from beans using ResultSets and PreparedStatements. Use the superclass to enforce consistency. * For details on the paradigm for a loader (and what its methods do), see {@link BeanLoader} */ public class DrugInteractionBeanLoader implements BeanLoader<DrugInteractionBean> { public DrugInteractionBeanLoader() { } @Override public List<DrugInteractionBean> loadList(ResultSet rs) throws SQLException { ArrayList<DrugInteractionBean> list = new ArrayList<DrugInteractionBean>(); while (rs.next()) { list.add(loadSingle(rs)); } return list; } @Override public DrugInteractionBean loadSingle(ResultSet rs) throws SQLException { DrugInteractionBean drugIt = new DrugInteractionBean(); drugIt.setDescription(rs.getString("Description")); drugIt.setFirstDrug(rs.getString("FirstDrug")); drugIt.setSecondDrug(rs.getString("SecondDrug")); return drugIt; } @Override public PreparedStatement loadParameters(PreparedStatement ps, DrugInteractionBean bean) throws SQLException { throw new IllegalStateException("unimplemented!"); } }
1,394
30.704545
122
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/beans/loaders/DrugReactionOverrideBeanLoader.java
package edu.ncsu.csc.itrust.model.old.beans.loaders; 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.model.old.beans.OverrideReasonBean; /** * A loader for OverrideReasonBeans. * * Loads in information to/from beans using ResultSets and PreparedStatements. Use the superclass to enforce consistency. * For details on the paradigm for a loader (and what its methods do), see {@link BeanLoader} */ public class DrugReactionOverrideBeanLoader implements BeanLoader<OverrideReasonBean> { public DrugReactionOverrideBeanLoader() { } @Override public List<OverrideReasonBean> loadList(ResultSet rs) throws SQLException { List<OverrideReasonBean> list = new ArrayList<OverrideReasonBean>(); while (rs.next()) { list.add(loadSingle(rs)); } return list; } @Override public OverrideReasonBean loadSingle(ResultSet rs) throws SQLException { OverrideReasonBean orc = new OverrideReasonBean(rs.getString("Code")); orc.setDescription(rs.getString("Description")); return orc; } @Override public PreparedStatement loadParameters(PreparedStatement ps, OverrideReasonBean bean) throws SQLException { return null; } }
1,269
27.863636
122
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/beans/loaders/EmailBeanLoader.java
package edu.ncsu.csc.itrust.model.old.beans.loaders; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import edu.ncsu.csc.itrust.model.old.beans.Email; /** * A loader for Fake Emails. * * Loads in information to/from beans using ResultSets and PreparedStatements. Use the superclass to enforce consistency. * For details on the paradigm for a loader (and what its methods do), see {@link BeanLoader} */ public class EmailBeanLoader implements BeanLoader<Email> { @Override public List<Email> loadList(ResultSet rs) throws SQLException { List<Email> list = new ArrayList<Email>(); while (rs.next()) list.add(loadSingle(rs)); return list; } @Override public PreparedStatement loadParameters(PreparedStatement ps, Email email) throws SQLException { ps.setString(1, email.getToListStr()); ps.setString(2, email.getFrom()); ps.setString(3, email.getSubject()); ps.setString(4, email.getBody()); return ps; } @Override public Email loadSingle(ResultSet rs) throws SQLException { Email email = new Email(); email.setFrom(rs.getString("FromAddr")); email.setToList(Arrays.asList(rs.getString("ToAddr").split(","))); email.setBody(rs.getString("Body")); email.setSubject(rs.getString("Subject")); email.setTimeAdded(rs.getTimestamp("AddedDate")); return email; } }
1,431
28.22449
122
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/beans/loaders/FamilyBeanLoader.java
package edu.ncsu.csc.itrust.model.old.beans.loaders; 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.model.old.beans.FamilyMemberBean; /** * A loader for FamilyMemberBeans. * * Loads in information to/from beans using ResultSets and PreparedStatements. Use the superclass to enforce consistency. * For details on the paradigm for a loader (and what its methods do), see {@link BeanLoader} */ public class FamilyBeanLoader implements BeanLoader<FamilyMemberBean> { private String relation; public FamilyBeanLoader(String relation) { this.relation = relation; } @Override public List<FamilyMemberBean> loadList(ResultSet rs) throws SQLException { ArrayList<FamilyMemberBean> list = new ArrayList<FamilyMemberBean>(); while (rs.next()) { list.add(loadSingle(rs)); } return list; } @Override public PreparedStatement loadParameters(PreparedStatement ps, FamilyMemberBean bean) throws SQLException { throw new IllegalStateException("unimplemented!"); } @Override public FamilyMemberBean loadSingle(ResultSet rs) throws SQLException { FamilyMemberBean fam = new FamilyMemberBean(); fam.setRelation(relation); fam.setFirstName(rs.getString("FirstName")); fam.setLastName(rs.getString("LastName")); fam.setMid(rs.getInt("MID")); return fam; } }
1,412
28.4375
122
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/beans/loaders/HospitalBeanLoader.java
package edu.ncsu.csc.itrust.model.old.beans.loaders; 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.model.old.beans.HospitalBean; /** * A loader for HospitalBeans. * * Loads in information to/from beans using ResultSets and PreparedStatements. Use the superclass to enforce consistency. * For details on the paradigm for a loader (and what its methods do), see {@link BeanLoader} */ public class HospitalBeanLoader implements BeanLoader<HospitalBean> { @Override public List<HospitalBean> loadList(ResultSet rs) throws SQLException { ArrayList<HospitalBean> list = new ArrayList<HospitalBean>(); while (rs.next()) { list.add(loadSingle(rs)); } return list; } @Override public HospitalBean loadSingle(ResultSet rs) throws SQLException { HospitalBean hosp = new HospitalBean(rs.getString("HospitalID"), rs.getString("HospitalName"), rs.getString("Address"), rs.getString("City"), rs.getString("State"), rs.getString("Zip")); return hosp; } @Override public PreparedStatement loadParameters(PreparedStatement ps, HospitalBean bean) throws SQLException { throw new IllegalStateException("unimplemented!"); } }
1,268
31.538462
188
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/beans/loaders/MedicationBeanLoader.java
package edu.ncsu.csc.itrust.model.old.beans.loaders; 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.model.old.beans.MedicationBean; /** * A loader for MedicationBeans. * * Loads in information to/from beans using ResultSets and PreparedStatements. Use the superclass to enforce consistency. * For details on the paradigm for a loader (and what its methods do), see {@link BeanLoader} */ public class MedicationBeanLoader implements BeanLoader<MedicationBean> { public MedicationBeanLoader() { } @Override public List<MedicationBean> loadList(ResultSet rs) throws SQLException { ArrayList<MedicationBean> list = new ArrayList<MedicationBean>(); while (rs.next()) { list.add(loadSingle(rs)); } return list; } @Override public MedicationBean loadSingle(ResultSet rs) throws SQLException { MedicationBean med = new MedicationBean(rs.getString("Code")); med.setDescription(rs.getString("Description")); return med; } @Override public PreparedStatement loadParameters(PreparedStatement ps, MedicationBean bean) throws SQLException { throw new IllegalStateException("unimplemented!"); } }
1,250
28.093023
122
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/beans/loaders/MessageBeanLoader.java
package edu.ncsu.csc.itrust.model.old.beans.loaders; 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.model.old.beans.MessageBean; /** * A loader for MessageBeans. * * Loads in information to/from beans using ResultSets and PreparedStatements. Use the superclass to enforce consistency. * For details on the paradigm for a loader (and what its methods do), see {@link BeanLoader} */ public class MessageBeanLoader implements BeanLoader<MessageBean> { @Override public List<MessageBean> loadList(ResultSet rs) throws SQLException { List<MessageBean> list = new ArrayList<MessageBean>(); while (rs.next()) list.add(loadSingle(rs)); return list; } @Override public PreparedStatement loadParameters(PreparedStatement ps, MessageBean message) throws SQLException { ps.setLong(1, message.getFrom()); ps.setLong(2, message.getTo()); ps.setString(3, message.getBody()); ps.setString(4, message.getSubject()); ps.setInt(5, message.getRead()); ps.setLong(6, message.getParentMessageId()); ps.setLong(7, message.getOriginalMessageId()); return ps; } @Override public MessageBean loadSingle(ResultSet rs) throws SQLException { MessageBean message = new MessageBean(); message.setMessageId(rs.getLong("message_id")); message.setFrom(rs.getLong("from_id")); message.setTo(rs.getLong("to_id")); message.setSubject(rs.getString("subject")); message.setBody(rs.getString("message")); message.setSentDate(rs.getTimestamp("sent_date")); message.setRead(rs.getInt("been_read")); message.setParentMessageId(rs.getLong("parent_msg_id")); message.setOriginalMessageId(rs.getLong("original_msg_id")); return message; } }
1,791
31
122
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/beans/loaders/OperationalProfileLoader.java
package edu.ncsu.csc.itrust.model.old.beans.loaders; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; import edu.ncsu.csc.itrust.model.old.beans.OperationalProfile; import edu.ncsu.csc.itrust.model.old.enums.TransactionType; /** * A loader for the operational profile. * * Loads in information to/from beans using ResultSets and PreparedStatements. Use the superclass to enforce consistency. * For details on the paradigm for a loader (and what its methods do), see {@link BeanLoader} */ public class OperationalProfileLoader implements BeanLoader<OperationalProfile> { @Override public List<OperationalProfile> loadList(ResultSet rs) throws SQLException { throw new IllegalStateException("unimplemented!"); } @Override public PreparedStatement loadParameters(PreparedStatement ps, OperationalProfile bean) throws SQLException { throw new IllegalStateException("unimplemented!"); } @Override public OperationalProfile loadSingle(ResultSet rs) throws SQLException { OperationalProfile op = new OperationalProfile(); int grandTotal = 0; int grandPatient = 0; int grandPersonnel = 0; while (rs.next()) { TransactionType type = TransactionType.parse(rs.getInt("TransactionCode")); int totalCount = rs.getInt("TotalCount"); int patientCount = rs.getInt("PatientCount"); int personnelCount = rs.getInt("PersonnelCount"); op.getTotalCount().put(type, totalCount); op.getPatientCount().put(type, patientCount); op.getPersonnelCount().put(type, personnelCount); grandTotal += totalCount; grandPatient += patientCount; grandPersonnel += personnelCount; } op.setNumTotalTransactions(grandTotal); op.setNumPatientTransactions(grandPatient); op.setNumPersonnelTransactions(grandPersonnel); return op; } }
1,836
33.660377
122
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/beans/loaders/OverrideReasonBeanLoader.java
package edu.ncsu.csc.itrust.model.old.beans.loaders; 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.model.old.beans.OverrideReasonBean; /** * A loader for MedicationBeans. * * Loads in information to/from beans using ResultSets and PreparedStatements. Use the superclass to enforce consistency. * For details on the paradigm for a loader (and what its methods do), see {@link BeanLoader} */ public class OverrideReasonBeanLoader implements BeanLoader<OverrideReasonBean> { public OverrideReasonBeanLoader() { } @Override public List<OverrideReasonBean> loadList(ResultSet rs) throws SQLException { ArrayList<OverrideReasonBean> list = new ArrayList<OverrideReasonBean>(); while (rs.next()) { list.add(loadSingle(rs)); } return list; } @Override public OverrideReasonBean loadSingle(ResultSet rs) throws SQLException { OverrideReasonBean reason = new OverrideReasonBean(); reason.setORCode(rs.getString("OverrideCode")); return reason; } @Override public PreparedStatement loadParameters(PreparedStatement ps, OverrideReasonBean bean) throws SQLException { throw new IllegalStateException("unimplemented!"); } }
1,279
28.767442
122
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/beans/loaders/PatientLoader.java
package edu.ncsu.csc.itrust.model.old.beans.loaders; import java.sql.Date; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.List; import edu.ncsu.csc.itrust.model.old.beans.PatientBean; /** * A loader for PatientBeans. * * Loads in information to/from beans using ResultSets and PreparedStatements. Use the superclass to enforce consistency. * For details on the paradigm for a loader (and what its methods do), see {@link BeanLoader} */ public class PatientLoader implements BeanLoader<PatientBean> { private final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("MM/dd/yyyy"); /** * loadList * @param rs rs * @throws SQLException */ @Override public List<PatientBean> loadList(ResultSet rs) throws SQLException { List<PatientBean> list = new ArrayList<PatientBean>(); while (rs.next()) { list.add(loadSingle(rs)); } return list; } private void loadCommon(ResultSet rs, PatientBean p) throws SQLException{ p.setMID(rs.getInt("MID")); p.setFirstName(rs.getString("firstName")); p.setLastName(rs.getString("LastName")); Date dateOfBirth = rs.getDate("DateOfBirth"); if (dateOfBirth != null){ p.setDateOfBirthStr(DATE_FORMAT.format(dateOfBirth)); } Date dateOfDeath = rs.getDate("DateOfDeath"); if (dateOfDeath != null){ p.setDateOfDeathStr(DATE_FORMAT.format(dateOfDeath)); } p.setCauseOfDeath(rs.getString("CauseOfDeath")); p.setEmail(rs.getString("Email")); p.setStreetAddress1(rs.getString("address1")); p.setStreetAddress2(rs.getString("address2")); p.setCity(rs.getString("City")); p.setState(rs.getString("State")); p.setZip((rs.getString("Zip"))); p.setPhone((rs.getString("phone"))); p.setEmergencyName(rs.getString("eName")); p.setEmergencyPhone(rs.getString("ePhone")); p.setIcName(rs.getString("icName")); p.setIcAddress1(rs.getString("icAddress1")); p.setIcAddress2(rs.getString("icAddress2")); p.setIcCity(rs.getString("icCity")); p.setIcState(rs.getString("icState")); p.setIcZip(rs.getString("icZip")); p.setIcPhone(rs.getString("icPhone")); p.setIcID(rs.getString("icID")); p.setMotherMID(rs.getString("MotherMID")); p.setFatherMID(rs.getString("FatherMID")); p.setBloodTypeStr(rs.getString("BloodType")); p.setEthnicityStr(rs.getString("Ethnicity")); p.setGenderStr(rs.getString("Gender")); p.setTopicalNotes(rs.getString("TopicalNotes")); p.setCreditCardType(rs.getString("CreditCardType")); p.setCreditCardNumber(rs.getString("CreditCardNumber")); p.setDirectionsToHome(rs.getString("DirectionsToHome")); p.setReligion(rs.getString("Religion")); p.setLanguage(rs.getString("Language")); p.setSpiritualPractices(rs.getString("SpiritualPractices")); p.setAlternateName(rs.getString("AlternateName")); Date dateOfDeactivation = rs.getDate("DateOfDeactivation"); if (dateOfDeactivation != null){ p.setDateOfDeactivationStr(DATE_FORMAT.format(dateOfDeactivation)); } } /** * loadSingle * @param rs rs * @return p * @throws SQLException */ @Override public PatientBean loadSingle(ResultSet rs) throws SQLException { PatientBean p = new PatientBean(); loadCommon(rs, p); return p; } /** * loadParameters * @throws SQLException */ @Override public PreparedStatement loadParameters(PreparedStatement ps, PatientBean p) throws SQLException { int i = 1; ps.setString(i++, p.getFirstName()); ps.setString(i++, p.getLastName()); ps.setString(i++, p.getEmail()); ps.setString(i++, p.getStreetAddress1()); ps.setString(i++, p.getStreetAddress2()); ps.setString(i++, p.getCity()); ps.setString(i++, p.getState()); ps.setString(i++, p.getZip()); ps.setString(i++, p.getPhone()); ps.setString(i++, p.getEmergencyName()); ps.setString(i++, p.getEmergencyPhone()); ps.setString(i++, p.getIcName()); ps.setString(i++, p.getIcAddress1()); ps.setString(i++, p.getIcAddress2()); ps.setString(i++, p.getIcCity()); ps.setString(i++, p.getIcState()); ps.setString(i++, p.getIcZip()); ps.setString(i++, p.getIcPhone()); ps.setString(i++, p.getIcID()); Date date = null; try { date = new java.sql.Date(DATE_FORMAT.parse(p.getDateOfBirthStr()) .getTime()); } catch (ParseException e) { //TODO } ps.setDate(i++, date); date = null; try { date = new java.sql.Date(DATE_FORMAT.parse(p.getDateOfDeathStr()) .getTime()); } catch (ParseException e) { if ("".equals(p.getDateOfDeathStr())){ date = null; }else{ } } ps.setDate(i++, date); ps.setString(i++, p.getCauseOfDeath()); ps.setString(i++, p.getMotherMID()); ps.setString(i++, p.getFatherMID()); ps.setString(i++, p.getBloodType().getName()); ps.setString(i++, p.getEthnicity().getName()); ps.setString(i++, p.getGender().getName()); ps.setString(i++, p.getTopicalNotes()); ps.setString(i++, p.getCreditCardType()); ps.setString(i++, p.getCreditCardNumber()); ps.setString(i++, p.getDirectionsToHome()); ps.setString(i++, p.getReligion()); ps.setString(i++, p.getLanguage()); ps.setString(i++, p.getSpiritualPractices()); ps.setString(i++, p.getAlternateName()); date = null; try { date = new java.sql.Date(DATE_FORMAT.parse(p.getDateOfDeactivationStr()) .getTime()); } catch (ParseException e) { if ("".equals(p.getDateOfDeactivationStr())){ date = null; }else{ } }catch (NullPointerException e) { if ("".equals(p.getDateOfDeactivationStr())){ date = null; }else{ } } ps.setDate(i++, date); return ps; } }
5,653
30.411111
122
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/beans/loaders/PersonnelLoader.java
package edu.ncsu.csc.itrust.model.old.beans.loaders; 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.model.old.beans.PersonnelBean; /** * A loader for PersonnelBeans. * * Loads in information to/from beans using ResultSets and PreparedStatements. Use the superclass to enforce consistency. * For details on the paradigm for a loader (and what its methods do), see {@link BeanLoader} */ public class PersonnelLoader implements BeanLoader<PersonnelBean> { @Override public List<PersonnelBean> loadList(ResultSet rs) throws SQLException { List<PersonnelBean> list = new ArrayList<PersonnelBean>(); while (rs.next()) { list.add(loadSingle(rs)); } return list; } @Override public PersonnelBean loadSingle(ResultSet rs) throws SQLException { PersonnelBean p = new PersonnelBean(); p.setMID(rs.getLong("MID")); p.setAMID(rs.getLong("amid")); p.setRoleString(rs.getString("role")); p.setLastName(rs.getString("lastName")); p.setFirstName(rs.getString("firstName")); p.setPhone(rs.getString("phone")); p.setStreetAddress1(rs.getString("address1")); p.setStreetAddress2(rs.getString("address2")); p.setCity(rs.getString("city")); p.setState(rs.getString("state")); p.setZip((rs.getString("zip"))); p.setEmail(rs.getString("email")); p.setSpecialty(rs.getString("specialty")); return p; } @Override public PreparedStatement loadParameters(PreparedStatement ps, PersonnelBean p) throws SQLException { int i = 1; ps.setLong(i++, p.getAMID()); ps.setString(i++, p.getFirstName()); ps.setString(i++, p.getLastName()); ps.setString(i++, p.getPhone()); ps.setString(i++, p.getStreetAddress1()); ps.setString(i++, p.getStreetAddress2()); ps.setString(i++, p.getCity()); ps.setString(i++, p.getState()); ps.setString(i++, p.getZip()); ps.setString(i++, p.getSpecialty()); ps.setString(i++, p.getEmail()); return ps; } }
2,011
30.936508
122
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/beans/loaders/RecordsReleaseBeanLoader.java
package edu.ncsu.csc.itrust.model.old.beans.loaders; 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.model.old.beans.RecordsReleaseBean; public class RecordsReleaseBeanLoader implements BeanLoader<RecordsReleaseBean> { @Override public List<RecordsReleaseBean> loadList(ResultSet rs) throws SQLException { ArrayList<RecordsReleaseBean> list = new ArrayList<RecordsReleaseBean>(); while (rs.next()) { list.add(loadSingle(rs)); } return list; } @Override public RecordsReleaseBean loadSingle(ResultSet rs) throws SQLException { RecordsReleaseBean bean = new RecordsReleaseBean(); bean.setReleaseID(rs.getLong("releaseID")); bean.setDateRequested(rs.getTimestamp("requestDate")); bean.setPid(rs.getLong("pid")); bean.setReleaseHospitalID(rs.getString("releaseHospitalID")); bean.setRecHospitalName(rs.getString("recHospitalName")); bean.setRecHospitalAddress(rs.getString("recHospitalAddress")); bean.setDocFirstName(rs.getString("docFirstName")); bean.setDocLastName(rs.getString("docLastName")); bean.setDocPhone(rs.getString("docPhone")); bean.setDocEmail(rs.getString("docEmail")); bean.setJustification(rs.getString("justification")); bean.setStatus(rs.getInt("status")); return bean; } @Override public PreparedStatement loadParameters(PreparedStatement ps, RecordsReleaseBean bean) throws SQLException { int i = 1; ps.setTimestamp(i++, bean.getDateRequested()); ps.setLong(i++, bean.getPid()); ps.setString(i++, bean.getReleaseHospitalID()); ps.setString(i++, bean.getRecHospitalName()); ps.setString(i++, bean.getRecHospitalAddress()); ps.setString(i++, bean.getDocFirstName()); ps.setString(i++, bean.getDocLastName()); ps.setString(i++, bean.getDocPhone()); ps.setString(i++, bean.getDocEmail()); ps.setString(i++, bean.getJustification()); ps.setInt(i++, bean.getStatus()); return ps; } }
2,003
32.966102
109
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/beans/loaders/RemoteMonitoringDataBeanLoader.java
package edu.ncsu.csc.itrust.model.old.beans.loaders; 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.model.old.beans.RemoteMonitoringDataBean; /** * A loader for RemoteMonitoringDataBeans. * * Loads in information to/from beans using ResultSets and PreparedStatements. Use the superclass to enforce consistency. * For details on the paradigm for a loader (and what its methods do), see {@link BeanLoader} */ public class RemoteMonitoringDataBeanLoader implements BeanLoader<RemoteMonitoringDataBean> { @Override public List<RemoteMonitoringDataBean> loadList(ResultSet rs) throws SQLException { List<RemoteMonitoringDataBean> list = new ArrayList<RemoteMonitoringDataBean>(); while (rs.next()) { list.add(loadSingle(rs)); } return list; } @Override public PreparedStatement loadParameters(PreparedStatement ps, RemoteMonitoringDataBean bean) throws SQLException { throw new IllegalStateException("unimplemented!"); } @Override public RemoteMonitoringDataBean loadSingle(ResultSet rs) throws SQLException { RemoteMonitoringDataBean d = new RemoteMonitoringDataBean(); d.setLoggedInMID(rs.getLong("PatientID")); d.setSystolicBloodPressure(rs.getInt("systolicBloodPressure")); d.setDiastolicBloodPressure(rs.getInt("diastolicBloodPressure")); d.setGlucoseLevel(rs.getInt("glucoseLevel")); d.setHeight(rs.getFloat("height")); d.setWeight(rs.getFloat("weight")); d.setPedometerReading(rs.getInt("pedometerReading")); d.setTime(rs.getTimestamp("timeLogged")); d.setReporterRole(rs.getString("ReporterRole")); d.setReporterMID(rs.getLong("ReporterID")); return d; } }
1,742
34.571429
122
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/beans/loaders/RemoteMonitoringListsBeanLoader.java
package edu.ncsu.csc.itrust.model.old.beans.loaders; 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.model.old.beans.TelemedicineBean; /** * A loader for RemoteMonitoringDataBeans. * * Loads in information to/from beans using ResultSets and PreparedStatements. Use the superclass to enforce consistency. * For details on the paradigm for a loader (and what its methods do), see {@link BeanLoader} */ public class RemoteMonitoringListsBeanLoader implements BeanLoader<TelemedicineBean> { @Override public List<TelemedicineBean> loadList(ResultSet rs) throws SQLException { List<TelemedicineBean> list = new ArrayList<TelemedicineBean>(); while (rs.next()) { list.add(loadSingle(rs)); } return list; } @Override public PreparedStatement loadParameters(PreparedStatement ps, TelemedicineBean bean) throws SQLException { throw new IllegalStateException("unimplemented!"); } @Override public TelemedicineBean loadSingle(ResultSet rs) throws SQLException { TelemedicineBean d = new TelemedicineBean(); d.setSystolicBloodPressureAllowed(rs.getBoolean("SystolicBloodPressure")); d.setDiastolicBloodPressureAllowed(rs.getBoolean("DiastolicBloodPressure")); d.setGlucoseLevelAllowed(rs.getBoolean("GlucoseLevel")); d.setHeightAllowed(rs.getBoolean("Height")); d.setWeightAllowed(rs.getBoolean("Weight")); d.setPedometerReadingAllowed(rs.getBoolean("PedometerReading")); return d; } }
1,547
33.4
122
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/beans/loaders/ReportRequestBeanLoader.java
package edu.ncsu.csc.itrust.model.old.beans.loaders; 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.model.old.beans.ReportRequestBean; /** * A loader for ReportRequestBeans. * * Loads in information to/from beans using ResultSets and PreparedStatements. Use the superclass to enforce consistency. * For details on the paradigm for a loader (and what its methods do), see {@link BeanLoader} */ public class ReportRequestBeanLoader implements BeanLoader<ReportRequestBean> { @Override public List<ReportRequestBean> loadList(ResultSet rs) throws SQLException { ArrayList<ReportRequestBean> list = new ArrayList<ReportRequestBean>(); while (rs.next()) { list.add(loadSingle(rs)); } return list; } @Override public ReportRequestBean loadSingle(ResultSet rs) throws SQLException { ReportRequestBean b = new ReportRequestBean(); b.setID(rs.getLong("ID")); b.setRequesterMID(rs.getLong("RequesterMID")); b.setPatientMID(rs.getLong("PatientMID")); b.setRequestedDate(rs.getTimestamp("RequestedDate")); b.setViewedDate(rs.getTimestamp("ViewedDate")); b.setStatus(rs.getString("Status")); return b; } @Override public PreparedStatement loadParameters(PreparedStatement ps, ReportRequestBean bean) throws SQLException { throw new IllegalStateException("unimplemented!"); } }
1,441
29.041667
122
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/beans/loaders/ReviewsBeanLoader.java
/** * */ package edu.ncsu.csc.itrust.model.old.beans.loaders; 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.model.old.beans.ReviewsBean; /** * To load information to/from the reviews table into/from ReviewsBeans. */ public class ReviewsBeanLoader implements BeanLoader<ReviewsBean> { /** * From a ResultSet input param, return a list of loaded ReviewsBeans. * @param ResultSet including the Bean info * @return Java.util Array List ReviewsBeans */ @Override public List<ReviewsBean> loadList(ResultSet rs) throws SQLException { ArrayList<ReviewsBean> list = new ArrayList<ReviewsBean>(); while(rs.next()){ list.add(loadSingle(rs)); } return list; } /** * ReviewsBeans are built and returned, when possible from info * in ResultSet. * @param ResultSet from query, holds DB info for ReviewsBean * @return the loaded ReviewsBean */ @Override public ReviewsBean loadSingle(ResultSet rs) throws SQLException { ReviewsBean rev = new ReviewsBean(); rev.setMID(rs.getLong("mid")); rev.setPID(rs.getLong("pid")); rev.setDateOfReview(rs.getDate("reviewdate")); rev.setDescriptiveReview(rs.getString("descriptivereview")); rev.setRating(rs.getInt("rating")); rev.setTitle(rs.getString("title")); return rev; } /** * We may decide to implement this later but for now, every call to here returns null. */ @Override public PreparedStatement loadParameters(PreparedStatement ps, ReviewsBean bean) throws SQLException { int i = 1; ps.setLong(i++, bean.getMID()); ps.setLong(i++, bean.getPID()); ps.setString(i++, bean.getDescriptiveReview()); ps.setDouble(i++, bean.getRating()); ps.setString(i++, bean.getTitle()); return ps; } }
1,834
25.985294
87
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/beans/loaders/TransactionBeanLoader.java
package edu.ncsu.csc.itrust.model.old.beans.loaders; 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.model.old.beans.TransactionBean; import edu.ncsu.csc.itrust.model.old.enums.TransactionType; /** * A loader for TransactionBeans. * * Loads in information to/from beans using ResultSets and PreparedStatements. Use the superclass to enforce consistency. * For details on the paradigm for a loader (and what its methods do), see {@link BeanLoader} */ public class TransactionBeanLoader implements BeanLoader<TransactionBean> { @Override public List<TransactionBean> loadList(ResultSet rs) throws SQLException { List<TransactionBean> list = new ArrayList<TransactionBean>(); while (rs.next()) { list.add(loadSingle(rs)); } return list; } @Override public PreparedStatement loadParameters(PreparedStatement ps, TransactionBean bean) throws SQLException { throw new IllegalStateException("unimplemented!"); } @Override public TransactionBean loadSingle(ResultSet rs) throws SQLException { TransactionBean t = new TransactionBean(); t.setAddedInfo(rs.getString("addedInfo")); t.setLoggedInMID(rs.getLong("loggedInMID")); t.setSecondaryMID(rs.getLong("secondaryMID")); t.setTimeLogged(rs.getTimestamp("timeLogged")); t.setTransactionType(TransactionType.parse(rs.getInt("transactionCode"))); t.setTransactionID(rs.getLong("transactionID")); return t; } }
1,523
31.425532
122
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/beans/loaders/WardBeanLoader.java
package edu.ncsu.csc.itrust.model.old.beans.loaders; 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.model.old.beans.WardBean; /** * A loader for WardBeans. * * Loads in information to/from beans using ResultSets and PreparedStatements. Use the superclass to enforce consistency. * For details on the paradigm for a loader (and what its methods do), see {@link BeanLoader} */ public class WardBeanLoader implements BeanLoader<WardBean> { @Override public List<WardBean> loadList(ResultSet rs) throws SQLException { ArrayList<WardBean> list = new ArrayList<WardBean>(); while (rs.next()) { list.add(loadSingle(rs)); } return list; } @Override public WardBean loadSingle(ResultSet rs) throws SQLException { WardBean ward = new WardBean(rs.getLong("WardID"), rs.getString("RequiredSpecialty"), rs.getLong("InHospital")); return ward; } @Override public PreparedStatement loadParameters(PreparedStatement ps, WardBean bean) throws SQLException { throw new IllegalStateException("unimplemented!"); } }
1,157
29.473684
122
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/beans/loaders/WardRoomBeanLoader.java
package edu.ncsu.csc.itrust.model.old.beans.loaders; 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.model.old.beans.WardRoomBean; public class WardRoomBeanLoader implements BeanLoader<WardRoomBean> { @Override public List<WardRoomBean> loadList(ResultSet rs) throws SQLException { ArrayList<WardRoomBean> list = new ArrayList<WardRoomBean>(); while (rs.next()) { list.add(loadSingle(rs)); } return list; } @Override public WardRoomBean loadSingle(ResultSet rs) throws SQLException { WardRoomBean wardRoom = new WardRoomBean(rs.getLong("RoomID"), rs.getLong("OccupiedBy"), rs.getLong("InWard"), rs.getString("roomName"), rs.getString("Status")); return wardRoom; } @Override public PreparedStatement loadParameters(PreparedStatement ps, WardRoomBean bean) throws SQLException { throw new IllegalStateException("unimplemented!"); } }
986
29.84375
163
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/beans/loaders/ZipCodeLoader.java
package edu.ncsu.csc.itrust.model.old.beans.loaders; 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.model.old.beans.ZipCodeBean; import edu.ncsu.csc.itrust.model.old.enums.State; /** * A loader for ZipCodeBeans. * * Loads in information to/from beans using ResultSets and PreparedStatements. Use the superclass to enforce consistency. * For details on the paradigm for a loader (and what its methods do), see {@link BeanLoader} */ public class ZipCodeLoader implements BeanLoader<ZipCodeBean> { /** * Loads a list of ZipCodeBeans */ @Override public List<ZipCodeBean> loadList(ResultSet rs) throws SQLException { List<ZipCodeBean> list = new ArrayList<ZipCodeBean>(); while (rs.next()) list.add(loadSingle(rs)); return list; } /** * Loads a single result set into a zip code bean. */ @Override public ZipCodeBean loadSingle(ResultSet rs) throws SQLException { ZipCodeBean bean = new ZipCodeBean(); bean.setCity(rs.getString("city")); bean.setFullState(rs.getString("full_state")); bean.setLatitude(rs.getString("latitude")); bean.setLongitude(rs.getString("longitude")); bean.setState(State.parse(rs.getString("state"))); bean.setZip(rs.getString("zip")); return bean; } @Override /** * */ public PreparedStatement loadParameters(PreparedStatement ps, ZipCodeBean bean) throws SQLException { return null; } }
1,502
25.839286
122
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/dao/DAOFactory.java
package edu.ncsu.csc.itrust.model.old.dao; import java.sql.Connection; import java.sql.SQLException; import edu.ncsu.csc.itrust.model.old.dao.mysql.*; /** * The central mediator for all Database Access Objects. The production instance uses the database connection * pool provided by Tomcat (so use the production instance when doing stuff from JSPs in the "real code"). * Both the production and the test instance parses the context.xml file to get the JDBC connection. * * Also, @see {@link EvilDAOFactory} and @see {@link TestDAOFactory}. * * Any DAO that is added to the system should be added in this class, in the same way that all other DAOs are. * * * */ public class DAOFactory { private static DAOFactory productionInstance = null; private IConnectionDriver driver; /** * * @return A production instance of the DAOFactory, to be used in deployment (by Tomcat). */ public static DAOFactory getProductionInstance() { if(productionInstance == null){ productionInstance = new DAOFactory(); } return productionInstance; } /** * Protected constructor. Call getProductionInstance to get an instance of the DAOFactory */ protected DAOFactory() { this.driver = new ProductionConnectionDriver(); } /** * * @return this DAOFactory's Connection * @throws SQLException */ public Connection getConnection() throws SQLException { return driver.getConnection(); } /** * * @return this DAOFactory's AccessDAO */ public AccessDAO getAccessDAO() { return new AccessDAO(this); } /** * * @return this DAOFactory's ZipCodeDAO */ public ZipCodeDAO getZipCodeDAO() { return new ZipCodeDAO(this); } /** * * @return this DAOFactory's AllergyDAO */ public AllergyDAO getAllergyDAO() { return new AllergyDAO(this); } /** * * @return this DAOFactory's ApptDAO */ public ApptDAO getApptDAO() { return new ApptDAO(this); } /** * * @return this DAOFactory's ApptRequestDAO */ public ApptRequestDAO getApptRequestDAO() { return new ApptRequestDAO(this); } /** * * @return this DAOFactory's ApptTypeDAO */ public ApptTypeDAO getApptTypeDAO() { return new ApptTypeDAO(this); } /** * * @return this DAOFactory's AuthDAO */ public AuthDAO getAuthDAO() { return new AuthDAO(this); } /** * * @return this DAOFactory's BillingDAO */ public BillingDAO getBillingDAO() { return new BillingDAO(this); } /** * * @return this DAOFactory's DrugInteractionDAO */ public DrugInteractionDAO getDrugInteractionDAO() { return new DrugInteractionDAO(this); } /** * * @return this DAOFactory's FamilyDAO */ public FamilyDAO getFamilyDAO() { return new FamilyDAO(this); } /** * * @return this DAOFactory's HospitalsDAO */ public HospitalsDAO getHospitalsDAO() { return new HospitalsDAO(this); } /** * * @return this DAOFactory's NDCodesDAO */ public NDCodesDAO getNDCodesDAO() { return new NDCodesDAO(this); } /** * * @return this DAOFactory's OfficeVisitDAO */ // public OfficeVisitDAO getOfficeVisitDAO() { // return new OfficeVisitDAO(this); // } /** * * @return this DAOFactory's PatientDAO */ public PatientDAO getPatientDAO() { return new PatientDAO(this); } /** * * @return this DAOFactory's PersonnelDAO */ public PersonnelDAO getPersonnelDAO() { return new PersonnelDAO(this); } /** * * @return this DAOFactory's TransactionDAO */ public TransactionDAO getTransactionDAO() { return new TransactionDAO(this); } /** * * @return this DAOFactory's FakeEmailDAO */ public FakeEmailDAO getFakeEmailDAO() { return new FakeEmailDAO(this); } /** * * @return this DAOFactory's ReportRequestDAO */ public ReportRequestDAO getReportRequestDAO() { return new ReportRequestDAO(this); } /** * * @return this DAOFactory's MessageDAO */ public MessageDAO getMessageDAO() { return new MessageDAO(this); } /** * * @return this DAOFactory's RemoteMonitoringDAO */ public RemoteMonitoringDAO getRemoteMonitoringDAO() { return new RemoteMonitoringDAO(this); } /** * * @return this DAOFactory's DrugReactionOverrideCodesDAO */ public DrugReactionOverrideCodesDAO getORCodesDAO() { return new DrugReactionOverrideCodesDAO(this); } /** * Gets the DAO for reviews with the DB table reviews. * @return this DAOFactory's ReviewsDAO */ public ReviewsDAO getReviewsDAO() { return new ReviewsDAO(this); } }
4,501
17.995781
110
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/dao/IConnectionDriver.java
package edu.ncsu.csc.itrust.model.old.dao; import java.sql.Connection; import java.sql.SQLException; /** * Used by DAOFactory to abstract away different ways of getting our JDBC connection * * * */ public interface IConnectionDriver { public Connection getConnection() throws SQLException; }
304
19.333333
84
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/dao/ProductionConnectionDriver.java
package edu.ncsu.csc.itrust.model.old.dao; import java.sql.Connection; import java.sql.SQLException; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.sql.DataSource; /** * Produces the JDBC connection from Tomcat's JDBC connection pool (defined in context.xml). Produces and * exception when running the unit tests because they're not being run through Tomcat. * * * */ public class ProductionConnectionDriver implements IConnectionDriver { private InitialContext initialContext; // In production situations public ProductionConnectionDriver() { } // For our special unit test - do not use unless you know what you are doing public ProductionConnectionDriver(InitialContext context) { initialContext = context; } @Override public Connection getConnection() throws SQLException { try { if (initialContext == null) initialContext = new InitialContext(); return ((DataSource) (((Context) initialContext.lookup("java:comp/env"))).lookup("jdbc/itrust")) .getConnection(); } catch (NamingException e) { throw new SQLException(("Context Lookup Naming Exception: " + e.getMessage())); } } }
1,200
28.292683
105
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/dao/mysql/AccessDAO.java
package edu.ncsu.csc.itrust.model.old.dao.mysql; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import edu.ncsu.csc.itrust.exception.DBException; import edu.ncsu.csc.itrust.model.old.dao.DAOFactory; /** * AccessDAO is for all queries related to authorization. * * DAO stands for Database Access Object. All DAOs are intended to be * reflections of the database, that is, one DAO per table in the database (most * of the time). For more complex sets of queries, extra DAOs are added. DAOs * can assume that all data has been validated and is correct. * * DAOs should never have setters or any other parameter to the constructor than * a factory. All DAOs should be accessed by DAOFactory (@see * {@link DAOFactory}) and every DAO should have a factory - for obtaining JDBC * connections and/or accessing other DAOs. * * * * */ @SuppressWarnings({}) public class AccessDAO { private transient final DAOFactory factory; /** * The typical constructor. * * @param factory * The {@link DAOFactory} associated with this DAO, which is used * for obtaining SQL connections, etc. */ public AccessDAO(final DAOFactory factory) { this.factory = factory; } /** * Returns the number of minutes it would take for a session to time out. * This is done by effectively using the database table as a hash table. If * a row in GlobalVariables does not exist, one is inserted with the default * value '20'. * * @return An int for the number of minutes. * @throws DBException */ public int getSessionTimeoutMins() throws DBException { try (Connection conn = factory.getConnection(); PreparedStatement stmt = conn.prepareStatement("SELECT Value FROM globalvariables WHERE Name='Timeout'")) { ResultSet rs = stmt.executeQuery(); if (rs.next()) { int returnVal = rs.getInt("Value"); return returnVal; } else { insertDefaultTimeout(20); return 20; } } catch (SQLException e) { throw new DBException(e); } } /** * Sets the number of minutes it would take for a session to timeout. * * @param mins * An int specifying the number of minutes * @throws DBException */ public void setSessionTimeoutMins(int mins) throws DBException { try (Connection conn = factory.getConnection(); PreparedStatement stmt = conn .prepareStatement("UPDATE globalvariables SET Value=? WHERE Name='Timeout'")) { stmt.setInt(1, mins); int numUpdated = stmt.executeUpdate(); if (numUpdated == 0) // no value in the table insertDefaultTimeout(mins); } catch (SQLException e) { throw new DBException(e); } } private void insertDefaultTimeout(final int mins) throws SQLException, DBException { try (Connection conn = factory.getConnection(); PreparedStatement stmt = conn.prepareStatement("INSERT INTO globalvariables(Name,Value) VALUES ('Timeout', ?)")) { stmt.setInt(1, mins); stmt.executeUpdate(); } catch (SQLException e) { throw new DBException(e); } } }
3,087
30.510204
118
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/dao/mysql/AllergyDAO.java
package edu.ncsu.csc.itrust.model.old.dao.mysql; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; import edu.ncsu.csc.itrust.exception.DBException; import edu.ncsu.csc.itrust.model.old.beans.AllergyBean; import edu.ncsu.csc.itrust.model.old.beans.loaders.AllergyBeanLoader; import edu.ncsu.csc.itrust.model.old.dao.DAOFactory; /** * DAO stands for Database Access Object. All DAOs are intended to be * reflections of the database, that is, one DAO per table in the database (most * of the time). For more complex sets of queries, extra DAOs are added. DAOs * can assume that all data has been validated and is correct. * * DAOs should never have setters or any other parameter to the constructor than * a factory. All DAOs should be accessed by DAOFactory (@see * {@link DAOFactory}) and every DAO should have a factory - for obtaining JDBC * connections and/or accessing other DAOs. */ public class AllergyDAO { private DAOFactory factory; private transient final AllergyBeanLoader allergyBeanLoader = new AllergyBeanLoader(); /** * The typical constructor. * * @param factory * The {@link DAOFactory} associated with this DAO, which is used * for obtaining SQL connections, etc. */ public AllergyDAO(final DAOFactory factory) { this.factory = factory; } /** * Returns a list of patient's allergies. * * @param pid * A long for the MID of the patient we are looking up. * @return A java.util.List of AllergyBeans associated with this patient. * @throws DBException */ public List<AllergyBean> getAllergies(final long pid) throws DBException { try (Connection conn = factory.getConnection(); PreparedStatement stmt = conn .prepareStatement("SELECT * FROM allergies WHERE PatientID=? ORDER BY FirstFound DESC")) { stmt.setLong(1, pid); final ResultSet results = stmt.executeQuery(); final List<AllergyBean> loadlist = allergyBeanLoader.loadList(results); return loadlist; } catch (SQLException e) { throw new DBException(e); } } /** * Adds an allergy to this patient's list. * * @param allergy * allergy bean * @throws DBException */ public void addAllergy(final AllergyBean allergy) throws DBException { try (Connection conn = factory.getConnection(); PreparedStatement stmt = conn.prepareStatement( "INSERT INTO allergies(PatientID, Code, FirstFound, Description) VALUES (?,?,?,?)")) { stmt.setLong(1, allergy.getPatientID()); stmt.setString(2, allergy.getNDCode()); if (allergy.getFirstFound() == null) { stmt.setDate(3, null); } else { stmt.setDate(3, new java.sql.Date(allergy.getFirstFound().getTime())); } stmt.setString(4, allergy.getDescription()); stmt.executeUpdate(); } catch (SQLException e) { throw new DBException(e); } } }
2,927
32.655172
96
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/dao/mysql/ApptDAO.java
package edu.ncsu.csc.itrust.model.old.dao.mysql; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; import edu.ncsu.csc.itrust.exception.DBException; import edu.ncsu.csc.itrust.model.old.beans.ApptBean; import edu.ncsu.csc.itrust.model.old.beans.loaders.ApptBeanLoader; import edu.ncsu.csc.itrust.model.old.dao.DAOFactory; public class ApptDAO { private transient final DAOFactory factory; private transient final ApptBeanLoader abloader; private transient final ApptTypeDAO apptTypeDAO; private static final int MIN_MID = 999999999; public ApptDAO(final DAOFactory factory) { this.factory = factory; this.apptTypeDAO = factory.getApptTypeDAO(); this.abloader = new ApptBeanLoader(); } public List<ApptBean> getAppt(final int apptID) throws SQLException, DBException { ResultSet results = null; try (Connection conn = factory.getConnection(); PreparedStatement stmt = conn.prepareStatement("SELECT * FROM appointment WHERE appt_id=?")) { stmt.setInt(1, apptID); results = stmt.executeQuery(); final List<ApptBean> abList = this.abloader.loadList(results); return abList; } catch (SQLException e) { throw new DBException(e); } } public List<ApptBean> getApptsFor(final long mid) throws SQLException, DBException { try (Connection conn = factory.getConnection(); PreparedStatement stmt = (mid >= MIN_MID) ? conn.prepareStatement( "SELECT * FROM appointment WHERE doctor_id=? AND sched_date > NOW() ORDER BY sched_date;") : conn.prepareStatement( "SELECT * FROM appointment WHERE patient_id=? AND sched_date > NOW() ORDER BY sched_date;")) { stmt.setLong(1, mid); ResultSet results = stmt.executeQuery(); List<ApptBean> abList = this.abloader.loadList(results); results.close(); return abList; } catch (SQLException e) { throw new DBException(e); } } public List<ApptBean> getAllApptsFor(long mid) throws SQLException, DBException { try (Connection conn = factory.getConnection(); PreparedStatement stmt = (mid >= MIN_MID) ? conn.prepareStatement("SELECT * FROM appointment WHERE doctor_id=? ORDER BY sched_date;") : conn.prepareStatement("SELECT * FROM appointment WHERE patient_id=? ORDER BY sched_date;")) { stmt.setLong(1, mid); final ResultSet results = stmt.executeQuery(); final List<ApptBean> abList = this.abloader.loadList(results); results.close(); return abList; } catch (SQLException e) { throw new DBException(e); } } public void scheduleAppt(final ApptBean appt) throws SQLException, DBException { try (Connection conn = factory.getConnection(); PreparedStatement stmt = this.abloader.loadParameters(conn.prepareStatement( "INSERT INTO appointment (appt_type, patient_id, doctor_id, sched_date, comment) " + "VALUES (?, ?, ?, ?, ?)"), appt)) { stmt.executeUpdate(); } catch (SQLException e) { throw new DBException(e); } } public void editAppt(final ApptBean appt) throws SQLException, DBException { try (Connection conn = factory.getConnection(); PreparedStatement stmt = conn .prepareStatement("UPDATE appointment SET appt_type=?, sched_date=?, comment=? WHERE appt_id=?")) { stmt.setString(1, appt.getApptType()); stmt.setTimestamp(2, appt.getDate()); stmt.setString(3, appt.getComment()); stmt.setInt(4, appt.getApptID()); stmt.executeUpdate(); } catch (SQLException e) { throw new DBException(e); } } public void removeAppt(final ApptBean appt) throws SQLException, DBException { try (Connection conn = factory.getConnection(); PreparedStatement stmt = conn.prepareStatement("DELETE FROM appointment WHERE appt_id=?")) { stmt.setInt(1, appt.getApptID()); stmt.executeUpdate(); stmt.close(); } catch (SQLException e) { throw new DBException(e); } } public List<ApptBean> getAllHCPConflictsForAppt(final long mid, final ApptBean appt) throws SQLException, DBException { final int duration = apptTypeDAO.getApptType(appt.getApptType()).getDuration(); try (Connection conn = factory.getConnection(); PreparedStatement stmt = conn.prepareStatement("SELECT * " + "FROM appointment a, appointmenttype type " // and the corresponding types + "WHERE a.appt_type=type.appt_type AND " // match them with types + "((DATE_ADD(a.sched_date, INTERVAL type.duration MINUTE)>? AND " // a1 ends after a2 starts AND + "a.sched_date<=?) OR " // a1 starts before a2 OR + "(DATE_ADD(?, INTERVAL ? MINUTE)>a.sched_date AND " // a2 ends after a1 starts AND + "?<=a.sched_date)) AND " // a2 starts before a1 starts + "a.doctor_id=? AND a.appt_id!=?;") ) { stmt.setTimestamp(1, appt.getDate()); stmt.setTimestamp(2, appt.getDate()); stmt.setTimestamp(3, appt.getDate()); stmt.setInt(4, duration); stmt.setTimestamp(5, appt.getDate()); stmt.setLong(6, mid); stmt.setInt(7, appt.getApptID()); final ResultSet results = stmt.executeQuery(); final List<ApptBean> conflictList = this.abloader.loadList(results); results.close(); return conflictList; } catch (SQLException e) { throw new DBException(e); } } public List<ApptBean> getAllPatientConflictsForAppt(final long mid, final ApptBean appt) throws SQLException, DBException { final int duration = apptTypeDAO.getApptType(appt.getApptType()).getDuration(); try (Connection conn = factory.getConnection(); PreparedStatement stmt = conn.prepareStatement("SELECT * " + "FROM appointment a, appointmenttype type " // and the corresponding types + "WHERE a.appt_type=type.appt_type AND " // match them with types + "((DATE_ADD(a.sched_date, INTERVAL type.duration MINUTE)>? AND "// a1 ends after a2 starts AND + "a.sched_date<=?) OR " // a1 starts before a2 OR + "(DATE_ADD(?, INTERVAL ? MINUTE)>a.sched_date AND " // a2 ends after a1 starts AND + "?<=a.sched_date)) AND " // a2 starts before a1 starts + "a.patient_id=? AND a.appt_id!=?;") ) { stmt.setTimestamp(1, appt.getDate()); stmt.setTimestamp(2, appt.getDate()); stmt.setTimestamp(3, appt.getDate()); stmt.setInt(4, duration); stmt.setTimestamp(5, appt.getDate()); stmt.setLong(6, mid); stmt.setInt(7, appt.getApptID()); final ResultSet results = stmt.executeQuery(); final List<ApptBean> conflictList = this.abloader.loadList(results); results.close(); return conflictList; } catch (SQLException e) { throw new DBException(e); } } /** * Returns all past and future appointment conflicts for the doctor with the * given MID * * @param mid * @throws SQLException */ public List<ApptBean> getAllConflictsForDoctor(final long mid) throws SQLException, DBException { try (Connection conn = factory.getConnection(); PreparedStatement stmt = conn.prepareStatement("SELECT a1.* " + "FROM appointment a1, appointment a2, " // all possible sets of 2 appts + "appointmenttype type1,appointmenttype type2 " // and the corresponding types + "WHERE a1.appt_id!=a2.appt_id AND " // exclude itself + "a1.appt_type=type1.appt_type AND a2.appt_type=type2.appt_type AND " // match then with types + "((DATE_ADD(a1.sched_date, INTERVAL type1.duration MINUTE)>a2.sched_date AND " // a1 ends after a2 starts AND + "a1.sched_date<=a2.sched_date) OR" // a1 starts before a2 OR + "(DATE_ADD(a2.sched_date, INTERVAL type2.duration MINUTE)>a1.sched_date AND " // a2 ends after a1 starts AND + "a2.sched_date<=a1.sched_date)) AND " // a2 starts before a1 starts + "a1.doctor_id=? AND a2.doctor_id=?;") ) { stmt.setLong(1, mid); stmt.setLong(2, mid); final ResultSet results = stmt.executeQuery(); final List<ApptBean> conflictList = this.abloader.loadList(results); results.close(); return conflictList; } catch (SQLException e) { throw new DBException(e); } } /** * Returns all past and future appointment conflicts for the patient with * the given MID * * @param mid * @throws SQLException * @throws DBException */ public List<ApptBean> getAllConflictsForPatient(final long mid) throws SQLException, DBException { try (Connection conn = factory.getConnection(); PreparedStatement stmt = conn.prepareStatement("SELECT a1.* " + "FROM appointment a1, appointment a2, " // all possible sets of 2 appts + "appointmenttype type1,appointmenttype type2 " // and the corresponding types + "WHERE a1.appt_id!=a2.appt_id AND " // exclude itself + "a1.appt_type=type1.appt_type AND a2.appt_type=type2.appt_type AND " // match them with types + "((DATE_ADD(a1.sched_date, INTERVAL type1.duration MINUTE)>a2.sched_date AND " // a1 ends after a2 starts AND + "a1.sched_date<=a2.sched_date) OR" // a1 starts before a2 OR + "(DATE_ADD(a2.sched_date, INTERVAL type2.duration MINUTE)>a1.sched_date AND " // a2 ends after a1 starts AND + "a2.sched_date<=a1.sched_date)) AND " // a2 starts before a1 starts + "a1.patient_id=? AND a2.patient_id=?;") ) { stmt.setLong(1, mid); stmt.setLong(2, mid); final ResultSet results = stmt.executeQuery(); final List<ApptBean> conflictList = this.abloader.loadList(results); results.close(); return conflictList; } catch (SQLException e) { throw new DBException(e); } } }
9,431
36.879518
117
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/dao/mysql/ApptRequestDAO.java
package edu.ncsu.csc.itrust.model.old.dao.mysql; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; import edu.ncsu.csc.itrust.exception.DBException; import edu.ncsu.csc.itrust.model.old.beans.ApptRequestBean; import edu.ncsu.csc.itrust.model.old.beans.loaders.ApptRequestBeanLoader; import edu.ncsu.csc.itrust.model.old.dao.DAOFactory; /** * * */ public class ApptRequestDAO { private transient final DAOFactory factory; private transient final ApptRequestBeanLoader loader; public ApptRequestDAO(final DAOFactory factory) { this.factory = factory; loader = new ApptRequestBeanLoader(); } /** * * @param hcpid * @return * @throws DBException */ public List<ApptRequestBean> getApptRequestsFor(final long hcpid) throws SQLException, DBException { try (Connection conn = factory.getConnection(); PreparedStatement stmt = conn .prepareStatement("SELECT * FROM appointmentrequests WHERE doctor_id=? ORDER BY sched_date")) { stmt.setLong(1, hcpid); final ResultSet results = stmt.executeQuery(); final List<ApptRequestBean> list = loader.loadList(results); results.close(); return list; } catch (SQLException e) { throw new DBException(e); } } /** * * @param req * @throws SQLException * @throws DBException */ public void addApptRequest(final ApptRequestBean req) throws SQLException, DBException { try (Connection conn = factory.getConnection(); PreparedStatement stmt = conn.prepareStatement( "INSERT INTO appointmentrequests (appt_type, patient_id, doctor_id, sched_date, " + "comment, pending, accepted) VALUES (?, ?, ?, ?, ?, ?, ?)")) { loader.loadParameters(stmt, req); stmt.executeUpdate(); } catch (SQLException e) { throw new DBException(e); } } /** * * @param req * @throws SQLException * @throws DBException */ public void updateApptRequest(final ApptRequestBean req) throws SQLException, DBException { try (Connection conn = factory.getConnection(); PreparedStatement stmt = conn .prepareStatement("UPDATE appointmentrequests SET pending=?, accepted=? WHERE appt_id=?")) { stmt.setBoolean(1, req.isPending()); stmt.setBoolean(2, req.isAccepted()); stmt.setInt(3, req.getRequestedAppt().getApptID()); stmt.executeUpdate(); } catch (SQLException e) { throw new DBException(e); } } public ApptRequestBean getApptRequest(final int reqID) throws SQLException, DBException { ApptRequestBean bean; try (Connection conn = factory.getConnection(); PreparedStatement stmt = conn.prepareStatement("SELECT * FROM appointmentrequests WHERE appt_id=?")) { stmt.setInt(1, reqID); final ResultSet results = stmt.executeQuery(); if (results.next()) { bean = loader.loadSingle(results); } else { bean = null; } results.close(); } catch (SQLException e) { throw new DBException(e); } return bean; } }
2,993
26.981308
106
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/dao/mysql/ApptTypeDAO.java
package edu.ncsu.csc.itrust.model.old.dao.mysql; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; import edu.ncsu.csc.itrust.exception.DBException; import edu.ncsu.csc.itrust.model.old.beans.ApptTypeBean; import edu.ncsu.csc.itrust.model.old.beans.loaders.ApptTypeBeanLoader; import edu.ncsu.csc.itrust.model.old.dao.DAOFactory; public class ApptTypeDAO { private transient final DAOFactory factory; private transient final ApptTypeBeanLoader atLoader; public ApptTypeDAO(final DAOFactory factory) { this.factory = factory; this.atLoader = new ApptTypeBeanLoader(); } public List<ApptTypeBean> getApptTypes() throws SQLException, DBException { try (Connection conn = factory.getConnection(); PreparedStatement stmt = conn.prepareStatement("SELECT * FROM appointmenttype")) { final ResultSet results = stmt.executeQuery(); final List<ApptTypeBean> atList = this.atLoader.loadList(results); results.close(); return atList; } catch (SQLException e) { throw new DBException(e); } } public boolean addApptType(final ApptTypeBean apptType) throws SQLException, DBException { try (Connection conn = factory.getConnection(); PreparedStatement stmt = conn.prepareStatement("INSERT INTO appointmenttype (appt_type, duration) " + "VALUES (?, ?)")) { this.atLoader.loadParameters(stmt, apptType); final int rowCount = stmt.executeUpdate(); return rowCount > 0; } catch (SQLException e) { throw new DBException(e); } } public boolean editApptType(final ApptTypeBean apptType) throws SQLException, DBException { try (Connection conn = factory.getConnection(); PreparedStatement stmt = conn.prepareStatement("UPDATE appointmenttype SET duration=? WHERE appt_type=?")) { stmt.setInt(1, apptType.getDuration()); stmt.setString(2, apptType.getName()); final int rowCount = stmt.executeUpdate(); return rowCount > 0; } catch (SQLException e) { throw new DBException(e); } } public ApptTypeBean getApptType(final String apptType) throws SQLException, DBException { ApptTypeBean bean = null; try (Connection conn = factory.getConnection(); PreparedStatement stmt = conn.prepareStatement("SELECT * FROM appointmenttype WHERE appt_type=?")) { stmt.setString(1, apptType); final ResultSet results = stmt.executeQuery(); final List<ApptTypeBean> beans = atLoader.loadList(results); if (!beans.isEmpty()) { bean = beans.get(0); } results.close(); } catch (SQLException e) { throw new DBException(e); } return bean; } }
2,631
31.493827
125
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/dao/mysql/AuthDAO.java
package edu.ncsu.csc.itrust.model.old.dao.mysql; import java.security.SecureRandom; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import org.apache.commons.codec.digest.DigestUtils; import org.apache.tomcat.util.buf.HexUtils; import edu.ncsu.csc.itrust.exception.DBException; import edu.ncsu.csc.itrust.exception.ITrustException; import edu.ncsu.csc.itrust.logger.TransactionLogger; import edu.ncsu.csc.itrust.model.old.dao.DAOFactory; import edu.ncsu.csc.itrust.model.old.enums.Role; import edu.ncsu.csc.itrust.model.old.enums.TransactionType; /** * AuthDAO is for anything that has to do with authentication. Most methods * access the users table. * * DAO stands for Database Access Object. All DAOs are intended to be * reflections of the database, that is, one DAO per table in the database (most * of the time). For more complex sets of queries, extra DAOs are added. DAOs * can assume that all data has been validated and is correct. * * DAOs should never have setters or any other parameter to the constructor than * a factory. All DAOs should be accessed by DAOFactory (@see * {@link DAOFactory}) and every DAO should have a factory - for obtaining JDBC * connections and/or accessing other DAOs. */ public class AuthDAO { /** LOGIN_TIMEOUT */ public static final long LOGIN_TIMEOUT = 15 * 60 * 1000; // 15 min private static final int SALT_LEN = 32; private transient final DAOFactory factory; private SecureRandom secureRandom; /** * The typical constructor. * * @param factory * The {@link DAOFactory} associated with this DAO, which is used * for obtaining SQL connections, etc. */ public AuthDAO(final DAOFactory factory) { this.factory = factory; this.secureRandom = new SecureRandom(); } /** * Add a particular user to the system. Does not add user-specific * information (e.g. Patient or HCP). Initially sets security question to a * random set of characters, so that nobody should be able to guess its * value. * * @param mid * The user's MID as a Long. * @param role * The role of the user as a Role enum {@link Role} * @param password * The password for the new user. * @return A string representing the newly added randomly-generated * password. * @throws DBException */ public String addUser(final Long mid, final Role role, final String password) throws DBException { try (Connection conn = factory.getConnection(); PreparedStatement stmt = conn.prepareStatement( "INSERT INTO users (MID, PASSWORD, SALT, ROLE, sQuestion, sAnswer) VALUES (?,?,?,?,?,?)")) { stmt.setLong(1, mid); String salt = generateRandomSalt(); final String hashedPassword = DigestUtils.sha256Hex(password + salt); stmt.setString(2, hashedPassword); stmt.setString(3, salt); stmt.setString(4, role.toString()); stmt.setString(5, "Enter the random password given in your account email"); stmt.setString(6, password); stmt.executeUpdate(); return password; } catch (SQLException e) { throw new DBException(e); } } /** * Reset the security question and answer for a particular user * * @param question * The security question as a string. * @param answer * The security answer as a string. * @param mid * The MID of the user as a long. * @throws DBException */ public void setSecurityQuestionAnswer(final String question, final String answer, final long mid) throws DBException { try (Connection conn = factory.getConnection(); PreparedStatement stmt = conn .prepareStatement("UPDATE users SET sQuestion = ?, sAnswer = ? WHERE MID = ?")) { stmt.setString(1, question); stmt.setString(2, answer); stmt.setLong(3, mid); stmt.executeUpdate(); } catch (SQLException e) { throw new DBException(e); } } /** * Returns the user name of a user from just the MID * * @param mid * The MID of the user to get the name of. * @return The user's name as a String. * @throws ITrustException */ public String getUserName(final long mid) throws ITrustException { final Role role = getUserRole(mid); String uName; switch (role) { case HCP: case PHA: case ADMIN: case UAP: case ER: case LT: uName = factory.getPersonnelDAO().getName(mid); break; case PATIENT: uName = factory.getPatientDAO().getName(mid); break; case TESTER: uName = String.valueOf(mid); break; default: throw new ITrustException("Role " + role + " not supported"); } return uName; } /** * Returns the role of a particular MID * * @param mid * The MID of the user to look up. * @return The {@link Role} of the user as an enum. * @throws ITrustException */ public Role getUserRole(final long mid) throws ITrustException { try (Connection conn = factory.getConnection(); PreparedStatement stmt = conn.prepareStatement("SELECT role FROM users WHERE MID=?")) { stmt.setLong(1, mid); final ResultSet results; results = stmt.executeQuery(); if (results.next()) { final Role result = Role.parse(results.getString("role")); results.close(); return result; } else { throw new ITrustException("User does not exist"); } } catch (SQLException e) { throw new DBException(e); } } /** * Returns whether a user is deactivated. Currently works only for patients * * @param mid * The MID of the user to look up. * @return Activation status of the user * @throws ITrustException */ public boolean getDeactivated(final long mid) throws ITrustException { final Role role = getUserRole(mid); boolean isDeactivated; if (role.equals(Role.PATIENT)) { try (Connection conn = factory.getConnection(); PreparedStatement stmt = conn .prepareStatement("SELECT DateOfDeactivation FROM patients WHERE MID=?")) { stmt.setLong(1, mid); ResultSet results; results = stmt.executeQuery(); if (results.next()) { if (results.getString("DateOfDeactivation") == null) { results.close(); isDeactivated = false; } else { results.close(); isDeactivated = true; } } else { throw new ITrustException("User does not exist"); } } catch (SQLException e) { throw new DBException(e); } } else { isDeactivated = false; } return isDeactivated; } /** * Change the password of a particular user * * @param mid * The MID of the user whose password we are changing. * @param password * The new password. * @throws DBException */ public void resetPassword(final long mid, final String password) throws DBException { try (Connection conn = factory.getConnection(); PreparedStatement stmt = conn.prepareStatement("UPDATE users SET password=?, salt=? WHERE MID=?")) { String salt = generateRandomSalt(); String newPassword = DigestUtils.sha256Hex(password + salt); stmt.setString(1, newPassword); stmt.setString(2, salt); stmt.setLong(3, mid); stmt.executeUpdate(); } catch (SQLException e) { throw new DBException(e); } } /** * Return the security question for a particular user. * * @param mid * The MID of the user we are looking up. * @return The security question of the user we are looking up. * @throws ITrustException */ public String getSecurityQuestion(final long mid) throws ITrustException { try (Connection conn = factory.getConnection(); PreparedStatement stmt = conn.prepareStatement("SELECT sQuestion FROM users WHERE MID=?")) { stmt.setLong(1, mid); final ResultSet results = stmt.executeQuery(); if (results.next()) { final String result = results.getString("sQuestion"); results.close(); return result; } else { results.close(); throw new ITrustException("No security question set for MID: " + mid); } } catch (SQLException e) { throw new DBException(e); } } /** * Return the security answer of a particular user * * @param mid * The MID of the user we are looking up. * @return The security answer as a String. * @throws ITrustException */ public String getSecurityAnswer(final long mid) throws ITrustException { try (Connection conn = factory.getConnection(); PreparedStatement stmt = conn.prepareStatement("SELECT sAnswer FROM users WHERE MID=?")) { stmt.setLong(1, mid); final ResultSet results = stmt.executeQuery(); if (results.next()) { final String result = results.getString("sAnswer"); results.close(); return result; } else { results.close(); throw new ITrustException("No security answer set for MID " + mid); } } catch (SQLException e) { throw new DBException(e); } } /** * Record a login failure, which blacklists the ipAddress. Uses the database * table like a hash table where the key is the user's IP address. If the * user's IP address is not in the table, a row with "1" is added. * * @param ipAddr * The IP address of the user as a String. * @throws DBException */ public void recordLoginFailure(final String ipAddr) throws DBException { try (Connection conn = factory.getConnection(); PreparedStatement stmt = conn.prepareStatement( "UPDATE loginfailures SET FailureCount=FailureCount+1, lastFailure=CURRENT_TIMESTAMP WHERE IPAddress=?")) { stmt.setString(1, ipAddr); final int numUpdated = stmt.executeUpdate(); if (numUpdated == 0) { // if no login failures yet for this IP insertLoginFailureRow(ipAddr, 1); // then insert one } } catch (SQLException e) { throw new DBException(e); } } /** * Record a reset password failure, which blacklists the ipAddress. Uses the * database table like a hash table where the key is the user's IP address. * If the user's IP address is not in the table, a row with "1" is added. * * @param ipAddr * The IP address of the user as a String. * @throws DBException */ public void recordResetPasswordFailure(final String ipAddr) throws DBException { try (Connection conn = factory.getConnection(); PreparedStatement stmt = conn.prepareStatement( "UPDATE resetpasswordfailures SET failurecount=failurecount+1 WHERE ipaddress=?")) { stmt.setString(1, ipAddr); final int numUpdated = stmt.executeUpdate(); if (numUpdated == 0) { // if no login failures yet for this IP insertResetPasswordRow(ipAddr, 1); // then insert one } } catch (SQLException e) { throw new DBException(e); } } /** * Return the number of failures from resetting a password, given an IP * address. * * @param ipAddr * An IP address for the associated attempt as a String. * @return An int representing the number of failures. * @throws DBException */ public int getResetPasswordFailures(final String ipAddr) throws DBException { int numFailures; try (Connection conn = factory.getConnection(); PreparedStatement stmt = conn .prepareStatement("SELECT * FROM resetpasswordfailures WHERE IPADDRESS=?")) { stmt.setString(1, ipAddr); final ResultSet results = stmt.executeQuery(); if (results.next()) { // if we're more than LOGIN_TIMEOUT minutes out, clear the // failure count if (System.currentTimeMillis() - results.getTimestamp("lastFailure").getTime() > LOGIN_TIMEOUT) { updateResetFailuresToZero(ipAddr); results.close(); numFailures = 0; } else { final int result = results.getInt("failureCount"); results.close(); numFailures = result; } } else { insertResetPasswordRow(ipAddr, 0); results.close(); numFailures = 0; } } catch (SQLException e) { throw new DBException(e); } return numFailures; } /** * Return the number of failures from login failures a password, given an IP * address. * * @param ipAddr * The IP address for this attempt as a String. * @return An int representing the number of failures which have occured. * @throws DBException */ public int getLoginFailures(final String ipAddr) throws DBException { int numFailures; try (Connection conn = factory.getConnection(); PreparedStatement stmt = conn.prepareStatement("SELECT * FROM loginfailures WHERE IPADDRESS=?")) { stmt.setString(1, ipAddr); final ResultSet results = stmt.executeQuery(); if (results.next()) { // if we're more than LOGIN_TIMEOUT minutes out, clear the // failure count if (System.currentTimeMillis() - results.getTimestamp("lastFailure").getTime() > LOGIN_TIMEOUT) { updateFailuresToZero(ipAddr); results.close(); numFailures = 0; } else { final int result = results.getInt("failureCount"); results.close(); numFailures = result; } } else { insertLoginFailureRow(ipAddr, 0); results.close(); numFailures = 0; } } catch (SQLException e) { throw new DBException(e); } return numFailures; } private void insertLoginFailureRow(final String ipAddr, int failureCount) throws DBException, SQLException { try (Connection conn = factory.getConnection(); PreparedStatement stmt = conn .prepareStatement("INSERT INTO loginfailures(IPAddress, failureCount) VALUES(?,?)")) { stmt.setString(1, ipAddr); stmt.setInt(2, failureCount); stmt.executeUpdate(); } catch (SQLException e) { throw new DBException(e); } } private void insertResetPasswordRow(final String ipAddr, final int failureCount) throws DBException, SQLException { try (Connection conn = factory.getConnection(); PreparedStatement stmt = conn .prepareStatement("INSERT INTO resetpasswordfailures(IPAddress, failureCount) VALUES(?,?)")) { stmt.setString(1, ipAddr); stmt.setInt(2, failureCount); stmt.executeUpdate(); } catch (SQLException e) { throw new DBException(e); } } private void updateFailuresToZero(final String ipAddr) throws DBException, SQLException { try (Connection conn = factory.getConnection(); PreparedStatement stmt = conn .prepareStatement("UPDATE loginfailures SET failureCount=0 WHERE IPAddress=?")) { stmt.setString(1, ipAddr); stmt.executeUpdate(); } catch (SQLException e) { throw new DBException(e); } } /** * Resets number of login failures for the given IP address to 0. * * @param ipAddr * The IP address to reset * @throws DBException * @throws SQLException */ public void resetLoginFailuresToZero(final String ipAddr) throws DBException, SQLException { try (Connection conn = factory.getConnection(); PreparedStatement stmt = conn .prepareStatement("UPDATE loginfailures SET failureCount=0 WHERE IPAddress=?")) { stmt.setString(1, ipAddr); stmt.executeUpdate(); } catch (SQLException e) { throw new DBException(e); } } private void updateResetFailuresToZero(final String ipAddr) throws DBException, SQLException { try (Connection conn = factory.getConnection(); PreparedStatement stmt = conn .prepareStatement("UPDATE resetpasswordfailures SET failureCount=0 WHERE IPAddress=?")) { stmt.setString(1, ipAddr); stmt.executeUpdate(); } catch (SQLException e) { throw new DBException(e); } } /** * Returns true if a user with given MID exists in the system. * * @param mid * The MID to check for * @return true if the user with given MID exists in the system. * @throws DBException */ public boolean checkUserExists(final long mid) throws DBException { try (Connection conn = factory.getConnection(); PreparedStatement stmt = conn.prepareStatement("SELECT * FROM users WHERE MID=?")) { stmt.setLong(1, mid); final ResultSet results = stmt.executeQuery(); final boolean check = results.next(); results.close(); return check; } catch (SQLException e) { throw new DBException(e); } } /** * Return whether the given MID/password pair is correct. * * @param mid * MID of the user * @param password * Password of the user * @return true if the password matches for that user */ public boolean authenticatePassword(final long mid, final String password) throws DBException { try (Connection conn = factory.getConnection(); PreparedStatement stmt = conn.prepareStatement("Select * FROM users WHERE MID=? AND password=?")) { String salt = getSalt(mid); stmt.setLong(1, mid); stmt.setString(2, DigestUtils.sha256Hex(password + salt)); final ResultSet results = stmt.executeQuery(); final boolean check = results.next(); results.close(); return check; } catch (SQLException e) { throw new DBException(e); } } /** * Change the dependency status of the specified user * * @param mid * the MID of the user to change dependency status * @param dependency * the dependency status to change user to * @throws DBException */ public void setDependent(long mid, boolean dependency) throws DBException { try (Connection conn = factory.getConnection(); PreparedStatement stmt = conn.prepareStatement("UPDATE users SET isDependent=? WHERE MID=?")) { stmt.setBoolean(1, dependency); stmt.setLong(2, mid); stmt.executeUpdate(); } catch (SQLException e) { throw new DBException(e); } } /** * Check that the specified user is a dependent * * @param mid * MID of the user * @return true if the user is a dependent, false otherwise * @throws DBException * if the SQL statement is not valid */ public boolean isDependent(final long mid) throws DBException { try (Connection conn = factory.getConnection(); PreparedStatement stmt = conn.prepareStatement("SELECT * FROM users WHERE MID=? AND isDependent=1")) { stmt.setLong(1, mid); final ResultSet results = stmt.executeQuery(); final boolean check = results.next(); results.close(); return check; } catch (SQLException e) { throw new DBException(e); } } /** * Returns the salt for user with given MID. * * @param mid * The user we are looking for. * @return The salt for that user. */ public String getSalt(long mid) { String result = ""; try (Connection conn = factory.getConnection(); PreparedStatement stmt = conn.prepareStatement("SELECT Salt FROM users WHERE MID=?")) { stmt.setLong(1, mid); ResultSet rs = stmt.executeQuery(); result = rs.next() ? rs.getString(1) : generateRandomSalt(); } catch (SQLException e) { result = generateRandomSalt(); } return result; } /** * Generates a random salt. * * @return A random string 64 characters long. */ private String generateRandomSalt() { byte[] buf = new byte[SALT_LEN]; secureRandom.nextBytes(buf); return HexUtils.toHexString(buf); } /** Logs that given user was logged in */ public void logUserAuthenticated(Long mid) { TransactionLogger.getInstance().logTransaction(TransactionType.LOGIN_SUCCESS, mid, null, ""); } /** Logs that given user was logged out */ public void logUserLoggedOut(Long mid) { TransactionLogger.getInstance().logTransaction(TransactionType.LOGOUT, mid, null, ""); } }
19,256
30.988372
116
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/dao/mysql/BillingDAO.java
package edu.ncsu.csc.itrust.model.old.dao.mysql; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Timestamp; import java.util.Date; import java.util.List; import edu.ncsu.csc.itrust.DBUtil; import edu.ncsu.csc.itrust.exception.DBException; import edu.ncsu.csc.itrust.model.old.beans.BillingBean; import edu.ncsu.csc.itrust.model.old.beans.loaders.BillingBeanLoader; import edu.ncsu.csc.itrust.model.old.dao.DAOFactory; /** * this class is used to interact with the datbaase to add, get, edit, or remove * bills */ public class BillingDAO { /** DAOfactory used to make a BillingDAO */ private transient final DAOFactory factory; /** used to get load things into the database or from the database */ private transient final BillingBeanLoader bbloader; /** * makes a new BillingDAO * * @param factory * the DAOfactory used to make a BillingDAO */ public BillingDAO(final DAOFactory factory) { this.factory = factory; this.bbloader = new BillingBeanLoader(); } /** * adds a bill to the database * * @param bill * the bill being added to the database * @return * @throws DBException */ public long addBill(final BillingBean bill) throws DBException { try (Connection conn = factory.getConnection(); PreparedStatement stmt = this.bbloader.loadParameters( conn.prepareStatement( "INSERT INTO billing (appt_id, PatientID, HCPID, amt, status, ccHolderName, billingAddress, ccType, ccNumber, cvv, insHolderName, insID, insProviderName, insAddress1, insAddress2, insCity, insState, insZip, insPhone, submissions, billTimeS) " + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"), bill)) { stmt.setDate(21, new java.sql.Date(new Date().getTime())); stmt.executeUpdate(); return DBUtil.getLastInsert(conn); } catch (SQLException e) { throw new DBException(e); } } /** * Returns the bill with a specific billID. * * @param billID * The ID of the bill * @return The bill with the id. * @throws DBException */ public BillingBean getBillId(long billID) throws DBException { BillingBean bill = null; try (Connection conn = factory.getConnection(); PreparedStatement stmt = conn.prepareStatement("SELECT * FROM billing WHERE billID=?");) { stmt.setLong(1, billID); ResultSet rs = stmt.executeQuery(); if (rs.next()) { bill = this.bbloader.loadSingle(rs); } rs.close(); } catch (SQLException e) { throw new DBException(e); } return bill; } /** * Returns a bill for a specific office visit. * * @param billID * The office visit id that I am looking for. * @return The bill for that visit. * @throws DBException */ public BillingBean getBillWithOVId(long billID) throws DBException { BillingBean bill = null; try (Connection conn = factory.getConnection(); PreparedStatement stmt = conn.prepareStatement("SELECT * FROM billing WHERE appt_id=?")) { stmt.setLong(1, billID); ResultSet rs = stmt.executeQuery(); if (rs.next()) { bill = this.bbloader.loadSingle(rs); } rs.close(); } catch (SQLException e) { throw new DBException(e); } return bill; } /** * gets a list of billing beans of all the bills from the database for the * given patient id * * @param mid * the patient id * @return the list of bills for the given patient id * @throws DBException */ public List<BillingBean> getBills(long mid) throws DBException { try (Connection conn = factory.getConnection(); PreparedStatement stmt = conn.prepareStatement("SELECT * FROM billing WHERE patientID=?")) { stmt.setLong(1, mid); final ResultSet results = stmt.executeQuery(); final List<BillingBean> bList = this.bbloader.loadList(results); results.close(); return bList; } catch (SQLException e) { throw new DBException(e); } } /** * Get a list of the patient's unpaid bills * * @param mid * @return list of BillingBeans where status is Unsubmitted * @throws DBException */ public List<BillingBean> getUnpaidBills(long mid) throws DBException { try (Connection conn = factory.getConnection(); PreparedStatement stmt = conn .prepareStatement("SELECT * FROM billing WHERE patientID=? and status='Unsubmitted'")) { stmt.setLong(1, mid); final ResultSet results = stmt.executeQuery(); final List<BillingBean> bList = this.bbloader.loadList(results); results.close(); return bList; } catch (SQLException e) { throw new DBException(e); } } /** * Get a list of the bills paid with insurance. * * @param mid * @return list of BillingBeans where paid by insurance. * @throws DBException */ public List<BillingBean> getInsuranceBills() throws DBException { final List<BillingBean> bList; try (Connection conn = factory.getConnection(); PreparedStatement stmt = conn .prepareStatement("SELECT * FROM billing WHERE isInsurance=1 ORDER BY subTime DESC")) { final ResultSet results = stmt.executeQuery(); bList = this.bbloader.loadList(results); results.close(); } catch (SQLException e) { throw new DBException(e); } return bList; } /** * Edits the bill giving as a parameter in the database * * @param bill * the bill that needs to be edited(already with the edit) * @throws DBException */ public void editBill(final BillingBean bill) throws DBException { try (Connection conn = factory.getConnection(); PreparedStatement stmt = conn.prepareStatement( "UPDATE billing SET appt_id=?, patientID=?, HCPID=?, amt=?, status=?, ccHolderName=?, billingAddress=?, ccType=?, ccNumber=?, cvv=?, insHolderName=?, insID=?, insProviderName=?, insAddress1=?, insAddress2=?, insCity=?, insState=?, insZip=?, insPhone=?, submissions=?, isInsurance=?, subTime=? WHERE billID=?")) { stmt.setInt(23, bill.getBillID()); this.bbloader.loadParameters(stmt, bill); stmt.setString(22, bill.getSubTime() != null ? bill.getSubTime().toString() : new Timestamp(0).toString()); stmt.executeUpdate(); } catch (SQLException e) { throw new DBException(e); } } /** * Removes a bill from the database * * @param bill * the bill that needs to be deleted * @throws DBException */ public void removeBill(final BillingBean bill) throws DBException { try (Connection conn = factory.getConnection(); PreparedStatement stmt = conn.prepareStatement("DELETE FROM billing WHERE billID=?")) { stmt.setInt(1, bill.getBillID()); stmt.executeUpdate(); } catch (SQLException e) { throw new DBException(e); } } /** * getPendingNum gets the number of pending bills. * * @return the nubmer of pending bills. * @throws DBException */ public int getPendingNum() throws DBException { int result = 0; try (Connection conn = factory.getConnection(); PreparedStatement stmt = conn.prepareStatement( "SELECT COUNT(*) FROM billing WHERE status='Pending' ORDER BY subTime DESC")) { final ResultSet results = stmt.executeQuery(); if (results.next()) result = results.getInt(1); results.close(); } catch (SQLException e) { throw new DBException(e); } return result; } /** * getDeniedNum gets the number of your denied bills. * * @param mid * Your Medical id. * @return the nubmer of your denied bills. * @throws DBException */ public int getDeniedNum(long mid) throws DBException { int result = 0; try (Connection conn = factory.getConnection(); PreparedStatement stmt = conn.prepareStatement( "SELECT COUNT(*) FROM billing WHERE status='Denied' AND PatientID=? ORDER BY subTime DESC")) { stmt.setLong(1, mid); final ResultSet results = stmt.executeQuery(); if (results.next()) { result = results.getInt(1); } results.close(); } catch (SQLException e) { throw new DBException(e); } return result; } /** * getDeniedNum gets the number of your denied bills. * * @param mid * Your Medical id. * @return the nubmer of your denied bills. * @throws DBException */ public int getApprovedNum(long mid) throws DBException { int result = 0; try (Connection conn = factory.getConnection(); PreparedStatement stmt = conn.prepareStatement( "SELECT COUNT(*) FROM billing WHERE status='Approved' AND PatientID=? ORDER BY subTime DESC")) { stmt.setLong(1, mid); final ResultSet results = stmt.executeQuery(); if (results.next()) result = results.getInt(1); results.close(); } catch (SQLException e) { throw new DBException(e); } return result; } }
8,720
29.707746
318
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/dao/mysql/DrugInteractionDAO.java
package edu.ncsu.csc.itrust.model.old.dao.mysql; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; import edu.ncsu.csc.itrust.exception.DBException; import edu.ncsu.csc.itrust.exception.ITrustException; import edu.ncsu.csc.itrust.model.old.beans.DrugInteractionBean; import edu.ncsu.csc.itrust.model.old.beans.loaders.DrugInteractionBeanLoader; import edu.ncsu.csc.itrust.model.old.dao.DAOFactory; /** * Used for managing drug interactions. * * DAO stands for Database Access Object. All DAOs are intended to be * reflections of the database, that is, one DAO per table in the database (most * of the time). For more complex sets of queries, extra DAOs are added. DAOs * can assume that all data has been validated and is correct. * * DAOs should never have setters or any other parameter to the constructor than * a factory. All DAOs should be accessed by DAOFactory (@see * {@link DAOFactory}) and every DAO should have a factory - for obtaining JDBC * connections and/or accessing other DAOs. * * @see http://www.fda.gov/Drugs/InformationOnDrugs/ucm142438.htm */ public class DrugInteractionDAO { private DAOFactory factory; private DrugInteractionBeanLoader interactionLoader; /** * The typical constructor. * * @param factory * The {@link DAOFactory} associated with this DAO, which is used * for obtaining SQL connections, etc. */ public DrugInteractionDAO(DAOFactory factory) { this.factory = factory; interactionLoader = new DrugInteractionBeanLoader(); } /** * Returns a list of all drug interactions for the input drug name * * @param drugCode * drugCode * @return A java.util.List of DrugInteractionBeans. * @throws DBException */ public List<DrugInteractionBean> getInteractions(String drugCode) throws DBException { try (Connection conn = factory.getConnection(); PreparedStatement stmt = conn.prepareStatement("SELECT * FROM druginteractions WHERE FirstDrug = ? OR SecondDrug = ?")) { stmt.setString(1, drugCode); stmt.setString(2, drugCode); ResultSet rs = stmt.executeQuery(); List<DrugInteractionBean> loadlist = interactionLoader.loadList(rs); rs.close(); return loadlist; } catch (SQLException e) { throw new DBException(e); } } /** * Adds a new drug interaction, returns whether or not the addition was * successful. If the code already exists, an iTrustException is thrown. * * @param firstDrug * The name of the first drug in an interaction. * @param secondDrug * The name of the second drug in an interaction. * @param description * Explanation of the drug interaction. * @return A boolean indicating success or failure. * @throws DBException * @throws ITrustException */ public boolean reportInteraction(String firstDrug, String secondDrug, String description) throws ITrustException { if (firstDrug.equals(secondDrug)) throw new ITrustException("Drug cannot interact with itself."); List<DrugInteractionBean> currentIntsDrug2 = getInteractions(secondDrug); for (DrugInteractionBean dib : currentIntsDrug2) { if (dib.getSecondDrug().equals(firstDrug)) { throw new ITrustException("Error: Interaction between these drugs already exists."); } } try (Connection conn = factory.getConnection(); PreparedStatement stmt = conn.prepareStatement( "INSERT INTO druginteractions (FirstDrug, SecondDrug, Description) " + "VALUES (?,?,?)")) { stmt.setString(1, firstDrug); stmt.setString(2, secondDrug); stmt.setString(3, description); boolean successfullyAdded = stmt.executeUpdate() == 1; return successfullyAdded; } catch (SQLException e) { if (e.getErrorCode() == 1062) throw new ITrustException("Error: Interaction between these drugs already exists."); throw new DBException(e); } } /** * Remove an interaction from the database * * @param firstDrug * The name of the first patient * @param secondDrug * The name of the second patient * @return true if removed successfully, false if not in list */ public boolean deleteInteraction(String firstDrug, String secondDrug) throws DBException { try (Connection conn = factory.getConnection(); PreparedStatement stmt = conn.prepareStatement( "DELETE FROM druginteractions WHERE (FirstDrug = ? OR SecondDrug = ?) AND (FirstDrug = ? OR SecondDrug = ?)")) { stmt.setString(1, firstDrug); stmt.setString(2, firstDrug); stmt.setString(3, secondDrug); stmt.setString(4, secondDrug); return stmt.executeUpdate() != 0; } catch (SQLException e) { throw new DBException(e); } } }
4,757
35.045455
125
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/dao/mysql/DrugReactionOverrideCodesDAO.java
package edu.ncsu.csc.itrust.model.old.dao.mysql; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; import edu.ncsu.csc.itrust.exception.DBException; import edu.ncsu.csc.itrust.exception.ITrustException; import edu.ncsu.csc.itrust.model.old.beans.OverrideReasonBean; import edu.ncsu.csc.itrust.model.old.beans.loaders.DrugReactionOverrideBeanLoader; import edu.ncsu.csc.itrust.model.old.dao.DAOFactory; /** * Used for managing the Reason Codes. * * DAO stands for Database Access Object. All DAOs are intended to be * reflections of the database, that is, one DAO per table in the database (most * of the time). For more complex sets of queries, extra DAOs are added. DAOs * can assume that all data has been validated and is correct. * * DAOs should never have setters or any other parameter to the constructor than * a factory. All DAOs should be accessed by DAOFactory (@see * {@link DAOFactory}) and every DAO should have a factory - for obtaining JDBC * connections and/or accessing other DAOs. * * The Override Reason Code (ORC) is a universal product identifier used in the * United States for drugs intended for human use. * * @see http://www.fda.gov/Drugs/InformationOnDrugs/ucm142438.htm */ public class DrugReactionOverrideCodesDAO { private DAOFactory factory; private DrugReactionOverrideBeanLoader orcLoader = new DrugReactionOverrideBeanLoader(); /** * The typical constructor. * * @param factory * The {@link DAOFactory} associated with this DAO, which is used * for obtaining SQL connections, etc. */ public DrugReactionOverrideCodesDAO(DAOFactory factory) { this.factory = factory; } /** * Returns a list of all ND codes * * @return A java.util.List of OverrideReasonBeans. * @throws DBException */ public List<OverrideReasonBean> getAllORCodes() throws DBException { try (Connection conn = factory.getConnection(); PreparedStatement stmt = conn.prepareStatement("SELECT * FROM drugreactionoverridecodes ORDER BY CODE"); ResultSet rs = stmt.executeQuery()) { List<OverrideReasonBean> loadlist = orcLoader.loadList(rs); return loadlist; } catch (SQLException e) { throw new DBException(e); } } /** * Returns a particular description for a given code. * * @param code * The override reason code to be looked up. * @return A bean representing the override reason that was looked up. * @throws DBException */ public OverrideReasonBean getORCode(String code) throws DBException { try (Connection conn = factory.getConnection(); PreparedStatement stmt = conn .prepareStatement("SELECT * FROM drugreactionoverridecodes WHERE Code = ?")) { stmt.setString(1, code); ResultSet rs = stmt.executeQuery(); if (rs.next()) { OverrideReasonBean result = orcLoader.loadSingle(rs); rs.close(); return result; } rs.close(); return null; } catch (SQLException e) { throw new DBException(e); } } /** * Adds a new override reason code, returns whether or not the change was * made. If the code already exists, an iTrustException is thrown. * * @param orc * The overridereason bean to be added. * @return A boolean indicating success or failure. * @throws DBException * @throws ITrustException */ public boolean addORCode(OverrideReasonBean orc) throws DBException, ITrustException { try (Connection conn = factory.getConnection(); PreparedStatement stmt = conn.prepareStatement( "INSERT INTO drugreactionoverridecodes (Code, Description) " + "VALUES (?,?)")) { stmt.setString(1, orc.getORCode()); stmt.setString(2, orc.getDescription()); return stmt.executeUpdate() == 1; } catch (SQLException e) { if (e.getErrorCode() == 1062) throw new ITrustException("Error: Code already exists."); throw new DBException(e); } } /** * Updates a particular code's description * * @param orc * A bean representing the particular override reason to be * updated. * @return An int representing the number of updated rows. * @throws DBException */ public int updateCode(OverrideReasonBean orc) throws DBException { try (Connection conn = factory.getConnection(); PreparedStatement stmt = conn.prepareStatement("UPDATE drugreactionoverridecodes SET Description = ? " + "WHERE Code = ?")) { stmt.setString(1, orc.getDescription()); stmt.setString(2, orc.getORCode()); return stmt.executeUpdate(); } catch (SQLException e) { throw new DBException(e); } } }
4,645
32.912409
129
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/dao/mysql/FakeEmailDAO.java
package edu.ncsu.csc.itrust.model.old.dao.mysql; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; import edu.ncsu.csc.itrust.exception.DBException; import edu.ncsu.csc.itrust.model.old.beans.Email; import edu.ncsu.csc.itrust.model.old.beans.loaders.EmailBeanLoader; import edu.ncsu.csc.itrust.model.old.dao.DAOFactory; /** * DAO stands for Database Access Object. All DAOs are intended to be * reflections of the database, that is, one DAO per table in the database (most * of the time). For more complex sets of queries, extra DAOs are added. DAOs * can assume that all data has been validated and is correct. * * DAOs should never have setters or any other parameter to the constructor than * a factory. All DAOs should be accessed by DAOFactory (@see * {@link DAOFactory}) and every DAO should have a factory - for obtaining JDBC * connections and/or accessing other DAOs. */ public class FakeEmailDAO { private DAOFactory factory; private EmailBeanLoader emailBeanLoader = new EmailBeanLoader(); /** * The typical constructor. * * @param factory * The {@link DAOFactory} associated with this DAO, which is used * for obtaining SQL connections, etc. */ public FakeEmailDAO(DAOFactory factory) { this.factory = factory; } /** * Return all emails that have been "sent" (inserted into the database) * * @return A java.util.List of Email objects representing fake e-mails. * @throws DBException */ public List<Email> getAllEmails() throws DBException { try (Connection conn = factory.getConnection(); PreparedStatement stmt = conn.prepareStatement("SELECT * FROM fakeemail ORDER BY AddedDate DESC"); ResultSet rs = stmt.executeQuery()) { List<Email> loadlist = emailBeanLoader.loadList(rs); return loadlist; } catch (SQLException e) { throw new DBException(e); } } /** * Return all emails that a person has sent * * @param email * The "From" email address as a string. * @return A java.util.List of fake emails. * @throws DBException */ public List<Email> getEmailsByPerson(String email) throws DBException { try (Connection conn = factory.getConnection(); PreparedStatement stmt = conn .prepareStatement("SELECT * FROM fakeemail WHERE ToAddr LIKE ? ORDER BY AddedDate DESC");) { stmt.setString(1, "%" + email + "%"); ResultSet rs = stmt.executeQuery(); List<Email> loadlist = emailBeanLoader.loadList(rs); return loadlist; } catch (SQLException e) { throw new DBException(e); } } /** * "Send" an email, which just inserts it into the database. * * @param email * The Email object to insert. * @throws DBException */ public void sendEmailRecord(Email email) throws DBException { try (Connection conn = factory.getConnection(); PreparedStatement stmt = conn.prepareStatement( "INSERT INTO fakeemail (ToAddr, FromAddr, Subject, Body) " + "VALUES (?,?,?,?)")) { emailBeanLoader.loadParameters(stmt, email); stmt.executeUpdate(); } catch (SQLException e) { throw new DBException(e); } } /** * Returns a list of emails that have the given string as a substring of the * body * * @param string * The string to search within the body. * @return A java.util.List of fake emails. * @throws DBException */ public List<Email> getEmailWithBody(String bodySubstring) throws DBException { try (Connection conn = factory.getConnection(); PreparedStatement stmt = conn.prepareStatement("SELECT * FROM fakeemail WHERE Instr(Body,?)>0 ORDER BY AddedDate DESC")) { stmt.setString(1, bodySubstring); ResultSet rs = stmt.executeQuery(); List<Email> loadlist = emailBeanLoader.loadList(rs); rs.close(); return loadlist; } catch (SQLException e) { throw new DBException(e); } } }
3,921
31.683333
126
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/dao/mysql/FamilyDAO.java
package edu.ncsu.csc.itrust.model.old.dao.mysql; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; import edu.ncsu.csc.itrust.exception.DBException; import edu.ncsu.csc.itrust.model.old.beans.FamilyMemberBean; import edu.ncsu.csc.itrust.model.old.beans.loaders.FamilyBeanLoader; import edu.ncsu.csc.itrust.model.old.dao.DAOFactory; /** * Used for queries related to families. * * DAO stands for Database Access Object. All DAOs are intended to be * reflections of the database, that is, one DAO per table in the database (most * of the time). For more complex sets of queries, extra DAOs are added. DAOs * can assume that all data has been validated and is correct. * * DAOs should never have setters or any other parameter to the constructor than * a factory. All DAOs should be accessed by DAOFactory (@see * {@link DAOFactory}) and every DAO should have a factory - for obtaining JDBC * connections and/or accessing other DAOs. * * * */ public class FamilyDAO { private DAOFactory factory; private FamilyBeanLoader familyBeanLoader; /** * The typical constructor. * * @param factory * The {@link DAOFactory} associated with this DAO, which is used * for obtaining SQL connections, etc. */ public FamilyDAO(DAOFactory factory) { this.factory = factory; } /** * Return the information of the mother and father of this patient * * @param pid * - this patient * @return * @throws DBException */ public List<FamilyMemberBean> getParents(long pid) throws DBException { return getFamilyMembers(pid, "Parent", "SELECT p2.FirstName AS FirstName, p2.LastName AS LastName, p2.MID as MID " + "FROM patients p1, patients p2 " + "WHERE p1.MID=? AND (p1.MotherMID=p2.MID OR p1.FatherMID=p2.MID)", false); } /** * Return a list of patients who share at least one parent (and that parent * is not '0') with this patient * * @param pid * - this patient * @return A java.util.list of FamilyMemberBeans. * @throws DBException */ public List<FamilyMemberBean> getSiblings(long pid) throws DBException { return getFamilyMembers(pid, "Sibling", "SELECT p2.FirstName AS FirstName, p2.LastName AS LastName, p2.MID as MID " + "FROM patients p1, patients p2 " + "WHERE p1.MID=? AND p1.MID<>p2.MID " + "AND( (p1.MotherMID=p2.MotherMID AND p2.MotherMID<>0)" + " OR (p1.FatherMID=p2.FatherMID AND p1.FatherMID<>0))", false); } /** * Return a list of patients whose mother or father is this patient * * @param pid * - this patient * @return A java.util.List of FamilyMemberBeans. * @throws DBException */ public List<FamilyMemberBean> getChildren(long pid) throws DBException { return getFamilyMembers(pid, "Child", "SELECT FirstName, LastName, MID FROM patients " + "WHERE MotherMID=? or FatherMID=?", true); } /** * Private helper method (since all three are alike) * * @param pid * @param relation * @param query * @param secondParam * - add the pid as the second parameter (the 3rd query was a * little different) * * @return A java.util.List of FamilyMemberBeans. * @throws DBException */ private List<FamilyMemberBean> getFamilyMembers(long pid, String relation, String query, boolean secondParam) throws DBException { familyBeanLoader = new FamilyBeanLoader(relation); try (Connection conn = factory.getConnection(); PreparedStatement stmt = conn.prepareStatement(query)) { stmt.setLong(1, pid); if (secondParam) stmt.setLong(2, pid); ResultSet rs = stmt.executeQuery(); List<FamilyMemberBean> loadlist = familyBeanLoader.loadList(rs); rs.close(); return loadlist; } catch (SQLException e) { throw new DBException(e); } } }
3,903
31
110
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/dao/mysql/HospitalsDAO.java
package edu.ncsu.csc.itrust.model.old.dao.mysql; 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.DBException; import edu.ncsu.csc.itrust.exception.ITrustException; import edu.ncsu.csc.itrust.model.old.beans.HospitalBean; import edu.ncsu.csc.itrust.model.old.beans.loaders.HospitalBeanLoader; import edu.ncsu.csc.itrust.model.old.dao.DAOFactory; /** * Used for managing hospitals * * DAO stands for Database Access Object. All DAOs are intended to be * reflections of the database, that is, one DAO per table in the database (most * of the time). For more complex sets of queries, extra DAOs are added. DAOs * can assume that all data has been validated and is correct. * * DAOs should never have setters or any other parameter to the constructor than * a factory. All DAOs should be accessed by DAOFactory (@see * {@link DAOFactory}) and every DAO should have a factory - for obtaining JDBC * connections and/or accessing other DAOs. */ public class HospitalsDAO { private DAOFactory factory; private HospitalBeanLoader hospitalLoader = new HospitalBeanLoader(); /** * The typical constructor. * * @param factory * The {@link DAOFactory} associated with this DAO, which is used * for obtaining SQL connections, etc. */ public HospitalsDAO(DAOFactory factory) { this.factory = factory; } /** * Returns a list of all hospitals sorted alphabetically * * @return A java.util.List of HospitalBeans. * @throws DBException */ public List<HospitalBean> getAllHospitals() throws DBException { try (Connection conn = factory.getConnection(); PreparedStatement stmt = conn.prepareStatement("SELECT * FROM hospitals ORDER BY HospitalName"); ResultSet rs = stmt.executeQuery()) { List<HospitalBean> loadlist = hospitalLoader.loadList(rs); return loadlist; } catch (SQLException e) { throw new DBException(e); } } /** * Returns a particular hospital given its ID * * @param id * The String ID of the hospital. * @return A HospitalBean representing this hospital. * @throws DBException */ public HospitalBean getHospital(String id) throws DBException { try (Connection conn = factory.getConnection(); PreparedStatement stmt = conn.prepareStatement("SELECT * FROM hospitals WHERE HospitalID = ?")) { stmt.setString(1, id); ResultSet rs = stmt.executeQuery(); if (rs.next()) { HospitalBean loaded = hospitalLoader.loadSingle(rs); rs.close(); return loaded; } rs.close(); return null; } catch (SQLException e) { throw new DBException(e); } } /** * Adds a hospital * * @param hosp * The HospitalBean object to insert. * @return A boolean indicating whether the insertion was successful. * @throws DBException * @throws ITrustException */ public boolean addHospital(HospitalBean hosp) throws DBException, ITrustException { try (Connection conn = factory.getConnection(); PreparedStatement stmt = conn.prepareStatement("INSERT INTO hospitals (HospitalID, HospitalName, Address, City, State, Zip) " + "VALUES (?,?,?,?,?,?)")) { stmt.setString(1, hosp.getHospitalID()); stmt.setString(2, hosp.getHospitalName()); stmt.setString(3, hosp.getHospitalAddress()); stmt.setString(4, hosp.getHospitalCity()); stmt.setString(5, hosp.getHospitalState()); stmt.setString(6, hosp.getHospitalZip()); return stmt.executeUpdate() == 1; } catch (SQLException e) { if (e.getErrorCode() == 1062) { throw new ITrustException("Error: Hospital already exists."); } else { throw new DBException(e); } } } /** * Updates a particular hospital's description. Returns the number of rows * affected (should be 1) * * @param hosp * The HospitalBean to update. * @return An int indicating the number of affected rows. * @throws DBException */ public int updateHospital(HospitalBean hosp) throws DBException { try (Connection conn = factory.getConnection(); PreparedStatement stmt = conn.prepareStatement( "UPDATE hospitals SET HospitalName=?,Address=?,City=?,State=?,Zip=?" + "WHERE HospitalID = ?");) { stmt.setString(1, hosp.getHospitalName()); stmt.setString(2, hosp.getHospitalAddress()); stmt.setString(3, hosp.getHospitalCity()); stmt.setString(4, hosp.getHospitalState()); stmt.setString(5, hosp.getHospitalZip()); stmt.setString(6, hosp.getHospitalID()); int rowsUpdated = stmt.executeUpdate(); return rowsUpdated; } catch (SQLException e) { throw new DBException(e); } } /** * Assign an HCP to a hospital. If they have already been assigned to that * hospital, then an iTrustException is thrown. * * @param hcpID * The HCP's MID to assign to the hospital. * @param hospitalID * The ID of the hospital to assign them to. * @return A boolean indicating whether the assignment was a success. * @throws DBException * @throws ITrustException */ public boolean assignHospital(long hcpID, String hospitalID) throws DBException, ITrustException { try (Connection conn = factory.getConnection(); PreparedStatement stmt = conn.prepareStatement("INSERT INTO hcpassignedhos (HCPID, HosID) VALUES (?,?)");) { stmt.setLong(1, hcpID); stmt.setString(2, hospitalID); boolean successfullyAdded = stmt.executeUpdate() == 1; return successfullyAdded; } catch (SQLException e) { if (1062 == e.getErrorCode()) { throw new ITrustException("HCP " + hcpID + " already assigned to hospital " + hospitalID); } else { throw new DBException(e); } } } /** * Unassigns an HCP to a hospital. Returns whether or not any changes were * made * * @param hcpID * The MID of the HCP to remove. * @param hospitalID * The ID of the hospital being removed from. * @return A boolean indicating success. * @throws DBException */ public boolean removeHospitalAssignment(long hcpID, String hospitalID) throws DBException { try (Connection conn = factory.getConnection(); PreparedStatement stmt = conn.prepareStatement("DELETE FROM hcpassignedhos WHERE HCPID = ? AND HosID = ?");) { stmt.setLong(1, hcpID); stmt.setString(2, hospitalID); boolean successfullyRemoved = stmt.executeUpdate() == 1; return successfullyRemoved; } catch (SQLException e) { throw new DBException(e); } } /** * Removes all hospital assignments for a particular HCP. Returns the number * of rows affected. * * @param hcpID * The MID of the HCP. * @return An int representing the number of hospital assignments removed. * @throws DBException */ public int removeAllHospitalAssignmentsFrom(long hcpID) throws DBException { try (Connection conn = factory.getConnection(); PreparedStatement stmt = conn.prepareStatement("DELETE FROM hcpassignedhos WHERE HCPID = ?");) { stmt.setLong(1, hcpID); int numRemoved = stmt.executeUpdate(); return numRemoved; } catch (SQLException e) { throw new DBException(e); } } /** * Checks to see if the LT has an assigned hospital * * @param hcpID * The MID of the LT. * @return true If the LT has an assigned hospital to them, false if not * @throws DBException */ public boolean checkLTHasHospital(long hcpID) throws DBException { try (Connection conn = factory.getConnection(); PreparedStatement stmt = conn.prepareStatement("SELECT * FROM hcpassignedhos WHERE HCPID = ?")) { stmt.setLong(1, hcpID); ResultSet rs = stmt.executeQuery(); boolean ltHasAssignedHospitals = rs.next(); rs.close(); return ltHasAssignedHospitals; } catch (SQLException e) { throw new DBException(e); } } public List<HospitalBean> getHospitalsAssignedToPhysician(long pid) throws DBException { List<String> hospitalIDs = new ArrayList<String>(); List<HospitalBean> hospitalNames = new ArrayList<HospitalBean>(); HospitalBeanLoader loader = new HospitalBeanLoader(); try (Connection conn = factory.getConnection(); PreparedStatement hcpAssignedHosStmt = conn.prepareStatement("SELECT hosID FROM hcpassignedhos WHERE HCPID=?"); PreparedStatement hospitalsStmt = conn.prepareStatement("SELECT * FROM hospitals WHERE hospitals.HospitalID=?")) { hcpAssignedHosStmt.setString(1, String.valueOf(pid)); ResultSet rs = hcpAssignedHosStmt.executeQuery(); while (rs.next()) { hospitalIDs.add(rs.getString("hosID")); } if (hospitalIDs.size() == 0) { return null; } for (String hID : hospitalIDs) { hospitalsStmt.setString(1, String.valueOf(hID)); rs = hospitalsStmt.executeQuery(); while (rs.next()) { hospitalNames.add(loader.loadSingle(rs)); } } rs.close(); } catch (SQLException e) { throw new DBException(e); } return hospitalNames; } }
8,974
32.996212
129
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/dao/mysql/MessageDAO.java
package edu.ncsu.csc.itrust.model.old.dao.mysql; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; import edu.ncsu.csc.itrust.exception.DBException; import edu.ncsu.csc.itrust.model.old.beans.MessageBean; import edu.ncsu.csc.itrust.model.old.beans.loaders.MessageBeanLoader; import edu.ncsu.csc.itrust.model.old.dao.DAOFactory; /** * Used for the logging mechanism. * * DAO stands for Database Access Object. All DAOs are intended to be * reflections of the database, that is, one DAO per table in the database (most * of the time). For more complex sets of queries, extra DAOs are added. DAOs * can assume that all data has been validated and is correct. * * DAOs should never have setters or any other parameter to the constructor than * a factory. All DAOs should be accessed by DAOFactory (@see * {@link DAOFactory}) and every DAO should have a factory - for obtaining JDBC * connections and/or accessing other DAOs. */ public class MessageDAO { private DAOFactory factory; private MessageBeanLoader mbLoader; /** * The typical constructor. * * @param factory * The {@link DAOFactory} associated with this DAO, which is used * for obtaining SQL connections, etc. */ public MessageDAO(DAOFactory factory) { this.factory = factory; this.mbLoader = new MessageBeanLoader(); } /** * Gets all the messages for a certain user MID. * * @param mid * The MID of the user to be looked up. * @return A java.util.List of MessageBeans. * @throws SQLException * @throws DBException */ public List<MessageBean> getMessagesForMID(long mid) throws SQLException, DBException { try (Connection conn = factory.getConnection(); PreparedStatement stmt = conn .prepareStatement("SELECT * FROM message WHERE to_id = ? ORDER BY sent_date DESC");) { stmt.setLong(1, mid); ResultSet rs = stmt.executeQuery(); List<MessageBean> messageList = this.mbLoader.loadList(rs); rs.close(); return messageList; } catch (SQLException e) { throw new DBException(e); } } /** * Gets all the messages for a certain user MID sorted by ascending time. * * @param mid * The MID of the user to be looked up. * @return A java.util.List of MessageBeans. * @throws SQLException * @throws DBException */ public List<MessageBean> getMessagesTimeAscending(long mid) throws SQLException, DBException { try (Connection conn = factory.getConnection(); PreparedStatement stmt = conn .prepareStatement("SELECT * FROM message WHERE to_id = ? ORDER BY sent_date ASC");) { stmt.setLong(1, mid); ResultSet rs = stmt.executeQuery(); List<MessageBean> messageList = this.mbLoader.loadList(rs); rs.close(); return messageList; } catch (SQLException e) { throw new DBException(e); } } /** * Gets all the messages for a certain user MID sorted by name ascending. * * @param mid * The MID of the user to be looked up. * @return A java.util.List of MessageBeans. * @throws SQLException * @throws DBException */ public List<MessageBean> getMessagesNameAscending(long mid) throws SQLException, DBException { try (Connection conn = factory.getConnection(); PreparedStatement stmt = (mid >= 999999999) ? conn.prepareStatement( "SELECT message.* FROM message, patients WHERE message.from_id=patients.mid AND message.to_id=? ORDER BY patients.lastName ASC, patients.firstName ASC, message.sent_date ASC") : conn.prepareStatement( "SELECT message.* FROM message, personnel WHERE message.from_id=personnel.mid AND message.to_id=? ORDER BY personnel.lastName ASC, personnel.firstName ASC, message.sent_date ASC")) { stmt.setLong(1, mid); ResultSet rs = stmt.executeQuery(); List<MessageBean> messageList = this.mbLoader.loadList(rs); rs.close(); return messageList; } catch (SQLException e) { throw new DBException(e); } } /** * Gets all the messages for a certain user MID sorted by name descending. * * @param mid * The MID of the user to be looked up. * @return A java.util.List of MessageBeans. * @throws SQLException * @throws DBException */ public List<MessageBean> getMessagesNameDescending(long mid) throws SQLException, DBException { try (Connection conn = factory.getConnection(); PreparedStatement stmt = (mid >= 999999999) ? conn.prepareStatement( "SELECT message.* FROM message, patients WHERE message.from_id=patients.mid AND message.to_id=? ORDER BY patients.lastName DESC, patients.firstName DESC, message.sent_date DESC") : conn.prepareStatement( "SELECT message.* FROM message, personnel WHERE message.from_id=personnel.mid AND message.to_id=? ORDER BY personnel.lastName DESC, personnel.firstName DESC, message.sent_date DESC")) { stmt.setLong(1, mid); ResultSet rs = stmt.executeQuery(); List<MessageBean> messageList = this.mbLoader.loadList(rs); rs.close(); return messageList; } catch (SQLException e) { throw new DBException(e); } } /** * Gets all the messages from a certain user MID. * * @param mid * The MID of the user to be looked up. * @return A java.util.List of MessageBeans. * @throws SQLException * @throws DBException */ public List<MessageBean> getMessagesFrom(long mid) throws SQLException, DBException { try (Connection conn = factory.getConnection(); PreparedStatement stmt = conn .prepareStatement("SELECT * FROM message WHERE from_id = ? ORDER BY sent_date DESC")) { stmt.setLong(1, mid); ResultSet rs = stmt.executeQuery(); List<MessageBean> messageList = this.mbLoader.loadList(rs); rs.close(); return messageList; } catch (SQLException e) { throw new DBException(e); } } /** * Gets all the messages for a certain user MID sorted by ascending time. * * @param mid * The MID of the user to be looked up. * @return A java.util.List of MessageBeans. * @throws SQLException */ public List<MessageBean> getMessagesFromTimeAscending(long mid) throws DBException, SQLException { try (Connection conn = factory.getConnection(); PreparedStatement stmt = conn .prepareStatement("SELECT * FROM message WHERE from_id = ? ORDER BY sent_date ASC")) { stmt.setLong(1, mid); ResultSet rs = stmt.executeQuery(); List<MessageBean> messageList = this.mbLoader.loadList(rs); rs.close(); return messageList; } catch (SQLException e) { throw new DBException(e); } } /** * Gets all the messages for a certain user MID sorted by name ascending. * * @param mid * The MID of the user to be looked up. * @return A java.util.List of MessageBeans. * @throws SQLException * @throws DBException */ public List<MessageBean> getMessagesFromNameAscending(long mid) throws SQLException, DBException { try (Connection conn = factory.getConnection(); PreparedStatement stmt = (mid >= 999999999) ? conn.prepareStatement( "SELECT message.* FROM message, patients WHERE message.to_id=patients.mid AND message.from_id=? ORDER BY patients.lastName ASC, patients.firstName ASC, message.sent_date ASC") : conn.prepareStatement( "SELECT message.* FROM message, personnel WHERE message.to_id=personnel.mid AND message.from_id=? ORDER BY personnel.lastName ASC, personnel.firstName ASC, message.sent_date ASC")) { stmt.setLong(1, mid); ResultSet rs = stmt.executeQuery(); List<MessageBean> messageList = this.mbLoader.loadList(rs); rs.close(); return messageList; } catch (SQLException e) { throw new DBException(e); } } /** * Gets all the messages for a certain user MID sorted by name descending. * * @param mid * The MID of the user to be looked up. * @return A java.util.List of MessageBeans. * @throws SQLException * @throws DBException */ public List<MessageBean> getMessagesFromNameDescending(long mid) throws SQLException, DBException { try (Connection conn = factory.getConnection(); PreparedStatement stmt = (mid >= 999999999) ? conn.prepareStatement( "SELECT message.* FROM message, patients WHERE message.to_id=patients.mid AND message.from_id=? ORDER BY patients.lastName DESC, patients.firstName DESC, message.sent_date DESC") : conn.prepareStatement( "SELECT message.* FROM message, personnel WHERE message.to_id=personnel.mid AND message.from_id=? ORDER BY personnel.lastName DESC, personnel.firstName DESC, message.sent_date DESC")) { stmt.setLong(1, mid); ResultSet rs = stmt.executeQuery(); List<MessageBean> messageList = this.mbLoader.loadList(rs); rs.close(); return messageList; } catch (SQLException e) { throw new DBException(e); } } /** * Adds a message to the database. * * @param mBean * A bean representing the message to be added. * @throws SQLException * @throws DBException */ public void addMessage(MessageBean mBean) throws SQLException, DBException { try (Connection conn = factory.getConnection(); PreparedStatement stmt = mbLoader.loadParameters(conn.prepareStatement( "INSERT INTO message (from_id, to_id, sent_date, message, subject, been_read, parent_msg_id, original_msg_id) " + " VALUES (?, ?, NOW(), ?, ?, ?, ?, ?)"), mBean)) { stmt.executeUpdate(); } catch (SQLException e) { throw new DBException(e); } } public void updateRead(MessageBean mBean) throws DBException { try (Connection conn = factory.getConnection(); PreparedStatement stmt = conn.prepareStatement("UPDATE message SET been_read=1 WHERE message_id=?")) { stmt.setLong(1, mBean.getMessageId()); stmt.executeUpdate(); } catch (SQLException e) { throw new DBException(e); } } public List<MessageBean> getCCdMessages(long refID) throws SQLException, DBException { try (Connection conn = factory.getConnection(); PreparedStatement stmt = conn.prepareStatement("SELECT * FROM message WHERE original_msg_id=?")) { stmt.setLong(1, refID); ResultSet rs = stmt.executeQuery(); List<MessageBean> messageList = this.mbLoader.loadList(rs); rs.close(); return messageList; } catch (SQLException e) { throw new DBException(e); } } }
10,354
33.983108
193
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/dao/mysql/NDCodesDAO.java
package edu.ncsu.csc.itrust.model.old.dao.mysql; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; import edu.ncsu.csc.itrust.exception.DBException; import edu.ncsu.csc.itrust.exception.ITrustException; import edu.ncsu.csc.itrust.model.old.beans.MedicationBean; import edu.ncsu.csc.itrust.model.old.beans.loaders.MedicationBeanLoader; import edu.ncsu.csc.itrust.model.old.dao.DAOFactory; /** * Used for managing the ND Codes. * * DAO stands for Database Access Object. All DAOs are intended to be * reflections of the database, that is, one DAO per table in the database (most * of the time). For more complex sets of queries, extra DAOs are added. DAOs * can assume that all data has been validated and is correct. * * DAOs should never have setters or any other parameter to the constructor than * a factory. All DAOs should be accessed by DAOFactory (@see * {@link DAOFactory}) and every DAO should have a factory - for obtaining JDBC * connections and/or accessing other DAOs. * * The National Drug Code (NDC) is a universal product identifier used in the * United States for drugs intended for human use. * * @see http://www.fda.gov/Drugs/InformationOnDrugs/ucm142438.htm */ public class NDCodesDAO { private DAOFactory factory; private MedicationBeanLoader medicationLoader = new MedicationBeanLoader(); /** * The typical constructor. * * @param factory * The {@link DAOFactory} associated with this DAO, which is used * for obtaining SQL connections, etc. */ public NDCodesDAO(DAOFactory factory) { this.factory = factory; } /** * Returns a list of all ND codes * * @return A java.util.List of MedicationBeans. * @throws DBException */ public List<MedicationBean> getAllNDCodes() throws DBException { try (Connection conn = factory.getConnection(); PreparedStatement stmt = conn.prepareStatement("SELECT * FROM ndcodes ORDER BY CODE"); ResultSet rs = stmt.executeQuery()) { List<MedicationBean> loadlist = medicationLoader.loadList(rs); return loadlist; } catch (SQLException e) { throw new DBException(e); } } /** * Returns a particular description for a given code. * * @param code * The ND code to be looked up. * @return A bean representing the Medication that was looked up. * @throws DBException */ public MedicationBean getNDCode(String code) throws DBException { try (Connection conn = factory.getConnection(); PreparedStatement stmt = conn.prepareStatement("SELECT * FROM ndcodes WHERE Code = ?")) { stmt.setString(1, code); ResultSet rs = stmt.executeQuery(); MedicationBean result = rs.next() ? medicationLoader.loadSingle(rs) : null; rs.close(); return result; } catch (SQLException e) { throw new DBException(e); } } /** * Adds a new ND code, returns whether or not the change was made. If the * code already exists, an iTrustException is thrown. * * @param med * The medication bean to be added. * @return A boolean indicating success or failure. * @throws DBException * @throws ITrustException */ public boolean addNDCode(MedicationBean med) throws DBException, ITrustException { try (Connection conn = factory.getConnection(); PreparedStatement stmt = conn .prepareStatement("INSERT INTO ndcodes (Code, Description) " + "VALUES (?,?)")) { stmt.setString(1, med.getNDCode()); stmt.setString(2, med.getDescription()); boolean successfullyAdded = stmt.executeUpdate() == 1; return successfullyAdded; } catch (SQLException e) { if (e.getErrorCode() == 1062) { throw new ITrustException("Error: Code already exists."); } else { throw new DBException(e); } } } /** * Updates a particular code's description * * @param med * A bean representing the particular medication to be updated. * @return An int representing the number of updated rows. * @throws DBException */ public int updateCode(MedicationBean med) throws DBException { try (Connection conn = factory.getConnection(); PreparedStatement stmt = conn.prepareStatement("UPDATE ndcodes SET Description = ? " + "WHERE Code = ?")) { stmt.setString(1, med.getDescription()); stmt.setString(2, med.getNDCode()); return stmt.executeUpdate(); } catch (SQLException e) { throw new DBException(e); } } /** * Removes a ND code, returns whether or not the change was made. * * @param med * The medication bean to be removed. * @return A boolean indicating success or failure. * @throws DBException * @throws ITrustException */ public boolean removeNDCode(MedicationBean med) throws DBException, ITrustException { try (Connection conn = factory.getConnection(); PreparedStatement stmt = conn.prepareStatement("DELETE FROM ndcodes WHERE Code=?")) { stmt.setString(1, med.getNDCode()); return stmt.executeUpdate() == 1; } catch (SQLException e) { throw new DBException(e); } } }
5,080
31.993506
111
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/dao/mysql/PatientDAO.java
package edu.ncsu.csc.itrust.model.old.dao.mysql; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; import java.util.Vector; import edu.ncsu.csc.itrust.DBUtil; import edu.ncsu.csc.itrust.exception.DBException; import edu.ncsu.csc.itrust.exception.ITrustException; 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.beans.loaders.PatientLoader; import edu.ncsu.csc.itrust.model.old.beans.loaders.PersonnelLoader; import edu.ncsu.csc.itrust.model.old.dao.DAOFactory; /** * Used for managing all static information related to a patient. For other * information related to all aspects of patient care, see the other DAOs. * * DAO stands for Database Access Object. All DAOs are intended to be * reflections of the database, that is, one DAO per table in the database (most * of the time). For more complex sets of queries, extra DAOs are added. DAOs * can assume that all data has been validated and is correct. * * DAOs should never have setters or any other parameter to the constructor than * a factory. All DAOs should be accessed by DAOFactory (@see * {@link DAOFactory}) and every DAO should have a factory - for obtaining JDBC * connections and/or accessing other DAOs. */ public class PatientDAO { private DAOFactory factory; private PatientLoader patientLoader; private PersonnelLoader personnelLoader; /** * The typical constructor. * * @param factory * The {@link DAOFactory} associated with this DAO, which is used * for obtaining SQL connections, etc. */ public PatientDAO(DAOFactory factory) { this.factory = factory; this.patientLoader = new PatientLoader(); this.personnelLoader = new PersonnelLoader(); } /** * Returns the name for the given MID * * @param mid * The MID of the patient in question. * @return A String representing the patient's first name and last name. * @throws ITrustException * @throws DBException */ public String getName(long mid) throws ITrustException, DBException { try (Connection conn = factory.getConnection(); PreparedStatement ps = conn.prepareStatement("SELECT firstName, lastName FROM patients WHERE MID=?")) { ps.setLong(1, mid); ResultSet rs; rs = ps.executeQuery(); if (rs.next()) { String result = rs.getString("firstName") + " " + rs.getString("lastName"); rs.close(); return result; } else { rs.close(); throw new ITrustException("User does not exist"); } } catch (SQLException e) { throw new DBException(e); } } /** * Returns the role of a particular patient - why is this in PatientDAO? It * should be in AuthDAO * * @param mid * The MID of the patient in question. * @param role * A String representing the role of the patient. * @return A String representing the patient's role. * @throws ITrustException * @throws DBException */ public String getRole(long mid, String role) throws ITrustException, DBException { try (Connection conn = factory.getConnection(); PreparedStatement ps = conn.prepareStatement("SELECT role FROM users WHERE MID=? AND Role=?")) { ps.setLong(1, mid); ps.setString(2, role); ResultSet rs; rs = ps.executeQuery(); if (rs.next()) { String result = rs.getString("role"); rs.close(); return result; } else { rs.close(); throw new ITrustException("User does not exist with the designated role"); } } catch (SQLException e) { throw new DBException(e); } } /** * Adds an empty patient to the table, returns the new MID * * @return The MID of the patient as a long. * @throws DBException */ public long addEmptyPatient() throws DBException { try (Connection conn = factory.getConnection(); PreparedStatement ps = conn.prepareStatement("INSERT INTO patients(MID) VALUES(NULL)")) { ps.executeUpdate(); return DBUtil.getLastInsert(conn); } catch (SQLException e) { throw new DBException(e); } } /** * Returns the patient's information for a given ID * * @param mid * The MID of the patient to retrieve. * @return A PatientBean representing the patient. * @throws DBException */ public PatientBean getPatient(long mid) throws DBException { try (Connection conn = factory.getConnection(); PreparedStatement ps = conn.prepareStatement("SELECT * FROM patients WHERE MID = ?")) { ps.setLong(1, mid); ResultSet rs = ps.executeQuery(); PatientBean patient = rs.next() ? patientLoader.loadSingle(rs) : null; rs.close(); return patient; } catch (SQLException e) { throw new DBException(e); } } /** * Updates a patient's information for the given MID * * @param p * The patient bean representing the new information for the * patient. * @throws DBException */ public void editPatient(PatientBean p, long hcpid) throws DBException { try (Connection conn = factory.getConnection(); PreparedStatement ps = patientLoader .loadParameters(conn.prepareStatement("UPDATE patients SET firstName=?,lastName=?,email=?," + "address1=?,address2=?,city=?,state=?,zip=?,phone=?," + "eName=?,ePhone=?,iCName=?,iCAddress1=?,iCAddress2=?,iCCity=?," + "ICState=?,iCZip=?,iCPhone=?,iCID=?,DateOfBirth=?," + "DateOfDeath=?,CauseOfDeath=?,MotherMID=?,FatherMID=?," + "BloodType=?,Ethnicity=?,Gender=?,TopicalNotes=?, CreditCardType=?, CreditCardNumber=?, " + "DirectionsToHome=?, Religion=?, Language=?, SpiritualPractices=?, " + "AlternateName=?, DateOfDeactivation=? WHERE MID=?"), p)) { ps.setLong(37, p.getMID()); ps.executeUpdate(); } catch (SQLException e) { throw new DBException(e); } } /** * Returns whether or not the patient exists * * @param pid * The MID of the patient in question. * @return A boolean indicating whether the patient exists. * @throws DBException */ public boolean checkPatientExists(long pid) throws DBException { try (Connection conn = factory.getConnection(); PreparedStatement ps = conn.prepareStatement("SELECT * FROM patients WHERE MID=?")) { ps.setLong(1, pid); ResultSet rs = ps.executeQuery(); boolean exists = rs.next(); rs.close(); return exists; } catch (SQLException e) { throw new DBException(e); } } /** * Returns a list of HCPs who are declared by the given patient * * @param pid * The MID of the patient in question. * @return A java.util.List of Personnel Beans. * @throws DBException */ public List<PersonnelBean> getDeclaredHCPs(long pid) throws DBException { if (pid == 0L) { throw new DBException(new SQLException("pid cannot be 0")); } try (Connection conn = factory.getConnection(); PreparedStatement ps = conn.prepareStatement("SELECT * FROM declaredhcp, personnel " + "WHERE PatientID=? AND personnel.MID=declaredhcp.HCPID")) { ps.setLong(1, pid); ResultSet rs = ps.executeQuery(); List<PersonnelBean> loadlist = personnelLoader.loadList(rs); rs.close(); return loadlist; } catch (SQLException e) { throw new DBException(e); } } /** * Declares an HCP for a particular patient * * @param pid * The MID of the patient in question. * @param hcpID * The HCP's MID. * @return A boolean as to whether the insertion was successful. * @throws DBException * @throws ITrustException */ public boolean declareHCP(long pid, long hcpID) throws DBException, ITrustException { try (Connection conn = factory.getConnection(); PreparedStatement ps = conn.prepareStatement("INSERT INTO declaredhcp(PatientID, HCPID) VALUES(?,?)")) { ps.setLong(1, pid); ps.setLong(2, hcpID); boolean successfullyAdded = ps.executeUpdate() == 1; return successfullyAdded; } catch (SQLException e) { if (e.getErrorCode() == 1062) { throw new ITrustException("HCP " + hcpID + " has already been declared for patient " + pid); } else { throw new DBException(e); } } } /** * Undeclare an HCP for a given patient * * @param pid * The MID of the patient in question. * @param hcpID * The MID of the HCP in question. * @return A boolean indicating whether the action was successful. * @throws DBException */ public boolean undeclareHCP(long pid, long hcpID) throws DBException { try (Connection conn = factory.getConnection(); PreparedStatement ps = conn.prepareStatement("DELETE FROM declaredhcp WHERE PatientID=? AND HCPID=?")) { ps.setLong(1, pid); ps.setLong(2, hcpID); boolean successfullyDeleted = ps.executeUpdate() == 1; return successfullyDeleted; } catch (SQLException e) { throw new DBException(e); } } /** * Check if a patient has declared the given HCP * * @param pid * The MID of the patient in question as a long. * @param hcpid * The MID of the HCP in question as a long. * @return * @throws DBException */ public boolean checkDeclaredHCP(long pid, long hcpid) throws DBException { try (Connection conn = factory.getConnection(); PreparedStatement ps = conn .prepareStatement("SELECT * FROM declaredhcp WHERE PatientID=? AND HCPID=?")) { ps.setLong(1, pid); ps.setLong(2, hcpid); boolean patientHasDeclaredHCP = (ps.executeQuery().next()); return patientHasDeclaredHCP; } catch (SQLException e) { throw new DBException(e); } } /** * Return a list of patients that the given patient represents * * @param pid * The MID of the patient in question. * @return A java.util.List of PatientBeans * @throws DBException */ public List<PatientBean> getRepresented(long pid) throws DBException { try (Connection conn = factory.getConnection(); PreparedStatement ps = conn.prepareStatement("SELECT patients.* FROM representatives, patients " + "WHERE RepresenterMID=? AND RepresenteeMID=patients.MID")) { ps.setLong(1, pid); ResultSet rs = ps.executeQuery(); List<PatientBean> loadlist = patientLoader.loadList(rs); rs.close(); return loadlist; } catch (SQLException e) { throw new DBException(e); } } /** * Return a list of patients that the given patient represents * * @param pid * The MID of the patient in question. * @return A java.util.List of PatientBeans * @throws DBException */ public List<PatientBean> getDependents(long pid) throws DBException { try (Connection conn = factory.getConnection(); PreparedStatement ps = conn.prepareStatement("SELECT patients.* FROM representatives, patients, users " + "WHERE RepresenterMID=? AND RepresenteeMID=patients.MID AND users.MID=patients.MID AND users.isDependent=1")) { ps.setLong(1, pid); ResultSet rs = ps.executeQuery(); List<PatientBean> dependentsList = patientLoader.loadList(rs); rs.close(); return dependentsList; } catch (SQLException e) { throw new DBException(e); } } /** * Return a list of patients that the given patient is represented by * * @param pid * The MID of the patient in question. * @return A java.util.List of PatientBeans. * @throws DBException */ public List<PatientBean> getRepresenting(long pid) throws DBException { try (Connection conn = factory.getConnection(); PreparedStatement ps = conn.prepareStatement("SELECT patients.* FROM representatives, patients " + "WHERE RepresenteeMID=? AND RepresenterMID=patients.MID")) { ps.setLong(1, pid); ResultSet rs = ps.executeQuery(); List<PatientBean> representingList = patientLoader.loadList(rs); rs.close(); return representingList; } catch (SQLException e) { throw new DBException(e); } } /** * Check if the given representer represents the representee * * @param representer * The MID of the representer in question. * @param representee * The MID of the representee in question. * @return A boolean indicating whether represenation is in place. * @throws DBException */ public boolean represents(long representer, long representee) throws DBException { try (Connection conn = factory.getConnection(); PreparedStatement ps = conn.prepareStatement( "SELECT * FROM representatives WHERE RepresenterMID=? AND RepresenteeMID=?")) { ps.setLong(1, representer); ps.setLong(2, representee); ResultSet rs = ps.executeQuery(); boolean doesRepresent = rs.next(); rs.close(); return doesRepresent; } catch (SQLException e) { throw new DBException(e); } } /** * Assign a representer to the representee * * @param representer * The MID of the representer as a long. * @param representee * The MID of the representee as a long. * @return A boolean as to whether the insertion was correct. * @throws DBException * @throws ITrustException */ public boolean addRepresentative(long representer, long representee) throws DBException, ITrustException { try (Connection conn = factory.getConnection(); PreparedStatement ps = conn .prepareStatement("INSERT INTO representatives(RepresenterMID,RepresenteeMID) VALUES (?,?)")) { ps.setLong(1, representer); ps.setLong(2, representee); boolean successfullyAdded = ps.executeUpdate() == 1; return successfullyAdded; } catch (SQLException e) { if (e.getErrorCode() == 1062) { throw new ITrustException("Patient " + representer + " already represents patient " + representee); } else { throw new DBException(e); } } } public boolean checkIfRepresenteeIsActive(long representee) throws DBException { if (representee == 0L) { throw new DBException(new SQLException("PID cannot be 0")); } try (Connection conn = factory.getConnection(); PreparedStatement ps = conn .prepareStatement("SELECT * FROM patients WHERE MID=? AND DateOfDeactivation IS NULL")) { ps.setLong(1, representee); ResultSet rs = ps.executeQuery(); PatientBean bean = new PatientBean(); if (rs.next()) bean = patientLoader.loadSingle(rs); rs.close(); return bean.getMID() == representee; } catch (SQLException e) { throw new DBException(e); } } public boolean checkIfPatientIsActive(long pid) throws ITrustException { if (pid == 0L) throw new DBException(new SQLException("PID cannot be 0")); try (Connection conn = factory.getConnection(); PreparedStatement ps = conn .prepareStatement("SELECT * FROM patients WHERE MID=? AND DateOfDeactivation IS NULL")) { ps.setLong(1, pid); ResultSet rs = ps.executeQuery(); PatientBean bean = rs.next() ? patientLoader.loadSingle(rs) : new PatientBean(); rs.close(); return bean.getMID() == pid; } catch (SQLException e) { throw new DBException(e); } } /** * Unassign the representation * * @param representer * The MID of the representer in question. * @param representee * The MID of the representee in question. * @return A boolean indicating whether the unassignment was sucessful. * @throws DBException */ public boolean removeRepresentative(long representer, long representee) throws DBException { try (Connection conn = factory.getConnection(); PreparedStatement ps = conn .prepareStatement("DELETE FROM representatives WHERE RepresenterMID=? AND RepresenteeMID=?")) { ps.setLong(1, representer); ps.setLong(2, representee); boolean successfullyDeleted = ps.executeUpdate() == 1; return successfullyDeleted; } catch (SQLException e) { throw new DBException(e); } } /** * Removes all dependencies represented by the patient passed in the * parameter * * @param representerMID * the mid for the patient to remove all representees for * @throws DBException */ public void removeAllRepresented(long representerMID) throws DBException { try (Connection conn = factory.getConnection(); PreparedStatement updateStatement = conn.prepareStatement( "UPDATE users U, representatives R SET U.isDependent=0 WHERE R.representerMID=? AND " + "R.representeeMID=U.MID AND R.representeeMID NOT IN " + "(SELECT representeeMID FROM representatives WHERE representerMID<>?)"); PreparedStatement deleteStatement = conn.prepareStatement("DELETE FROM representatives WHERE representerMID=?")) { updateStatement.setLong(1, representerMID); updateStatement.setLong(2, representerMID); updateStatement.executeUpdate(); deleteStatement.setLong(1, representerMID); deleteStatement.executeUpdate(); } catch (SQLException e) { throw new DBException(e); } } /** * Removes all dependencies participated by the patient passed in the * parameter * * @param representerMID * the mid for the patient to remove all representees for * @throws DBException */ public void removeAllRepresentee(long representeeMID) throws DBException { try (Connection conn = factory.getConnection(); PreparedStatement deleteStatement = conn.prepareStatement("DELETE FROM representatives WHERE representeeMID=?"); PreparedStatement updateStatement = conn.prepareStatement("UPDATE users SET isDependent=0 WHERE MID=?")) { deleteStatement.setLong(1, representeeMID); deleteStatement.executeUpdate(); updateStatement.setLong(1, representeeMID); updateStatement.executeUpdate(); } catch (SQLException e) { throw new DBException(e); } } /** * Lists every patient in the database. * * @return A java.util.List of PatientBeans representing the patients. * @throws DBException */ public List<PatientBean> getAllPatients() throws DBException { try (Connection conn = factory.getConnection(); PreparedStatement ps = conn.prepareStatement("SELECT * FROM patients "); ResultSet rs = ps.executeQuery()) { return patientLoader.loadList(rs); } catch (SQLException e) { throw new DBException(e); } } /** * Return a list of patients with a special-diagnosis-history who have the * logged in HCP as a DHCP and whose medications are going to expire within * seven days. * * @param hcpMID * The MID of the logged in HCP * @return A list of patients satisfying the conditions. * @throws DBException */ public List<PatientBean> getRenewalNeedsPatients(long hcpMID) throws DBException { try (Connection conn = factory.getConnection(); PreparedStatement ps = conn.prepareStatement("SELECT * FROM ( " + "SELECT DISTINCT patients.* FROM patients, declaredhcp, ovdiagnosis, officevisits, ovmedication" + " WHERE" + " declaredhcp.HCPID = ?" + " AND patients.MID = declaredhcp.PatientID" + " AND (ovdiagnosis.VisitID = officevisits.ID" + " AND officevisits.PatientID = declaredhcp.PatientID" + " AND ((ovdiagnosis.ICDCode >= ? AND ovdiagnosis.ICDCode < ?)" + " OR (ovdiagnosis.ICDCode >= ? AND ovdiagnosis.ICDCode < ?)" + " OR (ovdiagnosis.ICDCode >= ? AND ovdiagnosis.ICDCode < ?)))" + " UNION ALL" + " SELECT DISTINCT patients.* From patients, declaredhcp, ovdiagnosis, officevisits, ovmedication " + " WHERE" + " declaredhcp.HCPID = ?" + " AND patients.MID = declaredhcp.PatientID" + " AND (declaredhcp.PatientID = officevisits.PatientID" + " AND officevisits.ID = ovmedication.VisitID" + " AND ovmedication.EndDate BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 7 DAY)))" + " AS final" + " GROUP BY final.MID HAVING COUNT(*) = 2" + " ORDER BY final.lastname ASC, final.firstname ASC")) { ps.setLong(1, hcpMID); ps.setFloat(2, 250.0f); ps.setFloat(3, 251.0f); ps.setFloat(4, 493.0f); ps.setFloat(5, 494.0f); ps.setFloat(6, 390.0f); ps.setFloat(7, 460.99f); ps.setLong(8, hcpMID); ResultSet rs = ps.executeQuery(); List<PatientBean> loadlist = patientLoader.loadList(rs); rs.close(); return loadlist; } catch (SQLException e) { throw new DBException(e); } } /** * Returns all patients with names "LIKE" (as in SQL) the passed in * parameters. * * @param first * The patient's first name. * @param last * The patient's last name. * @return A java.util.List of PatientBeans. * @throws DBException */ public List<PatientBean> searchForPatientsWithName(String first, String last) throws DBException { if (first.equals("%") && last.equals("%")) { return new Vector<PatientBean>(); } try (Connection conn = factory.getConnection(); PreparedStatement ps = conn.prepareStatement("SELECT * FROM patients WHERE firstName LIKE ? AND lastName LIKE ?")) { ps.setString(1, first); ps.setString(2, last); ResultSet rs = ps.executeQuery(); List<PatientBean> patientsList = patientLoader.loadList(rs); rs.close(); return patientsList; } catch (SQLException e) { throw new DBException(e); } } /** * Returns all patients with names "LIKE" with wildcards (as in SQL) the * passed in parameters. * * @param first * The patient's first name. * @param last * The patient's last name. * @return A java.util.List of PatientBeans. * @throws DBException */ public List<PatientBean> fuzzySearchForPatientsWithName(String first, String last) throws DBException { if (first.equals("%") && last.equals("%")) { return new Vector<PatientBean>(); } try (Connection conn = factory.getConnection(); PreparedStatement ps = conn .prepareStatement("SELECT * FROM patients WHERE firstName LIKE ? AND lastName LIKE ?")) { ps.setString(1, "%" + first + "%"); ps.setString(2, "%" + last + "%"); ResultSet rs = ps.executeQuery(); List<PatientBean> loadlist = patientLoader.loadList(rs); rs.close(); return loadlist; } catch (SQLException e) { throw new DBException(e); } } /** * Returns all patients with the given MID as a substring in their MID * * @param MID * the patients MID * @return list of patients with that MID as a substring * @throws DBException */ public List<PatientBean> fuzzySearchForPatientsWithMID(long MID) throws DBException { try (Connection conn = factory.getConnection(); PreparedStatement ps = conn.prepareStatement("SELECT * FROM patients WHERE MID LIKE ? ORDER BY MID")) { ps.setString(1, "%" + MID + "%"); ResultSet rs = ps.executeQuery(); List<PatientBean> loadlist = patientLoader.loadList(rs); rs.close(); return loadlist; } catch (SQLException e) { throw new DBException(e); } } /** * Allows a patient to add a designated nutritionist. Only the designated * nutritionist will be able to view the patient's nutritional information. */ public int addDesignatedNutritionist(long patientMID, long HCPID) throws DBException { try (Connection conn = factory.getConnection(); PreparedStatement ps = conn.prepareStatement("INSERT INTO " + "designatedNutritionist(PatientID, HCPID) VALUES(?,?);")) { ps.setLong(1, patientMID); ps.setLong(2, HCPID); int updated = ps.executeUpdate(); return updated; } catch (SQLException e) { throw new DBException(e); } } /** * Returns the ID of the designated nutritionist for the patient returns -1 * if the patient does not have a designated nutritionist */ public long getDesignatedNutritionist(long patientMID) throws DBException { try (Connection conn = factory.getConnection(); PreparedStatement ps = conn.prepareStatement("SELECT HCPID FROM " + "designatedNutritionist WHERE PatientID = ?;")) { ps.setLong(1, patientMID); ResultSet results = ps.executeQuery(); long nutritionistMID = results.next() ? results.getLong(1) : -1; results.close(); return nutritionistMID; } catch (SQLException e) { throw new DBException(e); } } /** * Updates the designated nutritionist for this patient. Assumes that the * patient already has a designated nutritionist. */ public int updateDesignatedNutritionist(long patientMID, long HCPID) throws DBException { try (Connection conn = factory.getConnection(); PreparedStatement ps = conn.prepareStatement("UPDATE designatedNutritionist " + "SET HCPID = ? WHERE PatientID = ?;")) { ps.setLong(1, HCPID); ps.setLong(2, patientMID); int numUpdated = ps.executeUpdate(); return numUpdated; } catch (SQLException e) { throw new DBException(e); } } /** * Deletes the designated nutritionist for this patient. Assumes that the * patient already has a designated nutritionist */ public int deleteDesignatedNutritionist(long patientMID) throws DBException { try (Connection conn = factory.getConnection(); PreparedStatement ps = conn.prepareStatement("DELETE FROM designatedNutritionist " + "WHERE PatientID = ?;")) { ps.setLong(1, patientMID); int numDeleted = ps.executeUpdate(); return numDeleted; } catch (SQLException e) { throw new DBException(e); } } }
25,051
33.084354
125
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/dao/mysql/PersonnelDAO.java
package edu.ncsu.csc.itrust.model.old.dao.mysql; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; import java.util.Vector; import edu.ncsu.csc.itrust.exception.DBException; import edu.ncsu.csc.itrust.exception.ITrustException; import edu.ncsu.csc.itrust.model.old.beans.HospitalBean; import edu.ncsu.csc.itrust.model.old.beans.PersonnelBean; import edu.ncsu.csc.itrust.model.old.beans.loaders.HospitalBeanLoader; import edu.ncsu.csc.itrust.model.old.beans.loaders.PersonnelLoader; import edu.ncsu.csc.itrust.model.old.dao.DAOFactory; import edu.ncsu.csc.itrust.model.old.enums.Role; /** * Used for managing information related to personnel: HCPs, UAPs, Admins * * DAO stands for Database Access Object. All DAOs are intended to be * reflections of the database, that is, one DAO per table in the database (most * of the time). For more complex sets of queries, extra DAOs are added. DAOs * can assume that all data has been validated and is correct. * * DAOs should never have setters or any other parameter to the constructor than * a factory. All DAOs should be accessed by DAOFactory (@see * {@link DAOFactory}) and every DAO should have a factory - for obtaining JDBC * connections and/or accessing other DAOs. */ public class PersonnelDAO { private transient final DAOFactory factory; private transient final PersonnelLoader personnelLoader; private transient final HospitalBeanLoader hospBeanLoader; /** * The typical constructor. * * @param factory * The {@link DAOFactory} associated with this DAO, which is used * for obtaining SQL connections, etc. */ public PersonnelDAO(final DAOFactory factory) { this.factory = factory; personnelLoader = new PersonnelLoader(); hospBeanLoader = new HospitalBeanLoader(); } /** * Returns the name for a given MID * * @param mid * The MID of the personnel in question. * @return A String representing the name of the personnel. * @throws ITrustException * @throws DBException */ public String getName(final long mid) throws ITrustException, DBException { try (Connection conn = factory.getConnection(); PreparedStatement stmt = conn .prepareStatement("SELECT firstName, lastName FROM personnel WHERE MID=?");) { stmt.setLong(1, mid); ResultSet results = stmt.executeQuery(); if (!results.next()) { throw new ITrustException("User does not exist"); } final String result = results.getString("firstName") + " " + results.getString("lastName"); results.close(); return result; } catch (SQLException e) { throw new DBException(e); } } public long getNextID(final Role role) throws DBException, ITrustException { long minID = role.getMidFirstDigit() * 1000000000L; minID = minID == 0 ? 1 : minID; // Do not use 0 as an ID. final long maxID = minID + 999999998L; long nextID = minID; try (Connection conn = factory.getConnection(); PreparedStatement stmt = conn .prepareStatement("SELECT MAX(users.mid) FROM users WHERE mid BETWEEN ? AND ?")) { stmt.setLong(1, minID); stmt.setLong(2, maxID); final ResultSet results = stmt.executeQuery(); if (results.next()) { nextID = results.getLong(1) + 1; if (nextID < minID) { nextID = minID; } } results.close(); return nextID; } catch (SQLException e) { throw new DBException(e); } } /** * Adds an empty personnel, and returns the MID. * * @return A long indicating the new MID. * @param role * A {@link Role} enum indicating the personnel's specific role. * @throws DBException * @throws ITrustException */ public long addEmptyPersonnel(final Role role) throws DBException, ITrustException { final long nextID = getNextID(role); try (Connection conn = factory.getConnection(); PreparedStatement stmt = conn.prepareStatement("INSERT INTO personnel(MID, Role) VALUES(?,?)")) { stmt.setString(1, Long.valueOf(nextID).toString()); stmt.setString(2, role.name()); stmt.executeUpdate(); return nextID; } catch (SQLException e) { throw new DBException(e); } } /** * Retrieves a PersonnelBean with all of the specific information for a * given employee. * * @param mid * The MID of the personnel in question. * @return A PersonnelBean representing the employee. * @throws DBException */ public PersonnelBean getPersonnel(final long mid) throws DBException { PersonnelBean bean = null; try (Connection conn = factory.getConnection(); PreparedStatement stmt = conn.prepareStatement("SELECT * FROM personnel WHERE MID = ?")) { stmt.setLong(1, mid); final ResultSet results = stmt.executeQuery(); if (results.next()) { bean = personnelLoader.loadSingle(results); } results.close(); } catch (SQLException e) { throw new DBException(e); } return bean; } /** * Updates the demographics for a personnel. * * @param p * The personnel bean with the updated information. * @throws DBException */ public void editPersonnel(final PersonnelBean pBean) throws DBException { try (Connection conn = factory.getConnection(); PreparedStatement stmt = personnelLoader .loadParameters(conn.prepareStatement("UPDATE personnel SET AMID=?,firstName=?,lastName=?," + "phone=?, address1=?,address2=?,city=?, state=?, zip=?, specialty=?, email=?" + " WHERE MID=?"), pBean)) { stmt.setLong(12, pBean.getMID()); stmt.executeUpdate(); } catch (SQLException e) { throw new DBException(e); } } /** * Indicates whether a certain personnel is in the database. * * @param pid * The MID of the personnel in question. * @return A boolean indicating whether this personnel exists. * @throws DBException */ public boolean checkPersonnelExists(final long pid) throws DBException { try (Connection conn = factory.getConnection(); PreparedStatement stmt = conn.prepareStatement("SELECT * FROM personnel WHERE MID=?")) { stmt.setLong(1, pid); final ResultSet results = stmt.executeQuery(); final boolean exists = results.next(); results.close(); return exists; } catch (SQLException e) { throw new DBException(e); } } /** * Returns all of the hospitals this LHCP is associated with. * * @param mid * The MID of the personnel in question. * @return A java.util.List of HospitalBeans. * @throws DBException */ public List<HospitalBean> getHospitals(final long mid) throws DBException { try (Connection conn = factory.getConnection(); PreparedStatement stmt = conn.prepareStatement("SELECT * FROM hcpassignedhos hah,hospitals h " + "WHERE hah.HCPID=? AND hah.HosID=h.HospitalID ORDER BY HospitalName ASC")) { stmt.setLong(1, mid); final ResultSet results = stmt.executeQuery(); final List<HospitalBean> hospitals = hospBeanLoader.loadList(results); results.close(); return hospitals; } catch (SQLException e) { throw new DBException(e); } } /** * Returns all of the hospitals this uap's associated hcp is associated * with. * * @param mid * The MID of the personnel in question. * @return A java.util.List of HospitalBeans. * @throws DBException */ public List<HospitalBean> getUAPHospitals(final long mid) throws DBException { try (Connection conn = factory.getConnection(); PreparedStatement stmt = conn.prepareStatement("SELECT DISTINCT hospitals.* FROM hcpassignedhos hah " + "INNER JOIN hcprelations ON hah.HCPID = hcprelations.HCP " + "INNER JOIN hospitals ON hah.hosID = hospitals.HospitalID " + "WHERE hcprelations.UAP=? ORDER BY HospitalName ASC")) { stmt.setLong(1, mid); final ResultSet results = stmt.executeQuery(); final List<HospitalBean> hospitals = hospBeanLoader.loadList(results); results.close(); return hospitals; } catch (SQLException e) { throw new DBException(e); } } /** * Returns all personnel of specified specialty from the specified hospital. * * @param hosid, * the ID of the Hospital to get personnel from * @param specialty, * the type of specialty to search for * @return A java.util.List of PersonnelBeans. * @throws DBException */ public List<PersonnelBean> getPersonnelFromHospital(final String hosid, final String specialty) throws DBException { try (Connection conn = factory.getConnection(); PreparedStatement stmt = specialty.equalsIgnoreCase("all") ? conn.prepareStatement( "SELECT * FROM hcpassignedhos hah inner join personnel p where hah.hosID = ? and hah.HCPID = p.MID and p.role = 'hcp'") : conn.prepareStatement( "SELECT * FROM hcpassignedhos hah inner join personnel p where hah.hosID = ? and hah.HCPID = p.MID and p.specialty = ? and p.role = 'hcp'");) { stmt.setString(1, hosid); if (!specialty.equalsIgnoreCase("all")) { stmt.setString(2, specialty); } // NOTE: There is a possible NullPointerException Threat here! final ResultSet results = stmt.executeQuery(); final List<PersonnelBean> loadlist = personnelLoader.loadList(results); results.close(); return loadlist; } catch (SQLException e) { throw new DBException(e); } } /** * Returns all personnel of specified specialty from the specified hospital. * * @param hosid, * the ID of the Hospital to get personnel from * @param specialty, * the type of specialty to search for * @return A java.util.List of PersonnelBeans. * @throws DBException */ public List<PersonnelBean> getPersonnelFromHospital(final String hosid) throws DBException { try (Connection conn = factory.getConnection(); PreparedStatement stmt = conn.prepareStatement( "SELECT * FROM hcpassignedhos hah inner join personnel p where hah.hosID = ? and hah.HCPID = p.MID and p.role = 'hcp'")) { stmt.setString(1, hosid); final ResultSet results = stmt.executeQuery(); final List<PersonnelBean> personnelFromHospital = personnelLoader.loadList(results); results.close(); return personnelFromHospital; } catch (SQLException e) { throw new DBException(e); } } /** * Returns all personnel in the database. * * @return A java.util.List of personnel. * @throws DBException */ public List<PersonnelBean> getAllPersonnel() throws DBException { try (Connection conn = factory.getConnection(); PreparedStatement stmt = conn .prepareStatement("SELECT * FROM personnel where role in ('hcp','uap','er') ")) { final ResultSet results = stmt.executeQuery(); final List<PersonnelBean> allPersonnel = personnelLoader.loadList(results); results.close(); return allPersonnel; } catch (SQLException e) { throw new DBException(e); } } /** * Returns a list of UAPs who work for this LHCP. * * @param hcpid * The MID of the personnel in question. * @return A java.util.List of UAPs. * @throws DBException */ public List<PersonnelBean> getUAPsForHCP(final long hcpid) throws DBException { try (Connection conn = factory.getConnection(); PreparedStatement stmt = conn.prepareStatement( "SELECT * FROM personnel WHERE MID IN (SELECT UAP FROM hcprelations WHERE HCP=?)")) { stmt.setLong(1, hcpid); final ResultSet results = stmt.executeQuery(); final List<PersonnelBean> uaps = personnelLoader.loadList(results); results.close(); return uaps; } catch (SQLException e) { throw new DBException(e); } } /** * Matches all personnel who have names LIKE (as in SQL) the first and last * names passed in. * * @param first * The first name to be searched for. * @param last * The last name to be searched for. * @return A java.util.List of personnel who match these names. * @throws DBException */ public List<PersonnelBean> searchForPersonnelWithName(final String first, final String last) throws DBException { if ("%".equals(first) && "%".equals(last)) { return new Vector<PersonnelBean>(); } try (Connection conn = factory.getConnection(); PreparedStatement stmt = conn .prepareStatement("SELECT * FROM personnel WHERE firstName LIKE ? AND lastName LIKE ?")) { stmt.setString(1, first); stmt.setString(2, last); final ResultSet results = stmt.executeQuery(); final List<PersonnelBean> matchingPersonnel = personnelLoader.loadList(results); results.close(); return matchingPersonnel; } catch (SQLException e) { throw new DBException(e); } } /** * Returns list of personnel who are Lab Techs. * * @return List of personnel beans. * @throws DBException */ public List<PersonnelBean> getLabTechs() throws DBException { try (Connection conn = factory.getConnection(); PreparedStatement stmt = conn.prepareStatement("SELECT * FROM personnel WHERE role = 'lt' "); final ResultSet results = stmt.executeQuery()) { final List<PersonnelBean> labTechnicians = personnelLoader.loadList(results); return labTechnicians; } catch (SQLException e) { throw new DBException(e); } } /** * Returns all experts with names "LIKE" with wildcards (as in SQL) the * passed in parameters. * * @param first * The expert's first name. * @param last * The expert's last name. * @return A java.util.List of ExpertBeans. * @throws DBException */ public List<PersonnelBean> fuzzySearchForExpertsWithName(String first, String last) throws DBException { if (first.equals("%") && last.equals("%")) { return new Vector<PersonnelBean>(); } try (Connection conn = factory.getConnection(); PreparedStatement stmt = conn.prepareStatement( "SELECT * FROM personnel WHERE firstName LIKE ? AND lastName LIKE ? AND role='hcp'");) { stmt.setString(1, "%" + first + "%"); stmt.setString(2, "%" + last + "%"); ResultSet rs = stmt.executeQuery(); List<PersonnelBean> expertsList = personnelLoader.loadList(rs); rs.close(); return expertsList; } catch (SQLException e) { throw new DBException(e); } } /** * Returns all of the personnel who have a specialty of nutritionist */ public List<PersonnelBean> getAllNutritionists() throws DBException { try (Connection conn = factory.getConnection(); PreparedStatement ps = conn .prepareStatement("SELECT * FROM personnel WHERE UPPER(specialty) = 'NUTRITIONIST'; "); ResultSet rs = ps.executeQuery()) { List<PersonnelBean> loadList = personnelLoader.loadList(rs); return loadList; } catch (SQLException e) { throw new DBException(e); } } /** * Returns all of the personnel who have a specialty of ophthalmologist or * optometrist * * @return List of all personnel who have a specialty of ophthalmologist or * optometrist. * @throws DBException */ public List<PersonnelBean> getAllOphthalmologyPersonnel() throws DBException { try (Connection conn = factory.getConnection(); PreparedStatement ps = conn.prepareStatement("SELECT * FROM personnel " + "WHERE specialty = 'Optometrist' or specialty = 'Ophthalmologist'; "); ResultSet rs = ps.executeQuery()) { List<PersonnelBean> allOpthamologyPersonnel = personnelLoader.loadList(rs); return allOpthamologyPersonnel; } catch (SQLException e) { throw new DBException(e); } } }
15,403
33.30735
151
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/dao/mysql/RecordsReleaseDAO.java
package edu.ncsu.csc.itrust.model.old.dao.mysql; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; import edu.ncsu.csc.itrust.exception.DBException; import edu.ncsu.csc.itrust.model.old.beans.RecordsReleaseBean; import edu.ncsu.csc.itrust.model.old.beans.loaders.RecordsReleaseBeanLoader; import edu.ncsu.csc.itrust.model.old.dao.DAOFactory; public class RecordsReleaseDAO { DAOFactory factory; RecordsReleaseBeanLoader loader = new RecordsReleaseBeanLoader(); public RecordsReleaseDAO(DAOFactory factory) { this.factory = factory; } public boolean addRecordsRelease(RecordsReleaseBean bean) throws DBException { try (Connection conn = factory.getConnection(); PreparedStatement ps = loader.loadParameters(conn.prepareStatement( "INSERT INTO recordsrelease(requestDate,pid,releaseHospitalID,recHospitalName," + "recHospitalAddress,docFirstName,docLastName,docPhone,docEmail,justification,status) " + "VALUES(?,?,?,?,?,?,?,?,?,?,?)"), bean)) { int numInserted = ps.executeUpdate(); return numInserted == 1; } catch (SQLException e) { throw new DBException(e); } } public boolean updateRecordsRelease(RecordsReleaseBean bean) throws DBException { try (Connection conn = factory.getConnection(); PreparedStatement ps = loader.loadParameters( conn.prepareStatement("UPDATE recordsrelease SET requestDate=?, pid=?, releaseHospitalID=?, " + "recHospitalName=?, recHospitalAddress=?, docFirstName=?, docLastName=?, docPhone=?, " + "docEmail=?, justification=?, status=? WHERE releaseID=?"), bean)) { ps.setLong(12, bean.getReleaseID()); int numUpdated = ps.executeUpdate(); return numUpdated == 1; } catch (SQLException e) { throw new DBException(e); } } public RecordsReleaseBean getRecordsReleaseByID(long releaseID) throws DBException { try (Connection conn = factory.getConnection(); PreparedStatement ps = conn.prepareStatement("SELECT * FROM recordsrelease WHERE releaseID=?")) { ps.setLong(1, releaseID); ResultSet rs; rs = ps.executeQuery(); // Get the first and only records release bean List<RecordsReleaseBean> records = loader.loadList(rs); rs.close(); return (records.size() > 0) ? records.get(0) : null; } catch (SQLException e) { throw new DBException(e); } } public List<RecordsReleaseBean> getAllRecordsReleasesByHospital(String hospitalID) throws DBException { try (Connection conn = factory.getConnection(); PreparedStatement ps = conn.prepareStatement( "SELECT * FROM recordsrelease " + "WHERE releaseHospitalID=? ORDER BY requestDate DESC")) { ps.setString(1, hospitalID); ResultSet rs = ps.executeQuery(); List<RecordsReleaseBean> releases = loader.loadList(rs); rs.close(); return releases; } catch (SQLException e) { throw new DBException(e); } } public List<RecordsReleaseBean> getAllRecordsReleasesByPid(long pid) throws DBException { try (Connection conn = factory.getConnection(); PreparedStatement ps = conn .prepareStatement("SELECT * FROM recordsrelease " + "WHERE pid=? ORDER BY requestDate DESC")) { ps.setLong(1, pid); ResultSet rs = ps.executeQuery(); List<RecordsReleaseBean> releases = loader.loadList(rs); rs.close(); return releases; } catch (SQLException e) { throw new DBException(e); } } }
3,444
34.885417
104
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/dao/mysql/RemoteMonitoringDAO.java
package edu.ncsu.csc.itrust.model.old.dao.mysql; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Date; import java.util.List; import edu.ncsu.csc.itrust.exception.DBException; import edu.ncsu.csc.itrust.exception.ITrustException; import edu.ncsu.csc.itrust.model.old.beans.PersonnelBean; import edu.ncsu.csc.itrust.model.old.beans.RemoteMonitoringDataBean; import edu.ncsu.csc.itrust.model.old.beans.TelemedicineBean; import edu.ncsu.csc.itrust.model.old.beans.loaders.PersonnelLoader; import edu.ncsu.csc.itrust.model.old.beans.loaders.RemoteMonitoringDataBeanLoader; import edu.ncsu.csc.itrust.model.old.beans.loaders.RemoteMonitoringListsBeanLoader; import edu.ncsu.csc.itrust.model.old.dao.DAOFactory; /** * Used for the keeping track of remote monitoring data. * * DAO stands for Database Access Object. All DAOs are intended to be * reflections of the database, that is, one DAO per table in the database (most * of the time). For more complex sets of queries, extra DAOs are added. DAOs * can assume that all data has been validated and is correct. * * DAOs should never have setters or any other parameter to the constructor than * a factory. All DAOs should be accessed by DAOFactory (@see * {@link DAOFactory}) and every DAO should have a factory - for obtaining JDBC * connections and/or accessing other DAOs. */ public class RemoteMonitoringDAO { private transient final DAOFactory factory; private transient final RemoteMonitoringDataBeanLoader loader = new RemoteMonitoringDataBeanLoader(); private transient final RemoteMonitoringListsBeanLoader rmListLoader = new RemoteMonitoringListsBeanLoader(); private transient final PersonnelLoader personnelLoader = new PersonnelLoader(); /** * The typical constructor. * * @param factory * The {@link DAOFactory} associated with this DAO, which is used * for obtaining SQL connections, etc. */ public RemoteMonitoringDAO(final DAOFactory factory) { this.factory = factory; } /** * Return remote monitoring list data for a given patient. * * @param patientMID * Patient to retrieve data for. * @return List of TelemedicineBeans * @throws DBException */ public List<TelemedicineBean> getTelemedicineBean(final long patientMID) throws DBException { try (Connection conn = factory.getConnection(); PreparedStatement stmt = conn .prepareStatement("SELECT * FROM remotemonitoringlists WHERE PatientMID=?")) { stmt.setLong(1, patientMID); final ResultSet results = stmt.executeQuery(); final List<TelemedicineBean> telemedicine = rmListLoader.loadList(results); results.close(); return telemedicine; } catch (SQLException e) { throw new DBException(e); } } /** * Returns patient data for a given HCP * * @param loggedInMID * loggedInMID * @return dataList * @throws DBException */ public List<RemoteMonitoringDataBean> getPatientsData(final long loggedInMID) throws DBException { try (Connection conn = factory.getConnection(); PreparedStatement stmt = conn .prepareStatement("SELECT * FROM remotemonitoringlists WHERE HCPMID=? ORDER BY PatientMID"); PreparedStatement pstmt1 = conn.prepareStatement( "SELECT * FROM remotemonitoringdata WHERE timelogged >= CURRENT_DATE ORDER BY PatientID, timeLogged DESC"); final ResultSet dataRS = pstmt1.executeQuery()) { stmt.setLong(1, loggedInMID); final ResultSet patientRS = stmt.executeQuery(); final List<String> patientList = new ArrayList<String>(); while (patientRS.next()) { patientList.add(Long.valueOf(patientRS.getLong("PatientMID")).toString()); } final List<RemoteMonitoringDataBean> dataList = loader.loadList(dataRS); int idx1; int idx2; // Go through all patients and remove any that aren't monitored by // this HCP for (idx1 = 0; idx1 < dataList.size(); idx1++) { if (!patientList.contains(Long.valueOf(dataList.get(idx1).getPatientMID()).toString())) { dataList.remove(idx1); idx1--; } } // Add values in patient list with no data for today to list. boolean itsThere; for (idx1 = 0; idx1 < patientList.size(); idx1++) { itsThere = false; for (idx2 = 0; idx2 < dataList.size(); idx2++) { if (dataList.get(idx2).getPatientMID() == Long.parseLong(patientList.get(idx1))) { itsThere = true; break; } } if (!itsThere) { dataList.add(new RemoteMonitoringDataBean(Long.parseLong(patientList.get(idx1)))); } } return dataList; } catch (SQLException e) { throw new DBException(e); } } /** * getPatientDataByDate * * @param patientMID * patientMID * @param lower * lower * @param upper * upeer * @return dataList * @throws DBException */ public List<RemoteMonitoringDataBean> getPatientDataByDate(final long patientMID, final Date lower, final Date upper) throws DBException { try (Connection conn = factory.getConnection(); PreparedStatement stmt = conn.prepareStatement( "SELECT * FROM remotemonitoringdata WHERE PatientID=? AND timeLogged >= ? AND timeLogged <= ? ORDER BY timeLogged DESC")) { stmt.setLong(1, patientMID); stmt.setTimestamp(2, new Timestamp(lower.getTime())); // add 1 day's worth to include the upper stmt.setTimestamp(3, new Timestamp(upper.getTime() + 1000L * 60L * 60 * 24L)); final ResultSet results = stmt.executeQuery(); final List<RemoteMonitoringDataBean> dataList = loader.loadList(results); results.close(); return dataList; } catch (SQLException e) { throw new DBException(e); } } /** * Get the requested type of data for the specified patient. * * @param patientMID * The MID of the patient * @param dataType * The type of telemedicine data to return * @return A list of beans which all contain information of the requested * type * @throws DBException */ public List<RemoteMonitoringDataBean> getPatientDataByType(final long patientMID, final String dataType) throws DBException { try (Connection conn = factory.getConnection(); PreparedStatement stmt = conn .prepareStatement("SELECT * FROM remotemonitoringdata WHERE PatientID=? AND " + dataType + " != -1 ORDER BY timeLogged ASC")) { stmt.setLong(1, patientMID); final ResultSet results = stmt.executeQuery(); final List<RemoteMonitoringDataBean> dataList = loader.loadList(results); results.close(); return dataList; } catch (SQLException e) { throw new DBException(e); } } /** * Store pedometer reading and height/weight data for a given patient in the * RemoteMonitoringData table * * @param patientMID * The MID of the patient * @param bean * bean * @param height * The height of the patient * @param weight * The weight of the patient * @param reporterRole * The role of the person that reported these monitoring stats * @param reporterMID * The MID of the person that reported these monitoring stats * @throws ITrustException */ public void storePatientData(final long patientMID, final RemoteMonitoringDataBean bean, final String reporterRole, final long reporterMID) throws ITrustException { float height = bean.getHeight(); float weight = bean.getWeight(); int pedometer = bean.getPedometerReading(); int sbp = bean.getSystolicBloodPressure(); int dbp = bean.getDiastolicBloodPressure(); int glucose = bean.getGlucoseLevel(); if (height == 0) { height = -1; } if (weight == 0) { weight = -1; } if (pedometer == 0) { pedometer = -1; } if (sbp == 0) { sbp = -1; } if (dbp == 0) { dbp = -1; } if (glucose == 0) { glucose = -1; } if (getNumberOfDailyEntries(patientMID, "height") >= 1 && height != -1) { throw new ITrustException("Patient height entries for today cannot exceed 1."); } if (getNumberOfDailyEntries(patientMID, "weight") >= 1 && weight != -1) { throw new ITrustException("Patient weight entries for today cannot exceed 1."); } if (getNumberOfDailyEntries(patientMID, "pedometerReading") >= 1 && pedometer != -1) { throw new ITrustException("Patient pedometer reading entries for today cannot exceed 1."); } if (getNumberOfDailyEntries(patientMID, "glucoseLevel") >= 10 && glucose != -1) { throw new ITrustException("Patient glucose level entries for today cannot exceed 10."); } if (getNumberOfDailyEntries(patientMID, "systolicBloodPressure") >= 10 && sbp != -1) { throw new ITrustException("Patient systolic blood pressure entries for today cannot exceed 10."); } if (getNumberOfDailyEntries(patientMID, "diastolicBloodPressure") >= 10 && dbp != -1) { throw new ITrustException("Patient diastolic blood pressure entries for today cannot exceed 10."); } if ("patient representative".equals(reporterRole)) { validatePR(reporterMID, patientMID); } try (Connection conn = factory.getConnection(); PreparedStatement pstmt = conn .prepareStatement("INSERT INTO remotemonitoringdata(PatientID, height, weight, " + "pedometerReading, systolicBloodPressure, diastolicBloodPressure, glucoseLevel, ReporterRole, ReporterID) VALUES(?,?,?,?,?,?,?,?,?)")) { pstmt.setLong(1, patientMID); pstmt.setFloat(2, height); pstmt.setFloat(3, weight); pstmt.setInt(4, pedometer); pstmt.setInt(5, sbp); pstmt.setInt(6, dbp); pstmt.setInt(7, glucose); pstmt.setString(8, reporterRole); pstmt.setLong(9, reporterMID); pstmt.executeUpdate(); } catch (SQLException e) { throw new DBException(e); } } /** * Private method to get the number of entries for a certain patientID and a * certain data type for today. * * @param patientMID * @param dataType * @return the number of entries * @throws DBException */ private int getNumberOfDailyEntries(final long patientMID, final String dataType) throws DBException { try (Connection conn = factory.getConnection(); PreparedStatement stmt = conn .prepareStatement("SELECT * FROM remotemonitoringdata WHERE PatientID=? AND " + dataType + "!=? AND DATE(timeLogged)=CURRENT_DATE")) { stmt.setLong(1, patientMID); stmt.setInt(2, -1); final ResultSet results = stmt.executeQuery(); final List<RemoteMonitoringDataBean> patients = loader.loadList(results); results.close(); return patients.size(); } catch (SQLException e) { throw new DBException(e); } } /** * validatePR * * @param representativeMID * representativeMID * @param patientMID * patientMID * @throws ITrustException */ public void validatePR(final long representativeMID, final long patientMID) throws ITrustException { try (Connection conn = factory.getConnection(); PreparedStatement stmt = conn.prepareStatement( "SELECT * FROM representatives WHERE RepresenterMID=? AND RepresenteeMID=?")) { stmt.setLong(1, representativeMID); stmt.setLong(2, patientMID); final ResultSet results = stmt.executeQuery(); boolean exists = results.next(); results.close(); if (!exists) { throw new ITrustException("Representer is not valid for patient " + patientMID); } } catch (SQLException e) { throw new DBException(e); } } /** * Show the list of HCPs monitoring this patient * * @param patientMID * The MID of the patient * @return list of HCPs monitoring the provided patient */ public List<PersonnelBean> getMonitoringHCPs(final long patientMID) throws DBException { try (Connection conn = factory.getConnection(); PreparedStatement stmt = conn.prepareStatement("SELECT * FROM personnel, remotemonitoringlists " + "WHERE remotemonitoringlists.PatientMID=? AND remotemonitoringlists.HCPMID=personnel.MID")) { stmt.setLong(1, patientMID); final ResultSet results = stmt.executeQuery(); final List<PersonnelBean> personnel = personnelLoader.loadList(results); results.close(); return personnel; } catch (SQLException e) { throw new DBException(e); } } /** * Add a patient to the list of HCPs' monitoring lists of Patients * * @param patientMID * The MID of the patient * @param HCPMID * The MID of the HCP * @param tBean * The TelemedicineBean indicating what telemedicine data the * patient is allowed to enter. * @return true if added successfully, false if already in list */ public boolean addPatientToList(final long patientMID, final long HCPMID, final TelemedicineBean tBean) throws DBException { String permissionPS = "SystolicBloodPressure, DiastolicBloodPressure, GlucoseLevel, Height, Weight, PedometerReading"; try (Connection conn = factory.getConnection(); PreparedStatement stmt = conn .prepareStatement("SELECT * FROM remotemonitoringlists WHERE PatientMID = ? AND HCPMID = ?"); PreparedStatement stmt2 = conn.prepareStatement("INSERT INTO remotemonitoringlists(PatientMID, HCPMID, " + permissionPS + ") VALUES(?,?,?,?,?,?,?,?)")) { stmt.setLong(1, patientMID); stmt.setLong(2, HCPMID); final ResultSet results = stmt.executeQuery(); boolean hasResults = results.next(); results.close(); if (hasResults) { return false; } // TODO: somebody should probably make this use a loader of some kind stmt2.setLong(1, patientMID); stmt2.setLong(2, HCPMID); stmt2.setBoolean(3, tBean.isSystolicBloodPressureAllowed()); stmt2.setBoolean(4, tBean.isDiastolicBloodPressureAllowed()); stmt2.setBoolean(5, tBean.isGlucoseLevelAllowed()); stmt2.setBoolean(6, tBean.isHeightAllowed()); stmt2.setBoolean(7, tBean.isWeightAllowed()); stmt2.setBoolean(8, tBean.isPedometerReadingAllowed()); stmt2.executeUpdate(); return true; } catch (SQLException e) { throw new DBException(e); } } /** * Remove a patient from the list of HCPs' monitoring lists of Patients * * @param patientMID * The MID of the patient * @param HCPMID * The MID of the HCP * @return true if removed successfully, false if not in list */ public boolean removePatientFromList(final long patientMID, final long HCPMID) throws DBException { try (Connection conn = factory.getConnection(); PreparedStatement stmt = conn .prepareStatement("DELETE FROM remotemonitoringlists WHERE PatientMID = ? AND HCPMID = ?")) { stmt.setLong(1, patientMID); stmt.setLong(2, HCPMID); boolean removed = stmt.executeUpdate() != 0; return removed; } catch (SQLException e) { throw new DBException(e); } } }
14,812
34.269048
146
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/dao/mysql/ReportRequestDAO.java
package edu.ncsu.csc.itrust.model.old.dao.mysql; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Date; import java.util.List; import edu.ncsu.csc.itrust.DBUtil; import edu.ncsu.csc.itrust.exception.DBException; import edu.ncsu.csc.itrust.model.old.beans.ReportRequestBean; import edu.ncsu.csc.itrust.model.old.beans.loaders.ReportRequestBeanLoader; import edu.ncsu.csc.itrust.model.old.dao.DAOFactory; /** * Used for handling data related to report requests. * * DAO stands for Database Access Object. All DAOs are intended to be * reflections of the database, that is, one DAO per table in the database (most * of the time). For more complex sets of queries, extra DAOs are added. DAOs * can assume that all data has been validated and is correct. * * DAOs should never have setters or any other parameter to the constructor than * a factory. All DAOs should be accessed by DAOFactory (@see * {@link DAOFactory}) and every DAO should have a factory - for obtaining JDBC * connections and/or accessing other DAOs. */ public class ReportRequestDAO { private transient final DAOFactory factory; private transient final ReportRequestBeanLoader loader; /** * The typical constructor. * * @param factory * The {@link DAOFactory} associated with this DAO, which is used * for obtaining SQL connections, etc. */ public ReportRequestDAO(final DAOFactory factory) { this.factory = factory; loader = new ReportRequestBeanLoader(); } /** * Returns a full bean describing a given report request. * * @param id * The unique ID of the bean in the database. * @return The bean describing this report request. * @throws DBException */ public ReportRequestBean getReportRequest(final long id) throws DBException { if (id == 0L) { throw new DBException(new SQLException("ID cannot be null")); } try (Connection conn = factory.getConnection(); PreparedStatement stmt = conn.prepareStatement("SELECT * FROM reportrequests WHERE ID = ?")) { stmt.setLong(1, id); final ResultSet results = stmt.executeQuery(); results.next(); final ReportRequestBean result = loader.loadSingle(results); results.close(); return result; } catch (SQLException e) { throw new DBException(e); } } /** * Returns all report requests associated with a given requester. * * @param mid * The MID of the personnel in question. * @return A java.util.List of report requests. * @throws DBException */ public List<ReportRequestBean> getAllReportRequestsForRequester(final long mid) throws DBException { if (mid == 0L) { throw new DBException(new SQLException("Invalid RequesterMID")); } try (Connection conn = factory.getConnection(); PreparedStatement stmt = conn.prepareStatement("SELECT * FROM reportrequests WHERE RequesterMID = ?")) { stmt.setLong(1, mid); final ResultSet results = stmt.executeQuery(); final List<ReportRequestBean> reportRequests = loader.loadList(results); results.close(); return reportRequests; } catch (SQLException e) { throw new DBException(e); } } /** * Returns all of the report requests associated with a specific patient. * * @param pid * The MID of the patient in question. * @return A java.util.List of report requests. * @throws DBException */ public List<ReportRequestBean> getAllReportRequestsForPatient(final long pid) throws DBException { if (pid == 0L) { throw new DBException(new SQLException("PatientMID cannot be null")); } try (Connection conn = factory.getConnection(); PreparedStatement stmt = conn.prepareStatement("SELECT * FROM reportrequests WHERE PatientMID = ?")) { stmt.setLong(1, pid); final ResultSet results = stmt.executeQuery(); final List<ReportRequestBean> reportRequests = loader.loadList(results); results.close(); return reportRequests; } catch (SQLException e) { throw new DBException(e); } } /** * Adds a request for a report. * * @param requesterMID * The MID of the requester. * @param patientMID * The MID of the patient in question. * @param date * The date the request was made. * @return A long of the unique ID of the report request. * @throws DBException */ public long addReportRequest(final long requesterMID, final long patientMID, final Date date) throws DBException { if (requesterMID == 0L) { throw new DBException(new SQLException("RequesterMID cannot be null")); } try (Connection conn = factory.getConnection(); PreparedStatement pstmt = conn.prepareStatement( "INSERT INTO reportrequests (ID, RequesterMID, PatientMID, RequestedDate, Status) VALUES (null,?,?,?,'Requested')")) { pstmt.setLong(1, requesterMID); pstmt.setLong(2, patientMID); pstmt.setTimestamp(3, new java.sql.Timestamp(date.getTime())); pstmt.executeUpdate(); return DBUtil.getLastInsert(conn); } catch (SQLException e) { throw new DBException(e); } } /** * Sets the status of a report request to 'Viewed' * * @param ID * The unique ID of the request in question. * @param date * The date the request was viewed. * @throws DBException */ public void setViewed(final long ID, final Date date) throws DBException { if (ID == 0L) { throw new DBException(new SQLException("ID cannot be null")); } try (Connection conn = factory.getConnection(); PreparedStatement pstmt = conn.prepareStatement("UPDATE reportrequests set ViewedDate = ?, Status = 'Viewed' where ID = ?")) { pstmt.setTimestamp(1, new java.sql.Timestamp(date.getTime())); pstmt.setLong(2, ID); pstmt.executeUpdate(); } catch (SQLException e) { throw new DBException(e); } } }
5,862
32.502857
130
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/dao/mysql/ReviewsDAO.java
package edu.ncsu.csc.itrust.model.old.dao.mysql; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; import edu.ncsu.csc.itrust.exception.DBException; import edu.ncsu.csc.itrust.model.old.beans.ReviewsBean; import edu.ncsu.csc.itrust.model.old.beans.loaders.ReviewsBeanLoader; import edu.ncsu.csc.itrust.model.old.dao.DAOFactory; /** * Provide a way to handle database queries for the reviews table, store HCP * review information. */ public class ReviewsDAO { private DAOFactory factory; private ReviewsBeanLoader loader; /** * The basic constructor for the ReviewsDAO object. * * @param factory * DAOFactory entry param */ public ReviewsDAO(DAOFactory factory) { this.factory = factory; loader = new ReviewsBeanLoader(); } /** * Based on the information from the ReviewsBean, add a review for an HCP * (given by HCP in the bean) into the reviews table. * * @param bean * containing the rating * @return true if the review was added successfully and false otherwise * @throws DBException */ public boolean addReview(ReviewsBean bean) throws DBException { if (bean == null) { return false; } try (Connection conn = factory.getConnection(); PreparedStatement ps = loader.loadParameters( conn.prepareStatement( "INSERT INTO reviews(mid, pid, reviewdate, descriptivereview, rating, title) VALUES (?,?,(CURRENT_TIMESTAMP),?,?,?)"), bean)) { boolean added = ps.executeUpdate() > 0; return added; } catch (SQLException e) { throw new DBException(e); } } /** * Get a list of all reviews for a given HCP with id matching input param * pid. * * @param pid * ID of the HCP whose reviews to return * @return list of all reviews, null if there aren't any * @throws DBException */ public List<ReviewsBean> getAllReviews(long pid) throws DBException { try (Connection conn = factory.getConnection(); PreparedStatement ps = conn.prepareStatement("SELECT * FROM reviews WHERE pid=?")) { ps.setLong(1, pid); ResultSet rs = ps.executeQuery(); return loader.loadList(rs); } catch (SQLException e) { throw new DBException(e); } } /** * Get a list of all reviews for a given HCP with id matching input param * pid. * * @param pid * ID of the HCP whose reviews to return * @return list of all reviews, null if there aren't any * @throws DBException */ public List<ReviewsBean> getAllReviews() throws DBException { try (Connection conn = factory.getConnection(); PreparedStatement ps = conn.prepareStatement("SELECT * FROM reviews"); ResultSet rs = ps.executeQuery()) { List<ReviewsBean> records = loader.loadList(rs); return records; } catch (SQLException e) { throw new DBException(e); } } /** * Get a list of all reviews for a given HCP with id matching input param * pid. * * @param pid * ID of the HCP whose reviews to return * @return list of all reviews, null if there aren't any * @throws DBException */ public List<ReviewsBean> getReviews(long pid) throws DBException { try (Connection conn = factory.getConnection(); PreparedStatement ps = conn.prepareStatement("SELECT * FROM reviews WHERE pid=?")) { ps.setLong(1, pid); ResultSet rs = ps.executeQuery(); List<ReviewsBean> records = loader.loadList(rs); return records; } catch (SQLException e) { throw new DBException(e); } } /** * Get average rating for the given HCP overall, all categories and all * reviews. * * @param pid * HCP with ratings wanted * @return the average rating of all the overall ratings * @throws DBException */ public double getTotalAverageRating(long pid) throws DBException { try (Connection conn = factory.getConnection(); PreparedStatement ps = conn.prepareStatement("SELECT AVG(rating) FROM reviews WHERE pid=?")) { ps.setLong(1, pid); ResultSet rs = ps.executeQuery(); double averageRating = rs.next() ? rs.getDouble("AVG(rating)") : 0; rs.close(); return averageRating; } catch (SQLException e) { throw new DBException(e); } } /** * This checks the appointment table in the DB to see if the there is an * appointment entry for the input mid(patient_id) and pid(doctor_id) * params. It returns true if the patient has seen the given doctor, false * otherwise. * * @param mid * Patient ID * @param pid * HCP ID * @return true if the patient has had an appointment with the HCP, false * otherwise * @throws DBException */ public boolean isRateable(long mid, long pid) throws DBException { try (Connection conn = factory.getConnection(); PreparedStatement ps = conn .prepareStatement("SELECT * FROM appointment WHERE patient_id =? AND doctor_id=?")) { ps.setLong(1, mid); ps.setLong(2, pid); ResultSet rs = ps.executeQuery(); boolean isRatable = rs.next(); return isRatable; } catch (SQLException e) { throw new DBException(e); } } }
5,131
28.837209
127
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/dao/mysql/TransactionDAO.java
package edu.ncsu.csc.itrust.model.old.dao.mysql; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Timestamp; import java.util.List; import edu.ncsu.csc.itrust.exception.DBException; import edu.ncsu.csc.itrust.logger.TransactionLogger; import edu.ncsu.csc.itrust.model.old.beans.OperationalProfile; import edu.ncsu.csc.itrust.model.old.beans.TransactionBean; import edu.ncsu.csc.itrust.model.old.beans.loaders.OperationalProfileLoader; import edu.ncsu.csc.itrust.model.old.beans.loaders.TransactionBeanLoader; import edu.ncsu.csc.itrust.model.old.dao.DAOFactory; import edu.ncsu.csc.itrust.model.old.enums.TransactionType; /** * Used for the logging mechanism. * * DAO stands for Database Access Object. All DAOs are intended to be * reflections of the database, that is, one DAO per table in the database (most * of the time). For more complex sets of queries, extra DAOs are added. DAOs * can assume that all data has been validated and is correct. * * DAOs should never have setters or any other parameter to the constructor than * a factory. All DAOs should be accessed by DAOFactory (@see * {@link DAOFactory}) and every DAO should have a factory - for obtaining JDBC * connections and/or accessing other DAOs. */ public class TransactionDAO { private DAOFactory factory; private TransactionBeanLoader loader = new TransactionBeanLoader(); private OperationalProfileLoader operationalProfileLoader = new OperationalProfileLoader(); /** * The typical constructor. * * @param factory * The {@link DAOFactory} associated with this DAO, which is used * for obtaining SQL connections, etc. */ public TransactionDAO(DAOFactory factory) { this.factory = factory; } /** * Returns the whole transaction log * * @return * @throws DBException */ public List<TransactionBean> getAllTransactions() throws DBException { try (Connection conn = factory.getConnection(); PreparedStatement ps = conn.prepareStatement("SELECT * FROM transactionlog ORDER BY timeLogged DESC"); ResultSet rs = ps.executeQuery()) { List<TransactionBean> loadlist = loader.loadList(rs); return loadlist; } catch (SQLException e) { throw new DBException(e); } } /** * Log a transaction, with all of the info. The meaning of secondaryMID and * addedInfo changes depending on the transaction type. * * @param type * The {@link TransactionType} enum representing the type this * transaction is. * @param loggedInMID * The MID of the user who is logged in. * @param secondaryMID * Typically, the MID of the user who is being acted upon. * @param addedInfo * A note about a subtransaction, or specifics of this * transaction (for posterity). * @throws DBException */ public void logTransaction(TransactionType type, Long loggedInMID, Long secondaryMID, String addedInfo) throws DBException { // Use 0 as the default secondaryMID if (secondaryMID == null) { secondaryMID = 0L; } try (Connection conn = factory.getConnection(); PreparedStatement ps = conn.prepareStatement("INSERT INTO transactionlog(loggedInMID, secondaryMID, " + "transactionCode, addedInfo) VALUES(?,?,?,?)")) { ps.setLong(1, loggedInMID); ps.setLong(2, secondaryMID); ps.setInt(3, type.getCode()); ps.setString(4, addedInfo); ps.executeUpdate(); } catch (SQLException e) { throw new DBException(e); } } /** * Return a list of all transactions in which an HCP accessed the given * patient's record * * @param patientID * The MID of the patient in question. * @return A java.util.List of transactions. * @throws DBException */ public List<TransactionBean> getAllRecordAccesses(long patientID, long dlhcpID, boolean getByRole) throws DBException { try (Connection conn = factory.getConnection(); PreparedStatement ps = conn .prepareStatement("SELECT * FROM transactionlog WHERE secondaryMID=? AND transactionCode " + "IN(" + TransactionType.patientViewableStr + ") AND loggedInMID!=? ORDER BY timeLogged DESC")) { ps.setLong(1, patientID); ps.setLong(2, dlhcpID); ResultSet rs = ps.executeQuery(); List<TransactionBean> transactionList = loader.loadList(rs); transactionList = addAndSortRoles(transactionList, patientID, getByRole); rs.close(); return transactionList; } catch (SQLException e) { throw new DBException(e); } } /** * The Most Thorough Fetch * * @param mid * MID of the logged in user * @param dlhcpID * MID of the user's DLHCP * @param start * Index to start pulling entries from * @param range * Number of entries to retrieve * @return List of <range> TransactionBeans affecting the user starting from * the <start>th entry * @throws DBException */ public List<TransactionBean> getTransactionsAffecting(long mid, long dlhcpID, java.util.Date start, int range) throws DBException { try (Connection conn = factory.getConnection(); PreparedStatement ps = conn.prepareStatement("SELECT * FROM transactionlog WHERE ((timeLogged <= ?) " + "AND (secondaryMID=? AND transactionCode " + "IN (" + TransactionType.patientViewableStr + ")) " + "OR (loggedInMID=? AND transactionCode=?) ) " + "AND NOT (loggedInMID=? AND transactionCode IN (" + // exclude // if // DLHCP // as // specified // in // UC43 TransactionType.dlhcpHiddenStr + ")) " + "ORDER BY timeLogged DESC LIMIT 0,?")) { ps.setString(2, mid + ""); ps.setString(3, mid + ""); ps.setInt(4, TransactionType.LOGIN_SUCCESS.getCode()); ps.setTimestamp(1, new Timestamp(start.getTime())); ps.setLong(5, dlhcpID); ps.setInt(6, range); ResultSet rs = ps.executeQuery(); List<TransactionBean> transactionList = loader.loadList(rs); rs.close(); return transactionList; } catch (SQLException e) { throw new DBException(e); } } /** * Return a list of all transactions in which an HCP accessed the given * patient's record, within the dates * * @param patientID * The MID of the patient in question. * @param lower * The starting date as a java.util.Date * @param upper * The ending date as a java.util.Date * @return A java.util.List of transactions. * @throws DBException */ public List<TransactionBean> getRecordAccesses(long patientID, long dlhcpID, java.util.Date lower, java.util.Date upper, boolean getByRole) throws DBException { try (Connection conn = factory.getConnection(); PreparedStatement ps = conn .prepareStatement("SELECT * FROM transactionlog WHERE secondaryMID=? AND transactionCode IN (" + TransactionType.patientViewableStr + ") " + "AND timeLogged >= ? AND timeLogged <= ? " + "AND loggedInMID!=? " + "ORDER BY timeLogged DESC")) { ps.setLong(1, patientID); ps.setTimestamp(2, new Timestamp(lower.getTime())); // add 1 day's worth to include the upper ps.setTimestamp(3, new Timestamp(upper.getTime() + 1000L * 60L * 60 * 24L)); ps.setLong(4, dlhcpID); ResultSet rs = ps.executeQuery(); List<TransactionBean> transactionList = loader.loadList(rs); transactionList = addAndSortRoles(transactionList, patientID, getByRole); rs.close(); return transactionList; } catch (SQLException e) { throw new DBException(e); } } /** * Returns the operation profile * * @return The OperationalProfile as a bean. * @throws DBException */ public OperationalProfile getOperationalProfile() throws DBException { return getOperationalProfile(0L); } /** * Returns the operation profile * * @return The OperationalProfile as a bean. * @throws DBException */ public OperationalProfile getOperationalProfile(long loggedInMID) throws DBException { try (Connection conn = factory.getConnection(); PreparedStatement ps = conn .prepareStatement("SELECT TransactionCode, count(transactionID) as TotalCount, " + "count(if(loggedInMID<9000000000, transactionID, null)) as PatientCount, " + "count(if(loggedInMID>=9000000000, transactionID, null)) as PersonnelCount " + "FROM transactionlog GROUP BY transactionCode ORDER BY transactionCode ASC"); ResultSet rs = ps.executeQuery()) { TransactionLogger.getInstance().logTransaction(TransactionType.OPERATIONAL_PROFILE_VIEW, loggedInMID, 0L, ""); OperationalProfile result = operationalProfileLoader.loadSingle(rs); return result; } catch (SQLException e) { throw new DBException(e); } } /** * * @param transactionList * @param patientID * @param sortByRole * @return * @throws DBException */ private List<TransactionBean> addAndSortRoles(List<TransactionBean> transactionList, long patientID, boolean sortByRole) throws DBException { for (TransactionBean t : transactionList) { String rawRole = getRoleStringForMID(t.getLoggedInMID()); String formattedRole; switch (rawRole) { case "er": formattedRole = "Emergency Responder"; break; case "uap": formattedRole = "UAP"; break; case "hcp": formattedRole = getHCPRole(patientID, t.getLoggedInMID()); break; case "patient": formattedRole = getPatientRole(patientID, t.getLoggedInMID()); break; default: formattedRole = ""; break; } t.setRole(formattedRole); } if (sortByRole) { TransactionBean[] array = new TransactionBean[transactionList.size()]; array[0] = transactionList.get(0); TransactionBean t; for (int i = 1; i < transactionList.size(); i++) { t = transactionList.get(i); String role = t.getRole(); int j = 0; while (array[j] != null && role.compareToIgnoreCase(array[j].getRole()) >= 0) j++; for (int k = i; k > j; k--) { array[k] = array[k - 1]; } array[j] = t; } int size = transactionList.size(); for (int i = 0; i < size; i++) transactionList.set(i, array[i]); } return transactionList; } /** * Returns the role for the given MID, or empty string if no user exists for * the given MID. */ private String getRoleStringForMID(Long mid) throws DBException { try (Connection conn = factory.getConnection(); PreparedStatement roleQuery = conn.prepareStatement("SELECT Role FROM users WHERE MID=?")) { roleQuery.setLong(1, mid); ResultSet rs = roleQuery.executeQuery(); String role = rs.next() ? rs.getString("Role") : ""; rs.close(); return role; } catch (SQLException e) { throw new DBException(e); } } /** * Returns the HCP role (LHCP or DLHCP) for the given patient and HCP MIDs. */ private String getHCPRole(Long patientID, Long hcpID) throws DBException { try (Connection conn = factory.getConnection(); PreparedStatement ps = conn.prepareStatement("SELECT PatientID FROM declaredhcp WHERE HCPID=?")) { ps.setLong(1, hcpID); ResultSet rs = ps.executeQuery(); String role = "LHCP"; while (rs.next()) { if (rs.getLong("PatientID") == patientID) { role = "DLHCP"; break; } } rs.close(); return role; } catch (SQLException e) { throw new DBException(e); } } /** * Returns the patient role (Patient or Personal Health Representative) for * the given patient and HCP MIDs. */ private String getPatientRole(Long patientID, Long mid) throws DBException { try (Connection conn = factory.getConnection(); PreparedStatement ps = conn .prepareStatement("SELECT representeeMID FROM representatives WHERE representerMID=?")) { ps.setLong(1, mid); ResultSet rs = ps.executeQuery(); String role = "Patient"; while (rs.next()) { if (rs.getLong("representeeMID") == patientID) { role = "Personal Health Representative"; break; } } rs.close(); return role; } catch (SQLException e) { throw new DBException(e); } } }
12,134
32.337912
113
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/dao/mysql/WardDAO.java
package edu.ncsu.csc.itrust.model.old.dao.mysql; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; import edu.ncsu.csc.itrust.exception.DBException; import edu.ncsu.csc.itrust.exception.ITrustException; import edu.ncsu.csc.itrust.model.old.beans.HospitalBean; import edu.ncsu.csc.itrust.model.old.beans.PersonnelBean; import edu.ncsu.csc.itrust.model.old.beans.WardBean; import edu.ncsu.csc.itrust.model.old.beans.WardRoomBean; import edu.ncsu.csc.itrust.model.old.beans.loaders.HospitalBeanLoader; import edu.ncsu.csc.itrust.model.old.beans.loaders.PersonnelLoader; import edu.ncsu.csc.itrust.model.old.beans.loaders.WardBeanLoader; import edu.ncsu.csc.itrust.model.old.beans.loaders.WardRoomBeanLoader; import edu.ncsu.csc.itrust.model.old.dao.DAOFactory; /** * Used for managing Wards * * DAO stands for Database Access Object. All DAOs are intended to be * reflections of the database, that is, one DAO per table in the database (most * of the time). For more complex sets of queries, extra DAOs are added. DAOs * can assume that all data has been validated and is correct. * * DAOs should never have setters or any other parameter to the constructor than * a factory. All DAOs should be accessed by DAOFactory (@see * {@link DAOFactory}) and every DAO should have a factory - for obtaining JDBC * connections and/or accessing other DAOs. */ public class WardDAO { private DAOFactory factory; private WardBeanLoader wardLoader = new WardBeanLoader(); private WardRoomBeanLoader wardRoomLoader = new WardRoomBeanLoader(); private PersonnelLoader personnelLoader = new PersonnelLoader(); private HospitalBeanLoader hospitalLoader = new HospitalBeanLoader(); /** * The typical constructor. * * @param factory * The {@link DAOFactory} associated with this DAO, which is used * for obtaining SQL connections, etc. */ public WardDAO(DAOFactory factory) { this.factory = factory; } /** * Returns a list of all wards under a hospital sorted alphabetically * * @param id * The ID of the hospital to get wards from * @return A java.util.List of WardBeans. * @throws DBException */ public List<WardBean> getAllWardsByHospitalID(String id) throws DBException { try (Connection conn = factory.getConnection(); PreparedStatement ps = conn .prepareStatement("SELECT * FROM WARDS WHERE InHospital = ? ORDER BY RequiredSpecialty")) { ps.setString(1, id); ResultSet rs = ps.executeQuery(); List<WardBean> wards = wardLoader.loadList(rs); rs.close(); return wards; } catch (SQLException e) { throw new DBException(e); } } /** * Adds a Ward * * @param ward * The WardBean object to insert. * @return A boolean indicating whether the insertion was successful. * @throws DBException * @throws ITrustException */ public boolean addWard(WardBean ward) throws DBException, ITrustException { try (Connection conn = factory.getConnection(); PreparedStatement ps = conn .prepareStatement("INSERT INTO wards (requiredSpecialty, inHospital) " + "VALUES (?,?)")) { ps.setString(1, ward.getRequiredSpecialty()); ps.setLong(2, ward.getInHospital()); boolean added = ps.executeUpdate() == 1; return added; } catch (SQLException e) { if (e.getErrorCode() == 1062) { throw new ITrustException("Error: Ward already exists."); } else { throw new DBException(e); } } } /** * Updates a particular ward's information. Returns the number of rows * affected (should be 1) * * @param ward * The WardBean to update. * @return An int indicating the number of affected rows. * @throws DBException */ public int updateWard(WardBean ward) throws DBException { try (Connection conn = factory.getConnection(); PreparedStatement ps = conn .prepareStatement("UPDATE wards SET requiredSpecialty=?, InHospital=? " + "WHERE WardID = ?")) { ps.setString(1, ward.getRequiredSpecialty()); ps.setLong(2, ward.getInHospital()); ps.setLong(3, ward.getWardID()); int result = ps.executeUpdate(); return result; } catch (SQLException e) { throw new DBException(e); } } /** * Removes a ward from a hospital. Returns whether or not any changes were * made * * @param id * The WardId of the Ward to remove. * @return A boolean indicating success. * @throws DBException */ public boolean removeWard(long id) throws DBException { try (Connection conn = factory.getConnection(); PreparedStatement ps = conn.prepareStatement("DELETE FROM wards WHERE wardID = ?")) { ps.setLong(1, id); boolean deleted = ps.executeUpdate() == 1; return deleted; } catch (SQLException e) { throw new DBException(e); } } /** * Returns a list of all wardrooms under a ward sorted alphabetically * * @param id * The id of the ward to get all rooms for * @return A java.util.List of all WardRoomBeans in a ward. * @throws DBException */ public List<WardRoomBean> getAllWardRoomsByWardID(long id) throws DBException { try (Connection conn = factory.getConnection(); PreparedStatement ps = conn .prepareStatement("SELECT * FROM wardrooms WHERE inWard = ? ORDER BY roomName")) { ps.setLong(1, id); ResultSet rs = ps.executeQuery(); List<WardRoomBean> wards = wardRoomLoader.loadList(rs); rs.close(); return wards; } catch (SQLException e) { throw new DBException(e); } } /** * Adds a WardRoom * * @param wardRoom * The WardRoomBean object to insert. * @return A boolean indicating whether the insertion was successful. * @throws DBException * @throws ITrustException */ public boolean addWardRoom(WardRoomBean wardRoom) throws DBException, ITrustException { try (Connection conn = factory.getConnection(); PreparedStatement ps = conn .prepareStatement("INSERT INTO wardrooms (InWard, RoomName, Status) " + "VALUES (?,?,?)")) { ps.setLong(1, wardRoom.getInWard()); ps.setString(2, wardRoom.getRoomName()); ps.setString(3, wardRoom.getStatus()); boolean added = ps.executeUpdate() == 1; return added; } catch (SQLException e) { throw e.getErrorCode() == 1062 ? new ITrustException("Error: WardRoom already exists.") : new DBException(e); } } /** * Updates a particular wardroom's information. Returns the number of rows * affected (should be 1) * * @param wardRoom * The WardRoomBean to update. * @return An int indicating the number of affected rows. * @throws DBException */ public int updateWardRoom(WardRoomBean wardRoom) throws DBException { try (Connection conn = factory.getConnection(); PreparedStatement ps = conn.prepareStatement( "UPDATE wardrooms SET InWard=?, RoomName=?, Status=? " + "WHERE RoomID = ?")) { ps.setLong(1, wardRoom.getInWard()); ps.setString(2, wardRoom.getRoomName()); ps.setString(3, wardRoom.getStatus()); ps.setLong(4, wardRoom.getRoomID()); int result = ps.executeUpdate(); return result; } catch (SQLException e) { throw new DBException(e); } } /** * Removes a room from a ward. Returns whether or not any changes were made * * @param id * The RoomId of the Room to remove. * @return A boolean indicating success. * @throws DBException */ public boolean removeWardRoom(long id) throws DBException { try (Connection conn = factory.getConnection(); PreparedStatement ps = conn.prepareStatement("DELETE FROM WardRooms WHERE RoomID = ?")) { ps.setLong(1, id); boolean removed = ps.executeUpdate() == 1; return removed; } catch (SQLException e) { throw new DBException(e); } } /** * Returns a list of all wards assigned to a HCP sorted alphabetically * * @param id * The id of the HCP to get wards for * @return A java.util.List of all WardBeans. * @throws DBException */ public List<WardBean> getAllWardsByHCP(long id) throws DBException { try (Connection conn = factory.getConnection(); PreparedStatement ps = conn.prepareStatement( "SELECT * FROM HCPAssignedToWard haw INNER JOIN Wards w WHERE HCP = ? AND haw.ward = w.wardid ORDER BY RequiredSpecialty")) { ps.setLong(1, id); ResultSet rs = ps.executeQuery(); List<WardBean> wards = wardLoader.loadList(rs); rs.close(); return wards; } catch (SQLException e) { throw new DBException(e); } } /** * Returns a list of all HCPs assigned to a ward sorted alphabetically * * @param id * The id of the ward to get HCPs for * @return A java.util.List of PersonnelBean that represent the HCPs * assigned to a ward. * @throws DBException */ public List<PersonnelBean> getAllHCPsAssignedToWard(long id) throws DBException { try (Connection conn = factory.getConnection(); PreparedStatement ps = conn.prepareStatement( "SELECT * FROM HCPAssignedToWard haw INNER JOIN Personnel p WHERE haw.HCP = p.MID AND WARD = ? ORDER BY lastName")) { ps.setLong(1, id); ResultSet rs = ps.executeQuery(); List<PersonnelBean> assignedHCPs = personnelLoader.loadList(rs); rs.close(); return assignedHCPs; } catch (SQLException e) { throw new DBException(e); } } /** * Assigns an HCP to a the specified ward. * * @param hcpID * The id of the HCP to assign * @param wardID * The ward to assign the HCP to. * @return A boolean whether or not the insert worked correctly. * @throws ITrustException */ public boolean assignHCPToWard(long hcpID, long wardID) throws ITrustException { try (Connection conn = factory.getConnection(); PreparedStatement ps = conn.prepareStatement("INSERT INTO HCPAssignedToWard (HCP, WARD) Values(?,?)")) { ps.setLong(1, hcpID); ps.setLong(2, wardID); boolean assigned = ps.executeUpdate() == 1; return assigned; } catch (SQLException e) { if (e.getErrorCode() == 1062) { throw new ITrustException("Error: HCP or WARD ID don't exist!"); } else { throw new DBException(e); } } } /** * Removes a HCP and Ward association * * @param wardID * The Ward ID of the Ward associated to the HCP. * @param hcpID * The HCP ID of the HCP associated with the Ward. * @return A boolean indicating success. * @throws DBException */ public boolean removeWard(long hcpID, long wardID) throws DBException { try (Connection conn = factory.getConnection(); PreparedStatement ps = conn .prepareStatement("DELETE FROM HCPAssignedToWard WHERE Ward = ? and hcp = ?")) { ps.setLong(1, wardID); ps.setLong(2, hcpID); boolean removed = ps.executeUpdate() == 1; return removed; } catch (SQLException e) { throw new DBException(e); } } /** * Updates a particular wardroom's occupiedBy information. Returns the * number of rows affected (should be 1) * * @param wardRoom * The WardRoomBean to update. * @return An int indicating the number of affected rows. * @throws DBException */ public int updateWardRoomOccupant(WardRoomBean wardRoom) throws DBException { try (Connection conn = factory.getConnection(); PreparedStatement ps = conn .prepareStatement("UPDATE wardRooms SET OccupiedBy=? " + "WHERE RoomID = ?")) { if (wardRoom.getOccupiedBy() == null) { ps.setNull(1, java.sql.Types.BIGINT); } else { ps.setLong(1, wardRoom.getOccupiedBy()); } ps.setLong(2, wardRoom.getRoomID()); int result = ps.executeUpdate(); return result; } catch (SQLException e) { throw new DBException(e); } } /** * Returns a list of all wards with the status specified that the hcp has * access to * * @param status * The Status to search on * @param hcpID * The id of the HCP to get wards for * @return A java.util.List of WardRoomBeans that the specified hcp has * access too. * @throws DBException */ public List<WardRoomBean> getWardRoomsByStatus(String status, Long hcpID) throws DBException { try (Connection conn = factory.getConnection(); PreparedStatement ps = conn.prepareStatement( "SELECT * FROM wardrooms wr inner join hcpassignedtoward hw where wr.status = ? and wr.inward = hw.ward and hw.hcp = ?")) { ps.setString(1, status); ps.setLong(2, hcpID); ResultSet rs = ps.executeQuery(); List<WardRoomBean> wards = wardRoomLoader.loadList(rs); rs.close(); return wards; } catch (SQLException e) { throw new DBException(e); } } /** * Returns a WardRoom specified by the id * * @param wardRoomID * The id of the ward room to get * @return A WardRoomBean with the ID specified * @throws DBException */ public WardRoomBean getWardRoom(String wardRoomID) throws DBException { try (Connection conn = factory.getConnection(); PreparedStatement ps = conn.prepareStatement("SELECT * FROM wardrooms where RoomID = ?")) { ps.setString(1, wardRoomID); ResultSet rs = ps.executeQuery(); WardRoomBean loaded = rs.next() ? wardRoomLoader.loadSingle(rs) : null; rs.close(); return loaded; } catch (SQLException e) { throw new DBException(e); } } /** * Returns a Ward specified by the id * * @param wardID * The id of the ward to get * @return A WardBean with the ID specified * @throws DBException */ public WardBean getWard(String wardID) throws DBException { try (Connection conn = factory.getConnection(); PreparedStatement ps = conn.prepareStatement("SELECT * FROM wards where wardid = ?")) { ps.setString(1, wardID); ResultSet rs = ps.executeQuery(); WardBean ward = rs.next() ? wardLoader.loadSingle(rs) : null; rs.close(); return ward; } catch (SQLException e) { throw new DBException(e); } } /** * Returns the hospital that the specified ward room is located in * * @param wardRoomID * The id of the ward room to get the hospital for * @return The HospitalBean that the specified ward room is located in. * @throws DBException */ public HospitalBean getHospitalByWard(String wardRoomID) throws DBException { try (Connection conn = factory.getConnection(); PreparedStatement ps = conn.prepareStatement( "SELECT * FROM hospitals h inner join wards ward inner join wardrooms room where room.RoomID = ? and room.inward = ward.wardid and ward.inhospital = h.hospitalid")) { ps.setString(1, wardRoomID); ResultSet rs = ps.executeQuery(); HospitalBean hospital = rs.next() ? hospitalLoader.loadSingle(rs) : null; rs.close(); return hospital; } catch (SQLException e) { throw new DBException(e); } } /** * Logs the checkout reason for a patient * * @param mid * The mid of the Patient checking out * @param reason * The reason the patient is being checked out. * @return Whether 1 patient was inserted * @throws ITrustException */ public boolean checkOutPatientReason(long mid, String reason) throws DBException { try (Connection conn = factory.getConnection(); PreparedStatement ps = conn .prepareStatement("INSERT INTO WardRoomCheckout (PID, Reason) Values(?,?)")) { ps.setLong(1, mid); ps.setString(2, reason); boolean logged = ps.executeUpdate() == 1; return logged; } catch (SQLException e) { throw new DBException(e); } } /** * Returns the hospital that the specified user is located in * * @param pid * The id of the user to get the hospital for * @return The HospitalBean that the specified patient is located in. * @throws DBException */ public HospitalBean getHospitalByPatientID(long pid) throws DBException { try (Connection conn = factory.getConnection(); PreparedStatement ps = conn.prepareStatement( "SELECT * FROM hospitals h inner join wards ward inner join wardrooms room where room.OccupiedBy = ? and room.inward = ward.wardid and ward.inhospital = h.hospitalid")) { ps.setLong(1, pid); ResultSet rs = ps.executeQuery(); HospitalBean hospital = rs.next() ? hospitalLoader.loadSingle(rs) : null; rs.close(); return hospital; } catch (SQLException e) { throw new DBException(e); } } }
16,294
32.187373
176
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/dao/mysql/ZipCodeDAO.java
package edu.ncsu.csc.itrust.model.old.dao.mysql; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import edu.ncsu.csc.itrust.exception.DBException; import edu.ncsu.csc.itrust.model.old.beans.ZipCodeBean; import edu.ncsu.csc.itrust.model.old.beans.loaders.ZipCodeLoader; import edu.ncsu.csc.itrust.model.old.dao.DAOFactory; /** * DAO for the Zip Code table */ public class ZipCodeDAO { private DAOFactory factory; public ZipCodeDAO(DAOFactory factory) { this.factory = factory; } /** * Returns the zip code bean for a particular zip code. * * @param zipCode * @return * @throws DBException */ public ZipCodeBean getZipCode(String zipCode) throws DBException { ZipCodeLoader loader = new ZipCodeLoader(); try (Connection conn = factory.getConnection(); PreparedStatement ps = conn.prepareStatement("SELECT * FROM zipcodes WHERE zip=?")) { ps.setString(1, zipCode); ResultSet rs = ps.executeQuery(); ZipCodeBean zipCodeBean = rs.next() ? loader.loadSingle(rs) : null; rs.close(); return zipCodeBean; } catch (SQLException e) { throw new DBException(e); } } }
1,185
25.954545
89
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/enums/BloodType.java
package edu.ncsu.csc.itrust.model.old.enums; /** * All possible blood types * * * */ public enum BloodType { APos("A+"), ANeg("A-"), BPos("B+"), BNeg("B-"), ABPos("AB+"), ABNeg("AB-"), OPos("O+"), ONeg("O-"), NS( "N/S"); private String name; private BloodType(String name) { this.name = name; } public String getName() { return name; } @Override public String toString() { return getName(); } public static BloodType parse(String bloodTypeStr) { for (BloodType type : BloodType.values()) { if (type.getName().equals(bloodTypeStr)) { return type; } } return NS; } }
615
16.111111
104
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/enums/Ethnicity.java
package edu.ncsu.csc.itrust.model.old.enums; /** * All possible ethnicities represented in iTrust. */ public enum Ethnicity { Caucasian("Caucasian"), AfricanAmerican("African American"), Hispanic("Hispanic"), AmericanIndian( "American Indian"), Asian("Asian"), NotSpecified("Not Specified"); private String name; private Ethnicity(String name) { this.name = name; } public String getName() { return name; } @Override public String toString() { return getName(); } public static Ethnicity parse(String input) { for (Ethnicity ethnicity : Ethnicity.values()) { if (ethnicity.name.equals(input)) return ethnicity; } return NotSpecified; } }
678
20.21875
99
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/enums/ExerciseType.java
package edu.ncsu.csc.itrust.model.old.enums; /** * ExerciseType.java Version 1 4/2/2015 Copyright notice: none * * The types of exercise a patient can log. * */ public enum ExerciseType { /** Running, cycling, etc */ Cardio("Cardio"), /** Bench press, curls, etc */ Weights("Weight Training"); private String name; /** * Sets the name of the exercise * * @param name * the name of the exercise */ private ExerciseType(String name) { this.name = name; } /** * Returns the name of the exercise * * @return the name of the exercise */ public String getName() { return name; } /** * Returns the name of the exercise * * @return the name of the exercise */ @Override public String toString() { return getName(); } /** * Tries to parse a string into one of the 2 valid exercise types. Throws an * IllegalArgumentException if the string is not one of the given exercise * types * * @param str * the name of the exercise * @return a ExerciseType with the appropriate name */ public static ExerciseType parse(String str) { for (ExerciseType xt : ExerciseType.values()) { if (xt.name.equals(str)) { return xt; } } throw new IllegalArgumentException("Exercise Type " + str + " does not exist"); } }
1,313
19.215385
77
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/enums/Gender.java
package edu.ncsu.csc.itrust.model.old.enums; /** * Male or Female. Not specified is provided as well, for incomplete forms or patient's discretion. */ public enum Gender { Male("Male"), Female("Female"), NotSpecified("Not Specified"); private String name; private Gender(String name) { this.name = name; } public String getName() { return name; } @Override public String toString() { return getName(); } public static Gender parse(String input) { for (Gender gender : Gender.values()) { if (gender.name.equals(input)) return gender; } return NotSpecified; } }
598
18.322581
100
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/enums/MealType.java
package edu.ncsu.csc.itrust.model.old.enums; /** * MealType.java * Version 1 * 2/21/2015 * Copyright notice: none * * All of the different types of meals that can be entered * into the food diary. */ public enum MealType { /** Meal was eaten for breakfast */ Breakfast("Breakfast"), /** Meal was eaten for lunch */ Lunch("Lunch"), /** Meal was eaten as a snack */ Snack("Snack"), /** Meal was eaten for dinner */ Dinner("Dinner"); private String name; /** * Sets the name of the meal * @param name the name of the meal */ private MealType(String name) { this.name = name; } /** * Returns the name of the meal * @return the name of the meal */ public String getName() { return name; } /** * Returns the name of the meal * @return the name of the meal */ @Override public String toString() { return getName(); } /** * Tries to parse a string into one of the 4 valid meal types. * Throws an illegalargumentexception if the string is not one of the * given meal types * @param str the name of the meal * @return a MealType with the appropriate name */ public static MealType parse(String str) { for (MealType meal : MealType.values()) { if (meal.name.equals(str)) { return meal; } } throw new IllegalArgumentException("Meal Type " + str + " does not exist"); } }
1,362
19.651515
71
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/enums/Role.java
package edu.ncsu.csc.itrust.model.old.enums; /** * The iTrust user roles: Patient, ER, HCP, UAP, LT, PHA, Administrator and Tester. * Consult the requirements for the contextual meanings of these individual choices. */ public enum Role { /**PATIENT*/ PATIENT("patient", "Patients", 0L), /**ER*/ ER("er", "Personnel", 9L), /**HCP*/ HCP("hcp", "Personnel", 9L), /**UAP*/ UAP("uap", "Personnel", 8L), /**LT*/ LT("lt", "Personnel", 5L), /**ADMIN*/ ADMIN("admin", "Personnel", 0L), /**PHA*/ PHA("pha", "Personnel", 7L), /**TESTER*/ TESTER("tester", "", 0L); private String userRolesString; private String dbTable; private long midFirstDigit; /** * Role * @param userRolesString userRolesString * @param dbTable dbTable * @param midFirstDigit midFirstDigit */ Role(String userRolesString, String dbTable, long midFirstDigit) { this.userRolesString = userRolesString; this.dbTable = dbTable; this.midFirstDigit = midFirstDigit; } /** * getDBTable * @return dbTable */ public String getDBTable() { return dbTable; } /** * getUserRolesString * @return userRolesString */ public String getUserRolesString() { return userRolesString; } /** * getMidFirstDigit * @return midFirstDigit */ public long getMidFirstDigit() { return midFirstDigit; } /** * parse * @param str str * @return role */ public static Role parse(String str) { for (Role role : values()) { if (role.userRolesString.toLowerCase().equals(str.toLowerCase())) return role; } throw new IllegalArgumentException("Role " + str + " does not exist"); } }
1,612
19.679487
84
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/enums/SleepType.java
package edu.ncsu.csc.itrust.model.old.enums; /** * SleepType.java Version 1 4/6/2015 Copyright notice: none * * The types of sleep a patient can log. */ public enum SleepType { Nightly("Nightly"), Nap("Nap"); private String name; /** * Sets the name of the sleep * * @param name * the name of the sleep */ private SleepType(String name) { this.name = name; } /** * Returns the name of the sleep * * @return the name of the sleep */ public String getName() { return name; } /** * Returns the name of the sleep * * @return the name of the sleep */ @Override public String toString() { return getName(); } /** * Tries to parse a string into one of the 2 valid sleep types. Throws an * IllegalArgumentException if the string is not one of the given sleep * types * * @param str * the name of the sleep * @return a SleepType with the appropriate name */ public static SleepType parse(String str) { for (SleepType xt : SleepType.values()) { if (xt.name.equals(str)) { return xt; } } throw new IllegalArgumentException("Sleep Type " + str + " does not exist"); } }
1,180
17.746032
74
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/enums/SortDirection.java
package edu.ncsu.csc.itrust.model.old.enums; /** * Sorting direction. Used to dynamically build SQL queries. */ public enum SortDirection { ASCENDING("ASC"), DESCENDING("DESC"); private String dirString; SortDirection(String dirString) { this.dirString = dirString; } @Override public String toString() { return dirString; } public static SortDirection parse(String str) { for (SortDirection sort : values()) { if (sort.dirString.toLowerCase().equals(str.toLowerCase())) return sort; } if (str.toLowerCase().equals("ascending")) { return ASCENDING; } if (str.toLowerCase().equals("descending")) { return DESCENDING; } throw new IllegalArgumentException("SortDirection " + str + " does not exist"); } }
753
20.542857
81
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/enums/State.java
package edu.ncsu.csc.itrust.model.old.enums; /** * All of our wonderful states. * * * */ public enum State { AL("Alabama"), AK("Alaska"), AZ("Arizona"), AR("Arkansas"), CA("California"), CO("Colorado"), CT( "Connecticut"), DE("Delaware"), DC("District of Columbia"), FL("Florida"), GA("Georgia"), HI( "Hawaii"), ID("Idaho"), IL("Illinois"), IN("Indiana"), IA("Iowa"), KS("Kansas"), KY("Kentucky"), LA( "Louisiana"), ME("Maine"), MD("Maryland"), MA("Massachusetts"), MI("Michigan"), MN("Minnesota"), MS( "Mississippi"), MO("Missouri"), MT("Montana"), NE("Nebraska"), NV("Nevada"), NH("New Hampshire"), NJ( "New Jersey"), NM("New Mexico"), NY("New York"), NC("North Carolina"), ND("North Dakota"), OH( "Ohio"), OK("Oklahoma"), OR("Oregon"), PA("Pennsylvania"), RI("Rhode Island"), SC( "South Carolina"), SD("South Dakota"), TN("Tennessee"), TX("Texas"), UT("Utah"), VT("Vermont"), VA( "Virginia"), WA("Washington"), WV("West Virginia"), WI("Wisconsin"), WY("Wyoming"); private String name; private State(String name) { this.name = name; } public String getName() { return name; } public String getAbbrev() { return toString(); } // Just to show that this is intentional @Override public String toString() { return super.toString(); } public static State parse(String state) { State[] values = State.values(); for (State myState : values) { if (myState.getName().equals(state) || myState.getAbbrev().equals(state)) return myState; } return State.NC; } }
1,527
30.833333
104
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/enums/TransactionType.java
package edu.ncsu.csc.itrust.model.old.enums; /** * All of the possible transaction types, in no particular order, used in producing the operational profile. * TransactionCode -- identification code * Description -- basic description of the event * ActionPhrase -- a patient-centered English sentence describing the action (used in activity feeds) * PatientViewable -- boolean for if the action will be displayed in the patient activity feed */ public enum TransactionType { /**LOGIN_FAILURE*/ LOGIN_FAILURE(1, "Failed login", "tried to authenticate unsuccessfully", true), /**HOME_VIEW*/ HOME_VIEW(10, "User views homepage", "has viewed the iTrust user homepage", false), /**UNCAUGHT_EXCEPTION*/ UNCAUGHT_EXCEPTION(20, "Exception occured and was not caught", "caused an unhandled exception", false), /**GLOBAL_PREFERENCES_VIEW*/ GLOBAL_PREFERENCES_VIEW(30, "View global preferences", "viewed global preferences for iTrust", false), /**GLOBAL_PREFERENCES_EDIT*/ GLOBAL_PREFERENCES_EDIT(31, "Edit global preferences", "edited global preferences for iTrust", false), /**USER_PREFERENCES_VIEW*/ USER_PREFERENCES_VIEW(32, "View preferences", "viewed user preferences", false), /**USER_PREFERENCES_EDIT*/ USER_PREFERENCES_EDIT(33, "Edit peferences", "edited user preferences", false), /**PATIENT_CREATE*/ PATIENT_CREATE(100, "Create a patient", "created your account", true), /**PATIENT_DISABLE*/ PATIENT_DISABLE(101, "Disable a patient", "disabled your account", true), /**PATIENT_DEACTIVATE*/ PATIENT_DEACTIVATE(102, "Deactivate a patient", "deactivated your account", true), /**PATIENT_ACTIVATE*/ PATIENT_ACTIVATE(103, "Activate a patient", "activated your account", true), /**LHCP_CREATE*/ LHCP_CREATE(200, "Create a LHCP", "created an LHCP", false), /**LHCP_EDIT*/ LHCP_EDIT(201, "Edit LHCP information", "edited LHCP information", false), /**LHCP_DISABLE*/ LHCP_DISABLE(202, "Disable a LHCP", "disbaled an LHCP", false), /**ER_CREATE*/ ER_CREATE(210, "Create an ER", "created an ER", false), /**ER_EDIT*/ ER_EDIT(211, "Edit ER information", "edited ER information", false), /**ER_DISABLE*/ ER_DISABLE(212, "Disable an ER", "disabled an ER", false), /**PHA_CREATE*/ PHA_CREATE(220, "Create a PHA", "created a PHA", false), /**PHA_EDIT*/ PHA_EDIT(221, "Edit PHA information", "edited PHA information", false), /**PHA_DISABLE*/ PHA_DISABLE(222, "Disable a PHA", "disabled a PHA", false), /**LHCP_ASSIGN_HOSPITAL*/ LHCP_ASSIGN_HOSPITAL(230, "Assign LHCP to a hospital", "assigned an LHCP to a hospital", false), /**LHCP_REMOVE_HOSPITAL*/ LHCP_REMOVE_HOSPITAL(231, "Unassign LHCP from a hospital", "unassigned an LHCP from a hospital", false), /**LT_ASSIGN_HOSPITAL*/ LT_ASSIGN_HOSPITAL(232, "Assign LT to a hospital", "assigned an LT to a hospital", false), /**LT_REMOVE_HOSPITAL*/ LT_REMOVE_HOSPITAL(233, "Unassign LT from a hospital", "unassigned an LT from a hospital", false), /**UAP_CREATE*/ UAP_CREATE(240, "Create a UAP", "created a UAP", false), /**UAP_EDIT*/ UAP_EDIT(241, "Edit a UAP", "edited a UAP", false), /**UAP_DISABLE*/ UAP_DISABLE(242, "Disable a UAP", "disabled a UAP", false), /**PERSONNEL_VIEW*/ PERSONNEL_VIEW(250, "View a personnel's information", "viewed a personnel member's information", false), /**LT_CREATE*/ LT_CREATE(260, "Create a LT", "created an LT", false), /**LT_EDIT*/ LT_EDIT(261, "Edit LT information", "edited LT information", false), /**LT_DISABLE*/ LT_DISABLE(262, "Disable a LT", "disabled an LT", false), /**LOGIN_SUCCESS*/ LOGIN_SUCCESS(300, "Login Succeded", "successfully authenticated", true), /**LOGOUT*/ LOGOUT(301, "Logged out", "logged out of iTrust", true), /**LOGOUT_INACTIVE*/ LOGOUT_INACTIVE(302, "Logged out from inactivity", "logged out due to inactivity", true), /**PASSWORD_RESET*/ PASSWORD_RESET(310, "Password changed", "changed your iTrust password", true), /**DEMOGRAPHICS_VIEW*/ DEMOGRAPHICS_VIEW(400, "View patient demographics", "viewed your demographics", true), /**DEMOGRAPHICS_EDIT*/ //Set to false as per the requirements page for UC43 as it is not supposed to be shown for LHCP or DLHCP DEMOGRAPHICS_EDIT(410, "Edit patient demographics", "edited your demographics", false), /**PATIENT_PHOTO_UPLOAD*/ PATIENT_PHOTO_UPLOAD(411, "Upload patient photo", "uploaded a photo of you to your record", false), /**PATIENT_PHOTO_REMOVE*/ PATIENT_PHOTO_REMOVE(412, "Remove patient photo", "removed your photograph from your record", false), /**DEPEND_DEMOGRAPHICS_EDIT*/ DEPEND_DEMOGRAPHICS_EDIT(421, "Edit dependent demographics", "edited dependent's demographics", true), /**LHCP_VIEW*/ LHCP_VIEW(600, "View LHCP information", "viewed LHCP information", false), /**LHCP_DECLARE_DLHCP*/ LHCP_DECLARE_DLHCP(601, "Declare LHCP as DLHCP", "declared a LHCP", true), /**LHCP_UNDECLARE_DLHCP*/ LHCP_UNDECLARE_DLHCP(602, "Undeclare LHCP as DLHCP", "undeclared an LHCP", true), /**ACCESS_LOG_VIEW*/ ACCESS_LOG_VIEW(800, "View access log", "viewed your access log", false), /**MEDICAL_RECORD_VIEW*/ MEDICAL_RECORD_VIEW(900, "View medical records", "viewed your medical records", true), /**PATIENT_HEALTH_INFORMATION_VIEW*/ PATIENT_HEALTH_INFORMATION_VIEW(1000, "View personal health information", "viewed your basic health information", true), /**PATIENT_HEALTH_INFORMATION_EDIT*/ PATIENT_HEALTH_INFORMATION_EDIT(1001, "Enter/edit personal health information", "edited your basic health information", true), /**BASIC_HEALTH_CHARTS_VIEW*/ BASIC_HEALTH_CHARTS_VIEW(1002, "View Basic Health Charts", "viewed you basic health information charts", true), /**OFFICE_VISIT_CREATE*/ OFFICE_VISIT_CREATE(1100, "Create Office Visits", "created an office visit", true), /**OFFICE_VISIT_VIEW*/ OFFICE_VISIT_VIEW(1101, "View Office Visits", "viewed your office visit", true), /**OFFICE_VISIT_EDIT*/ OFFICE_VISIT_EDIT(1102, "Edit Office Visits", "edited your office visit", true), /**PRESCRIPTION_ADD*/ PRESCRIPTION_ADD(1110, "Add Prescription", "Added a prescription to your office visit", true), /**PRESCRIPTION_EDIT*/ PRESCRIPTION_EDIT(1111, "Edit Prescription", "Edited a prescription in your office visit", true), /**PRESCRIPTION_REMOVE*/ PRESCRIPTION_REMOVE(1112, "Remove Prescription", "Removed a prescription from your office visit", true), /**LAB_PROCEDURE_ADD*/ LAB_PROCEDURE_ADD(1120, "Add Lab Procedure", "Added a lab procedure to your office visit", true), /**LAB_PROCEDURE_EDIT*/ LAB_PROCEDURE_EDIT(1121, "Edit Lab Procedure", "Edited a lab procedure in your office visit", true), /**LAB_PROCEDURE_REMOVE*/ LAB_PROCEDURE_REMOVE(1122, "Remove Lab Procedure", "Removed a lab procedure from your office visit", true), /**DIAGNOSIS_ADD*/ DIAGNOSIS_ADD(1130, "Add Diagnosis", "Added a diagnosis to your office visit", true), /**DIAGNOSIS_REMOVE*/ DIAGNOSIS_REMOVE(1132, "Remove Diagnosis", "Removed a diagnosis from your office visit", true), /**DIAGNOSIS_URL_EDIT*/ DIAGNOSIS_URL_EDIT(1133, "Edit Diagnosis URL", "Diagnosis URL was edited", true), /**PROCEDURE_ADD*/ PROCEDURE_ADD(1140, "Add Procedure", "Added a procedure to your office visit", true), /**PROCEDURE_EDIT*/ PROCEDURE_EDIT(1141, "Edit Procedure", "Edited a procedure in your office visit", true), /**PROCEDURE_REMOVE*/ PROCEDURE_REMOVE(1142, "Remove Procedure", "Removed a procedure from your office visit", true), /**IMMUNIZATION_ADD*/ IMMUNIZATION_ADD(1150, "Add Immunization", "Added an immunization to your office visit", true), /**IMMUNIZATION_REMOVE*/ IMMUNIZATION_REMOVE(1152, "Remove Immunization", "Removed an immunization from your office visit", true), /**OFFICE_VISIT_BILLED*/ OFFICE_VISIT_BILLED(1160, "Office Visit Billed", "Billed an office visit", false), /**OPERATIONAL_PROFILE_VIEW*/ OPERATIONAL_PROFILE_VIEW(1200, "View Operational Profile", "viewed the operational profile", false), /**HEALTH_REPRESENTATIVE_DECLARE*/ HEALTH_REPRESENTATIVE_DECLARE(1300, "Declare personal health representative", "declared a personal health representative", true), /**HEALTH_REPRESENTATIVE_UNDECLARE*/ HEALTH_REPRESENTATIVE_UNDECLARE(1301, "Undeclare personal health representative", "undeclared a personal health representative", true), /**MEDICAL_PROCEDURE_CODE_ADD*/ MEDICAL_PROCEDURE_CODE_ADD(1500, "Add Medical procedure code", "added a medical procedure code", false), /**MEDICAL_PROCEDURE_CODE_VIEW*/ MEDICAL_PROCEDURE_CODE_VIEW(1501, "View Medical procedure code", "viewed a medical procedure code", false), /**MEDICAL_PROCEDURE_CODE_EDIT*/ MEDICAL_PROCEDURE_CODE_EDIT(1502, "Edit Medical procedure code", "edited a medical procedure code", false), /**IMMUNIZATION_CODE_ADD*/ IMMUNIZATION_CODE_ADD(1510, "Add Immunization code", "added an immunization code", false), /**IMMUNIZATION_CODE_VIEW*/ IMMUNIZATION_CODE_VIEW(1511, "View Immunization code", "viewed an immunization code", false), /**IMMUNIZATION_CODE_EDIT*/ IMMUNIZATION_CODE_EDIT(1512, "Edit Immunization code", "edited an immunization code", false), /**DIAGNOSIS_CODE_ADD*/ DIAGNOSIS_CODE_ADD(1520, "Add Diagnosis code", "added a diagnosis code", false), /**DIAGNOSIS_CODE_VIEW*/ DIAGNOSIS_CODE_VIEW(1521, "View Diagnosis code", "viewed a diagnosis code", false), /**DIAGNOSIS_CODE_EDIT*/ DIAGNOSIS_CODE_EDIT(1522, "Edit Diagnosis code", "edited a diagnosis code", false), /**DRUG_CODE_ADD*/ DRUG_CODE_ADD(1530, "Add Drug code", "added a drug code", false), /**DRUG_CODE_VIEW*/ DRUG_CODE_VIEW(1531, "View Drug code", "viewed a drug code", false), /**DRUG_CODE_EDIT*/ DRUG_CODE_EDIT(1532, "Edit Drug code", "edited a drug code", false), /**DRUG_CODE_REMOVE*/ DRUG_CODE_REMOVE(1533, "Remove Drug code", "removed a drug code", false), /**LOINC_CODE_ADD*/ LOINC_CODE_ADD(1540, "Add Physical Services code", "added a physical service code", false), /**LOINC_CODE_VIEW*/ LOINC_CODE_VIEW(1541, "View Physical Services code", "viewed a physical service code", false), /**LOINC_CODE_EDIT*/ LOINC_CODE_EDIT(1542, "Edit Physical Services code", "edited a physical service code", false), /**LOINC_CODE_FILE_ADD*/ LOINC_CODE_FILE_ADD(1549, "Upload Physical Services file", "uploaded a LOINC file", false), /**RISK_FACTOR_VIEW*/ RISK_FACTOR_VIEW(1600, "View risk factors", "viewed your risk factors", true), /**PATIENT_REMINDERS_VIEW*/ PATIENT_REMINDERS_VIEW(1700, "Proactively determine necessary patient care", "proactively determined your necessary patient care", true), /**HOSPITAL_LISTING_ADD*/ HOSPITAL_LISTING_ADD(1800, "Add a hospital listing", "added a hospital listing", false), /**HOSPITAL_LISTING_VIEW*/ HOSPITAL_LISTING_VIEW(1801, "View a hospital listing", "viewed a hospital listing", false), /**HOSPITAL_LISTING_EDIT*/ HOSPITAL_LISTING_EDIT(1802, "Edit a hospital listing", "edited a hospital listing", false), /**PRESCRIPTION_REPORT_VIEW*/ PRESCRIPTION_REPORT_VIEW(1900, "View prescription report", "viewed your prescription report", true), /**DEATH_TRENDS_VIEW*/ DEATH_TRENDS_VIEW(2000, "View Cause of Death Trends", "viewed cause of death trends", false), /**EMERGENCY_REPORT_CREATE*/ EMERGENCY_REPORT_CREATE(2100, "Create emergency report", "created an emergency report for you", true), /**EMERGENCY_REPORT_VIEW*/ EMERGENCY_REPORT_VIEW(2101, "View emergency report", "viewed your emergency report", true), /**APPOINTMENT_TYPE_ADD*/ APPOINTMENT_TYPE_ADD(2200, "Add appointment type listing", "added an appointment type", false), /**APPOINTMENT_TYPE_VIEW*/ APPOINTMENT_TYPE_VIEW(2201, "View appointment type listing", "viewed an appointment type", false), /**APPOINTMENT_TYPE_EDIT*/ APPOINTMENT_TYPE_EDIT(2202, "Edit appointment type listing", "edited an appointment type", false), /**APPOINTMENT_ADD*/ APPOINTMENT_ADD(2210, "Schedule Appointments", "scheduled an appointment with you", true), /**APPOINTMENT_VIEW*/ APPOINTMENT_VIEW(2211, "View Scheduled Appointment", "viewed your scheduled appointment", true), /**APPOINTMENT_EDIT*/ APPOINTMENT_EDIT(2212, "Edit Scheduled Appointment", "edited your scheduled appointment", true), /**APPOINTMENT_REMOVE*/ APPOINTMENT_REMOVE(2213, "Delete Scheduled Appointment", "canceled your scheduled appointment", true), /**APPOINTMENT_ALL_VIEW*/ APPOINTMENT_ALL_VIEW(2220, "View All Scheduled Appointments", "viewed all scheduled appointments", true), /**APPOINTMENT_CONFLICT_OVERRIDE*/ APPOINTMENT_CONFLICT_OVERRIDE(2230, "Schedule conflict override", "overrided a schedule conflict", true), /**APPOINTMENT_REQUEST_SUBMITTED*/ APPOINTMENT_REQUEST_SUBMITTED(2240, "Appointment request submitted", "requested an appointment", true), /**APPOINTMENT_REQUEST_APPROVED*/ APPOINTMENT_REQUEST_APPROVED(2250, "Appointment request approved", "approved an appointment request", true), /**APPOINTMENT_REQUEST_REJECTED*/ APPOINTMENT_REQUEST_REJECTED(2251, "Appointment request rejected", "rejected an appointment request", true), /**APPOINTMENT_REQUEST_VIEW*/ APPOINTMENT_REQUEST_VIEW(2260, "View All Appointment Requests", "viewed all appointment requests", true), /**COMPREHENSIVE_REPORT_VIEW*/ COMPREHENSIVE_REPORT_VIEW(2300, "Comprehensive Report", "viewed your comprehensive report", true), /**COMPREHENSIVE_REPORT_ADD*/ COMPREHENSIVE_REPORT_ADD(2301, "Request Comprehensive Report", "requested a comprehensive report for you", true), /**SATISFACTION_SURVEY_TAKE*/ SATISFACTION_SURVEY_TAKE(2400, "Take Satisfaction Survey", "completed a satisfaction survey", true), /**SATISFACTION_SURVEY_VIEW*/ SATISFACTION_SURVEY_VIEW(2500, "View physician satisfaction results", "viewed physician satisfaction survey results", false), /**LAB_RESULTS_UNASSIGNED*/ LAB_RESULTS_UNASSIGNED(2600, "Unassigned lab results log value", "", false), /**LAB_RESULTS_CREATE*/ LAB_RESULTS_CREATE(2601, "Create laboratory procedure", "created your lab procedure", true), /**LAB_RESULTS_VIEW*/ LAB_RESULTS_VIEW(2602, "View laboratory procedure results", "viewed your lab procedure results", true), /**LAB_RESULTS_REASSIGN*/ LAB_RESULTS_REASSIGN(2603, "Reassign laboratory test to a new lab technician", "assigned your laboratory test to a new lab tech", false), /**LAB_RESULTS_REMOVE*/ LAB_RESULTS_REMOVE(2604, "Remove a laboratory procedure", "removed your lab procedure", true), /**LAB_RESULTS_ADD_COMMENTARY*/ LAB_RESULTS_ADD_COMMENTARY(2605, "Add commentary to a laboratory procedure", "marked a lab procedure as completed", true), /**LAB_RESULTS_VIEW_QUEUE*/ LAB_RESULTS_VIEW_QUEUE(2606, "View laboratory procedure queue", "viewed your lab procedure queue", false), /**LAB_RESULTS_RECORD*/ LAB_RESULTS_RECORD(2607, "Record laboratory test results", "recorded your lab procedure results", false), /**LAB_RESULTS_RECEIVED*/ LAB_RESULTS_RECEIVED(2608, "Laboratory procedure received by lab technician", "the lab tech received your lab procedure", false), /**EMAIL_SEND*/ EMAIL_SEND(2700, "Send an email", "sent an email", false), /**EMAIL_HISTORY_VIEW*/ EMAIL_HISTORY_VIEW(2710, "View email history", "viewed email history", false), /**PATIENT_LIST_VIEW*/ PATIENT_LIST_VIEW(2800, "View patient list", "viewed his/her patient list", false), /**EXPERIENCED_LHCP_FIND*/ EXPERIENCED_LHCP_FIND(2900, "Find LHCPs with experience with a diagnosis", "found LHCPs with experience with a diagnosis", false), /**MESSAGE_SEND*/ MESSAGE_SEND(3000, "Send messages", "sent a message", false), /**MESSAGE_VIEW*/ MESSAGE_VIEW(3001, "View messages", "viewed a message", false), /**INBOX_VIEW*/ INBOX_VIEW(3010, "View inbox", "viewed message inbox", false), /**OUTBOX_VIEW*/ OUTBOX_VIEW(3011, "View outbox", "viewed message outbox", false), /**PATIENT_FIND_LHCP_FOR_RENEWAL*/ PATIENT_FIND_LHCP_FOR_RENEWAL(3100, "Find LHCPs for prescription renewal", "found LHCPs for prescription renewal", true), /**EXPIRED_PRESCRIPTION_VIEW*/ EXPIRED_PRESCRIPTION_VIEW(3110, "View expired prescriptions", "viewed your expired prescriptions", true), /**PRECONFIRM_PRESCRIPTION_RENEWAL*/ PRECONFIRM_PRESCRIPTION_RENEWAL(3200, "Proactively confirm prescription-renewal needs", "proactively confirmed your prescription renewal needs", true), /**DIAGNOSES_LIST_VIEW*/ DIAGNOSES_LIST_VIEW(3210, "View list of diagnoses", "viewed a list of diagnosis", false), /**CONSULTATION_REFERRAL_CREATE*/ CONSULTATION_REFERRAL_CREATE(3300, "Refer a patient for consultations", "referred you to another HCP", true), /**CONSULTATION_REFERRAL_VIEW*/ CONSULTATION_REFERRAL_VIEW(3310, "View referral for consultation", "viewed your consultation referral", true), /**CONSULTATION_REFERRAL_EDIT*/ CONSULTATION_REFERRAL_EDIT(3311, "Modify referral for consultation", "modified your consultation referral", true), /**CONSULTATION_REFERRAL_CANCEL*/ CONSULTATION_REFERRAL_CANCEL(3312, "Cancel referral for consultation", "canceled your consultation referral", true), /**PATIENT_LIST_ADD*/ PATIENT_LIST_ADD(3400, "Patient added to monitoring list", "added you to the telemedicine monitoring list", true), /**PATIENT_LIST_EDIT*/ PATIENT_LIST_EDIT(3401, "Patient telemedicine permissions changed", "changed the data you report for telemedicine monitoring", true), /**PATIENT_LIST_REMOVE*/ PATIENT_LIST_REMOVE(3402, "Patient removed from monitoring list", "removed you from the telemedicine monitoring list", true), /**TELEMEDICINE_DATA_REPORT*/ TELEMEDICINE_DATA_REPORT(3410, "Remote monitoring levels are reported", "reported your telemedicine data", true), /**TELEMEDICINE_DATA_VIEW*/ TELEMEDICINE_DATA_VIEW(3420, "Remote monitoring levels are viewed", "viewed your telemedicine data reports", true), /**ADVERSE_EVENT_REPORT*/ ADVERSE_EVENT_REPORT(3500, "Adverse event reporting", "reported an adverse event", true), /**ADVERSE_EVENT_VIEW*/ ADVERSE_EVENT_VIEW(3600, "Adverse event monitoring", "reviewed an adverse event report", false), /**ADVERSE_EVENT_REMOVE*/ ADVERSE_EVENT_REMOVE(3601, "Remove adverse event", "removed an adverse event report", false), /**ADVERSE_EVENT_REQUEST_MORE*/ ADVERSE_EVENT_REQUEST_MORE(3602, "Request More Adverse Event Details", "requested more adverse event details", false), /**ADVERSE_EVENT_CHART_VIEW*/ ADVERSE_EVENT_CHART_VIEW(3603, "View Adverse Event Chart", "viewed adverse event chart", false), /**OVERRIDE_INTERACTION_WARNING*/ OVERRIDE_INTERACTION_WARNING(3700, "Override interaction warning", "Overrode an interaction warning", true), /**OVERRIDE_CODE_ADD*/ OVERRIDE_CODE_ADD(3710, "Add overriding reason listing", "added a medication override reason", false), /**OVERRIDE_CODE_EDIT*/ OVERRIDE_CODE_EDIT(3711, "Edit overriding reason listing", "edited a medication override reason", false), /**DRUG_INTERACTION_ADD*/ DRUG_INTERACTION_ADD(3800, "Add Drug Interactions Code", "added a drug interaction code", false), /**DRUG_INTERACTION_EDIT*/ DRUG_INTERACTION_EDIT(3801, "Edit Drug Interactions Code", "edited a drug interaction code", false), /**DRUG_INTERACTION_DELETE*/ DRUG_INTERACTION_DELETE(3802, "Delete Drug Interactions Code", "deleted a drug interaction code", false), /**CALENDAR_VIEW*/ CALENDAR_VIEW(4000, "View calendar", "viewed your calendar", false), /**UPCOMING_APPOINTMENTS_VIEW*/ UPCOMING_APPOINTMENTS_VIEW(4010, "View Upcoming Appointments", "viewed upcoming appointments", false), /**NOTIFICATIONS_VIEW*/ NOTIFICATIONS_VIEW(4200, "View Notifications", "viewed your notification center", false), /**ACTIVITY_FEED_VIEW*/ ACTIVITY_FEED_VIEW(4300, "View activity feed", "viewed your activity feed", false), /**PATIENT_INSTRUCTIONS_ADD*/ PATIENT_INSTRUCTIONS_ADD(4400, "Add Patient Specific Instructions for Office Visit", "added a patient-specific instruction", true), /**PATIENT_INSTRUCTIONS_EDIT*/ PATIENT_INSTRUCTIONS_EDIT(4401, "Edit Patient Specific Instructions for Office Visit", "edited a patient-specific instruction", true), /**PATIENT_INSTRUCTIONS_DELETE*/ PATIENT_INSTRUCTIONS_DELETE(4402, " Delete Patient Specific Instructions for Office Visit", "deleted a patient-specific instruction", true), /**PATIENT_INSTRUCTIONS_VIEW*/ PATIENT_INSTRUCTIONS_VIEW(4403, " View Patient Specific Instructions", "viewed your patient-specific instructions", true), /**DIAGNOSIS_TRENDS_VIEW*/ DIAGNOSIS_TRENDS_VIEW(4500, "View diagnosis statistics", "viewed your diagnosis count", false), /**DIAGNOSIS_EPIDEMICS_VIEW*/ DIAGNOSIS_EPIDEMICS_VIEW(4600, "View Epidemic Detection", "viewed epidemic detection", false), /**GROUP_REPORT_VIEW*/ GROUP_REPORT_VIEW(4601, "View Group Report", "viewed group report", false), /**FIND_EXPERT*/ FIND_EXPERT(4700, "Find an Expert", "searched for experts", true), /**FIND_EXPERT_ZIP_ERROR*/ FIND_EXPERT_ZIP_ERROR(4701, "Find an Expert - Zip Code Error", "entered an incorrect ZIP code for Find an Expert", true), /**PATIENT_ASSIGNED_TO_ROOM*/ PATIENT_ASSIGNED_TO_ROOM(4800, "Patient Assigned", "Patient assigned to room", false), /**PATIENT_REMOVED_FROM_ROOM*/ PATIENT_REMOVED_FROM_ROOM(4801, "Patient Removed", "Patient removed from room", false), /**ROOMS_FULL*/ ROOMS_FULL(4802, "Rooms Full", "Patients cannot be assigned to any room meeting that criteria", false), /**CREATE_BASIC_HEALTH_METRICS*/ CREATE_BASIC_HEALTH_METRICS(5100, "Create Basic Health Metrics", "created a basic health metrics record for you", true), /**VIEW_BASIC_HEALTH_METRICS*/ VIEW_BASIC_HEALTH_METRICS(5101, "View Basic Health Metrics", "viewed your basic health metrics", true), /**EDIT_BASIC_HEALTH_METRICS*/ EDIT_BASIC_HEALTH_METRICS(5102, "Edit Basic Health Metrics", "editted your basic health metrics", true), /**REMOVE_BASIC_HEALTH_METRICS*/ REMOVE_BASIC_HEALTH_METRICS(5103, "Remove Basic Health Metrics", "removed a basic health metrics record from your office visit", true), /**PATIENT_VIEW_BASIC_HEALTH_METRICS*/ PATIENT_VIEW_BASIC_HEALTH_METRICS(5200, "Patient View of Basic Health Metrics", "viewed your health records history", true), /**HCP_VIEW_BASIC_HEALTH_METRICSc*/ HCP_VIEW_BASIC_HEALTH_METRICS(5201, "HCP View of Basic Health Metrics", "viewed your health records history", true), /**HCP_VIEW_PERCENTILES_CHART*/ HCP_VIEW_PERCENTILES_CHART(5301, "HCP View of Basic Health Metric Percentiles", "viewed your percentile data.", true), /**PATIENT_VIEW_PERCENTILES_CHART*/ PATIENT_VIEW_PERCENTILES_CHART(5300, "Pateint View of Basic Health Metric Percentiles", "viewed your percentile data.", true), /**ADMIN_UPLOAD_CDCMETRICS*/ ADMIN_UPLOAD_CDCMETRICS(5302, "Admin upload of CDC Metrics", "Uploaded CDC Metrics Successfully", false), /**PASSWORD_CHANGE*/ PASSWORD_CHANGE(5700, "User Successful Password Change", " changed password", false), /**PASSWORD_CHANGE_FAILED*/ PASSWORD_CHANGE_FAILED(5701, "User Failed Password Change", " failed to change password", false), /**IMMUNIZATION_REPORT_PATIENT_VIEW*/ IMMUNIZATION_REPORT_PATIENT_VIEW(5500, "Patient View of Immunization Report", " viewed their immunization report", true), /**IMMUNIZATION_REPORT_HCP_VIEW*/ IMMUNIZATION_REPORT_HCP_VIEW(5501, "HCP View of Immunization Report", " viewed patient's immunization report", true), /**PATIENT_RELEASE_HEALTH_RECORDS*/ PATIENT_RELEASE_HEALTH_RECORDS(5600, "Patient Release of Health Records", "requested the release of your health records", true), /**PATIENT_VIEW_RELEASE_REQUEST*/ PATIENT_VIEW_RELEASE_REQUEST(5601, "Patient View of Health Records Release", "viewed a records release request", true), /**HCP_RELEASE_APPROVAL*/ HCP_RELEASE_APPROVAL(5602, "HCP Approval of Health Records Release", "approved your health records release request", true), /**HCP_RELEASE_DENIAL*/ HCP_RELEASE_DENIAL(5603, "HCP Denial of Health Records Release", "denied your health records release request", true), /**UAP_RELEASE_APPROVAL*/ UAP_RELEASE_APPROVAL(5604, "UAP Approval of Health Records Release", "approved your health records release request", true), /**UAP_RELEASE_DENIAL*/ UAP_RELEASE_DENIAL(5605, "UAP Denial of Health Records Release", "denied your health records release request", true), /**HCP_CREATED_DEPENDENT_PATIENT*/ HCP_CREATED_DEPENDENT_PATIENT(5800, "HCP Create Dependent Patient", "created your account as a dependent user", true), /**HCP_CHANGE_PATIENT_DEPENDENCY*/ HCP_CHANGE_PATIENT_DEPENDENCY(5801, "HCP Change Patient Dependency Status", "changed your dependency status", true), /**PATIENT_VIEW_DEPENDENT_REQUESTS*/ PATIENT_VIEW_DEPENDENT_REQUESTS(5900, "Patient View of Dependent's Release Requests", "viewed a dependent's records release request", true), /**PATIENT_REQUEST_DEPEDENT_RECORDS*/ PATIENT_REQUEST_DEPEDENT_RECORDS(5901, "Patient Requests Dependent's Records Release", "requested a dependent's records release", true), /**PATIENT_VIEWS_BILLS*/ PATIENT_BILLS_VIEW_ALL(6000, "Patient has viewed their list of bills", "viewed list of bills", true), /**PATIENT_VIEWS_BILL*/ PATIENT_VIEWS_BILL(6001, "Patient has view a single bill", "viewed single bill", true), /**PATIENT_PAYS_BILL*/ PATIENT_PAYS_BILL(6002, "Patient has paid a bill", "paid a bill", true), /**PATIENT_SUBMITS_INSURANCE*/ PATIENT_SUBMITS_INSURANCE(6003, "Patient has sumbitted an insurance claim", "submitted insurance claim", true), /**UAP_INITIAL_APPROVAL*/ UAP_INITIAL_APPROVAL(6004, "UAP approves the patient's first insurance claim", "approved initial claim", true), /**UAP_INITIAL_DENIAL*/ UAP_INITIAL_DENIAL(6005, "UAP denies the patient's first insurance claim", "denied initial claim", true), /**UAP_SECOND_APPORVAL*/ UAP_SECOND_APPROVAL(6006, "UAP approves the patient's second insurance claim", "approved second claim", true), /**UAP_SECOND_DENIAL*/ UAP_SECOND_DENIAL(6007, "UAP denies the patient's second insurance claim", "denied second claim", true), /**PATIENT_RESUBITS_INSURANCE*/ PATIENT_RESUBMITS_INSURANCE(6008, "Patient submits a second insurance claim", "submitted second insurnace claim", true), /**VIEW_EXPERT_SEARCH*/ VIEW_EXPERT_SEARCH_NAME(6100, "Pateint viewed the search expert by name page.", "searched for an expert by name", false), /**VIEW_REVIEWS*/ VIEW_REVIEWS(6101, "Patient viewed reviews for an HCP.", "viewed reviews", false), /**SUBMIT_REVIEW*/ SUBMIT_REVIEW(6102, "Patient submitted a review for an HCP.", "submitted review", true), /**CREATE_INITIAL_OBSTETRICS_RECORD**/ CREATE_INITIAL_OBSTETRICS_RECORD(6300, "Create Initial Obstetric Record", "Create Initial Obstetric Record", true), /**VIEW_INITIAL_OBSTETRICS_RECORD**/ VIEW_INITIAL_OBSTETRICS_RECORD(6301, "View Initial Obstetric Record", "View Initial Obstetric Record", true), /**CREATE_INITIAL_OBSTETRICS_RECORD**/ CREATE_OBSTETRICS_OV(6400, "Create Obstetric Office Visit", "Create Obstetric Office Visit", true), /**VIEW_INITIAL_OBSTETRICS_RECORD**/ VIEW_OBSTETRICS_OV(6401, "View Obstetric Office Visit", "View Obstetric Office Visit", true), /**VIEW_INITIAL_OBSTETRICS_RECORD**/ EDIT_OBSTETRICS_OV(6402, "Edit Obstetric Office Visit", "Edit Obstetric Office Visit", true), /**ADD_ALLERGY**/ ADD_ALLERGY(6700, "Add Allergy", "Add Allergy", true), /**Added to the Food Diary **/ FOOD_DIARY_ADD(6800, "Add Food Entry", "added an entry to your Food Diary", true), /**Patient viewed food diary**/ PATIENT_VIEW_FOOD_DIARY(6801, "Patient Viewed Food Diary", "viewed your Food Diary", true), /**Nutritionist viewed food diary **/ NUTRITIONIST_VIEW_FOOD_DIARY(6900, "Nutritionist viewed Food Diary", "viewed your Food Diary", true), /** Patient edited an entry from their food diary */ PATIENT_EDIT_FOOD_ENTRY(7000, "Patient edited Food Diary entry", "edited an entry in your Food Diary", true), /** Patient deleted an entry from their food diary */ DELETE_FOOD_ENTRY(7001, "Patient deleted Food Diary entry", "deleted an entry from your Food Diary", true), /** Patient changed their designated Nutritionist */ EDIT_DESIGNATED_NUTRITIONIST(7300, "Patient edited designated Nutritionist", "edited your designated Nutritionist", true), /**Added to the Sleep Diary **/ SLEEP_DIARY_ADD(7700, "Add Sleep Entry", "added an entry to your Sleep Diary", true), /**Patient viewed Sleep diary**/ PATIENT_VIEW_SLEEP_DIARY(7801, "Patient Viewed Sleep Diary", "viewed your Sleep Diary", true), /**HCP viewed Sleep diary **/ HCP_VIEW_SLEEP_DIARY(7802, "HCP viewed Sleep Diary", "viewed your Sleep Diary", true), /** Patient edited an entry from their Sleep diary */ PATIENT_EDIT_SLEEP_ENTRY(7901, "Patient edited Sleep Diary entry", "edited an entry in your Sleep Diary", true), /** Patient deleted an entry from their Sleep diary */ DELETE_SLEEP_ENTRY(7902, "Patient deleted Sleep Diary entry", "deleted an entry from your Sleep Diary", true), /**Added to the Exercise Diary **/ EXERCISE_DIARY_ADD(8000, "Add Exercise Entry", "added an entry to your Exercise Diary", true), /**Patient viewed Exercise diary**/ PATIENT_VIEW_EXERCISE_DIARY(8101, "Patient Viewed Exercise Diary", "viewed your Exercise Diary", true), /**Trainer viewed Exercise diary **/ TRAINER_VIEW_EXERCISE_DIARY(8102, "Trainer viewed Exercise Diary", "viewed your Exercise Diary", true), /** Patient edited an entry from their Exercise diary */ PATIENT_EDIT_EXERCISE_ENTRY(8201, "Patient edited Exercise Diary entry", "edited an entry in your Exercise Diary", true), /** Patient deleted an entry from their Exercise diary */ DELETE_EXERCISE_ENTRY(8202, "Patient deleted Exercise Diary entry", "deleted an entry from your Exercise Diary", true), /**Added to Labels **/ LABEL_ADD(7400, "Add Label", "added a new Label", true), /**Patient edited a Label**/ EDIT_LABEL(7401, "Patient edited a Label", "edited a Label", true), /**Patient deleted a Label **/ DELETE_LABEL(7402, "Patient deleted a Label", "deleted a Label", true), /**Patient edited a Label**/ HCP_VIEW_MACRONUTRIENTS(7200, "HCP viewed macronutrients", "viewed macronutrients", true), /**Patient edited a Label**/ VIEW_MACRONUTRIENTS_GRAPH(7100, "Patient generated graph", "generated a graph", true), /**Patient edited a Label**/ CALCULATE_MACRONUTRIENTS(7101, "Patient calculated macronutrients", "calculated macronutrients", true), /**CREATE_OPHTHALMOLOGY_OV**/ CREATE_OPHTHALMOLOGY_OV(8300, "Create Ophthalmology Office Visit", "Ophthalmology Office Visit", true), /**VIEW_OPHTHALMOLOGY_OV**/ VIEW_OPHTHALMOLOGY_OV(8301, "View Ophthalmology Office Visit", "View Ophthalmology Office Visit", true), /**EDIT_OPHTHALMOLOGY_OV**/ EDIT_OPHTHALMOLOGY_OV(8302, "Edit Ophthalmology Office Visit", "Edit Ophthalmology Office Visit", true), /**PATIENT_VIEW_OPHTHALMOLOGY_OV**/ PATIENT_VIEW_OPHTHALMOLOGY_OV(8400, "View Patient Ophthalmology Office Visit", "View Patient Ophthalmology Office Visit", true), /**PATIENT_VIEW_DEPENDENT_OPHTHALMOLOGY_OV**/ PATIENT_VIEW_DEPENDENT_OPHTHALMOLOGY_OV(8401, "View Dependent Ophthalmology Office Visit", "View Dependent Ophthalmology Office Visit", true), /**CREATE_OPHTHALMOLOGY_SURGERY**/ CREATE_OPHTHALMOLOGY_SURGERY(8600, "Create Ophthalmology Surgery", "Ophthalmology Surgery", true), /**VIEW_OPHTHALMOLOGY_SURGERY**/ VIEW_OPHTHALMOLOGY_SURGERY(8601, "View Ophthalmology Surgery", "View Ophthalmology Surgery", true), /**EDIT_OPHTHALMOLOGY_SURGERY**/ EDIT_OPHTHALMOLOGY_SURGERY(8602, "Edit Ophthalmology Surgery", "Edit Ophthalmology Surgery", true), /**PATIENT_VIEW_OPHTHALMOLOGY_SURGERY**/ ; /** * This string is used in the SQL statement associated with pulling events for * display in a patient's Access Log */ public static String patientViewableStr; static { for(TransactionType t : TransactionType.values()) { if(t.isPatientViewable()) { patientViewableStr += "," + t.code; } } } /** * This string is used in the SQL statement associated with excluding events as specified in UC43 */ public static final String dlhcpHiddenStr = "400, 900, 1000, 1001, 1100, 1101, 1102, 1110, 1111, 1112, 1120, 1121, 1122, 1130, 1131, 1132, 1140, 1141, 1142, 1150, 1152, 1600, 1700, 1900, 2101, 2300, 2601, 2602, 3200,5201"; private TransactionType(int code, String description, String actionPhrase, boolean patientViewable) { this.code = code; this.description = description; this.actionPhrase = actionPhrase; this.patientView = patientViewable; } private int code; private String description; private String actionPhrase; private boolean patientView; /** * getCode * @return code */ public int getCode() { return code; } /** * getDescription * @return description */ public String getDescription() { return description; } /** * getActionPhrase * @return actionPhrase */ public String getActionPhrase() { return actionPhrase; } /** * isPatientViewable * @return patientView */ public boolean isPatientViewable(){ return patientView; } /** * parse * @param code code * @return type */ public static TransactionType parse(int code) { for (TransactionType type : TransactionType.values()) { if (type.code == code) return type; } throw new IllegalArgumentException("No transaction type exists for code " + code); } }
33,474
56.517182
223
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/validate/AddPatientValidator.java
package edu.ncsu.csc.itrust.model.old.validate; import edu.ncsu.csc.itrust.action.AddPatientAction; import edu.ncsu.csc.itrust.exception.ErrorList; import edu.ncsu.csc.itrust.exception.FormValidationException; import edu.ncsu.csc.itrust.model.old.beans.PatientBean; /** * The validator used by {@link AddPatientAction}. Only checks first name, last name, and email * * * */ public class AddPatientValidator extends BeanValidator<PatientBean> { /** * The default constructor. */ public AddPatientValidator() { } /** * 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(PatientBean 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("Email", p.getEmail(), ValidationFormat.EMAIL, false)); if (errorList.hasErrors()) throw new FormValidationException(errorList); } }
1,286
32.868421
104
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/validate/AddPersonnelValidator.java
package edu.ncsu.csc.itrust.model.old.validate; import edu.ncsu.csc.itrust.action.AddPatientAction; import edu.ncsu.csc.itrust.exception.ErrorList; import edu.ncsu.csc.itrust.exception.FormValidationException; import edu.ncsu.csc.itrust.model.old.beans.PersonnelBean; /** * The validator used by {@link AddPatientAction}. Only checks first name, last name, and email * * * */ public class AddPersonnelValidator extends BeanValidator<PersonnelBean> { /** * The default constructor. */ public AddPersonnelValidator() { } /** * 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("Email", p.getEmail(), ValidationFormat.EMAIL, false)); if (errorList.hasErrors()) throw new FormValidationException(errorList); } }
1,296
33.131579
104
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/validate/AllergyBeanValidator.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.AllergyBean; /** * Validator used to validate adding a new allergy in {@link EditOfficeVisitAction} * * * */ public class AllergyBeanValidator extends BeanValidator<AllergyBean> { /** * The default constructor. */ public AllergyBeanValidator() { } /** * 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(AllergyBean m) throws FormValidationException { ErrorList errorList = new ErrorList(); errorList.addIfNotNull(checkFormat("Allergy Description", m.getDescription(), ValidationFormat.ALLERGY_DESCRIPTION, false)); if (errorList.hasErrors()) throw new FormValidationException(errorList); } }
1,061
29.342857
104
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/validate/ApptBeanValidator.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.ApptBean; public class ApptBeanValidator extends BeanValidator<ApptBean>{ @Override public void validate(ApptBean bean) throws FormValidationException { ErrorList errorList = new ErrorList(); if(bean.getComment() == null) return; errorList.addIfNotNull(checkFormat("Appointment Comment", bean.getComment(), ValidationFormat.APPT_COMMENT, false)); if (errorList.hasErrors()) throw new FormValidationException(errorList); } }
646
31.35
118
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/validate/ApptTypeBeanValidator.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.ApptTypeBean; public class ApptTypeBeanValidator extends BeanValidator<ApptTypeBean> { @Override public void validate(ApptTypeBean a) throws FormValidationException { ErrorList errorList = new ErrorList(); errorList.addIfNotNull(checkFormat("Appointment Type Name", a.getName(), ValidationFormat.APPT_TYPE_NAME, false)); errorList.addIfNotNull(checkFormat("Appointment Type Duration", a.getDuration()+"", ValidationFormat.APPT_TYPE_DURATION, false)); if(a.getDuration()<=0){ errorList.addIfNotNull("Appointment duration must be greater than zero."); } if (errorList.hasErrors()) throw new FormValidationException(errorList); } }
855
37.909091
131
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/validate/BeanValidator.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.enums.Gender; /** * Abstract class used by all validators that provides utility methods for checking formatting of a particular * field. Specify the Bean to be validated * * * * @param <T> * The bean type to be validated */ abstract public class BeanValidator<T> { abstract public void validate(T bean) throws FormValidationException; /** * Check the format against the given enum. isNullable will check if the string is empty or a Java null. * Otherwise, an error message will be returned. Use this in conjunction with {@link ErrorList}. * * @param name * @param value * @param format * @param isNullable * @return */ protected String checkFormat(String name, String value, ValidationFormat format, boolean isNullable) { String errorMessage = name + ": " + format.getDescription(); if (value == null || "".equals(value)) return isNullable ? "" : errorMessage; else if (format.getRegex().matcher(value).matches()) return ""; else return errorMessage; } /** * Check a long value against a particular format. isNullable will check if it is empty or a Java null. * Otherwise, an error message will be returned. Use this in conjunction with {@link ErrorList}. * * @param name * @param longValue * @param format * @param isNullable * @return */ protected String checkFormat(String name, Long longValue, ValidationFormat format, boolean isNullable) { String str = ""; if (longValue != null) str = String.valueOf(longValue); return checkFormat(name, str, format, isNullable); } /** * Check the format against the given enum. isNullable will check if it is a Java null. Otherwise, an * error message will be returned. Use this in conjunction with {@link ErrorList}. * * @param name * @param doubleValue * @param format * @param isNullable * @return */ protected String checkFormat(String name, Double doubleValue, ValidationFormat format, boolean isNullable) { String str = ""; if (doubleValue != null) str = String.valueOf(doubleValue); return checkFormat(name, str, format, isNullable); } /** * Check the format against the given enum. isNullable will check if it is a Java null. Otherwise, an * error message will be returned. Use this in conjunction with {@link ErrorList}. * * @param name * @param doubleValue * @param format * @param isNullable * @return */ protected String checkFormat(String name, Integer intValue, ValidationFormat format, boolean isNullable) { String str = ""; if (intValue != null) str = String.valueOf(intValue); return checkFormat(name, str, format, isNullable); } /** * Check against the proper gender * * @param name * @param gen * @param format * @param isNullable * @return */ protected String checkGender(String name, Gender gen, ValidationFormat format, boolean isNullable) { String str = ""; if (gen != null) str = gen.toString(); return checkFormat(name, str, format, isNullable); } /** * The that an integer is the proper format, and is in the correct range * * @param name * @param value * @param lower * @param upper * @param isNullable * @return */ protected String checkInt(String name, String value, int lower, int upper, boolean isNullable) { if (isNullable && (value == null || "".equals(value))) return ""; try { int intValue = Integer.valueOf(value); if (lower <= intValue && intValue <= upper) return ""; } catch (NumberFormatException e) { // just fall through to returning the error message } return name + " must be an integer in [" + lower + "," + upper + "]"; } /** * Check that a double is in the proper format and is in the correct range * * @param name * @param value * @param lower * @param upper * @return */ protected String checkDouble(String name, String value, double lower, double upper) { try { double doubleValue = Double.valueOf(value); if (lower <= doubleValue && doubleValue < upper) return ""; } catch (NumberFormatException e) { // just fall through to returning the error message } return name + " must be a decimal in [" + lower + "," + upper + ")"; } /** * Check that the value fits the "true" or "false" * * @param name * @param value * @return */ protected String checkBoolean(String name, String value) { if ("true".equals(value) || "false".equals(value)) return ""; else return name + " must be either 'true' or 'false'"; } protected String checkNotZero(String name, String value, ValidationFormat format, boolean isNullable) { String s = checkFormat(name, value, format, isNullable); if (s.equals("")) { if (Double.valueOf(value) < 0.1) { return name + " must be greater than 0"; } } return s; } }
5,005
27.443182
110
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/validate/DrugInteractionValidator.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.DrugInteractionBean; /** * Validates a drug interaction bean, from {@link DrugInteractionAction} */ public class DrugInteractionValidator extends BeanValidator<DrugInteractionBean> { /** * The default constructor. */ public DrugInteractionValidator() { } /** * 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 d A bean of the type to be validated. */ @Override public void validate(DrugInteractionBean d) throws FormValidationException { ErrorList errorList = new ErrorList(); errorList.addIfNotNull(checkFormat("FirstDrug", d.getFirstDrug(), ValidationFormat.ND, false)); errorList.addIfNotNull(checkFormat("SecondDrug", d.getSecondDrug(), ValidationFormat.ND, false)); errorList.addIfNotNull(checkFormat("description", d.getDescription(), ValidationFormat.DRUG_INT_COMMENTS, false)); if (errorList.hasErrors()) throw new FormValidationException(errorList); } }
1,252
36.969697
116
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/validate/EMailValidator.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; public class EMailValidator extends BeanValidator<MessageBean> { /** * The default constructor. */ public EMailValidator(){ } /** * 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 m A bean of the type to be validated. */ @Override public void validate(MessageBean m) throws FormValidationException { ErrorList errorList = new ErrorList(); errorList.addIfNotNull(checkFormat("body", m.getBody(), ValidationFormat.EMAILS, false)); if (errorList.hasErrors()) throw new FormValidationException(errorList); } }
918
25.257143
104
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/validate/HospitalBeanValidator.java
package edu.ncsu.csc.itrust.model.old.validate; import edu.ncsu.csc.itrust.action.UpdateHospitalListAction; import edu.ncsu.csc.itrust.exception.ErrorList; import edu.ncsu.csc.itrust.exception.FormValidationException; import edu.ncsu.csc.itrust.model.old.beans.HospitalBean; /** * Validates the input for hospital beans, {@link UpdateHospitalListAction} * * * */ public class HospitalBeanValidator extends BeanValidator<HospitalBean> { /** * The default constructor. */ public HospitalBeanValidator() { } /** * 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(HospitalBean h) throws FormValidationException { ErrorList errorList = new ErrorList(); errorList.addIfNotNull(checkFormat("Hospital ID", h.getHospitalID(), ValidationFormat.HOSPITAL_ID, false)); errorList.addIfNotNull(checkFormat("Hospital Name", h.getHospitalName(), ValidationFormat.HOSPITAL_NAME, false)); if(!h.getHospitalAddress().isEmpty()){ errorList.addIfNotNull(checkFormat("Hospital Address", h.getHospitalAddress(), ValidationFormat.ADDRESS, false)); } if(!h.getHospitalCity().isEmpty()){ errorList.addIfNotNull(checkFormat("Hospital City", h.getHospitalCity(), ValidationFormat.CITY, false)); } if(!h.getHospitalState().isEmpty()){ errorList.addIfNotNull(checkFormat("Hospital State", h.getHospitalState(), ValidationFormat.STATE, false)); } if(!h.getHospitalZip().isEmpty()){ errorList.addIfNotNull(checkFormat("Hospital Zip", h.getHospitalZip(), ValidationFormat.ZIPCODE, false)); } if (errorList.hasErrors()) { throw new FormValidationException(errorList); } } }
1,853
32.107143
116
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/model/old/validate/MailValidator.java
package edu.ncsu.csc.itrust.model.old.validate; import edu.ncsu.csc.itrust.exception.FormValidationException; import org.apache.commons.validator.*; public class MailValidator extends EmailValidator { /** * The default constructor. */ public MailValidator(){ } /** * 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. */ public boolean validateEmail(String email) throws FormValidationException { MailValidator val = new MailValidator(); return val.isValid(email); } }
695
21.451613
104
java